summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSebastien Delafond <seb@untangle.com>2017-08-02 11:47:03 -0700
committerSebastien Delafond <seb@untangle.com>2017-08-02 11:47:03 -0700
commitf41dc76cb81204c4ef33420f69eecfc387d7f2a5 (patch)
tree652270789f46934981ba73535a733722d79576be
Import org-mode_9.0.9+dfsg.orig.tar.xz
[dgit import orig org-mode_9.0.9+dfsg.orig.tar.xz]
-rw-r--r--COPYING674
-rw-r--r--Makefile97
-rw-r--r--README47
-rw-r--r--contrib/README103
-rw-r--r--contrib/lisp/htmlize.el1924
-rw-r--r--contrib/lisp/ob-csharp.el83
-rw-r--r--contrib/lisp/ob-eukleides.el98
-rw-r--r--contrib/lisp/ob-fomus.el92
-rw-r--r--contrib/lisp/ob-julia.el301
-rw-r--r--contrib/lisp/ob-mathematica.el81
-rw-r--r--contrib/lisp/ob-mathomatic.el145
-rw-r--r--contrib/lisp/ob-oz.el294
-rw-r--r--contrib/lisp/ob-stata.el312
-rw-r--r--contrib/lisp/ob-tcl.el128
-rw-r--r--contrib/lisp/ob-vbnet.el84
-rw-r--r--contrib/lisp/org-annotate-file.el157
-rw-r--r--contrib/lisp/org-bibtex-extras.el137
-rw-r--r--contrib/lisp/org-bookmark.el89
-rw-r--r--contrib/lisp/org-bullets.el122
-rw-r--r--contrib/lisp/org-checklist.el141
-rw-r--r--contrib/lisp/org-choose.el496
-rw-r--r--contrib/lisp/org-collector.el231
-rw-r--r--contrib/lisp/org-contacts.el1150
-rw-r--r--contrib/lisp/org-contribdir.el38
-rw-r--r--contrib/lisp/org-depend.el420
-rw-r--r--contrib/lisp/org-drill.el3367
-rw-r--r--contrib/lisp/org-ebib.el47
-rw-r--r--contrib/lisp/org-effectiveness.el369
-rw-r--r--contrib/lisp/org-eldoc.el173
-rw-r--r--contrib/lisp/org-elisp-symbol.el161
-rw-r--r--contrib/lisp/org-eval-light.el199
-rw-r--r--contrib/lisp/org-eval.el216
-rw-r--r--contrib/lisp/org-expiry.el361
-rw-r--r--contrib/lisp/org-git-link.el229
-rw-r--r--contrib/lisp/org-index.el3006
-rw-r--r--contrib/lisp/org-interactive-query.el311
-rw-r--r--contrib/lisp/org-invoice.el401
-rw-r--r--contrib/lisp/org-learn.el177
-rw-r--r--contrib/lisp/org-license.el540
-rw-r--r--contrib/lisp/org-link-edit.el390
-rw-r--r--contrib/lisp/org-mac-iCal.el250
-rw-r--r--contrib/lisp/org-mac-link.el947
-rw-r--r--contrib/lisp/org-mairix.el333
-rw-r--r--contrib/lisp/org-man.el75
-rw-r--r--contrib/lisp/org-mew.el354
-rw-r--r--contrib/lisp/org-mime.el345
-rw-r--r--contrib/lisp/org-notify.el394
-rw-r--r--contrib/lisp/org-notmuch.el135
-rw-r--r--contrib/lisp/org-panel.el638
-rw-r--r--contrib/lisp/org-passwords.el384
-rw-r--r--contrib/lisp/org-registry.el272
-rw-r--r--contrib/lisp/org-screen.el106
-rw-r--r--contrib/lisp/org-screenshot.el529
-rw-r--r--contrib/lisp/org-secretary.el230
-rw-r--r--contrib/lisp/org-static-mathjax.el187
-rw-r--r--contrib/lisp/org-sudoku.el288
-rw-r--r--contrib/lisp/org-toc.el508
-rw-r--r--contrib/lisp/org-track.el211
-rw-r--r--contrib/lisp/org-velocity.el819
-rw-r--r--contrib/lisp/org-vm.el168
-rw-r--r--contrib/lisp/org-wikinodes.el327
-rw-r--r--contrib/lisp/org-wl.el302
-rw-r--r--contrib/lisp/orgtbl-sqlinsert.el118
-rw-r--r--contrib/lisp/ox-bibtex.el431
-rw-r--r--contrib/lisp/ox-confluence.el228
-rw-r--r--contrib/lisp/ox-deck.el585
-rw-r--r--contrib/lisp/ox-extra.el211
-rw-r--r--contrib/lisp/ox-freemind.el527
-rw-r--r--contrib/lisp/ox-groff.el1962
-rw-r--r--contrib/lisp/ox-koma-letter.el917
-rw-r--r--contrib/lisp/ox-rss.el419
-rw-r--r--contrib/lisp/ox-s5.el432
-rw-r--r--contrib/lisp/ox-taskjuggler.el1038
-rw-r--r--contrib/scripts/.gitignore1
-rw-r--r--contrib/scripts/StartOzServer.oz231
-rwxr-xr-xcontrib/scripts/dir2org.zsh56
-rw-r--r--contrib/scripts/docco.css185
-rw-r--r--contrib/scripts/org-docco.org206
-rwxr-xr-xcontrib/scripts/org2hpda106
-rw-r--r--contrib/scripts/staticmathjax/.gitignore1
-rw-r--r--contrib/scripts/staticmathjax/README.org79
-rw-r--r--contrib/scripts/staticmathjax/application.ini11
-rw-r--r--contrib/scripts/staticmathjax/chrome/chrome.manifest1
-rw-r--r--contrib/scripts/staticmathjax/chrome/content/main.js198
-rw-r--r--contrib/scripts/staticmathjax/chrome/content/main.xul11
-rw-r--r--contrib/scripts/staticmathjax/defaults/preferences/prefs.js1
-rw-r--r--contrib/scripts/x11idle.c28
-rw-r--r--etc/Makefile31
-rw-r--r--etc/ORG-NEWS3824
-rw-r--r--etc/schema/od-manifest-schema-v1.2-os.rnc88
-rw-r--r--etc/schema/od-schema-v1.2-os.rnc6280
-rw-r--r--etc/schema/schemas.xml7
-rw-r--r--etc/styles/OrgOdtContentTemplate.xml275
-rw-r--r--etc/styles/OrgOdtStyles.xml861
-rw-r--r--etc/styles/README36
-rw-r--r--lisp/Makefile93
-rw-r--r--lisp/ob-C.el448
-rw-r--r--lisp/ob-J.el186
-rw-r--r--lisp/ob-R.el469
-rw-r--r--lisp/ob-abc.el92
-rw-r--r--lisp/ob-asymptote.el139
-rw-r--r--lisp/ob-awk.el111
-rw-r--r--lisp/ob-calc.el110
-rw-r--r--lisp/ob-clojure.el118
-rw-r--r--lisp/ob-comint.el161
-rw-r--r--lisp/ob-coq.el78
-rw-r--r--lisp/ob-core.el3135
-rw-r--r--lisp/ob-css.el48
-rw-r--r--lisp/ob-ditaa.el124
-rw-r--r--lisp/ob-dot.el90
-rw-r--r--lisp/ob-ebnf.el83
-rw-r--r--lisp/ob-emacs-lisp.el94
-rw-r--r--lisp/ob-eval.el149
-rw-r--r--lisp/ob-exp.el412
-rw-r--r--lisp/ob-forth.el87
-rw-r--r--lisp/ob-fortran.el168
-rw-r--r--lisp/ob-gnuplot.el278
-rw-r--r--lisp/ob-groovy.el116
-rw-r--r--lisp/ob-haskell.el213
-rw-r--r--lisp/ob-io.el108
-rw-r--r--lisp/ob-java.el85
-rw-r--r--lisp/ob-js.el164
-rw-r--r--lisp/ob-keys.el106
-rw-r--r--lisp/ob-latex.el226
-rw-r--r--lisp/ob-ledger.el70
-rw-r--r--lisp/ob-lilypond.el412
-rw-r--r--lisp/ob-lisp.el127
-rw-r--r--lisp/ob-lob.el151
-rw-r--r--lisp/ob-lua.el403
-rw-r--r--lisp/ob-makefile.el48
-rw-r--r--lisp/ob-matlab.el47
-rw-r--r--lisp/ob-maxima.el127
-rw-r--r--lisp/ob-mscgen.el84
-rw-r--r--lisp/ob-ocaml.el171
-rw-r--r--lisp/ob-octave.el266
-rw-r--r--lisp/ob-org.el72
-rw-r--r--lisp/ob-perl.el157
-rw-r--r--lisp/ob-picolisp.el187
-rw-r--r--lisp/ob-plantuml.el100
-rw-r--r--lisp/ob-processing.el195
-rw-r--r--lisp/ob-python.el347
-rw-r--r--lisp/ob-ref.el249
-rw-r--r--lisp/ob-ruby.el268
-rw-r--r--lisp/ob-sass.el70
-rw-r--r--lisp/ob-scala.el114
-rw-r--r--lisp/ob-scheme.el208
-rw-r--r--lisp/ob-screen.el143
-rw-r--r--lisp/ob-sed.el107
-rw-r--r--lisp/ob-shell.el283
-rw-r--r--lisp/ob-shen.el78
-rw-r--r--lisp/ob-sql.el283
-rw-r--r--lisp/ob-sqlite.el161
-rw-r--r--lisp/ob-stan.el84
-rw-r--r--lisp/ob-table.el153
-rw-r--r--lisp/ob-tangle.el602
-rw-r--r--lisp/ob.el43
-rw-r--r--lisp/org-agenda.el10276
-rw-r--r--lisp/org-archive.el615
-rw-r--r--lisp/org-attach.el554
-rw-r--r--lisp/org-bbdb.el506
-rw-r--r--lisp/org-bibtex.el737
-rw-r--r--lisp/org-capture.el1901
-rw-r--r--lisp/org-clock.el2981
-rw-r--r--lisp/org-colview.el1661
-rw-r--r--lisp/org-compat.el507
-rw-r--r--lisp/org-crypt.el275
-rw-r--r--lisp/org-ctags.el533
-rw-r--r--lisp/org-datetree.el231
-rw-r--r--lisp/org-docview.el103
-rw-r--r--lisp/org-element.el6085
-rw-r--r--lisp/org-entities.el597
-rw-r--r--lisp/org-eshell.el66
-rw-r--r--lisp/org-eww.el175
-rw-r--r--lisp/org-faces.el653
-rw-r--r--lisp/org-feed.el713
-rw-r--r--lisp/org-footnote.el1005
-rw-r--r--lisp/org-gnus.el295
-rw-r--r--lisp/org-habit.el442
-rw-r--r--lisp/org-id.el685
-rw-r--r--lisp/org-indent.el412
-rw-r--r--lisp/org-info.el144
-rw-r--r--lisp/org-inlinetask.el348
-rw-r--r--lisp/org-install.el17
-rw-r--r--lisp/org-irc.el253
-rw-r--r--lisp/org-lint.el1225
-rw-r--r--lisp/org-list.el3591
-rw-r--r--lisp/org-loaddefs.el3829
-rw-r--r--lisp/org-macro.el307
-rw-r--r--lisp/org-macs.el309
-rw-r--r--lisp/org-mhe.el219
-rw-r--r--lisp/org-mobile.el1115
-rw-r--r--lisp/org-mouse.el1111
-rw-r--r--lisp/org-pcomplete.el391
-rw-r--r--lisp/org-plot.el354
-rw-r--r--lisp/org-protocol.el717
-rw-r--r--lisp/org-rmail.el115
-rw-r--r--lisp/org-src.el1104
-rw-r--r--lisp/org-table.el5505
-rw-r--r--lisp/org-timer.el509
-rw-r--r--lisp/org-version.el27
-rw-r--r--lisp/org-w3m.el183
-rw-r--r--lisp/org.el25144
-rw-r--r--lisp/ox-ascii.el2179
-rw-r--r--lisp/ox-beamer.el1141
-rw-r--r--lisp/ox-html.el3723
-rw-r--r--lisp/ox-icalendar.el960
-rw-r--r--lisp/ox-latex.el3711
-rw-r--r--lisp/ox-man.el1141
-rw-r--r--lisp/ox-md.el647
-rw-r--r--lisp/ox-odt.el4325
-rw-r--r--lisp/ox-org.el352
-rw-r--r--lisp/ox-publish.el1333
-rw-r--r--lisp/ox-texinfo.el1696
-rw-r--r--lisp/ox.el6630
-rw-r--r--mk/default.mk176
-rw-r--r--mk/org-fixup.el200
-rw-r--r--mk/targets.mk167
-rw-r--r--mk/version.mk2
-rw-r--r--request-assign-future.txt44
219 files changed, 165031 insertions, 0 deletions
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..f6312f2
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,97 @@
+# Makefile - for the org-mode distribution
+# GNU make is required
+#
+# This file is not part of GNU Emacs
+
+# set up environment
+ include mk/default.mk # defaults, customizable via "local.mk"
+-include local.mk # optional local customization, use default.mk as template
+
+# default target is "all" unless overridden in local.mk
+all::
+
+# Describe valid make targets for org-mode.
+.PHONY: targets help helpall
+targets: help
+help helpall::
+ $(info )
+ $(info Getting Help)
+ $(info ============)
+ $(info make help - show brief help)
+ $(info make targets - ditto)
+ $(info make helpall - show extended help)
+ $(info )
+ $(info Build and Check)
+ $(info ===============)
+ $(info make - build Org ELisp and all documentation)
+ $(info make all - ditto)
+ $(info make compile - build Org ELisp files)
+ $(info make single - build Org ELisp files, single Emacs per source)
+ $(info make autoloads - create org-loaddefs.el to load Org in-place)
+ $(info make test - build Org ELisp files and run test suite)
+ $(info make vanilla - run Emacs with this Org-mode and no personal config)
+helpall::
+ $(info make test-dirty - check without building first)
+ $(info make compile-dirty - build only stale Org ELisp files)
+ $(info )
+ $(info Compatibility)
+ $(info =============)
+ $(info make oldorg - what the old make did: compile autoloads info)
+ $(info )
+ $(info Cleaning)
+ $(info ========)
+ $(info make clean - remove built Org ELisp files and documentation)
+ $(info make cleanall - remove everything that can be built and all remnants)
+ $(info make clean-install - remove previous Org installation)
+ $(info )
+ $(info Configuration Check)
+ $(info ===================)
+help helpall::
+ $(info make config - check main configuration)
+helpall::
+ $(info make config-version - check Org version)
+ $(info make config-test - check test configuration)
+ $(info make config-exe - check executables configuration)
+ $(info make config-cmd - check command configuration)
+ $(info make config-all - check all configuration)
+ $(info )
+ $(info Documentation)
+ $(info =============)
+help helpall::
+ $(info make doc - build all documentation)
+helpall::
+ $(info make docs - ditto)
+help helpall::
+ $(info make info - build Info documentation)
+helpall::
+ $(info make html - build HTML documentation)
+ $(info make pdf - build PDF documentation)
+ $(info make card - build reference cards)
+ $(info make refcard - ditto)
+help helpall::
+ $(info )
+ $(info Installation)
+ $(info ============)
+ $(info make install - build and install Org)
+helpall::
+ $(info make install-etc - build and install files in /etc)
+ $(info make install-lisp - build and install Org Elisp files)
+ $(info make install-info - build and install Info documentation)
+ $(info )
+ $(info Convenience)
+ $(info ===========)
+ $(info make up0 - pull from upstream)
+ $(info make up1 - pull from upstream, build and check)
+ $(info make up2 - pull from upstream, build, check and install)
+ $(info make update - pull from upstream and build)
+ $(info make update2 - pull from upstream, build and install)
+ $(info make uncompiled - combine cleanlisp and autoloads)
+ $(info make local.mk - create new local.mk as template for adaptation)
+help helpall::
+ $(info )
+ $(info Full documentation on Worg)
+ $(info ==========================)
+ $(info http://orgmode.org/worg/dev/org-build-system.html)
+ @echo ""
+
+ include mk/targets.mk # toplevel make machinery
diff --git a/README b/README
new file mode 100644
index 0000000..425701c
--- /dev/null
+++ b/README
@@ -0,0 +1,47 @@
+The is a distribution of Org, a plain text notes and project planning
+tool for Emacs.
+
+The homepage of Org is at:
+ http://orgmode.org
+
+The installations instructions are at:
+ http://orgmode.org/org.html#Installation
+
+This distribution contains:
+
+README
+ This file.
+
+COPYING
+ The GNU General Public License.
+
+Makefile
+ The makefile to compile and install Org. For installation
+ instructions, see the manual or the more detailed procedure
+ on Worg: http://orgmode.org/worg/dev/org-build-system.html
+
+mk/
+ Files needed for building Org.
+
+lisp/
+ Directory with all the Emacs Lisp files that make up Org.
+
+doc/
+ The documentation files. org.texi is the source of the
+ documentation, org.html and org.pdf are formatted versions of it.
+
+contrib/
+ A directory with third-party additions for Org. Some really cool
+ stuff is in there.
+
+etc/
+ Files needed for the ODT exporter.
+
+testing/
+ Testing suite for Org.
+
+request-assign-future.txt
+ The form that contributors have to sign and get processed with
+ the FSF before contributed changes can be integrated into the Org
+ core. All files in this distribution except the contrib/ directory
+ have copyright assigned to the FSF.
diff --git a/contrib/README b/contrib/README
new file mode 100644
index 0000000..48c58b9
--- /dev/null
+++ b/contrib/README
@@ -0,0 +1,103 @@
+This directory contains add-ons to Org-mode.
+
+These contributions are not part of GNU Emacs or of the official
+Org-mode package. But the git repository for Org-mode is glad to
+provide useful way to distribute and develop them as long as they
+are distributed under a free software license.
+
+Please put your contribution in one of these directories:
+
+LISP (Emacs Lisp)
+=================
+
+Org utils
+~~~~~~~~~
+org-annotate-file.el --- Annotate a file with org syntax
+org-bibtex-extras.el --- Extras for working with org-bibtex entries
+org-bookmark.el --- Links to bookmarks
+org-bullets.el --- Show bullets in org-mode as UTF-8 characters
+org-checklist.el --- org functions for checklist handling
+org-choose.el --- Use TODO keywords to mark decision states
+org-collector.el --- Collect properties into tables
+org-colview-xemacs.el --- Column View in Org-mode, XEmacs-specific version
+org-contacts.el --- Contacts management
+org-contribdir.el --- Dummy file to mark the org contrib Lisp directory
+org-depend.el --- TODO dependencies for Org-mode
+org-drill.el --- Self-testing with org-learn
+org-effectiveness.el --- Measuring your personal effectiveness
+org-element.el --- Parser and applications for Org syntax
+org-eldoc.el --- Eldoc documentation for SRC blocks
+org-elisp-symbol.el --- Org links to emacs-lisp symbols
+org-eval-light.el --- Evaluate in-buffer code on demand
+org-eval.el --- The <lisp> tag, adapted from Muse
+org-expiry.el --- Expiry mechanism for Org entries
+org-export-generic.el --- Export framework for configurable backends
+org-git-link.el --- Provide org links to specific file version
+org-index.el --- A personal index for org and beyond
+org-interactive-query.el --- Interactive modification of tags query
+org-invoice.el --- Help manage client invoices in OrgMode
+org-learn.el --- SuperMemo's incremental learning algorithm
+org-license.el --- Insert free licenses to your org documents
+org-link-edit.el --- Slurp and barf with Org links
+org-mac-iCal.el --- Imports events from iCal.app to the Emacs diary
+org-mac-link.el --- Grab links and URLs from various Mac applications
+org-mairix.el --- Hook mairix search into Org for different MUAs
+org-man.el --- Support for links to manpages in Org-mode
+org-mew.el --- Support for links to Mew messages
+org-mime.el --- org html export for text/html MIME emails
+org-mtags.el --- Support for some Muse-like tags in Org-mode
+org-notify.el --- Notifications for Org-mode
+org-notmuch.el --- Support for links to notmuch messages
+org-panel.el --- Simple routines for us with bad memory
+org-registry.el --- A registry for Org links
+org-screen.el --- Visit screen sessions through Org-mode links
+org-screenshot.el --- Take and manage screenshots in Org-mode files
+org-secretary.el --- Team management with org-mode
+org-static-mathjax.el --- Muse-like tags in Org-mode
+org-sudoku.el --- Create and solve SUDOKU puzzles in Org tables
+org-toc.el --- Table of contents for Org-mode buffer
+org-track.el --- Keep up with Org development
+org-velocity.el --- something like Notational Velocity for Org
+org-vm.el --- Support for links to VM messages
+org-w3m.el --- Support link/copy/paste from w3m to Org-mode
+org-wikinodes.el --- CamelCase wiki-like links for Org
+org-wl.el --- Support for links to Wanderlust messages
+orgtbl-sqlinsert.el --- Convert Org-mode tables to SQL insertions
+
+Org exporters
+~~~~~~~~~~~~~
+ox-confluence.el --- Confluence Wiki exporter
+ox-deck.el --- deck.js presentations exporter
+ox-groff.el --- Groff exporter
+ox-koma-letter.el --- KOMA Scrlttr2 exporter
+ox-rss.el --- RSS 2.0 exporter
+ox-s5.el --- S5 presentations exporter
+ox-taskjuggler.el --- TaskJuggler exporter
+
+Org Babel languages
+~~~~~~~~~~~~~~~~~~~
+ob-eukleides.el --- Org-babel functions for eukleides evaluation
+ob-fomus.el --- Org-babel functions for fomus evaluation
+ob-julia.el --- Org-babel functions for julia evaluation
+ob-mathomatic.el --- Org-babel functions for mathomatic evaluation
+ob-oz.el --- Org-babel functions for Oz evaluation
+ob-stata.el --- Org-babel functions for Stata evaluation
+ob-tcl.el --- Org-babel functions for tcl evaluation
+
+External libraries
+~~~~~~~~~~~~~~~~~~
+htmlize.el --- Convert buffer text and decorations to HTML
+
+
+SCRIPTS (shell, bash, etc.)
+===========================
+StartOzServer.oz --- implements the Oz-side of the Org-babel Oz interface
+dir2org.zsh --- Org compatible fs structure output
+ditaa.jar --- ASCII to PNG converter by Stathis Sideris, GPL
+org-docco.org --- docco side-by-side annotated code export to HTML
+org2hpda --- Generate hipster pda style printouts from Org-mode
+staticmathjax --- XULRunner application to process MathJax statically
+x11idle.c --- get the idle time of your X session
+
+This directory also contains supporting files for the following
+packages: ob-oz.el, org-docco.org, and org-static-mathjax.el.
diff --git a/contrib/lisp/htmlize.el b/contrib/lisp/htmlize.el
new file mode 100644
index 0000000..8358830
--- /dev/null
+++ b/contrib/lisp/htmlize.el
@@ -0,0 +1,1924 @@
+;;; htmlize.el --- Convert buffer text and decorations to HTML.
+
+;; Copyright (C) 1997-2013 Hrvoje Niksic
+
+;; Author: Hrvoje Niksic <hniksic@xemacs.org>
+;; Keywords: hypermedia, extensions
+;; Version: 1.43
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 2, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+
+;; This package converts the buffer text and the associated
+;; decorations to HTML. Mail to <hniksic@xemacs.org> to discuss
+;; features and additions. All suggestions are more than welcome.
+
+;; To use it, just switch to the buffer you want HTML-ized and type
+;; `M-x htmlize-buffer'. You will be switched to a new buffer that
+;; contains the resulting HTML code. You can edit and inspect this
+;; buffer, or you can just save it with C-x C-w. `M-x htmlize-file'
+;; will find a file, fontify it, and save the HTML version in
+;; FILE.html, without any additional intervention. `M-x
+;; htmlize-many-files' allows you to htmlize any number of files in
+;; the same manner. `M-x htmlize-many-files-dired' does the same for
+;; files marked in a dired buffer.
+
+;; htmlize supports three types of HTML output, selected by setting
+;; `htmlize-output-type': `css', `inline-css', and `font'. In `css'
+;; mode, htmlize uses cascading style sheets to specify colors; it
+;; generates classes that correspond to Emacs faces and uses <span
+;; class=FACE>...</span> to color parts of text. In this mode, the
+;; produced HTML is valid under the 4.01 strict DTD, as confirmed by
+;; the W3C validator. `inline-css' is like `css', except the CSS is
+;; put directly in the STYLE attribute of the SPAN element, making it
+;; possible to paste the generated HTML into existing HTML documents.
+;; In `font' mode, htmlize uses <font color="...">...</font> to
+;; colorize HTML, which is not standard-compliant, but works better in
+;; older browsers. `css' mode is the default.
+
+;; You can also use htmlize from your Emacs Lisp code. When called
+;; non-interactively, `htmlize-buffer' and `htmlize-region' will
+;; return the resulting HTML buffer, but will not change current
+;; buffer or move the point. htmlize will do its best to work on
+;; non-windowing Emacs sessions but the result will be limited to
+;; colors supported by the terminal.
+
+;; htmlize aims for compatibility with Emacsen version 21 and later.
+;; Please let me know if it doesn't work on the version of XEmacs or
+;; GNU Emacs that you are using. The package relies on the presence
+;; of CL extensions, especially for cross-emacs compatibility; please
+;; don't try to remove that dependency. I see no practical problems
+;; with using the full power of the CL extensions, except that one
+;; might learn to like them too much.
+
+;; The latest version is available as a git repository at:
+;;
+;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.git>
+;;
+;; The snapshot of the latest release can be obtained at:
+;;
+;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.cgi>
+;;
+;; You can find a sample of htmlize's output (possibly generated with
+;; an older version) at:
+;;
+;; <http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html>
+
+;; Thanks go to the many people who have sent reports and contributed
+;; comments, suggestions, and fixes. They include Ron Gut, Bob
+;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels,
+;; Juri Linkov, Maciek Pasternacki, and many others.
+
+;; User quotes: "You sir, are a sick, sick, _sick_ person. :)"
+;; -- Bill Perry, author of Emacs/W3
+
+
+;;; Code:
+
+(require 'cl)
+(eval-when-compile
+ (defvar unresolved)
+ (if (string-match "XEmacs" emacs-version)
+ (byte-compiler-options
+ (warnings (- unresolved))))
+ (defvar font-lock-auto-fontify)
+ (defvar font-lock-support-mode)
+ (defvar global-font-lock-mode))
+
+(defconst htmlize-version "1.43")
+
+(defgroup htmlize nil
+ "Convert buffer text and faces to HTML."
+ :group 'hypermedia)
+
+(defcustom htmlize-head-tags ""
+ "Additional tags to insert within HEAD of the generated document."
+ :type 'string
+ :group 'htmlize)
+
+(defcustom htmlize-output-type 'css
+ "Output type of generated HTML, one of `css', `inline-css', or `font'.
+When set to `css' (the default), htmlize will generate a style sheet
+with description of faces, and use it in the HTML document, specifying
+the faces in the actual text with <span class=\"FACE\">.
+
+When set to `inline-css', the style will be generated as above, but
+placed directly in the STYLE attribute of the span ELEMENT: <span
+style=\"STYLE\">. This makes it easier to paste the resulting HTML to
+other documents.
+
+When set to `font', the properties will be set using layout tags
+<font>, <b>, <i>, <u>, and <strike>.
+
+`css' output is normally preferred, but `font' is still useful for
+supporting old, pre-CSS browsers, and both `inline-css' and `font' for
+easier embedding of colorized text in foreign HTML documents (no style
+sheet to carry around)."
+ :type '(choice (const css) (const inline-css) (const font))
+ :group 'htmlize)
+
+(defcustom htmlize-use-images t
+ "Whether htmlize generates `img' for images attached to buffer contents."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-force-inline-images nil
+ "Non-nil means generate all images inline using data URLs.
+Normally htmlize converts image descriptors with :file properties to
+relative URIs, and those with :data properties to data URIs. With this
+flag set, the images specified as a file name are loaded into memory and
+embedded in the HTML as data URIs."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-max-alt-text 100
+ "Maximum size of text to use as ALT text in images.
+
+Normally when htmlize encounters text covered by the `display' property
+that specifies an image, it generates an `alt' attribute containing the
+original text. If the text is larger than `htmlize-max-alt-text' characters,
+this will not be done.")
+
+(defcustom htmlize-transform-image 'htmlize-default-transform-image
+ "Function called to modify the image descriptor.
+
+The function is called with the image descriptor found in the buffer and
+the text the image is supposed to replace. It should return a (possibly
+different) image descriptor property list or a replacement string to use
+instead of of the original buffer text.
+
+Returning nil is the same as returning the original text."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-generate-hyperlinks t
+ "Non-nil means auto-generate the links from URLs and mail addresses in buffer.
+
+This is on by default; set it to nil if you don't want htmlize to
+autogenerate such links. Note that this option only turns off automatic
+search for contents that looks like URLs and converting them to links.
+It has no effect on whether htmlize respects the `htmlize-link' property."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-hyperlink-style "
+ a {
+ color: inherit;
+ background-color: inherit;
+ font: inherit;
+ text-decoration: inherit;
+ }
+ a:hover {
+ text-decoration: underline;
+ }
+"
+ "The CSS style used for hyperlinks when in CSS mode."
+ :type 'string
+ :group 'htmlize)
+
+(defcustom htmlize-replace-form-feeds t
+ "Non-nil means replace form feeds in source code with HTML separators.
+Form feeds are the ^L characters at line beginnings that are sometimes
+used to separate sections of source code. If this variable is set to
+`t', form feed characters are replaced with the <hr> separator. If this
+is a string, it specifies the replacement to use. Note that <pre> is
+temporarily closed before the separator is inserted, so the default
+replacement is effectively \"</pre><hr /><pre>\". If you specify
+another replacement, don't forget to close and reopen the <pre> if you
+want the output to remain valid HTML.
+
+If you need more elaborate processing, set this to nil and use
+htmlize-after-hook."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-html-charset nil
+ "The charset declared by the resulting HTML documents.
+When non-nil, causes htmlize to insert the following in the HEAD section
+of the generated HTML:
+
+ <meta http-equiv=\"Content-Type\" content=\"text/html; charset=CHARSET\">
+
+where CHARSET is the value you've set for htmlize-html-charset. Valid
+charsets are defined by MIME and include strings like \"iso-8859-1\",
+\"iso-8859-15\", \"utf-8\", etc.
+
+If you are using non-Latin-1 charsets, you might need to set this for
+your documents to render correctly. Also, the W3C validator requires
+submitted HTML documents to declare a charset. So if you care about
+validation, you can use this to prevent the validator from bitching.
+
+Needless to say, if you set this, you should actually make sure that
+the buffer is in the encoding you're claiming it is in. (This is
+normally achieved by using the correct file coding system for the
+buffer.) If you don't understand what that means, you should probably
+leave this option in its default setting."
+ :type '(choice (const :tag "Unset" nil)
+ string)
+ :group 'htmlize)
+
+(defcustom htmlize-convert-nonascii-to-entities t
+ "Whether non-ASCII characters should be converted to HTML entities.
+
+When this is non-nil, characters with codes in the 128-255 range will be
+considered Latin 1 and rewritten as \"&#CODE;\". Characters with codes
+above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode
+code point of the character. If the code point cannot be determined,
+the character will be copied unchanged, as would be the case if the
+option were nil.
+
+When the option is nil, the non-ASCII characters are copied to HTML
+without modification. In that case, the web server and/or the browser
+must be set to understand the encoding that was used when saving the
+buffer. (You might also want to specify it by setting
+`htmlize-html-charset'.)
+
+Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point,
+which has nothing to do with the charset the page is in. For example,
+\"&#169;\" *always* refers to the copyright symbol, regardless of charset
+specified by the META tag or the charset sent by the HTTP server. In
+other words, \"&#169;\" is exactly equivalent to \"&copy;\".
+
+For most people htmlize will work fine with this option left at the
+default setting; don't change it unless you know what you're doing."
+ :type 'sexp
+ :group 'htmlize)
+
+(defcustom htmlize-ignore-face-size 'absolute
+ "Whether face size should be ignored when generating HTML.
+If this is nil, face sizes are used. If set to t, sizes are ignored
+If set to `absolute', only absolute size specifications are ignored.
+Please note that font sizes only work with CSS-based output types."
+ :type '(choice (const :tag "Don't ignore" nil)
+ (const :tag "Ignore all" t)
+ (const :tag "Ignore absolute" absolute))
+ :group 'htmlize)
+
+(defcustom htmlize-css-name-prefix ""
+ "The prefix used for CSS names.
+The CSS names that htmlize generates from face names are often too
+generic for CSS files; for example, `font-lock-type-face' is transformed
+to `type'. Use this variable to add a prefix to the generated names.
+The string \"htmlize-\" is an example of a reasonable prefix."
+ :type 'string
+ :group 'htmlize)
+
+(defcustom htmlize-use-rgb-txt t
+ "Whether `rgb.txt' should be used to convert color names to RGB.
+
+This conversion means determining, for instance, that the color
+\"IndianRed\" corresponds to the (205, 92, 92) RGB triple. `rgb.txt'
+is the X color database that maps hundreds of color names to such RGB
+triples. When this variable is non-nil, `htmlize' uses `rgb.txt' to
+look up color names.
+
+If this variable is nil, htmlize queries Emacs for RGB components of
+colors using `color-instance-rgb-components' and `color-values'.
+This can yield incorrect results on non-true-color displays.
+
+If the `rgb.txt' file is not found (which will be the case if you're
+running Emacs on non-X11 systems), this option is ignored."
+ :type 'boolean
+ :group 'htmlize)
+
+(defcustom htmlize-html-major-mode nil
+ "The mode the newly created HTML buffer will be put in.
+Set this to nil if you prefer the default (fundamental) mode."
+ :type '(radio (const :tag "No mode (fundamental)" nil)
+ (function-item html-mode)
+ (function :tag "User-defined major mode"))
+ :group 'htmlize)
+
+(defvar htmlize-before-hook nil
+ "Hook run before htmlizing a buffer.
+The hook functions are run in the source buffer (not the resulting HTML
+buffer).")
+
+(defvar htmlize-after-hook nil
+ "Hook run after htmlizing a buffer.
+Unlike `htmlize-before-hook', these functions are run in the generated
+HTML buffer. You may use them to modify the outlook of the final HTML
+output.")
+
+(defvar htmlize-file-hook nil
+ "Hook run by `htmlize-file' after htmlizing a file, but before saving it.")
+
+(defvar htmlize-buffer-places)
+
+;;; Some cross-Emacs compatibility.
+
+;; I try to conditionalize on features rather than Emacs version, but
+;; in some cases checking against the version *is* necessary.
+(defconst htmlize-running-xemacs (string-match "XEmacs" emacs-version))
+
+;; We need a function that efficiently finds the next change of a
+;; property regardless of whether the change occurred because of a
+;; text property or an extent/overlay.
+(cond
+ (htmlize-running-xemacs
+ (defun htmlize-next-change (pos prop &optional limit)
+ (if prop
+ (next-single-char-property-change pos prop nil (or limit (point-max)))
+ (next-property-change pos nil (or limit (point-max)))))
+ (defun htmlize-next-face-change (pos &optional limit)
+ (htmlize-next-change pos 'face limit)))
+ ((fboundp 'next-single-char-property-change)
+ ;; GNU Emacs 21+
+ (defun htmlize-next-change (pos prop &optional limit)
+ (if prop
+ (next-single-char-property-change pos prop nil limit)
+ (next-char-property-change pos limit)))
+ (defun htmlize-overlay-faces-at (pos)
+ (delq nil (mapcar (lambda (o) (overlay-get o 'face)) (overlays-at pos))))
+ (defun htmlize-next-face-change (pos &optional limit)
+ ;; (htmlize-next-change pos 'face limit) would skip over entire
+ ;; overlays that specify the `face' property, even when they
+ ;; contain smaller text properties that also specify `face'.
+ ;; Emacs display engine merges those faces, and so must we.
+ (or limit
+ (setq limit (point-max)))
+ (let ((next-prop (next-single-property-change pos 'face nil limit))
+ (overlay-faces (htmlize-overlay-faces-at pos)))
+ (while (progn
+ (setq pos (next-overlay-change pos))
+ (and (< pos next-prop)
+ (equal overlay-faces (htmlize-overlay-faces-at pos)))))
+ (setq pos (min pos next-prop))
+ ;; Additionally, we include the entire region that specifies the
+ ;; `display' property.
+ (when (get-char-property pos 'display)
+ (setq pos (next-single-char-property-change pos 'display nil limit)))
+ pos)))
+ (t
+ (error "htmlize requires next-single-property-change or \
+next-single-char-property-change")))
+
+(defmacro htmlize-lexlet (&rest letforms)
+ (declare (indent 1) (debug let))
+ (if (and (boundp 'lexical-binding)
+ lexical-binding)
+ `(let ,@letforms)
+ ;; cl extensions have a macro implementing lexical let
+ `(lexical-let ,@letforms)))
+
+;; Simple overlay emulation for XEmacs
+
+(cond
+ (htmlize-running-xemacs
+ (defalias 'htmlize-make-overlay 'make-extent)
+ (defalias 'htmlize-overlay-put 'set-extent-property)
+ (defalias 'htmlize-overlay-get 'extent-property)
+ (defun htmlize-overlays-in (beg end) (extent-list nil beg end))
+ (defalias 'htmlize-delete-overlay 'detach-extent))
+ (t
+ (defalias 'htmlize-make-overlay 'make-overlay)
+ (defalias 'htmlize-overlay-put 'overlay-put)
+ (defalias 'htmlize-overlay-get 'overlay-get)
+ (defalias 'htmlize-overlays-in 'overlays-in)
+ (defalias 'htmlize-delete-overlay 'delete-overlay)))
+
+
+;;; Transformation of buffer text: HTML escapes, untabification, etc.
+
+(defvar htmlize-basic-character-table
+ ;; Map characters in the 0-127 range to either one-character strings
+ ;; or to numeric entities.
+ (let ((table (make-vector 128 ?\0)))
+ ;; Map characters in the 32-126 range to themselves, others to
+ ;; &#CODE entities;
+ (dotimes (i 128)
+ (setf (aref table i) (if (and (>= i 32) (<= i 126))
+ (char-to-string i)
+ (format "&#%d;" i))))
+ ;; Set exceptions manually.
+ (setf
+ ;; Don't escape newline, carriage return, and TAB.
+ (aref table ?\n) "\n"
+ (aref table ?\r) "\r"
+ (aref table ?\t) "\t"
+ ;; Escape &, <, and >.
+ (aref table ?&) "&amp;"
+ (aref table ?<) "&lt;"
+ (aref table ?>) "&gt;"
+ ;; Not escaping '"' buys us a measurable speedup. It's only
+ ;; necessary to quote it for strings used in attribute values,
+ ;; which htmlize doesn't typically do.
+ ;(aref table ?\") "&quot;"
+ )
+ table))
+
+;; A cache of HTML representation of non-ASCII characters. Depending
+;; on the setting of `htmlize-convert-nonascii-to-entities', this maps
+;; non-ASCII characters to either "&#<code>;" or "<char>" (mapconcat's
+;; mapper must always return strings). It's only filled as characters
+;; are encountered, so that in a buffer with e.g. French text, it will
+;; only ever contain French accented characters as keys. It's cleared
+;; on each entry to htmlize-buffer-1 to allow modifications of
+;; `htmlize-convert-nonascii-to-entities' to take effect.
+(defvar htmlize-extended-character-cache (make-hash-table :test 'eq))
+
+(defun htmlize-protect-string (string)
+ "HTML-protect string, escaping HTML metacharacters and I18N chars."
+ ;; Only protecting strings that actually contain unsafe or non-ASCII
+ ;; chars removes a lot of unnecessary funcalls and consing.
+ (if (not (string-match "[^\r\n\t -%'-;=?-~]" string))
+ string
+ (mapconcat (lambda (char)
+ (cond
+ ((< char 128)
+ ;; ASCII: use htmlize-basic-character-table.
+ (aref htmlize-basic-character-table char))
+ ((gethash char htmlize-extended-character-cache)
+ ;; We've already seen this char; return the cached
+ ;; string.
+ )
+ ((not htmlize-convert-nonascii-to-entities)
+ ;; If conversion to entities is not desired, always
+ ;; copy the char literally.
+ (setf (gethash char htmlize-extended-character-cache)
+ (char-to-string char)))
+ ((< char 256)
+ ;; Latin 1: no need to call encode-char.
+ (setf (gethash char htmlize-extended-character-cache)
+ (format "&#%d;" char)))
+ ((encode-char char 'ucs)
+ ;; Must check if encode-char works for CHAR;
+ ;; it fails for Arabic and possibly elsewhere.
+ (setf (gethash char htmlize-extended-character-cache)
+ (format "&#%d;" (encode-char char 'ucs))))
+ (t
+ ;; encode-char doesn't work for this char. Copy it
+ ;; unchanged and hope for the best.
+ (setf (gethash char htmlize-extended-character-cache)
+ (char-to-string char)))))
+ string "")))
+
+(defun htmlize-attr-escape (string)
+ ;; Like htmlize-protect-string, but also escapes double-quoted
+ ;; strings to make it usable in attribute values.
+ (setq string (htmlize-protect-string string))
+ (if (not (string-match "\"" string))
+ string
+ (mapconcat (lambda (char)
+ (if (eql char ?\")
+ "&quot;"
+ (char-to-string char)))
+ string "")))
+
+(defsubst htmlize-concat (list)
+ (if (and (consp list) (null (cdr list)))
+ ;; Don't create a new string in the common case where the list only
+ ;; consists of one element.
+ (car list)
+ (apply #'concat list)))
+
+(defun htmlize-format-link (linkprops text)
+ (let ((uri (if (stringp linkprops)
+ linkprops
+ (plist-get linkprops :uri)))
+ (escaped-text (htmlize-protect-string text)))
+ (if uri
+ (format "<a href=\"%s\">%s</a>" (htmlize-attr-escape uri) escaped-text)
+ escaped-text)))
+
+(defun htmlize-escape-or-link (string)
+ ;; Escape STRING and/or add hyperlinks. STRING comes from a
+ ;; `display' property.
+ (let ((pos 0) (end (length string)) outlist)
+ (while (< pos end)
+ (let* ((link (get-char-property pos 'htmlize-link string))
+ (next-link-change (next-single-property-change
+ pos 'htmlize-link string end))
+ (chunk (substring string pos next-link-change)))
+ (push
+ (cond (link
+ (htmlize-format-link link chunk))
+ ((get-char-property 0 'htmlize-literal chunk)
+ chunk)
+ (t
+ (htmlize-protect-string chunk)))
+ outlist)
+ (setq pos next-link-change)))
+ (htmlize-concat (nreverse outlist))))
+
+(defun htmlize-display-prop-to-html (display text)
+ (let (desc)
+ (cond ((stringp display)
+ ;; Emacs ignores recursive display properties.
+ (htmlize-escape-or-link display))
+ ((not (eq (car-safe display) 'image))
+ (htmlize-protect-string text))
+ ((null (setq desc (funcall htmlize-transform-image
+ (cdr display) text)))
+ (htmlize-escape-or-link text))
+ ((stringp desc)
+ (htmlize-escape-or-link desc))
+ (t
+ (htmlize-generate-image desc text)))))
+
+(defun htmlize-string-to-html (string)
+ ;; Convert the string to HTML, including images attached as
+ ;; `display' property and links as `htmlize-link' property. In a
+ ;; string without images or links, this is equivalent to
+ ;; `htmlize-protect-string'.
+ (let ((pos 0) (end (length string)) outlist)
+ (while (< pos end)
+ (let* ((display (get-char-property pos 'display string))
+ (next-display-change (next-single-property-change
+ pos 'display string end))
+ (chunk (substring string pos next-display-change)))
+ (push
+ (if display
+ (htmlize-display-prop-to-html display chunk)
+ (htmlize-escape-or-link chunk))
+ outlist)
+ (setq pos next-display-change)))
+ (htmlize-concat (nreverse outlist))))
+
+(defun htmlize-default-transform-image (imgprops _text)
+ "Default transformation of image descriptor to something usable in HTML.
+
+If `htmlize-use-images' is nil, the function always returns nil, meaning
+use original text. Otherwise, it tries to find the image for images that
+specify a file name. If `htmlize-force-inline-images' is non-nil, it also
+converts the :file attribute to :data and returns the modified property
+list."
+ (when htmlize-use-images
+ (when (plist-get imgprops :file)
+ (let ((location (plist-get (cdr (find-image (list imgprops))) :file)))
+ (when location
+ (setq imgprops (plist-put (copy-list imgprops) :file location)))))
+ (if htmlize-force-inline-images
+ (let ((location (plist-get imgprops :file))
+ data)
+ (when location
+ (with-temp-buffer
+ (condition-case nil
+ (progn
+ (insert-file-contents-literally location)
+ (setq data (buffer-string)))
+ (error nil))))
+ ;; if successful, return the new plist, otherwise return
+ ;; nil, which will use the original text
+ (and data
+ (plist-put (plist-put imgprops :file nil)
+ :data data)))
+ imgprops)))
+
+(defun htmlize-alt-text (_imgprops origtext)
+ (and (/= (length origtext) 0)
+ (<= (length origtext) htmlize-max-alt-text)
+ (not (string-match "[\0-\x1f]" origtext))
+ origtext))
+
+(defun htmlize-generate-image (imgprops origtext)
+ (let* ((alt-text (htmlize-alt-text imgprops origtext))
+ (alt-attr (if alt-text
+ (format " alt=\"%s\"" (htmlize-attr-escape alt-text))
+ "")))
+ (cond ((plist-get imgprops :file)
+ ;; Try to find the image in image-load-path
+ (let* ((found-props (cdr (find-image (list imgprops))))
+ (file (or (plist-get found-props :file)
+ (plist-get imgprops :file))))
+ (format "<img src=\"%s\"%s />"
+ (htmlize-attr-escape (file-relative-name file))
+ alt-attr)))
+ ((plist-get imgprops :data)
+ (if (equalp (plist-get imgprops :type) 'svg)
+ (plist-get imgprops :data)
+ (format "<img src=\"data:image/%s;base64,%s\"%s />"
+ (or (plist-get imgprops :type) "")
+ (base64-encode-string (plist-get imgprops :data))
+ alt-attr))))))
+
+(defconst htmlize-ellipsis "...")
+(put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
+
+(defun htmlize-match-inv-spec (inv)
+ (member* inv buffer-invisibility-spec
+ :key (lambda (i)
+ (if (symbolp i) i (car i)))))
+
+(defun htmlize-decode-invisibility-spec (invisible)
+ ;; Return t, nil, or `ellipsis', depending on how invisible text should be inserted.
+
+ (if (not (listp buffer-invisibility-spec))
+ ;; If buffer-invisibility-spec is not a list, then all
+ ;; characters with non-nil `invisible' property are visible.
+ (not invisible)
+
+ ;; Otherwise, the value of a non-nil `invisible' property can be:
+ ;; 1. a symbol -- make the text invisible if it matches
+ ;; buffer-invisibility-spec.
+ ;; 2. a list of symbols -- make the text invisible if
+ ;; any symbol in the list matches
+ ;; buffer-invisibility-spec.
+ ;; If the match of buffer-invisibility-spec has a non-nil
+ ;; CDR, replace the invisible text with an ellipsis.
+ (let ((match (if (symbolp invisible)
+ (htmlize-match-inv-spec invisible)
+ (some #'htmlize-match-inv-spec invisible))))
+ (cond ((null match) t)
+ ((cdr-safe (car match)) 'ellipsis)
+ (t nil)))))
+
+(defun htmlize-add-before-after-strings (beg end text)
+ ;; Find overlays specifying before-string and after-string in [beg,
+ ;; pos). If any are found, splice them into TEXT and return the new
+ ;; text.
+ (let (additions)
+ (dolist (overlay (overlays-in beg end))
+ (let ((before (overlay-get overlay 'before-string))
+ (after (overlay-get overlay 'after-string)))
+ (when after
+ (push (cons (- (overlay-end overlay) beg)
+ after)
+ additions))
+ (when before
+ (push (cons (- (overlay-start overlay) beg)
+ before)
+ additions))))
+ (if additions
+ (let ((textlist nil)
+ (strpos 0))
+ (dolist (add (stable-sort additions #'< :key #'car))
+ (let ((addpos (car add))
+ (addtext (cdr add)))
+ (push (substring text strpos addpos) textlist)
+ (push addtext textlist)
+ (setq strpos addpos)))
+ (push (substring text strpos) textlist)
+ (apply #'concat (nreverse textlist)))
+ text)))
+
+(defun htmlize-copy-prop (prop beg end string)
+ ;; Copy the specified property from the specified region of the
+ ;; buffer to the target string. We cannot rely on Emacs to copy the
+ ;; property because we want to handle properties coming from both
+ ;; text properties and overlays.
+ (let ((pos beg))
+ (while (< pos end)
+ (let ((value (get-char-property pos prop))
+ (next-change (htmlize-next-change pos prop end)))
+ (when value
+ (put-text-property (- pos beg) (- next-change beg)
+ prop value string))
+ (setq pos next-change)))))
+
+(defun htmlize-get-text-with-display (beg end)
+ ;; Like buffer-substring-no-properties, except it copies the
+ ;; `display' property from the buffer, if found.
+ (let ((text (buffer-substring-no-properties beg end)))
+ (htmlize-copy-prop 'display beg end text)
+ (htmlize-copy-prop 'htmlize-link beg end text)
+ (unless htmlize-running-xemacs
+ (setq text (htmlize-add-before-after-strings beg end text)))
+ text))
+
+(defun htmlize-buffer-substring-no-invisible (beg end)
+ ;; Like buffer-substring-no-properties, but don't copy invisible
+ ;; parts of the region. Where buffer-substring-no-properties
+ ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
+ (let ((pos beg)
+ visible-list invisible show last-show next-change)
+ ;; Iterate over the changes in the `invisible' property and filter
+ ;; out the portions where it's non-nil, i.e. where the text is
+ ;; invisible.
+ (while (< pos end)
+ (setq invisible (get-char-property pos 'invisible)
+ next-change (htmlize-next-change pos 'invisible end)
+ show (htmlize-decode-invisibility-spec invisible))
+ (cond ((eq show t)
+ (push (htmlize-get-text-with-display pos next-change)
+ visible-list))
+ ((and (eq show 'ellipsis)
+ (not (eq last-show 'ellipsis))
+ ;; Conflate successive ellipses.
+ (push htmlize-ellipsis visible-list))))
+ (setq pos next-change last-show show))
+ (htmlize-concat (nreverse visible-list))))
+
+(defun htmlize-trim-ellipsis (text)
+ ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
+ ;; starts with it. It checks for the special property of the
+ ;; ellipsis so it doesn't work on ordinary text that begins with
+ ;; "...".
+ (if (get-text-property 0 'htmlize-ellipsis text)
+ (substring text (length htmlize-ellipsis))
+ text))
+
+(defconst htmlize-tab-spaces
+ ;; A table of strings with spaces. (aref htmlize-tab-spaces 5) is
+ ;; like (make-string 5 ?\ ), except it doesn't cons.
+ (let ((v (make-vector 32 nil)))
+ (dotimes (i (length v))
+ (setf (aref v i) (make-string i ?\ )))
+ v))
+
+(defun htmlize-untabify (text start-column)
+ "Untabify TEXT, assuming it starts at START-COLUMN."
+ (let ((column start-column)
+ (last-match 0)
+ (chunk-start 0)
+ chunks match-pos tab-size)
+ (while (string-match "[\t\n]" text last-match)
+ (setq match-pos (match-beginning 0))
+ (cond ((eq (aref text match-pos) ?\t)
+ ;; Encountered a tab: create a chunk of text followed by
+ ;; the expanded tab.
+ (push (substring text chunk-start match-pos) chunks)
+ ;; Increase COLUMN by the length of the text we've
+ ;; skipped since last tab or newline. (Encountering
+ ;; newline resets it.)
+ (incf column (- match-pos last-match))
+ ;; Calculate tab size based on tab-width and COLUMN.
+ (setq tab-size (- tab-width (% column tab-width)))
+ ;; Expand the tab, carefully recreating the `display'
+ ;; property if one was on the TAB.
+ (let ((display (get-text-property match-pos 'display text))
+ (expanded-tab (aref htmlize-tab-spaces tab-size)))
+ (when display
+ (put-text-property 0 tab-size 'display display expanded-tab))
+ (push expanded-tab chunks))
+ (incf column tab-size)
+ (setq chunk-start (1+ match-pos)))
+ (t
+ ;; Reset COLUMN at beginning of line.
+ (setq column 0)))
+ (setq last-match (1+ match-pos)))
+ ;; If no chunks have been allocated, it means there have been no
+ ;; tabs to expand. Return TEXT unmodified.
+ (if (null chunks)
+ text
+ (when (< chunk-start (length text))
+ ;; Push the remaining chunk.
+ (push (substring text chunk-start) chunks))
+ ;; Generate the output from the available chunks.
+ (htmlize-concat (nreverse chunks)))))
+
+(defun htmlize-extract-text (beg end trailing-ellipsis)
+ ;; Extract buffer text, sans the invisible parts. Then
+ ;; untabify it and escape the HTML metacharacters.
+ (let ((text (htmlize-buffer-substring-no-invisible beg end)))
+ (when trailing-ellipsis
+ (setq text (htmlize-trim-ellipsis text)))
+ ;; If TEXT ends up empty, don't change trailing-ellipsis.
+ (when (> (length text) 0)
+ (setq trailing-ellipsis
+ (get-text-property (1- (length text))
+ 'htmlize-ellipsis text)))
+ (setq text (htmlize-untabify text (current-column)))
+ (setq text (htmlize-string-to-html text))
+ (values text trailing-ellipsis)))
+
+(defun htmlize-despam-address (string)
+ "Replace every occurrence of '@' in STRING with %40.
+This is used to protect mailto links without modifying their meaning."
+ ;; Suggested by Ville Skytta.
+ (while (string-match "@" string)
+ (setq string (replace-match "%40" nil t string)))
+ string)
+
+(defun htmlize-make-tmp-overlay (beg end props)
+ (let ((overlay (htmlize-make-overlay beg end)))
+ (htmlize-overlay-put overlay 'htmlize-tmp-overlay t)
+ (while props
+ (htmlize-overlay-put overlay (pop props) (pop props)))
+ overlay))
+
+(defun htmlize-delete-tmp-overlays ()
+ (dolist (overlay (htmlize-overlays-in (point-min) (point-max)))
+ (when (htmlize-overlay-get overlay 'htmlize-tmp-overlay)
+ (htmlize-delete-overlay overlay))))
+
+(defun htmlize-make-link-overlay (beg end uri)
+ (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri))))
+
+(defun htmlize-create-auto-links ()
+ "Add `htmlize-link' property to all mailto links in the buffer."
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward
+ "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>"
+ nil t)
+ (let* ((address (match-string 3))
+ (beg (match-beginning 0)) (end (match-end 0))
+ (uri (concat "mailto:" (htmlize-despam-address address))))
+ (htmlize-make-link-overlay beg end uri)))
+ (goto-char (point-min))
+ (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;>]+\\)\\)>"
+ nil t)
+ (htmlize-make-link-overlay
+ (match-beginning 0) (match-end 0) (match-string 3)))))
+
+;; Tests for htmlize-create-auto-links:
+
+;; <mailto:hniksic@xemacs.org>
+;; <http://fly.srk.fer.hr>
+;; <URL:http://www.xemacs.org>
+;; <http://www.mail-archive.com/bbdb-info@xemacs.org/>
+;; <hniksic@xemacs.org>
+;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org>
+
+(defun htmlize-shadow-form-feeds ()
+ (let ((s "\n<hr />"))
+ (put-text-property 0 (length s) 'htmlize-literal t s)
+ (let ((disp `(display ,s)))
+ (while (re-search-forward "\n\^L" nil t)
+ (htmlize-make-tmp-overlay (match-beginning 0) (match-end 0) disp)))))
+
+(defun htmlize-defang-local-variables ()
+ ;; Juri Linkov reports that an HTML-ized "Local variables" can lead
+ ;; visiting the HTML to fail with "Local variables list is not
+ ;; properly terminated". He suggested changing the phrase to
+ ;; syntactically equivalent HTML that Emacs doesn't recognize.
+ (goto-char (point-min))
+ (while (search-forward "Local Variables:" nil t)
+ (replace-match "Local Variables&#58;" nil t)))
+
+
+;;; Color handling.
+
+(defvar htmlize-x-library-search-path
+ `(,data-directory
+ "/etc/X11/rgb.txt"
+ "/usr/share/X11/rgb.txt"
+ ;; the remainder of this list really belongs in a museum
+ "/usr/X11R6/lib/X11/"
+ "/usr/X11R5/lib/X11/"
+ "/usr/lib/X11R6/X11/"
+ "/usr/lib/X11R5/X11/"
+ "/usr/local/X11R6/lib/X11/"
+ "/usr/local/X11R5/lib/X11/"
+ "/usr/local/lib/X11R6/X11/"
+ "/usr/local/lib/X11R5/X11/"
+ "/usr/X11/lib/X11/"
+ "/usr/lib/X11/"
+ "/usr/local/lib/X11/"
+ "/usr/X386/lib/X11/"
+ "/usr/x386/lib/X11/"
+ "/usr/XFree86/lib/X11/"
+ "/usr/unsupported/lib/X11/"
+ "/usr/athena/lib/X11/"
+ "/usr/local/x11r5/lib/X11/"
+ "/usr/lpp/Xamples/lib/X11/"
+ "/usr/openwin/lib/X11/"
+ "/usr/openwin/share/lib/X11/"))
+
+(defun htmlize-get-color-rgb-hash (&optional rgb-file)
+ "Return a hash table mapping X color names to RGB values.
+The keys in the hash table are X11 color names, and the values are the
+#rrggbb RGB specifications, extracted from `rgb.txt'.
+
+If RGB-FILE is nil, the function will try hard to find a suitable file
+in the system directories.
+
+If no rgb.txt file is found, return nil."
+ (let ((rgb-file (or rgb-file (locate-file
+ "rgb.txt"
+ htmlize-x-library-search-path)))
+ (hash nil))
+ (when rgb-file
+ (with-temp-buffer
+ (insert-file-contents rgb-file)
+ (setq hash (make-hash-table :test 'equal))
+ (while (not (eobp))
+ (cond ((looking-at "^\\s-*\\([!#]\\|$\\)")
+ ;; Skip comments and empty lines.
+ )
+ ((looking-at
+ "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)")
+ (setf (gethash (downcase (match-string 4)) hash)
+ (format "#%02x%02x%02x"
+ (string-to-number (match-string 1))
+ (string-to-number (match-string 2))
+ (string-to-number (match-string 3)))))
+ (t
+ (error
+ "Unrecognized line in %s: %s"
+ rgb-file
+ (buffer-substring (point) (progn (end-of-line) (point))))))
+ (forward-line 1))))
+ hash))
+
+;; Compile the RGB map when loaded. On systems where rgb.txt is
+;; missing, the value of the variable will be nil, and rgb.txt will
+;; not be used.
+(defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
+
+;;; Face handling.
+
+(defun htmlize-face-specifies-property (face prop)
+ ;; Return t if face specifies PROP, as opposed to it being inherited
+ ;; from the default face. The problem with e.g.
+ ;; `face-foreground-instance' is that it returns an instance for
+ ;; EVERY face because every face inherits from the default face.
+ ;; However, we'd like htmlize-face-{fore,back}ground to return nil
+ ;; when called with a face that doesn't specify its own foreground
+ ;; or background.
+ (or (eq face 'default)
+ (assq 'global (specifier-spec-list (face-property face prop)))))
+
+(defun htmlize-face-color-internal (face fg)
+ ;; Used only under GNU Emacs. Return the color of FACE, but don't
+ ;; return "unspecified-fg" or "unspecified-bg". If the face is
+ ;; `default' and the color is unspecified, look up the color in
+ ;; frame parameters.
+ (let* ((function (if fg #'face-foreground #'face-background))
+ color)
+ (setq color (funcall function face nil t))
+ (when (and (eq face 'default) (null color))
+ (setq color (cdr (assq (if fg 'foreground-color 'background-color)
+ (frame-parameters)))))
+ (when (or (eq color 'unspecified)
+ (equal color "unspecified-fg")
+ (equal color "unspecified-bg"))
+ (setq color nil))
+ (when (and (eq face 'default)
+ (null color))
+ ;; Assuming black on white doesn't seem right, but I can't think
+ ;; of anything better to do.
+ (setq color (if fg "black" "white")))
+ color))
+
+(defun htmlize-face-foreground (face)
+ ;; Return the name of the foreground color of FACE. If FACE does
+ ;; not specify a foreground color, return nil.
+ (cond (htmlize-running-xemacs
+ ;; XEmacs.
+ (and (htmlize-face-specifies-property face 'foreground)
+ (color-instance-name (face-foreground-instance face))))
+ (t
+ ;; GNU Emacs.
+ (htmlize-face-color-internal face t))))
+
+(defun htmlize-face-background (face)
+ ;; Return the name of the background color of FACE. If FACE does
+ ;; not specify a background color, return nil.
+ (cond (htmlize-running-xemacs
+ ;; XEmacs.
+ (and (htmlize-face-specifies-property face 'background)
+ (color-instance-name (face-background-instance face))))
+ (t
+ ;; GNU Emacs.
+ (htmlize-face-color-internal face nil))))
+
+;; Convert COLOR to the #RRGGBB string. If COLOR is already in that
+;; format, it's left unchanged.
+
+(defun htmlize-color-to-rgb (color)
+ (let ((rgb-string nil))
+ (cond ((null color)
+ ;; Ignore nil COLOR because it means that the face is not
+ ;; specifying any color. Hence (htmlize-color-to-rgb nil)
+ ;; returns nil.
+ )
+ ((string-match "\\`#" color)
+ ;; The color is already in #rrggbb format.
+ (setq rgb-string color))
+ ((and htmlize-use-rgb-txt
+ htmlize-color-rgb-hash)
+ ;; Use of rgb.txt is requested, and it's available on the
+ ;; system. Use it.
+ (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash)))
+ (t
+ ;; We're getting the RGB components from Emacs.
+ (let ((rgb
+ (if (fboundp 'color-instance-rgb-components)
+ (mapcar (lambda (arg)
+ (/ arg 256))
+ (color-instance-rgb-components
+ (make-color-instance color)))
+ (mapcar (lambda (arg)
+ (/ arg 256))
+ (color-values color)))))
+ (when rgb
+ (setq rgb-string (apply #'format "#%02x%02x%02x" rgb))))))
+ ;; If RGB-STRING is still nil, it means the color cannot be found,
+ ;; for whatever reason. In that case just punt and return COLOR.
+ ;; Most browsers support a decent set of color names anyway.
+ (or rgb-string color)))
+
+;; We store the face properties we care about into an
+;; `htmlize-fstruct' type. That way we only have to analyze face
+;; properties, which can be time consuming, once per each face. The
+;; mapping between Emacs faces and htmlize-fstructs is established by
+;; htmlize-make-face-map. The name "fstruct" refers to variables of
+;; type `htmlize-fstruct', while the term "face" is reserved for Emacs
+;; faces.
+
+(defstruct htmlize-fstruct
+ foreground ; foreground color, #rrggbb
+ background ; background color, #rrggbb
+ size ; size
+ boldp ; whether face is bold
+ italicp ; whether face is italic
+ underlinep ; whether face is underlined
+ overlinep ; whether face is overlined
+ strikep ; whether face is struck through
+ css-name ; CSS name of face
+ )
+
+(defun htmlize-face-emacs21-attr (fstruct attr value)
+ ;; For ATTR and VALUE, set the equivalent value in FSTRUCT.
+ (case attr
+ (:foreground
+ (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value)))
+ (:background
+ (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value)))
+ (:height
+ (setf (htmlize-fstruct-size fstruct) value))
+ (:weight
+ (when (string-match (symbol-name value) "bold")
+ (setf (htmlize-fstruct-boldp fstruct) t)))
+ (:slant
+ (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic)
+ (eq value 'oblique))))
+ (:bold
+ (setf (htmlize-fstruct-boldp fstruct) value))
+ (:italic
+ (setf (htmlize-fstruct-italicp fstruct) value))
+ (:underline
+ (setf (htmlize-fstruct-underlinep fstruct) value))
+ (:overline
+ (setf (htmlize-fstruct-overlinep fstruct) value))
+ (:strike-through
+ (setf (htmlize-fstruct-strikep fstruct) value))))
+
+(defun htmlize-face-size (face)
+ ;; The size (height) of FACE, taking inheritance into account.
+ ;; Only works in Emacs 21 and later.
+ (let ((size-list
+ (loop
+ for f = face then (face-attribute f :inherit)
+ until (or (not f) (eq f 'unspecified))
+ for h = (face-attribute f :height)
+ collect (if (eq h 'unspecified) nil h))))
+ (reduce 'htmlize-merge-size (cons nil size-list))))
+
+(defun htmlize-face-css-name (face)
+ ;; Generate the css-name property for the given face. Emacs places
+ ;; no restrictions on the names of symbols that represent faces --
+ ;; any characters may be in the name, even control chars. We try
+ ;; hard to beat the face name into shape, both esthetically and
+ ;; according to CSS1 specs.
+ (let ((name (downcase (symbol-name face))))
+ (when (string-match "\\`font-lock-" name)
+ ;; font-lock-FOO-face -> FOO.
+ (setq name (replace-match "" t t name)))
+ (when (string-match "-face\\'" name)
+ ;; Drop the redundant "-face" suffix.
+ (setq name (replace-match "" t t name)))
+ (while (string-match "[^-a-zA-Z0-9]" name)
+ ;; Drop the non-alphanumerics.
+ (setq name (replace-match "X" t t name)))
+ (when (string-match "\\`[-0-9]" name)
+ ;; CSS identifiers may not start with a digit.
+ (setq name (concat "X" name)))
+ ;; After these transformations, the face could come out empty.
+ (when (equal name "")
+ (setq name "face"))
+ ;; Apply the prefix.
+ (concat htmlize-css-name-prefix name)))
+
+(defun htmlize-face-to-fstruct (face)
+ "Convert Emacs face FACE to fstruct."
+ (let ((fstruct (make-htmlize-fstruct
+ :foreground (htmlize-color-to-rgb
+ (htmlize-face-foreground face))
+ :background (htmlize-color-to-rgb
+ (htmlize-face-background face)))))
+ (if htmlize-running-xemacs
+ ;; XEmacs doesn't provide a way to detect whether a face is
+ ;; bold or italic, so we need to examine the font instance.
+ (let* ((font-instance (face-font-instance face))
+ (props (font-instance-properties font-instance)))
+ (when (equalp (cdr (assq 'WEIGHT_NAME props)) "bold")
+ (setf (htmlize-fstruct-boldp fstruct) t))
+ (when (or (equalp (cdr (assq 'SLANT props)) "i")
+ (equalp (cdr (assq 'SLANT props)) "o"))
+ (setf (htmlize-fstruct-italicp fstruct) t))
+ (setf (htmlize-fstruct-strikep fstruct)
+ (face-strikethru-p face))
+ (setf (htmlize-fstruct-underlinep fstruct)
+ (face-underline-p face)))
+ ;; GNU Emacs
+ (dolist (attr '(:weight :slant :underline :overline :strike-through))
+ (let ((value (face-attribute face attr nil t)))
+ (when (and value (not (eq value 'unspecified)))
+ (htmlize-face-emacs21-attr fstruct attr value))))
+ (let ((size (htmlize-face-size face)))
+ (unless (eql size 1.0) ; ignore non-spec
+ (setf (htmlize-fstruct-size fstruct) size))))
+ (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))
+ fstruct))
+
+(defmacro htmlize-copy-attr-if-set (attr-list dest source)
+ ;; Generate code with the following pattern:
+ ;; (progn
+ ;; (when (htmlize-fstruct-ATTR source)
+ ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source)))
+ ;; ...)
+ ;; for the given list of boolean attributes.
+ (cons 'progn
+ (loop for attr in attr-list
+ for attr-sym = (intern (format "htmlize-fstruct-%s" attr))
+ collect `(when (,attr-sym ,source)
+ (setf (,attr-sym ,dest) (,attr-sym ,source))))))
+
+(defun htmlize-merge-size (merged next)
+ ;; Calculate the size of the merge of MERGED and NEXT.
+ (cond ((null merged) next)
+ ((integerp next) next)
+ ((null next) merged)
+ ((floatp merged) (* merged next))
+ ((integerp merged) (round (* merged next)))))
+
+(defun htmlize-merge-two-faces (merged next)
+ (htmlize-copy-attr-if-set
+ (foreground background boldp italicp underlinep overlinep strikep)
+ merged next)
+ (setf (htmlize-fstruct-size merged)
+ (htmlize-merge-size (htmlize-fstruct-size merged)
+ (htmlize-fstruct-size next)))
+ merged)
+
+(defun htmlize-merge-faces (fstruct-list)
+ (cond ((null fstruct-list)
+ ;; Nothing to do, return a dummy face.
+ (make-htmlize-fstruct))
+ ((null (cdr fstruct-list))
+ ;; Optimize for the common case of a single face, simply
+ ;; return it.
+ (car fstruct-list))
+ (t
+ (reduce #'htmlize-merge-two-faces
+ (cons (make-htmlize-fstruct) fstruct-list)))))
+
+;; GNU Emacs 20+ supports attribute lists in `face' properties. For
+;; example, you can use `(:foreground "red" :weight bold)' as an
+;; overlay's "face", or you can even use a list of such lists, etc.
+;; We call those "attrlists".
+;;
+;; htmlize supports attrlist by converting them to fstructs, the same
+;; as with regular faces.
+
+(defun htmlize-attrlist-to-fstruct (attrlist)
+ ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input.
+ (let ((fstruct (make-htmlize-fstruct)))
+ (cond ((eq (car attrlist) 'foreground-color)
+ ;; ATTRLIST is (foreground-color . COLOR)
+ (setf (htmlize-fstruct-foreground fstruct)
+ (htmlize-color-to-rgb (cdr attrlist))))
+ ((eq (car attrlist) 'background-color)
+ ;; ATTRLIST is (background-color . COLOR)
+ (setf (htmlize-fstruct-background fstruct)
+ (htmlize-color-to-rgb (cdr attrlist))))
+ (t
+ ;; ATTRLIST is a plist.
+ (while attrlist
+ (let ((attr (pop attrlist))
+ (value (pop attrlist)))
+ (when (and value (not (eq value 'unspecified)))
+ (htmlize-face-emacs21-attr fstruct attr value))))))
+ (setf (htmlize-fstruct-css-name fstruct) "ATTRLIST")
+ fstruct))
+
+(defun htmlize-decode-face-prop (prop)
+ "Turn face property PROP into a list of face-like objects."
+ ;; PROP can be a symbol naming a face, a string naming such a
+ ;; symbol, a cons (foreground-color . COLOR) or (background-color
+ ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list
+ ;; of any of those.
+ ;;
+ ;; (htmlize-decode-face-prop 'face) -> (face)
+ ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2)
+ ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val"))
+ ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red")))
+ ;; -> ((:attr "val") face (foreground-color "red"))
+ ;;
+ ;; Unrecognized atoms or non-face symbols/strings are silently
+ ;; stripped away.
+ (cond ((null prop)
+ nil)
+ ((symbolp prop)
+ (and (facep prop)
+ (list prop)))
+ ((stringp prop)
+ (and (facep (intern-soft prop))
+ (list prop)))
+ ((atom prop)
+ nil)
+ ((and (symbolp (car prop))
+ (eq ?: (aref (symbol-name (car prop)) 0)))
+ (list prop))
+ ((or (eq (car prop) 'foreground-color)
+ (eq (car prop) 'background-color))
+ (list prop))
+ (t
+ (apply #'nconc (mapcar #'htmlize-decode-face-prop prop)))))
+
+(defun htmlize-make-face-map (faces)
+ ;; Return a hash table mapping Emacs faces to htmlize's fstructs.
+ ;; The keys are either face symbols or attrlists, so the test
+ ;; function must be `equal'.
+ (let ((face-map (make-hash-table :test 'equal))
+ css-names)
+ (dolist (face faces)
+ (unless (gethash face face-map)
+ ;; Haven't seen FACE yet; convert it to an fstruct and cache
+ ;; it.
+ (let ((fstruct (if (symbolp face)
+ (htmlize-face-to-fstruct face)
+ (htmlize-attrlist-to-fstruct face))))
+ (setf (gethash face face-map) fstruct)
+ (let* ((css-name (htmlize-fstruct-css-name fstruct))
+ (new-name css-name)
+ (i 0))
+ ;; Uniquify the face's css-name by using NAME-1, NAME-2,
+ ;; etc.
+ (while (member new-name css-names)
+ (setq new-name (format "%s-%s" css-name (incf i))))
+ (unless (equal new-name css-name)
+ (setf (htmlize-fstruct-css-name fstruct) new-name))
+ (push new-name css-names)))))
+ face-map))
+
+(defun htmlize-unstringify-face (face)
+ "If FACE is a string, return it interned, otherwise return it unchanged."
+ (if (stringp face)
+ (intern face)
+ face))
+
+(defun htmlize-faces-in-buffer ()
+ "Return a list of faces used in the current buffer.
+Under XEmacs, this returns the set of faces specified by the extents
+with the `face' property. (This covers text properties as well.) Under
+GNU Emacs, it returns the set of faces specified by the `face' text
+property and by buffer overlays that specify `face'."
+ (let (faces)
+ ;; Testing for (fboundp 'map-extents) doesn't work because W3
+ ;; defines `map-extents' under FSF.
+ (if htmlize-running-xemacs
+ (let (face-prop)
+ (map-extents (lambda (extent ignored)
+ (setq face-prop (extent-face extent)
+ ;; FACE-PROP can be a face or a list of
+ ;; faces.
+ faces (if (listp face-prop)
+ (union face-prop faces)
+ (adjoin face-prop faces)))
+ nil)
+ nil
+ ;; Specify endpoints explicitly to respect
+ ;; narrowing.
+ (point-min) (point-max) nil nil 'face))
+ ;; FSF Emacs code.
+ ;; Faces used by text properties.
+ (let ((pos (point-min)) face-prop next)
+ (while (< pos (point-max))
+ (setq face-prop (get-text-property pos 'face)
+ next (or (next-single-property-change pos 'face) (point-max)))
+ (setq faces (nunion (htmlize-decode-face-prop face-prop)
+ faces :test 'equal))
+ (setq pos next)))
+ ;; Faces used by overlays.
+ (dolist (overlay (overlays-in (point-min) (point-max)))
+ (let ((face-prop (overlay-get overlay 'face)))
+ (setq faces (nunion (htmlize-decode-face-prop face-prop)
+ faces :test 'equal)))))
+ faces))
+
+;; htmlize-faces-at-point returns the faces in use at point. The
+;; faces are sorted by increasing priority, i.e. the last face takes
+;; precedence.
+;;
+;; Under XEmacs, this returns all the faces in all the extents at
+;; point. Under GNU Emacs, this returns all the faces in the `face'
+;; property and all the faces in the overlays at point.
+
+(cond (htmlize-running-xemacs
+ (defun htmlize-faces-at-point ()
+ (let (extent extent-list face-list face-prop)
+ (while (setq extent (extent-at (point) nil 'face extent))
+ (push extent extent-list))
+ ;; extent-list is in reverse display order, meaning that
+ ;; smallest ones come last. That is the order we want,
+ ;; except it can be overridden by the `priority' property.
+ (setq extent-list (stable-sort extent-list #'<
+ :key #'extent-priority))
+ (dolist (extent extent-list)
+ (setq face-prop (extent-face extent))
+ ;; extent's face-list is in reverse order from what we
+ ;; want, but the `nreverse' below will take care of it.
+ (setq face-list (if (listp face-prop)
+ (append face-prop face-list)
+ (cons face-prop face-list))))
+ (nreverse face-list))))
+ (t
+ (defun htmlize-faces-at-point ()
+ (let (all-faces)
+ ;; Faces from text properties.
+ (let ((face-prop (get-text-property (point) 'face)))
+ (setq all-faces (htmlize-decode-face-prop face-prop)))
+ ;; Faces from overlays.
+ (let ((overlays
+ ;; Collect overlays at point that specify `face'.
+ (delete-if-not (lambda (o)
+ (overlay-get o 'face))
+ (overlays-at (point))))
+ list face-prop)
+ ;; Sort the overlays so the smaller (more specific) ones
+ ;; come later. The number of overlays at each one
+ ;; position should be very small, so the sort shouldn't
+ ;; slow things down.
+ (setq overlays (sort* overlays
+ ;; Sort by ascending...
+ #'<
+ ;; ...overlay size.
+ :key (lambda (o)
+ (- (overlay-end o)
+ (overlay-start o)))))
+ ;; Overlay priorities, if present, override the above
+ ;; established order. Larger overlay priority takes
+ ;; precedence and therefore comes later in the list.
+ (setq overlays (stable-sort
+ overlays
+ ;; Reorder (stably) by acending...
+ #'<
+ ;; ...overlay priority.
+ :key (lambda (o)
+ (or (overlay-get o 'priority) 0))))
+ (dolist (overlay overlays)
+ (setq face-prop (overlay-get overlay 'face)
+ list (nconc (htmlize-decode-face-prop face-prop) list)))
+ ;; Under "Merging Faces" the manual explicitly states
+ ;; that faces specified by overlays take precedence over
+ ;; faces specified by text properties.
+ (setq all-faces (nconc all-faces list)))
+ all-faces))))
+
+;; htmlize supports generating HTML in several flavors, some of which
+;; use CSS, and others the <font> element. We take an OO approach and
+;; define "methods" that indirect to the functions that depend on
+;; `htmlize-output-type'. The currently used methods are `doctype',
+;; `insert-head', `body-tag', and `text-markup'. Not all output types
+;; define all methods.
+;;
+;; Methods are called either with (htmlize-method METHOD ARGS...)
+;; special form, or by accessing the function with
+;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION).
+;; The latter form is useful in tight loops because `htmlize-method'
+;; conses.
+
+(defmacro htmlize-method (method &rest args)
+ ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of
+ ;; `htmlize-output-type' at run time.
+ `(funcall (htmlize-method-function ',method) ,@args))
+
+(defun htmlize-method-function (method)
+ ;; Return METHOD's function definition for the current output type.
+ ;; The returned object can be safely funcalled.
+ (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method))))
+ (indirect-function (if (fboundp sym)
+ sym
+ (let ((default (intern (concat "htmlize-default-"
+ (symbol-name method)))))
+ (if (fboundp default)
+ default
+ 'ignore))))))
+
+(defvar htmlize-memoization-table (make-hash-table :test 'equal))
+
+(defmacro htmlize-memoize (key generator)
+ "Return the value of GENERATOR, memoized as KEY.
+That means that GENERATOR will be evaluated and returned the first time
+it's called with the same value of KEY. All other times, the cached
+\(memoized) value will be returned."
+ (let ((value (gensym)))
+ `(let ((,value (gethash ,key htmlize-memoization-table)))
+ (unless ,value
+ (setq ,value ,generator)
+ (setf (gethash ,key htmlize-memoization-table) ,value))
+ ,value)))
+
+;;; Default methods.
+
+(defun htmlize-default-doctype ()
+ nil ; no doc-string
+ ;; Note that the `font' output is technically invalid under this DTD
+ ;; because the DTD doesn't allow embedding <font> in <pre>.
+ "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"
+ )
+
+(defun htmlize-default-body-tag (face-map)
+ nil ; no doc-string
+ face-map ; shut up the byte-compiler
+ "<body>")
+
+;;; CSS based output support.
+
+;; Internal function; not a method.
+(defun htmlize-css-specs (fstruct)
+ (let (result)
+ (when (htmlize-fstruct-foreground fstruct)
+ (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
+ result))
+ (when (htmlize-fstruct-background fstruct)
+ (push (format "background-color: %s;"
+ (htmlize-fstruct-background fstruct))
+ result))
+ (let ((size (htmlize-fstruct-size fstruct)))
+ (when (and size (not (eq htmlize-ignore-face-size t)))
+ (cond ((floatp size)
+ (push (format "font-size: %d%%;" (* 100 size)) result))
+ ((not (eq htmlize-ignore-face-size 'absolute))
+ (push (format "font-size: %spt;" (/ size 10.0)) result)))))
+ (when (htmlize-fstruct-boldp fstruct)
+ (push "font-weight: bold;" result))
+ (when (htmlize-fstruct-italicp fstruct)
+ (push "font-style: italic;" result))
+ (when (htmlize-fstruct-underlinep fstruct)
+ (push "text-decoration: underline;" result))
+ (when (htmlize-fstruct-overlinep fstruct)
+ (push "text-decoration: overline;" result))
+ (when (htmlize-fstruct-strikep fstruct)
+ (push "text-decoration: line-through;" result))
+ (nreverse result)))
+
+(defun htmlize-css-insert-head (buffer-faces face-map)
+ (insert " <style type=\"text/css\">\n <!--\n")
+ (insert " body {\n "
+ (mapconcat #'identity
+ (htmlize-css-specs (gethash 'default face-map))
+ "\n ")
+ "\n }\n")
+ (dolist (face (sort* (copy-list buffer-faces) #'string-lessp
+ :key (lambda (f)
+ (htmlize-fstruct-css-name (gethash f face-map)))))
+ (let* ((fstruct (gethash face face-map))
+ (cleaned-up-face-name
+ (let ((s
+ ;; Use `prin1-to-string' rather than `symbol-name'
+ ;; to get the face name because the "face" can also
+ ;; be an attrlist, which is not a symbol.
+ (prin1-to-string face)))
+ ;; If the name contains `--' or `*/', remove them.
+ (while (string-match "--" s)
+ (setq s (replace-match "-" t t s)))
+ (while (string-match "\\*/" s)
+ (setq s (replace-match "XX" t t s)))
+ s))
+ (specs (htmlize-css-specs fstruct)))
+ (insert " ." (htmlize-fstruct-css-name fstruct))
+ (if (null specs)
+ (insert " {")
+ (insert " {\n /* " cleaned-up-face-name " */\n "
+ (mapconcat #'identity specs "\n ")))
+ (insert "\n }\n")))
+ (insert htmlize-hyperlink-style
+ " -->\n </style>\n"))
+
+(defun htmlize-css-text-markup (fstruct-list buffer)
+ ;; Open the markup needed to insert text colored with FACES into
+ ;; BUFFER. Return the function that closes the markup.
+
+ ;; In CSS mode, this is easy: just nest the text in one <span
+ ;; class=...> tag for each face in FSTRUCT-LIST.
+ (dolist (fstruct fstruct-list)
+ (princ "<span class=\"" buffer)
+ (princ (htmlize-fstruct-css-name fstruct) buffer)
+ (princ "\">" buffer))
+ (htmlize-lexlet ((fstruct-list fstruct-list) (buffer buffer))
+ (lambda ()
+ (dolist (fstruct fstruct-list)
+ (ignore fstruct) ; shut up the byte-compiler
+ (princ "</span>" buffer)))))
+
+;; `inline-css' output support.
+
+(defun htmlize-inline-css-body-tag (face-map)
+ (format "<body style=\"%s\">"
+ (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
+ " ")))
+
+(defun htmlize-inline-css-text-markup (fstruct-list buffer)
+ (let* ((merged (htmlize-merge-faces fstruct-list))
+ (style (htmlize-memoize
+ merged
+ (let ((specs (htmlize-css-specs merged)))
+ (and specs
+ (mapconcat #'identity (htmlize-css-specs merged) " "))))))
+ (when style
+ (princ "<span style=\"" buffer)
+ (princ style buffer)
+ (princ "\">" buffer))
+ (htmlize-lexlet ((style style) (buffer buffer))
+ (lambda ()
+ (when style
+ (princ "</span>" buffer))))))
+
+;;; `font' tag based output support.
+
+(defun htmlize-font-body-tag (face-map)
+ (let ((fstruct (gethash 'default face-map)))
+ (format "<body text=\"%s\" bgcolor=\"%s\">"
+ (htmlize-fstruct-foreground fstruct)
+ (htmlize-fstruct-background fstruct))))
+
+(defun htmlize-font-text-markup (fstruct-list buffer)
+ ;; In `font' mode, we use the traditional HTML means of altering
+ ;; presentation: <font> tag for colors, <b> for bold, <u> for
+ ;; underline, and <strike> for strike-through.
+ (let* ((merged (htmlize-merge-faces fstruct-list))
+ (markup (htmlize-memoize
+ merged
+ (cons (concat
+ (and (htmlize-fstruct-foreground merged)
+ (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged)))
+ (and (htmlize-fstruct-boldp merged) "<b>")
+ (and (htmlize-fstruct-italicp merged) "<i>")
+ (and (htmlize-fstruct-underlinep merged) "<u>")
+ (and (htmlize-fstruct-strikep merged) "<strike>"))
+ (concat
+ (and (htmlize-fstruct-strikep merged) "</strike>")
+ (and (htmlize-fstruct-underlinep merged) "</u>")
+ (and (htmlize-fstruct-italicp merged) "</i>")
+ (and (htmlize-fstruct-boldp merged) "</b>")
+ (and (htmlize-fstruct-foreground merged) "</font>"))))))
+ (princ (car markup) buffer)
+ (htmlize-lexlet ((markup markup) (buffer buffer))
+ (lambda ()
+ (princ (cdr markup) buffer)))))
+
+(defun htmlize-buffer-1 ()
+ ;; Internal function; don't call it from outside this file. Htmlize
+ ;; current buffer, writing the resulting HTML to a new buffer, and
+ ;; return it. Unlike htmlize-buffer, this doesn't change current
+ ;; buffer or use switch-to-buffer.
+ (save-excursion
+ ;; Protect against the hook changing the current buffer.
+ (save-excursion
+ (run-hooks 'htmlize-before-hook))
+ ;; Convince font-lock support modes to fontify the entire buffer
+ ;; in advance.
+ (htmlize-ensure-fontified)
+ (clrhash htmlize-extended-character-cache)
+ (clrhash htmlize-memoization-table)
+ ;; It's important that the new buffer inherits default-directory
+ ;; from the current buffer.
+ (let ((htmlbuf (generate-new-buffer (if (buffer-file-name)
+ (htmlize-make-file-name
+ (file-name-nondirectory
+ (buffer-file-name)))
+ "*html*")))
+ (completed nil))
+ (unwind-protect
+ (let* ((buffer-faces (htmlize-faces-in-buffer))
+ (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
+ (places (gensym))
+ (title (if (buffer-file-name)
+ (file-name-nondirectory (buffer-file-name))
+ (buffer-name))))
+ (when htmlize-generate-hyperlinks
+ (htmlize-create-auto-links))
+ (when htmlize-replace-form-feeds
+ (htmlize-shadow-form-feeds))
+
+ ;; Initialize HTMLBUF and insert the HTML prolog.
+ (with-current-buffer htmlbuf
+ (buffer-disable-undo)
+ (insert (htmlize-method doctype) ?\n
+ (format "<!-- Created by htmlize-%s in %s mode. -->\n"
+ htmlize-version htmlize-output-type)
+ "<html>\n ")
+ (put places 'head-start (point-marker))
+ (insert "<head>\n"
+ " <title>" (htmlize-protect-string title) "</title>\n"
+ (if htmlize-html-charset
+ (format (concat " <meta http-equiv=\"Content-Type\" "
+ "content=\"text/html; charset=%s\">\n")
+ htmlize-html-charset)
+ "")
+ htmlize-head-tags)
+ (htmlize-method insert-head buffer-faces face-map)
+ (insert " </head>")
+ (put places 'head-end (point-marker))
+ (insert "\n ")
+ (put places 'body-start (point-marker))
+ (insert (htmlize-method body-tag face-map)
+ "\n ")
+ (put places 'content-start (point-marker))
+ (insert "<pre>\n"))
+ (let ((text-markup
+ ;; Get the inserter method, so we can funcall it inside
+ ;; the loop. Not calling `htmlize-method' in the loop
+ ;; body yields a measurable speed increase.
+ (htmlize-method-function 'text-markup))
+ ;; Declare variables used in loop body outside the loop
+ ;; because it's faster to establish `let' bindings only
+ ;; once.
+ next-change text face-list trailing-ellipsis
+ fstruct-list last-fstruct-list
+ (close-markup (lambda ())))
+ ;; This loop traverses and reads the source buffer, appending
+ ;; the resulting HTML to HTMLBUF. This method is fast
+ ;; because: 1) it doesn't require examining the text
+ ;; properties char by char (htmlize-next-face-change is used
+ ;; to move between runs with the same face), and 2) it doesn't
+ ;; require frequent buffer switches, which are slow because
+ ;; they rebind all buffer-local vars.
+ (goto-char (point-min))
+ (while (not (eobp))
+ (setq next-change (htmlize-next-face-change (point)))
+ ;; Get faces in use between (point) and NEXT-CHANGE, and
+ ;; convert them to fstructs.
+ (setq face-list (htmlize-faces-at-point)
+ fstruct-list (delq nil (mapcar (lambda (f)
+ (gethash f face-map))
+ face-list)))
+ (multiple-value-setq (text trailing-ellipsis)
+ (htmlize-extract-text (point) next-change trailing-ellipsis))
+ ;; Don't bother writing anything if there's no text (this
+ ;; happens in invisible regions).
+ (when (> (length text) 0)
+ ;; Open the new markup if necessary and insert the text.
+ (when (not (equalp fstruct-list last-fstruct-list))
+ (funcall close-markup)
+ (setq last-fstruct-list fstruct-list
+ close-markup (funcall text-markup fstruct-list htmlbuf)))
+ (princ text htmlbuf))
+ (goto-char next-change))
+
+ ;; We've gone through the buffer; close the markup from
+ ;; the last run, if any.
+ (funcall close-markup))
+
+ ;; Insert the epilog and post-process the buffer.
+ (with-current-buffer htmlbuf
+ (insert "</pre>")
+ (put places 'content-end (point-marker))
+ (insert "\n </body>")
+ (put places 'body-end (point-marker))
+ (insert "\n</html>\n")
+ (htmlize-defang-local-variables)
+ (goto-char (point-min))
+ (when htmlize-html-major-mode
+ ;; What sucks about this is that the minor modes, most notably
+ ;; font-lock-mode, won't be initialized. Oh well.
+ (funcall htmlize-html-major-mode))
+ (set (make-local-variable 'htmlize-buffer-places)
+ (symbol-plist places))
+ (run-hooks 'htmlize-after-hook)
+ (buffer-enable-undo))
+ (setq completed t)
+ htmlbuf)
+
+ (when (not completed)
+ (kill-buffer htmlbuf))
+ (htmlize-delete-tmp-overlays)))))
+
+;; Utility functions.
+
+(defmacro htmlize-with-fontify-message (&rest body)
+ ;; When forcing fontification of large buffers in
+ ;; htmlize-ensure-fontified, inform the user that he is waiting for
+ ;; font-lock, not for htmlize to finish.
+ `(progn
+ (if (> (buffer-size) 65536)
+ (message "Forcing fontification of %s..."
+ (buffer-name (current-buffer))))
+ ,@body
+ (if (> (buffer-size) 65536)
+ (message "Forcing fontification of %s...done"
+ (buffer-name (current-buffer))))))
+
+(defun htmlize-ensure-fontified ()
+ ;; If font-lock is being used, ensure that the "support" modes
+ ;; actually fontify the buffer. If font-lock is not in use, we
+ ;; don't care because, except in htmlize-file, we don't force
+ ;; font-lock on the user.
+ (when (and (boundp 'font-lock-mode)
+ font-lock-mode)
+ ;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
+ (cond
+ ((and (boundp 'jit-lock-mode)
+ (symbol-value 'jit-lock-mode))
+ (htmlize-with-fontify-message
+ (jit-lock-fontify-now (point-min) (point-max))))
+ ((and (boundp 'lazy-lock-mode)
+ (symbol-value 'lazy-lock-mode))
+ (htmlize-with-fontify-message
+ (lazy-lock-fontify-region (point-min) (point-max))))
+ ((and (boundp 'lazy-shot-mode)
+ (symbol-value 'lazy-shot-mode))
+ (htmlize-with-fontify-message
+ ;; lazy-shot is amazing in that it must *refontify* the region,
+ ;; even if the whole buffer has already been fontified. <sigh>
+ (lazy-shot-fontify-region (point-min) (point-max))))
+ ;; There's also fast-lock, but we don't need to handle specially,
+ ;; I think. fast-lock doesn't really defer fontification, it
+ ;; just saves it to an external cache so it's not done twice.
+ )))
+
+
+;;;###autoload
+(defun htmlize-buffer (&optional buffer)
+ "Convert BUFFER to HTML, preserving colors and decorations.
+
+The generated HTML is available in a new buffer, which is returned.
+When invoked interactively, the new buffer is selected in the current
+window. The title of the generated document will be set to the buffer's
+file name or, if that's not available, to the buffer's name.
+
+Note that htmlize doesn't fontify your buffers, it only uses the
+decorations that are already present. If you don't set up font-lock or
+something else to fontify your buffers, the resulting HTML will be
+plain. Likewise, if you don't like the choice of colors, fix the mode
+that created them, or simply alter the faces it uses."
+ (interactive)
+ (let ((htmlbuf (with-current-buffer (or buffer (current-buffer))
+ (htmlize-buffer-1))))
+ (when (interactive-p)
+ (switch-to-buffer htmlbuf))
+ htmlbuf))
+
+;;;###autoload
+(defun htmlize-region (beg end)
+ "Convert the region to HTML, preserving colors and decorations.
+See `htmlize-buffer' for details."
+ (interactive "r")
+ ;; Don't let zmacs region highlighting end up in HTML.
+ (when (fboundp 'zmacs-deactivate-region)
+ (zmacs-deactivate-region))
+ (let ((htmlbuf (save-restriction
+ (narrow-to-region beg end)
+ (htmlize-buffer-1))))
+ (when (interactive-p)
+ (switch-to-buffer htmlbuf))
+ htmlbuf))
+
+(defun htmlize-region-for-paste (beg end)
+ "Htmlize the region and return just the HTML as a string.
+This forces the `inline-css' style and only returns the HTML body,
+but without the BODY tag. This should make it useful for inserting
+the text to another HTML buffer."
+ (let* ((htmlize-output-type 'inline-css)
+ (htmlbuf (htmlize-region beg end)))
+ (unwind-protect
+ (with-current-buffer htmlbuf
+ (buffer-substring (plist-get htmlize-buffer-places 'content-start)
+ (plist-get htmlize-buffer-places 'content-end)))
+ (kill-buffer htmlbuf))))
+
+(defun htmlize-make-file-name (file)
+ "Make an HTML file name from FILE.
+
+In its default implementation, this simply appends `.html' to FILE.
+This function is called by htmlize to create the buffer file name, and
+by `htmlize-file' to create the target file name.
+
+More elaborate transformations are conceivable, such as changing FILE's
+extension to `.html' (\"file.c\" -> \"file.html\"). If you want them,
+overload this function to do it and htmlize will comply."
+ (concat file ".html"))
+
+;; Older implementation of htmlize-make-file-name that changes FILE's
+;; extension to ".html".
+;(defun htmlize-make-file-name (file)
+; (let ((extension (file-name-extension file))
+; (sans-extension (file-name-sans-extension file)))
+; (if (or (equal extension "html")
+; (equal extension "htm")
+; (equal sans-extension ""))
+; (concat file ".html")
+; (concat sans-extension ".html"))))
+
+;;;###autoload
+(defun htmlize-file (file &optional target)
+ "Load FILE, fontify it, convert it to HTML, and save the result.
+
+Contents of FILE are inserted into a temporary buffer, whose major mode
+is set with `normal-mode' as appropriate for the file type. The buffer
+is subsequently fontified with `font-lock' and converted to HTML. Note
+that, unlike `htmlize-buffer', this function explicitly turns on
+font-lock. If a form of highlighting other than font-lock is desired,
+please use `htmlize-buffer' directly on buffers so highlighted.
+
+Buffers currently visiting FILE are unaffected by this function. The
+function does not change current buffer or move the point.
+
+If TARGET is specified and names a directory, the resulting file will be
+saved there instead of to FILE's directory. If TARGET is specified and
+does not name a directory, it will be used as output file name."
+ (interactive (list (read-file-name
+ "HTML-ize file: "
+ nil nil nil (and (buffer-file-name)
+ (file-name-nondirectory
+ (buffer-file-name))))))
+ (let ((output-file (if (and target (not (file-directory-p target)))
+ target
+ (expand-file-name
+ (htmlize-make-file-name (file-name-nondirectory file))
+ (or target (file-name-directory file)))))
+ ;; Try to prevent `find-file-noselect' from triggering
+ ;; font-lock because we'll fontify explicitly below.
+ (font-lock-mode nil)
+ (font-lock-auto-fontify nil)
+ (global-font-lock-mode nil)
+ ;; Ignore the size limit for the purposes of htmlization.
+ (font-lock-maximum-size nil)
+ ;; Disable font-lock support modes. This will only work in
+ ;; more recent Emacs versions, so htmlize-buffer-1 still needs
+ ;; to call htmlize-ensure-fontified.
+ (font-lock-support-mode nil))
+ (with-temp-buffer
+ ;; Insert FILE into the temporary buffer.
+ (insert-file-contents file)
+ ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
+ ;; up. Restore it afterwards so with-temp-buffer's kill-buffer
+ ;; doesn't complain about killing a modified buffer.
+ (let ((buffer-file-name file))
+ ;; Set the major mode for the sake of font-lock.
+ (normal-mode)
+ (font-lock-mode 1)
+ (unless font-lock-mode
+ ;; In GNU Emacs (font-lock-mode 1) doesn't force font-lock,
+ ;; contrary to the documentation. This seems to work.
+ (font-lock-fontify-buffer))
+ ;; htmlize the buffer and save the HTML.
+ (with-current-buffer (htmlize-buffer-1)
+ (unwind-protect
+ (progn
+ (run-hooks 'htmlize-file-hook)
+ (write-region (point-min) (point-max) output-file))
+ (kill-buffer (current-buffer)))))))
+ ;; I haven't decided on a useful return value yet, so just return
+ ;; nil.
+ nil)
+
+;;;###autoload
+(defun htmlize-many-files (files &optional target-directory)
+ "Convert FILES to HTML and save the corresponding HTML versions.
+
+FILES should be a list of file names to convert. This function calls
+`htmlize-file' on each file; see that function for details. When
+invoked interactively, you are prompted for a list of files to convert,
+terminated with RET.
+
+If TARGET-DIRECTORY is specified, the HTML files will be saved to that
+directory. Normally, each HTML file is saved to the directory of the
+corresponding source file."
+ (interactive
+ (list
+ (let (list file)
+ ;; Use empty string as DEFAULT because setting DEFAULT to nil
+ ;; defaults to the directory name, which is not what we want.
+ (while (not (equal (setq file (read-file-name
+ "HTML-ize file (RET to finish): "
+ (and list (file-name-directory
+ (car list)))
+ "" t))
+ ""))
+ (push file list))
+ (nreverse list))))
+ ;; Verify that TARGET-DIRECTORY is indeed a directory. If it's a
+ ;; file, htmlize-file will use it as target, and that doesn't make
+ ;; sense.
+ (and target-directory
+ (not (file-directory-p target-directory))
+ (error "target-directory must name a directory: %s" target-directory))
+ (dolist (file files)
+ (htmlize-file file target-directory)))
+
+;;;###autoload
+(defun htmlize-many-files-dired (arg &optional target-directory)
+ "HTMLize dired-marked files."
+ (interactive "P")
+ (htmlize-many-files (dired-get-marked-files nil arg) target-directory))
+
+(provide 'htmlize)
+
+;; Local Variables:
+;; byte-compile-warnings: (not cl-functions lexical unresolved obsolete)
+;; lexical-binding: t
+;; End:
+
+;;; htmlize.el ends here
diff --git a/contrib/lisp/ob-csharp.el b/contrib/lisp/ob-csharp.el
new file mode 100644
index 0000000..c4aa046
--- /dev/null
+++ b/contrib/lisp/ob-csharp.el
@@ -0,0 +1,83 @@
+;;; ob-csharp.el --- org-babel functions for csharp evaluation
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: thomas "at" friendlyvillagers.com based on ob-java.el by Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Currently this only supports the external compilation and execution
+;; of csharp code blocks (i.e., no session support).
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("csharp" . "cs"))
+
+(defcustom org-babel-csharp-command "mono"
+ "Name of the csharp command.
+May be either a command in the path, like mono
+or an absolute path name, like /usr/local/bin/mono
+parameters may be used, like mono -verbose"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defcustom org-babel-csharp-compiler "mcs"
+ "Name of the csharp compiler.
+May be either a command in the path, like mcs
+or an absolute path name, like /usr/local/bin/mcs
+parameters may be used, like mcs -warnaserror+"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defun org-babel-execute:csharp (body params)
+ (let* ((full-body (org-babel-expand-body:generic body params))
+ (cmpflag (or (cdr (assq :cmpflag params)) ""))
+ (cmdline (or (cdr (assq :cmdline params)) ""))
+ (src-file (org-babel-temp-file "csharp-src-" ".cs"))
+ (exe-file (concat (file-name-sans-extension src-file) ".exe"))
+ (compile
+ (progn (with-temp-file src-file (insert full-body))
+ (org-babel-eval
+ (concat org-babel-csharp-compiler " " cmpflag " " src-file) ""))))
+ (let ((results (org-babel-eval (concat org-babel-csharp-command " " cmdline " " exe-file) "")))
+ (org-babel-reassemble-table
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (org-babel-read results)
+ (let ((tmp-file (org-babel-temp-file "c-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(defun org-babel-prep-session:csharp (session params)
+ "Return an error because csharp does not support sessions."
+ (error "Sessions are not supported for CSharp"))
+
+(provide 'ob-csharp)
+
+
+
+;;; ob-csharp.el ends here
diff --git a/contrib/lisp/ob-eukleides.el b/contrib/lisp/ob-eukleides.el
new file mode 100644
index 0000000..d3ad993
--- /dev/null
+++ b/contrib/lisp/ob-eukleides.el
@@ -0,0 +1,98 @@
+;;; ob-eukleides.el --- Org-babel functions for eukleides evaluation
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Luis Anaya
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating eukleides script.
+;;
+;; Inspired by Ian Yang's org-export-blocks-format-eukleides
+;; http://www.emacswiki.org/emacs/org-export-blocks-format-eukleides.el
+
+;;; Requirements:
+
+;; eukleides | http://eukleides.org
+;; eukleides | `org-eukleides-path' should point to the eukleides executablexs
+
+;;; Code:
+(require 'ob)
+(require 'ob-eval)
+
+(defvar org-babel-default-header-args:eukleides
+ '((:results . "file") (:exports . "results"))
+ "Default arguments for evaluating a eukleides source block.")
+
+(defcustom org-eukleides-path nil
+ "Path to the eukleides executable file."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-eukleides-eps-to-raster nil
+ "Command used to convert EPS to raster. Nil for no conversion."
+ :group 'org-babel
+ :type '(choice
+ (repeat :tag "Shell Command Sequence" (string :tag "Shell Command"))
+ (const :tag "sam2p" "a=%s;b=%s;sam2p ${a} ${b}" )
+ (const :tag "NetPNM" "a=%s;b=%s;pstopnm -stdout ${a} | pnmtopng > ${b}" )
+ (const :tag "None" nil)))
+
+(defun org-babel-execute:eukleides (body params)
+ "Execute a block of eukleides code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((result-params (split-string (or (cdr (assq :results params)) "")))
+ (out-file (or (cdr (assq :file params))
+ (error "Eukleides requires a \":file\" header argument")))
+ (cmdline (cdr (assq :cmdline params)))
+ (in-file (org-babel-temp-file "eukleides-"))
+ (java (or (cdr (assq :java params)) ""))
+ (cmd (if (not org-eukleides-path)
+ (error "`org-eukleides-path' is not set")
+ (concat (expand-file-name org-eukleides-path)
+ " -b --output="
+ (org-babel-process-file-name
+ (concat
+ (file-name-sans-extension out-file) ".eps"))
+ " "
+ (org-babel-process-file-name in-file)))))
+ (unless (file-exists-p org-eukleides-path)
+ (error "Could not find eukleides at %s" org-eukleides-path))
+
+ (if (string= (file-name-extension out-file) "png")
+ (if org-eukleides-eps-to-raster
+ (shell-command (format org-eukleides-eps-to-raster
+ (concat (file-name-sans-extension out-file) ".eps")
+ (concat (file-name-sans-extension out-file) ".png")))
+ (error "Conversion to PNG not supported. Use a file with an EPS name")))
+
+ (with-temp-file in-file (insert body))
+ (message "%s" cmd) (org-babel-eval cmd "")
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:eukleides (session params)
+ "Return an error because eukleides does not support sessions."
+ (error "Eukleides does not support sessions"))
+
+(provide 'ob-eukleides)
+
+
+
+;;; ob-eukleides.el ends here
diff --git a/contrib/lisp/ob-fomus.el b/contrib/lisp/ob-fomus.el
new file mode 100644
index 0000000..30f292f
--- /dev/null
+++ b/contrib/lisp/ob-fomus.el
@@ -0,0 +1,92 @@
+;;; ob-fomus.el --- Org-babel functions for fomus evaluation
+
+;; Copyright (C) 2011-2014 Torsten Anders
+
+;; Author: Torsten Anders
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating Fomus source code.
+;; For information on Fomus see http://fomus.sourceforge.net/
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in fomus
+;;
+;; 2) we are generally only going to return results of type "file"
+;;
+;; 3) we are adding the "file" and "cmdline" header arguments
+;;
+;; 4) there are no variables (at least for now)
+
+;;; Code:
+(require 'ob)
+(require 'ob-eval)
+
+(defvar org-babel-default-header-args:fomus
+ '((:results . "file") (:exports . "results"))
+ "Default arguments to use when evaluating a fomus source block.")
+
+(defun org-babel-expand-body:fomus (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (mapc
+ (lambda (pair)
+ (let ((name (symbol-name (car pair)))
+ (value (cdr pair)))
+ (setq body
+ (replace-regexp-in-string
+ (concat "\$" (regexp-quote name))
+ (if (stringp value) value (format "%S" value))
+ body))))
+ vars)
+ body))
+
+(defun org-babel-execute:fomus (body params)
+ "Execute a block of Fomus code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((result-params (cdr (assq :result-params params)))
+ (out-file (cdr (assq :file params)))
+ (cmdline (cdr (assq :cmdline params)))
+ (cmd (or (cdr (assq :cmd params)) "fomus"))
+ (in-file (org-babel-temp-file "fomus-" ".fms")))
+ (with-temp-file in-file
+ (insert (org-babel-expand-body:fomus body params)))
+ ;; TMP: testing
+ ;; (message (concat cmd
+ ;; " " (org-babel-process-file-name in-file)
+ ;; " " cmdline
+ ;; " -o " (org-babel-process-file-name out-file)))
+ (org-babel-eval
+ (concat cmd
+ " " (org-babel-process-file-name in-file)
+ " " cmdline
+ " -o " (org-babel-process-file-name out-file)) "")
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:fomus (session params)
+ "Return an error because Fomus does not support sessions."
+ (error "Fomus does not support sessions"))
+
+(provide 'ob-fomus)
+
+;;; ob-fomus.el ends here
diff --git a/contrib/lisp/ob-julia.el b/contrib/lisp/ob-julia.el
new file mode 100644
index 0000000..41c8b5a
--- /dev/null
+++ b/contrib/lisp/ob-julia.el
@@ -0,0 +1,301 @@
+;;; ob-julia.el --- org-babel functions for julia code evaluation
+
+;; Copyright (C) 2013, 2014 G. Jay Kerns
+;; Author: G. Jay Kerns, based on ob-R.el by Eric Schulte and Dan Davison
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; The file provides Org-Babel support for evaluating julia code.
+;;
+;; See https://github.com/gjkerns/ob-julia/blob/master/ob-julia-doc.org
+;; for detailed instructions on how to get started. The git repository
+;; contains more documentation: git://github.com/gjkerns/ob-julia.git
+
+;;; Code:
+(require 'ob)
+(require 'cl-lib)
+
+(declare-function orgtbl-to-csv "org-table" (table params))
+(declare-function julia "ext:ess-julia" (&optional start-args))
+(declare-function inferior-ess-send-input "ext:ess-inf" ())
+(declare-function ess-make-buffer-current "ext:ess-inf" ())
+(declare-function ess-eval-buffer "ext:ess-inf" (vis))
+(declare-function org-number-sequence "org-compat" (from &optional to inc))
+
+(defconst org-babel-header-args:julia
+ '((width . :any)
+ (horizontal . :any)
+ (results . ((file list vector table scalar verbatim)
+ (raw org html latex code pp wrap)
+ (replace silent append prepend)
+ (output value graphics))))
+ "julia-specific header arguments.")
+
+(add-to-list 'org-babel-tangle-lang-exts '("julia" . "jl"))
+
+(defvar org-babel-default-header-args:julia '())
+
+(defcustom org-babel-julia-command inferior-julia-program-name
+ "Name of command to use for executing julia code."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defvar ess-local-process-name) ; dynamically scoped
+(defun org-babel-edit-prep:julia (info)
+ (let ((session (cdr (assq :session (nth 2 info)))))
+ (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
+ (save-match-data (org-babel-julia-initiate-session session nil)))))
+
+(defun org-babel-expand-body:julia (body params &optional graphics-file)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((graphics-file
+ (or graphics-file (org-babel-julia-graphical-output-file params))))
+ (mapconcat
+ #'identity
+ ((lambda (inside)
+ (if graphics-file
+ inside
+ inside))
+ (append (org-babel-variable-assignments:julia params)
+ (list body))) "\n")))
+
+(defun org-babel-execute:julia (body params)
+ "Execute a block of julia code.
+This function is called by `org-babel-execute-src-block'."
+ (save-excursion
+ (let* ((result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (session (org-babel-julia-initiate-session
+ (cdr (assq :session params)) params))
+ (colnames-p (cdr (assq :colnames params)))
+ (rownames-p (cdr (assq :rownames params)))
+ (graphics-file (org-babel-julia-graphical-output-file params))
+ (full-body (org-babel-expand-body:julia body params graphics-file))
+ (result
+ (org-babel-julia-evaluate
+ session full-body result-type result-params
+ (or (equal "yes" colnames-p)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) colnames-p))
+ (or (equal "yes" rownames-p)
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) rownames-p)))))
+ (if graphics-file nil result))))
+
+(defun org-babel-prep-session:julia (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-julia-initiate-session session params))
+ (var-lines (org-babel-variable-assignments:julia params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:julia (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:julia session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:julia (params)
+ "Return list of julia statements assigning the block's variables."
+ (let ((vars (org-babel--get-vars params)))
+ (mapcar
+ (lambda (pair)
+ (org-babel-julia-assign-elisp
+ (car pair) (cdr pair)
+ (equal "yes" (cdr (assq :colnames params)))
+ (equal "yes" (cdr (assq :rownames params)))))
+ (mapcar
+ (lambda (i)
+ (cons (car (nth i vars))
+ (org-babel-reassemble-table
+ (cdr (nth i vars))
+ (cdr (nth i (cdr (assq :colname-names params))))
+ (cdr (nth i (cdr (assq :rowname-names params)))))))
+ (org-number-sequence 0 (1- (length vars)))))))
+
+(defun org-babel-julia-quote-csv-field (s)
+ "Quote field S for export to julia."
+ (if (stringp s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
+ (format "%S" s)))
+
+(defun org-babel-julia-assign-elisp (name value colnames-p rownames-p)
+ "Construct julia code assigning the elisp VALUE to a variable named NAME."
+ (if (listp value)
+ (let ((max (apply #'max (mapcar #'length (cl-remove-if-not
+ #'sequencep value))))
+ (min (apply #'min (mapcar #'length (cl-remove-if-not
+ #'sequencep value))))
+ (transition-file (org-babel-temp-file "julia-import-")))
+ ;; ensure VALUE has an orgtbl structure (depth of at least 2)
+ (unless (listp (car value)) (setq value (list value)))
+ (with-temp-file transition-file
+ (insert
+ (orgtbl-to-csv value '(:fmt org-babel-julia-quote-csv-field))
+ "\n"))
+ (let ((file (org-babel-process-file-name transition-file 'noquote))
+ (header (if (or (eq (nth 1 value) 'hline) colnames-p)
+ "TRUE" "FALSE"))
+ (row-names (if rownames-p "1" "NULL")))
+ (if (= max min)
+ (format "%s = readcsv(\"%s\")" name file)
+ (format "%s = readcsv(\"%s\")"
+ name file))))
+ (format "%s = %s" name (org-babel-julia-quote-csv-field value))))
+
+(defvar ess-ask-for-ess-directory) ; dynamically scoped
+
+(defun org-babel-julia-initiate-session (session params)
+ "If there is not a current julia process then create one."
+ (unless (string= session "none")
+ (let ((session (or session "*julia*"))
+ (ess-ask-for-ess-directory
+ (and (and (boundp 'ess-ask-for-ess-directory) ess-ask-for-ess-directory)
+ (not (cdr (assq :dir params))))))
+ (if (org-babel-comint-buffer-livep session)
+ session
+ (save-window-excursion
+ (require 'ess) (julia)
+ (rename-buffer
+ (if (bufferp session)
+ (buffer-name session)
+ (if (stringp session)
+ session
+ (buffer-name))))
+ (current-buffer))))))
+
+(defun org-babel-julia-associate-session (session)
+ "Associate julia code buffer with a julia session.
+Make SESSION be the inferior ESS process associated with the
+current code buffer."
+ (setq ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-make-buffer-current))
+
+(defun org-babel-julia-graphical-output-file (params)
+ "Name of file to which julia should send graphical output."
+ (and (member "graphics" (cdr (assq :result-params params)))
+ (cdr (assq :file params))))
+
+(defvar org-babel-julia-eoe-indicator "print(\"org_babel_julia_eoe\")")
+(defvar org-babel-julia-eoe-output "org_babel_julia_eoe")
+
+(defvar org-babel-julia-write-object-command "writecsv(\"%s\",%s)")
+
+;; The following was a very complicated write object command
+;; The replacement needs to add error catching
+;(defvar org-babel-julia-write-object-command "{function(object,transfer.file){object;invisible(if(inherits(try({tfile<-tempfile();write.table(object,file=tfile,sep=\"\\t\",na=\"nil\",row.names=%s,col.names=%s,quote=FALSE);file.rename(tfile,transfer.file)},silent=TRUE),\"try-error\")){if(!file.exists(transfer.file))file.create(transfer.file)})}}(object=%s,transfer.file=\"%s\")")
+
+(defun org-babel-julia-evaluate
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate julia code in BODY."
+ (if session
+ (org-babel-julia-evaluate-session
+ session body result-type result-params column-names-p row-names-p)
+ (org-babel-julia-evaluate-external-process
+ body result-type result-params column-names-p row-names-p)))
+
+(defun org-babel-julia-evaluate-external-process
+ (body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in external julia process.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (let ((tmp-file (org-babel-temp-file "julia-")))
+ (org-babel-eval org-babel-julia-command
+ (format org-babel-julia-write-object-command
+ (org-babel-process-file-name tmp-file 'noquote)
+ (format "begin\n%s\nend" body)))
+ (org-babel-julia-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (buffer-string))
+ (org-babel-import-elisp-from-file tmp-file '(4)))
+ column-names-p)))
+ (output (org-babel-eval org-babel-julia-command body))))
+
+(defun org-babel-julia-evaluate-session
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in SESSION.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (with-temp-buffer
+ (insert (org-babel-chomp body))
+ (let ((ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-eval-visibly-p nil))
+ (ess-eval-buffer nil)))
+ (let ((tmp-file (org-babel-temp-file "julia-")))
+ (org-babel-comint-eval-invisibly-and-wait-for-file
+ session tmp-file
+ (format org-babel-julia-write-object-command
+ (org-babel-process-file-name tmp-file 'noquote) "ans"))
+ (org-babel-julia-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (buffer-string))
+ (org-babel-import-elisp-from-file tmp-file '(4)))
+ column-names-p)))
+ (output
+ (mapconcat
+ #'org-babel-chomp
+ (butlast
+ (delq nil
+ (mapcar
+ (lambda (line) (when (> (length line) 0) line))
+ (mapcar
+ (lambda (line) ;; cleanup extra prompts left in output
+ (if (string-match
+ "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
+ (substring line (match-end 1))
+ line))
+ (org-babel-comint-with-output (session org-babel-julia-eoe-output)
+ (insert (mapconcat #'org-babel-chomp
+ (list body org-babel-julia-eoe-indicator)
+ "\n"))
+ (inferior-ess-send-input)))))) "\n"))))
+
+(defun org-babel-julia-process-value-result (result column-names-p)
+ "julia-specific processing of return value.
+Insert hline if column names in output have been requested."
+ (if column-names-p
+ (cons (car result) (cons 'hline (cdr result)))
+ result))
+
+(provide 'ob-julia)
+
+;;; ob-julia.el ends here
diff --git a/contrib/lisp/ob-mathematica.el b/contrib/lisp/ob-mathematica.el
new file mode 100644
index 0000000..cb35dec
--- /dev/null
+++ b/contrib/lisp/ob-mathematica.el
@@ -0,0 +1,81 @@
+;;; ob-mathematica.el --- org-babel functions for Mathematica evaluation
+
+;; Copyright (C) 2014 Yi Wang
+
+;; Authors: Yi Wang
+;; Keywords: literate programming, reproducible research
+;; Homepage: https://github.com/tririver/wy-els/blob/master/ob-mathematica.el
+;; Distributed under the GNU GPL v2 or later
+
+;; Org-Babel support for evaluating Mathematica source code.
+
+;;; Code:
+(require 'ob)
+(require 'ob-ref)
+(require 'ob-comint)
+(require 'ob-eval)
+
+(declare-function org-trim "org" (s &optional keep-lead))
+
+;; Optionally require mma.el for font lock, etc
+(require 'mma nil 'noerror)
+(add-to-list 'org-src-lang-modes '("mathematica" . "mma"))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("mathematica" . "m"))
+
+(defvar org-babel-default-header-args:mathematica '())
+
+(defvar org-babel-mathematica-command "MathematicaScript -script"
+ "Name of the command for executing Mathematica code.")
+
+(defvar org-babel-mathematica-command-alt "math -noprompt"
+ "Name of the command for executing Mathematica code.")
+
+(defun org-babel-expand-body:mathematica (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (concat
+ (mapconcat ;; define any variables
+ (lambda (pair)
+ (format "%s=%s;"
+ (car pair)
+ (org-babel-mathematica-var-to-mathematica (cdr pair))))
+ vars "\n") "\nPrint[\n" body "\n]\n")))
+
+(defun org-babel-execute:mathematica (body params)
+ "Execute a block of Mathematica code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (let* ((result-params (cdr (assq :result-params params)))
+ (full-body (org-babel-expand-body:mathematica body params))
+ (tmp-script-file (org-babel-temp-file "mathematica-"))
+ (cmd org-babel-mathematica-command))
+ ;; actually execute the source-code block
+ (with-temp-file tmp-script-file (insert full-body))
+ ;; (with-temp-file "/tmp/dbg" (insert full-body))
+ ((lambda (raw)
+ (if (or (member "code" result-params)
+ (member "pp" result-params)
+ (and (member "output" result-params)
+ (not (member "table" result-params))))
+ raw
+ (org-babel-script-escape (org-trim raw))))
+ (org-babel-eval (concat cmd " " tmp-script-file) ""))))
+
+(defun org-babel-prep-session:mathematica (session params)
+ "This function does nothing so far"
+ (error "Currently no support for sessions"))
+
+(defun org-babel-prep-session:mathematica (session body params)
+ "This function does nothing so far"
+ (error "Currently no support for sessions"))
+
+(defun org-babel-mathematica-var-to-mathematica (var)
+ "Convert an elisp value to a Mathematica variable.
+Convert an elisp value, VAR, into a string of Mathematica source code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "{" (mapconcat #'org-babel-mathematica-var-to-mathematica var ", ") "}")
+ (format "%S" var)))
+
+(provide 'ob-mathematica)
diff --git a/contrib/lisp/ob-mathomatic.el b/contrib/lisp/ob-mathomatic.el
new file mode 100644
index 0000000..c62e181
--- /dev/null
+++ b/contrib/lisp/ob-mathomatic.el
@@ -0,0 +1,145 @@
+;;; ob-mathomatic.el --- Org-babel functions for mathomatic evaluation
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric S Fraga
+;; Eric Schulte
+;; Luis Anaya (Mathomatic)
+
+;; Keywords: literate programming, reproducible research, mathomatic
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating mathomatic entries.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in mathomatic
+;;
+;; 2) we are adding the "cmdline" header argument
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("mathomatic" . "math"))
+
+(defvar org-babel-default-header-args:mathomatic '())
+
+(defcustom org-babel-mathomatic-command
+ (if (boundp 'mathomatic-command) mathomatic-command "mathomatic")
+ "Command used to call mathomatic on the shell."
+ :group 'org-babel)
+
+(defun org-babel-mathomatic-expand (body params)
+ "Expand a block of Mathomatic code according to its header arguments."
+ (let ((vars (org-babel--get-vars params)))
+ (mapconcat 'identity
+ (list
+ ;; graphic output
+ (let ((graphic-file (org-babel-mathomatic-graphical-output-file params)))
+ (if graphic-file
+ (cond
+ ((string-match ".\.eps$" graphic-file)
+ (format ;; Need to add command to send to file.
+ "set plot set terminal postscript eps\\;set output %S "
+ graphic-file))
+ ((string-match ".\.ps$" graphic-file)
+ (format ;; Need to add command to send to file.
+ "set plot set terminal postscript\\;set output %S "
+ graphic-file))
+
+ ((string-match ".\.pic$" graphic-file)
+ (format ;; Need to add command to send to file.
+ "set plot set terminal gpic\\;set output %S "
+ graphic-file))
+ (t
+ (format ;; Need to add command to send to file.
+ "set plot set terminal png\\;set output %S "
+ graphic-file)))
+ ""))
+ ;; variables
+ (mapconcat 'org-babel-mathomatic-var-to-mathomatic vars "\n")
+ ;; body
+ body
+ "")
+ "\n")))
+
+(defun org-babel-execute:mathomatic (body params)
+ "Execute a block of Mathomatic entries with org-babel. This function is
+called by `org-babel-execute-src-block'."
+ (message "executing Mathomatic source code block")
+ (let ((result-params (split-string (or (cdr (assq :results params)) "")))
+ (result
+ (let* ((cmdline (or (cdr (assq :cmdline params)) ""))
+ (in-file (org-babel-temp-file "mathomatic-" ".math"))
+ (cmd (format "%s -t -c -q %s %s"
+ org-babel-mathomatic-command in-file cmdline)))
+ (with-temp-file in-file (insert (org-babel-mathomatic-expand body params)))
+ (message cmd)
+ ((lambda (raw) ;; " | grep -v batch | grep -v 'replaced' | sed '/^$/d' "
+ (mapconcat
+ #'identity
+ (delq nil
+ (mapcar (lambda (line)
+ (unless (or (string-match "batch" line)
+ (string-match "^rat: replaced .*$" line)
+ (= 0 (length line)))
+ line))
+ (split-string raw "[\r\n]"))) "\n"))
+ (org-babel-eval cmd "")))))
+ (if (org-babel-mathomatic-graphical-output-file params)
+ nil
+ (if (or (member "scalar" result-params)
+ (member "verbatim" result-params)
+ (member "output" result-params))
+ result
+ (let ((tmp-file (org-babel-temp-file "mathomatic-res-")))
+ (with-temp-file tmp-file (insert result))
+ (org-babel-import-elisp-from-file tmp-file))))))
+
+(defun org-babel-prep-session:mathomatic (session params)
+ (error "Mathomatic does not support sessions"))
+
+(defun org-babel-mathomatic-var-to-mathomatic (pair)
+ "Convert an elisp val into a string of mathomatic code specifying a var
+of the same value."
+ (let ((var (car pair))
+ (val (cdr pair)))
+ (when (symbolp val)
+ (setq val (symbol-name val))
+ (when (= (length val) 1)
+ (setq val (string-to-char val))))
+ (format "%s=%s" var
+ (org-babel-mathomatic-elisp-to-mathomatic val))))
+
+(defun org-babel-mathomatic-graphical-output-file (params)
+ "Name of file to which mathomatic should send graphical output."
+ (and (member "graphics" (cdr (assq :result-params params)))
+ (cdr (assq :file params))))
+
+(defun org-babel-mathomatic-elisp-to-mathomatic (val)
+ "Return a string of mathomatic code which evaluates to VAL."
+ (if (listp val)
+ (mapconcat #'org-babel-mathomatic-elisp-to-mathomatic val " ")
+ (format "%s" val)))
+
+(provide 'ob-mathomatic)
+
+;;; ob-mathomatic.el ends here
diff --git a/contrib/lisp/ob-oz.el b/contrib/lisp/ob-oz.el
new file mode 100644
index 0000000..9beadeb
--- /dev/null
+++ b/contrib/lisp/ob-oz.el
@@ -0,0 +1,294 @@
+;;; ob-oz.el --- Org-babel functions for Oz evaluation
+
+;; Copyright (C) 2009-2014 Torsten Anders and Eric Schulte
+
+;; Author: Torsten Anders and Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+;; Version: 0.02
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating Oz source code.
+;;
+;; Oz code is always send to the Oz Programming Environment (OPI), the
+;; Emacs mode and compiler interface for Oz programs. Therefore, only
+;; session mode is supported. In practice, non-session code blocks are
+;; handled equally well by the session mode. However, only a single
+;; session is supported. Consequently, the :session header argument is
+;; ignored.
+;;
+;; The Org-babel header argument :results is interpreted as
+;; follows. :results output requires the respective code block to be
+;; an Oz statement and :results value requires an Oz
+;; expression. Currently, results are only supported for expressions
+;; (i.e. the result of :results output is always nil).
+;;
+;; Expression evaluation happens synchronously. Therefore there is an
+;; additional header argument :wait-time <number>, which specifies the
+;; maximum time to wait for the result of a given expression. nil
+;; means to wait as long as it takes to get a result (potentially wait
+;; forever).
+;;
+;; NOTE: Currently the copyright of this file may not be in a state to
+;; permit inclusion as core software into Emacs or Org-mode.
+
+;;; Requirements:
+
+;; - Mozart Programming System, the implementation of the Oz
+;; programming language (http://www.mozart-oz.org/), which includes
+;; the major mode mozart for editing Oz programs.
+;;
+;; - StartOzServer.oz which is located in the contrib/scripts
+;; directory of the Org-mode repository
+
+;;; TODO:
+
+;; - Decide: set communication to \\switch -threadedqueries?
+;;
+;; - Only start Oz compiler when required, e.g., load Org-babel only when needed?
+;;
+;; - Avoid synchronous evaluation to avoid blocking Emacs (complex
+;; Strasheela programs can take long to find a result..). In order
+;; to cleanly map code blocks to their associated results (which can
+;; arrive then in any order) I could use IDs
+;; (e.g. integers). However, how do I do concurrency in Emacs Lisp,
+;; and how can I define org-babel-execute:oz concurrently.
+;;
+;; - Expressions are rarely used in Oz at the top-level, and using
+;; them in documentation and Literate Programs will cause
+;; confusion. Idea: hide expression from reader and instead show
+;; them statement (e.g., MIDI output statement) and then include
+;; result in Org file. Implementation: for expressions (:results
+;; value) support an additional header argument that takes arbitrary
+;; Oz code. This code is not seen by the reader, but will be used
+;; for the actual expression at the end. Alternative: feed all
+;; relevant code as statement (:results output), then add expression
+;; as extra code block which outputs, e.g., file name (so the file
+;; name must be accessible by global var), but the code of this
+;; extra codeblock is not seen. Hm, in that case it might be even
+;; more easy to manually add this link to the Org file.
+;;
+
+
+(require 'ob)
+;;; major mode for editing Oz programs
+(require 'mozart nil t)
+
+;;
+;; Interface to communicate with Oz.
+;; (1) For statements without any results: oz-send-string
+;; (2) For expressions with a single result: oz-send-string-expression
+;; (defined in org-babel-oz-ResultsValue.el)
+;;
+
+;; oz-send-string-expression implements an additional very direct
+;; communication between Org-babel and the Oz compiler. Communication
+;; with the Oz server works already without this code via the function
+;; oz-send-string from mozart.el.in, but this function does not get
+;; back any results from Oz to Emacs. The following code creates a
+;; socket for sending code to the OPI compiler and results are
+;; returned by the same socket. On the Oz side, a socket is opened and
+;; conected to the compiler of the OPI (via oz-send-string). On the
+;; Emacs side, a connection to this socket is created for feeding code
+;; and receiving results. This additional communication channel to the
+;; OPI compiler ensures that results are returned cleanly (e.g., only
+;; the result of the sent code is returned, no parsing or any
+;; processing of *Oz Emulator* is required).
+;;
+;; There is no buffer, nor sentinel involved. Oz code is send
+;; directly, and results from Oz are send back, but Emacs Lisp
+;; requires a filter function for processing results.
+
+(defvar org-babel-oz-server-dir
+ (file-name-as-directory
+ (expand-file-name
+ "contrib/scripts"
+ (file-name-as-directory
+ (expand-file-name
+ "../../.."
+ (file-name-directory (or load-file-name buffer-file-name))))))
+ "Path to the contrib/scripts directory in which
+StartOzServer.oz is located.")
+
+(defvar org-babel-oz-port 6001
+ "Port for communicating with Oz compiler.")
+(defvar org-babel-oz-OPI-socket nil
+ "Socket for communicating with OPI.")
+
+(defvar org-babel-oz-collected-result nil
+ "Aux var to hand result from org-babel-oz-filter to oz-send-string-expression.")
+(defun org-babel-oz-filter (proc string)
+ "Processes output from socket org-babel-oz-OPI-socket."
+;; (setq org-babel-oz-collected-results (cons string org-babel-oz-collected-results))
+ (setq org-babel-oz-collected-result string)
+ )
+
+
+(defun org-babel-oz-create-socket ()
+ (message "Create OPI socket for evaluating expressions")
+ ;; Start Oz directly
+ (run-oz)
+ ;; Create socket on Oz side (after Oz was started).
+ (oz-send-string (concat "\\insert '" org-babel-oz-server-dir "StartOzServer.oz'"))
+ ;; Wait until socket is created before connecting to it.
+ ;; Quick hack: wait 3 sec
+ ;;
+ ;; extending time to 30 secs does not help when starting Emacs for
+ ;; the first time (and computer does nothing else)
+ (sit-for 3)
+ ;; connect to OPI socket
+ (setq org-babel-oz-OPI-socket
+ ;; Creates a socket. I/O interface of Emacs sockets as for processes.
+ (open-network-stream "*Org-babel-OPI-socket*" nil "localhost" org-babel-oz-port))
+ ;; install filter
+ (set-process-filter org-babel-oz-OPI-socket #'org-babel-oz-filter)
+)
+
+;; communication with org-babel-oz-OPI-socket is asynchronous, but
+;; oz-send-string-expression turns is into synchronous...
+(defun oz-send-string-expression (string &optional wait-time)
+ "Similar to oz-send-string, oz-send-string-expression sends a string to the OPI compiler. However, string must be expression and this function returns the result of the expression (as string). oz-send-string-expression is synchronous, wait-time allows to specify a maximum wait time. After wait-time is over with no result, the function returns nil."
+ (if (not org-babel-oz-OPI-socket)
+ (org-babel-oz-create-socket))
+ (let ((polling-delay 0.1)
+ result)
+ (process-send-string org-babel-oz-OPI-socket string)
+ ;; wait for result
+ (if wait-time
+ (let ((waited 0))
+ (unwind-protect
+ (progn
+ (while
+ ;; stop loop if org-babel-oz-collected-result \= nil or waiting time is over
+ (not (or (not (equal org-babel-oz-collected-result nil))
+ (> waited wait-time)))
+ (progn
+ (sit-for polling-delay)
+;; (message "org-babel-oz: next polling iteration")
+ (setq waited (+ waited polling-delay))))
+;; (message "org-babel-oz: waiting over, got result or waiting timed out")
+;; (message (format "wait-time: %s, waited: %s" wait-time waited))
+ (setq result org-babel-oz-collected-result)
+ (setq org-babel-oz-collected-result nil))))
+ (unwind-protect
+ (progn
+ (while (equal org-babel-oz-collected-result nil)
+ (sit-for polling-delay))
+ (setq result org-babel-oz-collected-result)
+ (setq org-babel-oz-collected-result nil))))
+ result))
+
+(defun org-babel-expand-body:oz (body params)
+ (let ((vars (org-babel--get-vars params)))
+ (if vars
+ ;; prepend code to define all arguments passed to the code block
+ (let ((var-string (mapcar (lambda (pair)
+ (format "%s=%s"
+ (car pair)
+ (org-babel-oz-var-to-oz (cdr pair))))
+ vars)))
+ ;; only add var declarations if any variables are there
+ (mapconcat #'identity
+ (append (list "local") var-string (list "in" body "end"))
+ "\n"))
+ body)))
+
+(defun org-babel-execute:oz (body params)
+ "Execute a block of Oz code with org-babel. This function is
+called by `org-babel-execute-src-block' via multiple-value-bind."
+ (let* ((result-params (cdr (assq :result-params params)))
+ (full-body (org-babel-expand-body:oz body params))
+ (wait-time (plist-get params :wait-time)))
+ ;; actually execute the source-code block
+ (org-babel-reassemble-table
+ (cond
+ ((member "output" result-params)
+ (message "Org-babel: executing Oz statement")
+ (oz-send-string full-body))
+ ((member "value" result-params)
+ (message "Org-babel: executing Oz expression")
+ (oz-send-string-expression full-body (or wait-time 1)))
+ (t (error "either 'output' or 'results' must be members of :results")))
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :roname-names params))
+ (cdr (assq :rownames params))))))
+
+;; This function should be used to assign any variables in params in
+;; the context of the session environment.
+(defun org-babel-prep-session:oz (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (error "org-babel-prep-session:oz unimplemented"))
+;; TODO: testing... (copied from org-babel-haskell.el)
+;; (defun org-babel-prep-session:oz (session params)
+;; "Prepare SESSION according to the header arguments specified in PARAMS."
+;; (save-window-excursion
+;; (org-babel-oz-initiate-session session)
+;; (let* ((vars (org-babel-ref-variables params))
+;; (var-lines (mapconcat ;; define any variables
+;; (lambda (pair)
+;; (format "%s=%s"
+;; (car pair)
+;; (org-babel-ruby-var-to-ruby (cdr pair))))
+;; vars "\n"))
+;; (vars-file (concat (make-temp-file "org-babel-oz-vars") ".oz")))
+;; (when vars
+;; (with-temp-buffer
+;; (insert var-lines) (write-file vars-file)
+;; (oz-mode)
+;; ;; (inferior-oz-load-file) ; ??
+;; ))
+;; (current-buffer))))
+;;
+
+
+;; TODO: testing... (simplified version of def in org-babel-prep-session:ocaml)
+;;
+;; BUG: does not work yet. Error: ad-Orig-error: buffer none doesn't exist or has no process
+;; UNUSED DEF
+(defun org-babel-oz-initiate-session (&optional session params)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session."
+ (unless (string= session "none")
+ ;; TODO: make it possible to have multiple sessions
+ (save-window-excursion
+ ;; (run-oz)
+ (get-buffer oz-compiler-buffer))))
+
+(defun org-babel-oz-var-to-oz (var)
+ "Convert an elisp var into a string of Oz source code
+specifying a var of the same value."
+ (if (listp var)
+;; (concat "[" (mapconcat #'org-babel-oz-var-to-oz var ", ") "]")
+ (eval var)
+ (format "%s" var) ; don't preserve string quotes.
+;; (format "%s" var)
+ ))
+
+;; TODO:
+(defun org-babel-oz-table-or-string (results)
+ "If the results look like a table, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (error "org-babel-oz-table-or-string unimplemented"))
+
+
+(provide 'ob-oz)
+;;; org-babel-oz.el ends here
diff --git a/contrib/lisp/ob-stata.el b/contrib/lisp/ob-stata.el
new file mode 100644
index 0000000..d8cf52a
--- /dev/null
+++ b/contrib/lisp/ob-stata.el
@@ -0,0 +1,312 @@
+;;; ob-stata.el --- org-babel functions for stata code evaluation
+
+;; Copyright (C) 2014 Ista Zahn
+;; Author: Ista Zahn istazahn@gmail.com
+;; G. Jay Kerns
+;; Eric Schulte
+;; Dan Davison
+
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; The file provides Org-Babel support for evaluating stata code.
+;; It is basically result of find-and-replace "stata" for "julia"
+;; in ob-julia.el by G. Jay Kerns. Only ":results output" works: the
+;; header args must include ":results output" (this is the default).
+;; Note that I'm not sure ':results value' makes sense or is useful
+;; but I have left all the value-processing stuff inherited from
+;; ob-julia and ob-R. ':results graphics' would be nice, but I have
+;; not tried to implement it.
+;; --Ista, 07/30/2014
+
+;;; Requirements:
+;; Stata: http://stata.com
+;; ESS: http://ess.r-project.org
+
+;;; Code:
+(require 'ob)
+(require 'cl-lib)
+
+(declare-function orgtbl-to-csv "org-table" (table params))
+(declare-function stata "ext:ess-stata" (&optional start-args))
+(declare-function inferior-ess-send-input "ext:ess-inf" ())
+(declare-function ess-make-buffer-current "ext:ess-inf" ())
+(declare-function ess-eval-buffer "ext:ess-inf" (vis))
+(declare-function org-number-sequence "org-compat" (from &optional to inc))
+
+(defconst org-babel-header-args:stata
+ '((width . :any)
+ (horizontal . :any)
+ (results . ((file list vector table scalar verbatim)
+ (raw org html latex code pp wrap)
+ (replace silent append prepend)
+ ;; NOTE: not sure 'value' makes sense in stata
+ ;; we may want to remove it from the list
+ (output value graphics))))
+ "stata-specific header arguments.")
+
+(add-to-list 'org-babel-tangle-lang-exts '("stata" . "do"))
+
+;; only ':results output' currently works, so make that the default
+(defvar org-babel-default-header-args:stata '((:results . "output")))
+
+(defcustom org-babel-stata-command inferior-STA-program-name
+ "Name of command to use for executing stata code."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'string)
+
+(defvar ess-local-process-name) ; dynamically scoped
+(defun org-babel-edit-prep:stata (info)
+ (let ((session (cdr (assq :session (nth 2 info)))))
+ (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
+ (save-match-data (org-babel-stata-initiate-session session nil)))))
+
+(defun org-babel-expand-body:stata (body params &optional graphics-file)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((graphics-file
+ (or graphics-file (org-babel-stata-graphical-output-file params))))
+ (mapconcat
+ #'identity
+ ((lambda (inside)
+ (if graphics-file
+ inside
+ inside))
+ (append (org-babel-variable-assignments:stata params)
+ (list body))) "\n")))
+
+(defun org-babel-execute:stata (body params)
+ "Execute a block of stata code.
+This function is called by `org-babel-execute-src-block'."
+ (save-excursion
+ (let* ((result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (session (org-babel-stata-initiate-session
+ (cdr (assq :session params)) params))
+ (colnames-p (cdr (assq :colnames params)))
+ (rownames-p (cdr (assq :rownames params)))
+ (graphics-file (org-babel-stata-graphical-output-file params))
+ (full-body (org-babel-expand-body:stata body params graphics-file))
+ (result
+ (org-babel-stata-evaluate
+ session full-body result-type result-params
+ (or (equal "yes" colnames-p)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) colnames-p))
+ (or (equal "yes" rownames-p)
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) rownames-p)))))
+ (if graphics-file nil result))))
+
+(defun org-babel-prep-session:stata (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-stata-initiate-session session params))
+ (var-lines (org-babel-variable-assignments:stata params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:stata (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:stata session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:stata (params)
+ "Return list of stata statements assigning the block's variables."
+ (let ((vars (org-babel--get-vars params)))
+ (mapcar
+ (lambda (pair)
+ (org-babel-stata-assign-elisp
+ (car pair) (cdr pair)
+ (equal "yes" (cdr (assq :colnames params)))
+ (equal "yes" (cdr (assq :rownames params)))))
+ (mapcar
+ (lambda (i)
+ (cons (car (nth i vars))
+ (org-babel-reassemble-table
+ (cdr (nth i vars))
+ (cdr (nth i (cdr (assq :colname-names params))))
+ (cdr (nth i (cdr (assq :rowname-names params)))))))
+ (org-number-sequence 0 (1- (length vars)))))))
+
+(defun org-babel-stata-quote-csv-field (s)
+ "Quote field S for export to stata."
+ (if (stringp s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
+ (format "%S" s)))
+
+(defun org-babel-stata-assign-elisp (name value colnames-p rownames-p)
+ "Construct stata code assigning the elisp VALUE to a variable named NAME."
+ (if (listp value)
+ (let ((max (apply #'max (mapcar #'length (cl-remove-if-not
+ #'sequencep value))))
+ (min (apply #'min (mapcar #'length (cl-remove-if-not
+ #'sequencep value))))
+ (transition-file (org-babel-temp-file "stata-import-")))
+ ;; ensure VALUE has an orgtbl structure (depth of at least 2)
+ (unless (listp (car value)) (setq value (list value)))
+ (with-temp-file transition-file
+ (insert
+ (orgtbl-to-csv value '(:fmt org-babel-stata-quote-csv-field))
+ "\n"))
+ (let ((file (org-babel-process-file-name transition-file 'noquote))
+ (header (if (or (eq (nth 1 value) 'hline) colnames-p)
+ "TRUE" "FALSE"))
+ (row-names (if rownames-p "1" "NULL")))
+ (if (= max min)
+ (format "%s = insheet using \"%s\"" name file)
+ (format "%s = insheet using \"%s\""
+ name file))))
+ (format "%s = %s" name (org-babel-stata-quote-csv-field value))))
+
+(defvar ess-ask-for-ess-directory) ; dynamically scoped
+
+(defun org-babel-stata-initiate-session (session params)
+ "If there is not a current stata process then create one."
+ (unless (string= session "none")
+ (let ((session (or session "*stata*"))
+ (ess-ask-for-ess-directory
+ (and (and (boundp 'ess-ask-for-ess-directory) ess-ask-for-ess-directory)
+ (not (cdr (assq :dir params))))))
+ (if (org-babel-comint-buffer-livep session)
+ session
+ (save-window-excursion
+ (require 'ess) (stata)
+ (rename-buffer
+ (if (bufferp session)
+ (buffer-name session)
+ (if (stringp session)
+ session
+ (buffer-name))))
+ (current-buffer))))))
+
+(defun org-babel-stata-associate-session (session)
+ "Associate stata code buffer with a stata session.
+Make SESSION be the inferior ESS process associated with the
+current code buffer."
+ (setq ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-make-buffer-current))
+
+(defun org-babel-stata-graphical-output-file (params)
+ "Name of file to which stata should send graphical output."
+ (and (member "graphics" (cdr (assq :result-params params)))
+ (cdr (assq :file params))))
+
+(defvar org-babel-stata-eoe-indicator "display \"org_babel_stata_eoe\"")
+(defvar org-babel-stata-eoe-output "org_babel_stata_eoe")
+
+(defvar org-babel-stata-write-object-command "outsheet using \"%s\"")
+
+(defun org-babel-stata-evaluate
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate stata code in BODY."
+ (if session
+ (org-babel-stata-evaluate-session
+ session body result-type result-params column-names-p row-names-p)
+ (org-babel-stata-evaluate-external-process
+ body result-type result-params column-names-p row-names-p)))
+
+(defun org-babel-stata-evaluate-external-process
+ (body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in external stata process.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (let ((tmp-file (org-babel-temp-file "stata-")))
+ (org-babel-eval org-babel-stata-command
+ (format org-babel-stata-write-object-command
+ (org-babel-process-file-name tmp-file 'noquote)
+ (format "begin\n%s\nend" body)))
+ (org-babel-stata-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (buffer-string))
+ (org-babel-import-elisp-from-file tmp-file '(4)))
+ column-names-p)))
+ (output (org-babel-eval org-babel-stata-command body))))
+
+(defun org-babel-stata-evaluate-session
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in SESSION.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (with-temp-buffer
+ (insert (org-babel-chomp body))
+ (let ((ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-eval-visibly-p nil))
+ (ess-eval-buffer nil)))
+ (let ((tmp-file (org-babel-temp-file "stata-")))
+ (org-babel-comint-eval-invisibly-and-wait-for-file
+ session tmp-file
+ (format org-babel-stata-write-object-command
+ (org-babel-process-file-name tmp-file 'noquote) "ans"))
+ (org-babel-stata-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (buffer-string))
+ (org-babel-import-elisp-from-file tmp-file '(4)))
+ column-names-p)))
+ (output
+ (mapconcat
+ #'org-babel-chomp
+ (butlast
+ (delq nil
+ (mapcar
+ (lambda (line) (when (> (length line) 0) line))
+ (mapcar
+ (lambda (line) ;; cleanup extra prompts left in output
+ (if (string-match
+ "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
+ (substring line (match-end 1))
+ line))
+ (org-babel-comint-with-output (session org-babel-stata-eoe-output)
+ (insert (mapconcat #'org-babel-chomp
+ (list body org-babel-stata-eoe-indicator)
+ "\n"))
+ (inferior-ess-send-input)))))) "\n"))))
+
+(defun org-babel-stata-process-value-result (result column-names-p)
+ "stata-specific processing of return value.
+Insert hline if column names in output have been requested."
+ (if column-names-p
+ (cons (car result) (cons 'hline (cdr result)))
+ result))
+
+(provide 'ob-stata)
+
+;;; ob-stata.el ends here
diff --git a/contrib/lisp/ob-tcl.el b/contrib/lisp/ob-tcl.el
new file mode 100644
index 0000000..c76b138
--- /dev/null
+++ b/contrib/lisp/ob-tcl.el
@@ -0,0 +1,128 @@
+;;; ob-tcl.el --- Org-babel functions for tcl evaluation
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Dan Davison
+;; Eric Schulte
+;; Luis Anaya (tcl)
+;;
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating tcl source code.
+
+;;; Code:
+(require 'ob)
+(require 'ob-eval)
+(eval-when-compile (require 'cl))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("tcl" . "tcl"))
+
+(defvar org-babel-default-header-args:tcl nil)
+
+(defcustom org-babel-tcl-command "tclsh"
+"Name of command to use for executing Tcl code."
+ :group 'org-babel
+ :type 'string)
+
+
+(defun org-babel-execute:tcl (body params)
+ "Execute a block of Tcl code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((session (cdr (assq :session params)))
+ (result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:tcl params)))
+ (session (org-babel-tcl-initiate-session session)))
+ (org-babel-reassemble-table
+ (org-babel-tcl-evaluate session full-body result-type)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:tcl (session params)
+ "Prepare SESSION according to the header arguments in PARAMS."
+ (error "Sessions are not supported for Tcl"))
+
+(defun org-babel-variable-assignments:tcl (params)
+ "Return list of tcl statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (format "set %s %s"
+ (car pair)
+ (org-babel-tcl-var-to-tcl (cdr pair))))
+ (org-babel--get-vars params)))
+
+;; helper functions
+
+(defun org-babel-tcl-var-to-tcl (var)
+ "Convert an elisp value to a tcl variable.
+The elisp value, VAR, is converted to a string of tcl source code
+specifying a var of the same value."
+ (if (listp var)
+ (concat "{" (mapconcat #'org-babel-tcl-var-to-tcl var " ") "}")
+ (format "%s" var)))
+
+(defvar org-babel-tcl-buffers '(:default . nil))
+
+(defun org-babel-tcl-initiate-session (&optional session params)
+ "Return nil because sessions are not supported by tcl."
+nil)
+
+(defvar org-babel-tcl-wrapper-method
+ "
+proc main {} {
+ %s
+}
+
+set r [eval main]
+set o [open \"%s\" \"w\"];
+puts $o $r
+flush $o
+close $o
+
+")
+
+(defvar org-babel-tcl-pp-wrapper-method
+ nil)
+
+(defun org-babel-tcl-evaluate (session body &optional result-type)
+ "Pass BODY to the Tcl process in SESSION.
+If RESULT-TYPE equals 'output then return a list of the outputs
+of the statements in BODY, if RESULT-TYPE equals 'value then
+return the value of the last statement in BODY, as elisp."
+ (when session (error "Sessions are not supported for Tcl"))
+ (case result-type
+ (output (org-babel-eval org-babel-tcl-command body))
+ (value (let ((tmp-file (org-babel-temp-file "tcl-")))
+ (org-babel-eval
+ org-babel-tcl-command
+ (format org-babel-tcl-wrapper-method body
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (org-babel-eval-read-file tmp-file)))))
+
+(provide 'ob-tcl)
+
+
+
+;;; ob-tcl.el ends here
diff --git a/contrib/lisp/ob-vbnet.el b/contrib/lisp/ob-vbnet.el
new file mode 100644
index 0000000..b0f2688
--- /dev/null
+++ b/contrib/lisp/ob-vbnet.el
@@ -0,0 +1,84 @@
+;;; ob-vbnet.el --- org-babel functions for VB.Net evaluation
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: thomas "at" friendlyvillagers.com based on ob-java.el by Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Currently this only supports the external compilation and execution
+;; of VB.Net code blocks (i.e., no session support).
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("vbnet" . "vb"))
+
+(defcustom org-babel-vbnet-command "mono"
+ "Name of the mono command.
+May be either a command in the path, like mono
+or an absolute path name, like /usr/local/bin/mono
+parameters may be used, like mono -verbose"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defcustom org-babel-vbnet-compiler "vbnc"
+ "Name of the VB.Net compiler.
+May be either a command in the path, like vbnc
+or an absolute path name, like /usr/local/bin/vbnc
+parameters may be used, like vbnc /warnaserror+"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defun org-babel-execute:vbnet (body params)
+ (let* ((full-body (org-babel-expand-body:generic body params))
+ (cmpflag (or (cdr (assq :cmpflag params)) ""))
+ (cmdline (or (cdr (assq :cmdline params)) ""))
+ (src-file (org-babel-temp-file "vbnet-src-" ".vb"))
+ (exe-file (concat (file-name-sans-extension src-file) ".exe"))
+ (compile
+ (progn (with-temp-file src-file (insert full-body))
+ (org-babel-eval
+ (concat org-babel-vbnet-compiler " " cmpflag " " src-file)
+ ""))))
+ (let ((results (org-babel-eval (concat org-babel-vbnet-command " " cmdline " " exe-file) "")))
+ (org-babel-reassemble-table
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (org-babel-read results)
+ (let ((tmp-file (org-babel-temp-file "c-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(defun org-babel-prep-session:vbnet (session params)
+ "Return an error because vbnet does not support sessions."
+ (error "Sessions are not supported for VB.Net"))
+
+(provide 'ob-vbnet)
+
+
+
+;;; ob-vbnet.el ends here
diff --git a/contrib/lisp/org-annotate-file.el b/contrib/lisp/org-annotate-file.el
new file mode 100644
index 0000000..b8e8bd9
--- /dev/null
+++ b/contrib/lisp/org-annotate-file.el
@@ -0,0 +1,157 @@
+;;; org-annotate-file.el --- Annotate a file with org syntax
+
+;; Copyright (C) 2008-2014 Philip Jackson
+
+;; Author: Philip Jackson <phil@shellarchive.co.uk>
+;; Version: 0.2
+
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING. If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+
+;; This is yet another implementation to allow the annotation of a
+;; file without modification of the file itself. The annotation is in
+;; org syntax so you can use all of the org features you are used to.
+
+;; To use you might put the following in your .emacs:
+;;
+;; (require 'org-annotate-file)
+;; (global-set-key (kbd "C-c C-l") 'org-annotate-file) ; for example
+;;
+;; To change the location of the annotation file:
+;;
+;; (setq org-annotate-file-storage-file "~/annotated.org")
+;;
+;; Then when you visit any file and hit C-c C-l you will find yourself
+;; in an org buffer on a headline which links to the file you were
+;; visiting, e.g:
+
+;; * ~/org-annotate-file.el
+
+;; Under here you can put anything you like, save the file
+;; and next time you hit C-c C-l you will hit those notes again.
+;;
+;; To put a subheading with a text search for the current line set
+;; `org-annotate-file-add-search` to non-nil value. Then when you hit
+;; C-c C-l (on the above line for example) you will get:
+
+;; * ~/org-annotate-file.el
+;; ** `org-annotate-file-add-search` to non-nil value. Then whe...
+
+;; Note that both of the above will be links.
+
+;;; Code:
+
+(require 'org)
+
+(defgroup org-annotate-file nil
+ "Org Annotate"
+ :group 'org)
+
+(defcustom org-annotate-file-storage-file "~/.org-annotate-file.org"
+ "File in which to keep annotations."
+ :group 'org-annotate-file
+ :type 'file)
+
+(defcustom org-annotate-file-add-search nil
+ "If non-nil, add a link as a second level to the actual file location."
+ :group 'org-annotate-file
+ :type 'boolean)
+
+(defcustom org-annotate-file-always-open t
+ "If non-nil, always expand the full tree when visiting the annotation file."
+ :group 'org-annotate-file
+ :type 'boolean)
+
+(defun org-annotate-file-ellipsify-desc (string &optional after)
+ "Return shortened STRING with appended ellipsis.
+Trim whitespace at beginning and end of STRING and replace any
+ characters that appear after the occurrence of AFTER with '...'"
+ (let* ((after (number-to-string (or after 30)))
+ (replace-map (list (cons "^[ \t]*" "")
+ (cons "[ \t]*$" "")
+ (cons (concat "^\\(.\\{" after
+ "\\}\\).*") "\\1..."))))
+ (mapc (lambda (x)
+ (when (string-match (car x) string)
+ (setq string (replace-match (cdr x) nil nil string))))
+ replace-map)
+ string))
+
+;;;###autoload
+(defun org-annotate-file ()
+ "Visit `org-annotate-file-storage-file` and add a new annotation section.
+The annotation is opened at the new section which will be referencing
+the point in the current file."
+ (interactive)
+ (unless (buffer-file-name)
+ (error "This buffer has no associated file!"))
+ (switch-to-buffer
+ (org-annotate-file-show-section org-annotate-file-storage-file)))
+
+;;;###autoload
+(defun org-annotate-file-show-section (storage-file &optional annotated-buffer)
+ "Add or show annotation entry in STORAGE-FILE and return the buffer.
+The annotation will link to ANNOTATED-BUFFER if specified,
+ otherwise the current buffer is used."
+ (let ((filename (abbreviate-file-name (or annotated-buffer
+ (buffer-file-name))))
+ (line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
+ (annotation-buffer (find-file-noselect storage-file)))
+ (with-current-buffer annotation-buffer
+ (org-annotate-file-annotate filename line))
+ annotation-buffer))
+
+(defun org-annotate-file-annotate (filename line)
+ "Add annotation for FILENAME at LINE using current buffer."
+ (let* ((link (org-make-link-string (concat "file:" filename) filename))
+ (search-link (org-make-link-string
+ (concat "file:" filename "::" line)
+ (org-annotate-file-ellipsify-desc line))))
+ (unless (eq major-mode 'org-mode)
+ (org-mode))
+ (goto-char (point-min))
+ (widen)
+ (when org-annotate-file-always-open
+ (show-all))
+ (unless (search-forward-regexp
+ (concat "^* " (regexp-quote link)) nil t)
+ (org-annotate-file-add-upper-level link))
+ (beginning-of-line)
+ (org-narrow-to-subtree)
+ ;; deal with a '::' search if need be
+ (when org-annotate-file-add-search
+ (unless (search-forward-regexp
+ (concat "^** " (regexp-quote search-link)) nil t)
+ (org-annotate-file-add-second-level search-link)))))
+
+(defun org-annotate-file-add-upper-level (link)
+ "Add and link heading to LINK."
+ (goto-char (point-min))
+ (call-interactively 'org-insert-heading)
+ (insert link))
+
+(defun org-annotate-file-add-second-level (link)
+ "Add and link subheading to LINK."
+ (goto-char (point-at-eol))
+ (call-interactively 'org-insert-subheading)
+ (insert link))
+
+(provide 'org-annotate-file)
+
+;;; org-annotate-file.el ends here
diff --git a/contrib/lisp/org-bibtex-extras.el b/contrib/lisp/org-bibtex-extras.el
new file mode 100644
index 0000000..c5b521a
--- /dev/null
+++ b/contrib/lisp/org-bibtex-extras.el
@@ -0,0 +1,137 @@
+;;; org-bibtex-extras --- extras for working with org-bibtex entries
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte <eric dot schulte at gmx dot com>
+;; Keywords: outlines, hypermedia, bibtex, d3
+;; Homepage: http://orgmode.org
+;; Version: 0.01
+
+;; This file is not yet part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Warning: This should certainly be considered EXPERIMENTAL and still
+;; in development, feedback is welcome, but don't expect it
+;; to work.
+
+;; This file add some extra functionality to your bibtex entries which
+;; are stored as Org-mode headlines using org-bibtex.el. Most
+;; features expect that you keep all of your reading notes in a single
+;; file, set the `obe-bibtex-file' variable to the path to this file.
+;;
+;; - d3 view :: d3 is a Javascript library which supports interactive
+;; display of graphs. To view your citations as a d3
+;; graph, execute the following which will create a .json
+;; export of your references file, then grab a copy of
+;; d3, edit examples/force/force.js to replace
+;;
+;; var source`"miserables.json";
+;;
+;; with
+;;
+;; var source`"your-references.json";
+;;
+;; then view examples/force/force.html in your browser.
+;;
+;; - HTML export :: Customize the `obe-html-link-base' variable so
+;; that it points to an html export of your
+;; references, then add the following to your html
+;; export hook, and citations will be resolved during
+;; html export.
+;;
+;; (add-hook 'org-export-first-hook
+;; (lambda ()
+;; (when (equal org-export-current-backend 'html)
+;; (obe-html-export-citations))))
+
+;;; Code:
+(require 'org-bibtex)
+
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defcustom obe-bibtex-file nil "File holding bibtex entries.")
+
+(defcustom obe-html-link-base nil
+ "Base of citation links.
+For example, to point to your `obe-bibtex-file' use the following.
+
+ (setq obe-html-link-base (format \"file:%s\" obe-bibtex-file))
+")
+
+(defvar obe-citations nil)
+(defun obe-citations ()
+ "Return all citations from `obe-bibtex-file'."
+ (or obe-citations
+ (save-window-excursion
+ (find-file (or obe-bibtex-file
+ (error "`obe-bibtex-file' has not been configured")))
+ (goto-char (point-min))
+ (while (re-search-forward " :CUSTOM_ID: \\(.+\\)$" nil t)
+ (push (org-no-properties (match-string 1))
+ obe-citations))
+ obe-citations)))
+
+(defun obe-html-export-citations ()
+ "Convert all \\cite{...} citations in the current file into HTML links."
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "\\\\cite{\\([^\000}]+\\)}" nil t)
+ (replace-match
+ (save-match-data
+ (mapconcat (lambda (c) (format "[[%s#%s][%s]]" obe-html-link-base c c))
+ (mapcar #'org-trim
+ (split-string (match-string 1) ",")) ", "))))))
+
+(defun obe-meta-to-json (meta &optional fields)
+ "Turn a list of META data from citations into a string of json."
+ (let ((counter 1) nodes links)
+ (flet ((id (it) (position it nodes :test #'string= :key #'car))
+ (col (k) (mapcar (lambda (r) (cdr (assoc k r))) meta))
+ (add (lst)
+ (dolist (el lst) (push (cons el counter) nodes))
+ (incf counter)))
+ ;; build the nodes of the graph
+ (add (col :title))
+ (add (remove-if (lambda (author) (string-match "others" author))
+ (remove-duplicates (apply #'append (col :authors))
+ :test #'string=)))
+ (dolist (field fields)
+ (add (remove-duplicates (col field) :test #'string=)))
+ ;; build the links in the graph
+ (dolist (citation meta)
+ (let ((dest (id (cdr (assq :title citation)))))
+ (dolist (author (mapcar #'id (cdr (assq :authors citation))))
+ (when author (push (cons author dest) links)))
+ (let ((jid (id (cdr (assq :journal citation)))))
+ (when jid (push (cons jid dest) links)))
+ (let ((cid (id (cdr (assq :category citation)))))
+ (when cid (push (cons cid dest) links)))))
+ ;; build the json string
+ (format "{\"nodes\":[%s],\"links\":[%s]}"
+ (mapconcat
+ (lambda (pair)
+ (format "{\"name\":%S,\"group\":%d}"
+ (car pair) (cdr pair)))
+ nodes ",")
+ (mapconcat
+ (lambda (link)
+ (format "{\"source\":%d,\"target\":%d,\"value\":1}"
+ (car link) (cdr link)))
+ (meta-to-links meta nodes) ",")))))
+
+(provide 'org-bibtex-extras)
+;;; org-bibtex-extras ends here
diff --git a/contrib/lisp/org-bookmark.el b/contrib/lisp/org-bookmark.el
new file mode 100644
index 0000000..04a473b
--- /dev/null
+++ b/contrib/lisp/org-bookmark.el
@@ -0,0 +1,89 @@
+;;; org-bookmark.el - Support for links to bookmark
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Tokuya Kameshima <kames AT fa2.so-net.ne.jp>
+;; Version: 1.0
+;; Keywords: outlines, hypermedia, calendar, wp
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; Emacs is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(require 'org)
+(require 'bookmark)
+
+(defgroup org-bookmark nil
+ "Options concerning the bookmark link."
+ :tag "Org Startup"
+ :group 'org-link)
+
+(defcustom org-bookmark-in-dired nil
+ "Use org-bookmark in dired."
+ :group 'org-bookmark
+ :type 'boolean)
+
+(defcustom org-bookmark-when-visiting-a-file nil
+ "Use org-bookmark in any buffer visiting a file."
+ :group 'org-bookmark
+ :type 'boolean)
+
+(defcustom org-bookmark-use-first-bookmark nil
+ "If several bookmarks links to the buffer, take the first one.
+Otherwise prompt the user for the right bookmark to use."
+ :group 'org-bookmark
+ :type 'boolean)
+
+(org-link-set-parameters "bookmark"
+ :follow #'org-bookmark-open
+ :store #'org-bookmark-store-link)
+
+(defun org-bookmark-open (bookmark)
+ "Visit the bookmark BOOKMARK."
+ (bookmark-jump bookmark))
+
+(defun org-bookmark-store-link ()
+ "Store a link to the current line's bookmark in bookmark list."
+ (let (file bookmark bmks)
+ (cond ((and org-bookmark-in-dired
+ (eq major-mode 'dired-mode))
+ (setq file (abbreviate-file-name (dired-get-filename))))
+ ((and org-bookmark-when-visiting-a-file
+ (buffer-file-name (buffer-base-buffer)))
+ (setq file (abbreviate-file-name
+ (buffer-file-name (buffer-base-buffer))))))
+ (if (not file)
+ (when (eq major-mode 'bookmark-bmenu-mode)
+ (setq bookmark (bookmark-bmenu-bookmark)))
+ (when (and (setq bmks
+ (mapcar (lambda (name)
+ (if (equal file
+ (abbreviate-file-name
+ (bookmark-location name)))
+ name))
+ (bookmark-all-names)))
+ (setq bmks (delete nil bmks)))
+ (setq bookmark
+ (if (or (eq 1 (length bmks)) org-bookmark-use-first-bookmark)
+ (car bmks)
+ (completing-read "Bookmark: " bmks nil t nil nil (car bmks))))))
+ (if bookmark
+ (org-store-link-props :link (concat "bookmark:" bookmark)
+ :description bookmark))))
+
+(provide 'org-bookmark)
+
+;;; org-bookmark.el ends here
diff --git a/contrib/lisp/org-bullets.el b/contrib/lisp/org-bullets.el
new file mode 100644
index 0000000..2951bf8
--- /dev/null
+++ b/contrib/lisp/org-bullets.el
@@ -0,0 +1,122 @@
+;;; org-bullets.el --- Show bullets in org-mode as UTF-8 characters
+;; Version: 0.2.2
+;; Author: sabof
+;; URL: https://github.com/sabof/org-bullets
+
+;; This file is NOT part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 3, or (at
+;; your option) any later version.
+;;
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING. If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+
+;; The project is hosted at https://github.com/sabof/org-bullets
+;; The latest version, and all the relevant information can be found there.
+
+;;; Code:
+
+(eval-when-compile (require 'cl))
+
+(defgroup org-bullets nil
+ "Display bullets as UTF-8 characters."
+ :group 'org-appearance)
+
+;; A nice collection of unicode bullets:
+;; http://nadeausoftware.com/articles/2007/11/latency_friendly_customized_bullets_using_unicode_characters
+(defcustom org-bullets-bullet-list
+ '(;;; Large
+ "◉"
+ "○"
+ "✸"
+ "✿"
+ ;; ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ☢ ❀ ◆ ◖ ▶
+ ;;; Small
+ ;; ► • ★ ▸
+ )
+ "This variable contains the list of bullets.
+It can contain any number of one-character strings.
+For levels beyond the size of the list, the stars will be
+displayed using the first items again."
+ :group 'org-bullets
+ :type '(repeat (string :tag "Bullet character")))
+
+(defcustom org-bullets-face-name nil
+ "Allows to override `org-mode' bullets face.
+If set to a name of a face, that face will be used.
+Otherwise the face of the heading level will be used."
+ :group 'org-bullets
+ :type 'symbol)
+
+(defvar org-bullets-bullet-map
+ '(keymap
+ (mouse-1 . org-cycle)
+ (mouse-2 . (lambda (e)
+ (interactive "e")
+ (mouse-set-point e)
+ (org-cycle))))
+ "Mouse events for bullets.
+If this is undesirable, one can remove them with
+
+\(setcdr org-bullets-bullet-map nil\)")
+
+(defun org-bullets-level-char (level)
+ "Return a character corresponding to LEVEL."
+ (string-to-char
+ (nth (mod (1- level)
+ (length org-bullets-bullet-list))
+ org-bullets-bullet-list)))
+
+;;;###autoload
+(define-minor-mode org-bullets-mode
+ "UTF-8 bullets for `org-mode'."
+ nil nil nil
+ (let* ((keyword
+ `((,org-outline-regexp-bol
+ (0 (let (( level (- (match-end 0) (match-beginning 0) 1)))
+ (compose-region (- (match-end 0) 2)
+ (- (match-end 0) 1)
+ (org-bullets-level-char level))
+ (when (facep org-bullets-face-name)
+ (put-text-property (- (match-end 0) 2)
+ (- (match-end 0) 1)
+ 'face
+ org-bullets-face-name))
+ (put-text-property (match-beginning 0)
+ (- (match-end 0) 2)
+ 'face (list :foreground
+ (face-attribute
+ 'default :background)))
+ (put-text-property (match-beginning 0)
+ (match-end 0)
+ 'keymap
+ org-bullets-bullet-map)
+ nil))))))
+ (if org-bullets-mode
+ (progn (font-lock-add-keywords nil keyword)
+ (font-lock-fontify-buffer))
+ (save-excursion
+ (goto-char (point-min))
+ (font-lock-remove-keywords nil keyword)
+ (while (re-search-forward org-outline-regexp-bol nil t)
+ (decompose-region (match-beginning 0) (match-end 0)))
+ (font-lock-fontify-buffer)))))
+
+(provide 'org-bullets)
+
+;; Local Variables:
+;; coding: utf-8-emacs
+;; End:
+
+;;; org-bullets.el ends here
diff --git a/contrib/lisp/org-checklist.el b/contrib/lisp/org-checklist.el
new file mode 100644
index 0000000..2bc00c0
--- /dev/null
+++ b/contrib/lisp/org-checklist.el
@@ -0,0 +1,141 @@
+;;; org-checklist.el --- org functions for checklist handling
+
+;; Copyright (C) 2008-2014 James TD Smith
+
+;; Author: James TD Smith (@ ahktenzero (. mohorovi cc))
+;; Version: 1.0
+;; Keywords: org, checklists
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file provides some functions for handing repeated tasks which involve
+;; checking off a list of items. By setting the RESET_CHECK_BOXES property in an
+;; item, when the TODO state is set to done all checkboxes under that item are
+;; cleared. If the LIST_EXPORT_BASENAME property is set, a file will be created
+;; using the value of that property plus a timestamp, containing all the items
+;; in the list which are not checked. Additionally the user will be prompted to
+;; print the list.
+;;
+;; I use this for to keep track of stores of various things (food stores,
+;; components etc) which I check periodically and use the exported list of items
+;; which are not present as a shopping list.
+;;
+;;; Usage:
+;; (require 'org-checklist)
+;;
+;; Set the RESET_CHECK_BOXES and LIST_EXPORT_BASENAME properties in items as
+;; needed.
+;;
+;;; Code:
+(require 'org)
+(load "a2ps-print" 'no-error)
+
+(setq org-default-properties (cons "RESET_CHECK_BOXES" (cons "LIST_EXPORT_BASENAME" org-default-properties)))
+
+(defgroup org-checklist nil
+ "Extended checklist handling for org"
+ :tag "Org-checklist"
+ :group 'org)
+
+(defcustom org-checklist-export-time-format "%Y%m%d%H%M"
+ "The format of timestamp appended to LIST_EXPORT_BASENAME to
+ make the name of the export file."
+ :link '(function-link format-time-string)
+ :group 'org-checklist
+ :type 'string)
+
+(defcustom org-checklist-export-function 'org-export-as-ascii
+ "function used to prepare the export file for printing"
+ :group 'org-checklist
+ :type '(radio (function-item :tag "ascii text" org-export-as-ascii)
+ (function-item :tag "HTML" org-export-as-html)
+ (function-item :tag "LaTeX" :value org-export-as-latex)
+ (function-item :tag "XOXO" :value org-export-as-xoxo)))
+
+(defcustom org-checklist-export-params nil
+ "options for the export function file for printing"
+ :group 'org-checklist
+ :type '(repeat string))
+
+(defcustom org-checklist-a2ps-params nil
+ "options for a2ps for printing"
+ :group 'org-checklist
+ :type '(repeat string))
+
+(defun org-reset-checkbox-state-maybe ()
+ "Reset all checkboxes in an entry if the `RESET_CHECK_BOXES' property is set"
+ (interactive "*")
+ (if (org-entry-get (point) "RESET_CHECK_BOXES")
+ (org-reset-checkbox-state-subtree)))
+
+
+(defun org-make-checklist-export ()
+ "Produce a checklist containing all unchecked items from a list
+of checkbox items"
+ (interactive "*")
+ (if (org-entry-get (point) "LIST_EXPORT_BASENAME")
+ (let* ((export-file (concat (org-entry-get (point) "LIST_EXPORT_BASENAME" nil)
+ "-" (format-time-string
+ org-checklist-export-time-format)
+ ".org"))
+ (print (case (org-entry-get (point) "PRINT_EXPORT" nil)
+ (("" "nil" nil) nil)
+ (t t)
+ (nil (y-or-n-p "Print list? "))))
+ exported-lines
+ (title "Checklist export"))
+ (save-restriction
+ (save-excursion
+ (org-narrow-to-subtree)
+ (org-update-checkbox-count-maybe)
+ (org-show-subtree)
+ (goto-char (point-min))
+ (when (looking-at org-complex-heading-regexp)
+ (setq title (match-string 4)))
+ (goto-char (point-min))
+ (let ((end (point-max)))
+ (while (< (point) end)
+ (when (and (org-at-item-checkbox-p)
+ (or (string= (match-string 0) "[ ]")
+ (string= (match-string 0) "[-]")))
+ (add-to-list 'exported-lines (thing-at-point 'line) t))
+ (beginning-of-line 2)))
+ (set-buffer (get-buffer-create export-file))
+ (org-insert-heading)
+ (insert (or title export-file) "\n")
+ (dolist (entry exported-lines) (insert entry))
+ (org-update-checkbox-count-maybe)
+ (write-file export-file)
+ (if (print)
+ (progn (funcall org-checklist-export-function
+ org-checklist-export-params)
+ (let* ((current-a2ps-switches a2ps-switches)
+ (a2ps-switches (append current-a2ps-switches
+ org-checklist-a2ps-params)))
+ (a2ps-buffer)))))))))
+
+(defun org-checklist ()
+ (when (member org-state org-done-keywords) ;; org-state dynamically bound in org.el/org-todo
+ (org-make-checklist-export)
+ (org-reset-checkbox-state-maybe)))
+
+(add-hook 'org-after-todo-state-change-hook 'org-checklist)
+
+(provide 'org-checklist)
+
+;;; org-checklist.el ends here
diff --git a/contrib/lisp/org-choose.el b/contrib/lisp/org-choose.el
new file mode 100644
index 0000000..c1006d0
--- /dev/null
+++ b/contrib/lisp/org-choose.el
@@ -0,0 +1,496 @@
+;;; org-choose.el --- decision management for org-mode
+
+;; Copyright (C) 2009-2014 Tom Breton (Tehom)
+
+;; This file is not part of GNU Emacs.
+
+;; Author: Tom Breton (Tehom)
+;; Keywords: outlines, convenience
+
+;; This file is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 2, or (at your option)
+;; any later version.
+
+;; This file is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+
+;; This is code to support decision management. It lets you treat a
+;; group of sibling items in org-mode as alternatives in a decision.
+
+;; There are no user commands in this file. You use it by:
+;; * Loading it (manually or by M-x customize-apropos org-modules)
+
+;; * Setting up at least one set of TODO keywords with the
+;; interpretation "choose" by either:
+
+;; * Using the file directive #+CHOOSE_TODO:
+
+;; * For instance, "#+CHOOSE_TODO: NO(,-) MAYBE(,0) YES"
+
+;; * Or by M-x customize-apropos org-todo-keywords
+
+;; * Operating on single items with the TODO commands.
+
+;; * Use C-S-right to change the keyword set. Use this to change to
+;; the "choose" keyword set that you just defined.
+
+;; * Use S-right to advance the TODO mark to the next setting.
+
+;; For "choose", that means you like this alternative more than
+;; before. Other alternatives will be automatically demoted to
+;; keep your settings consistent.
+
+;; * Use S-left to demote TODO to the previous setting.
+
+;; For "choose", that means you don't like this alternative as much
+;; as before. Other alternatives will be automatically promoted,
+;; if this item was all that was keeping them down.
+
+;; * All the other TODO commands are available and behave essentially
+;; the normal way.
+
+;;; Requires
+
+(require 'org)
+ ;(eval-when-compile
+ ; (require 'cl))
+(require 'cl)
+
+;;; Body
+;;; The variables
+
+(defstruct (org-choose-mark-data. (:type list))
+ "The format of an entry in org-choose-mark-data.
+Indexes are 0-based or `nil'.
+"
+ keyword
+ bot-lower-range
+ top-upper-range
+ range-length
+ static-default
+ all-keywords)
+
+(defvar org-choose-mark-data
+ ()
+ "Alist of information for choose marks.
+
+Each entry is an `org-choose-mark-data.'" )
+(make-variable-buffer-local 'org-choose-mark-data)
+;;;_ , For setup
+;;;_ . org-choose-filter-one
+
+(defun org-choose-filter-one (i)
+ "Return a list of
+ * a canonized version of the string
+ * optionally one symbol"
+
+ (if
+ (not
+ (string-match "(.*)" i))
+ (list i i)
+ (let*
+ (
+ (end-text (match-beginning 0))
+ (vanilla-text (substring i 0 end-text))
+ ;;Get the parenthesized part.
+ (match (match-string 0 i))
+ ;;Remove the parentheses.
+ (args (substring match 1 -1))
+ ;;Split it
+ (arglist
+ (let
+ ((arglist-x (org-split-string args ",")))
+ ;;When string starts with "," `split-string' doesn't
+ ;;make a first arg, so in that case make one
+ ;;manually.
+ (if
+ (string-match "^," args)
+ (cons nil arglist-x)
+ arglist-x)))
+ (decision-arg (second arglist))
+ (type
+ (cond
+ ((string= decision-arg "0")
+ 'default-mark)
+ ((string= decision-arg "+")
+ 'top-upper-range)
+ ((string= decision-arg "-")
+ 'bot-lower-range)
+ (t nil)))
+ (vanilla-arg (first arglist))
+ (vanilla-mark
+ (if vanilla-arg
+ (concat vanilla-text "("vanilla-arg")")
+ vanilla-text)))
+ (if type
+ (list vanilla-text vanilla-mark type)
+ (list vanilla-text vanilla-mark)))))
+
+;;;_ . org-choose-setup-vars
+(defun org-choose-setup-vars (bot-lower-range top-upper-range
+ static-default num-items all-mark-texts)
+ "Add to org-choose-mark-data according to arguments"
+ (let*
+ ((tail
+ ;;If there's no bot-lower-range or no default, we don't
+ ;;have ranges.
+ (cdr
+ (if (and static-default bot-lower-range)
+ (let*
+ ;;If there's no top-upper-range, use the last
+ ;;item.
+ ((top-upper-range
+ (or top-upper-range (1- num-items)))
+ (lower-range-length
+ (1+ (- static-default bot-lower-range)))
+ (upper-range-length
+ (- top-upper-range static-default))
+ (range-length
+ (min upper-range-length lower-range-length)))
+ (make-org-choose-mark-data.
+ :keyword nil
+ :bot-lower-range bot-lower-range
+ :top-upper-range top-upper-range
+ :range-length range-length
+ :static-default static-default
+ :all-keywords all-mark-texts))
+ (make-org-choose-mark-data.
+ :keyword nil
+ :bot-lower-range nil
+ :top-upper-range nil
+ :range-length nil
+ :static-default (or static-default 0)
+ :all-keywords all-mark-texts)))))
+ (dolist (text all-mark-texts)
+ (pushnew (cons text tail)
+ org-choose-mark-data
+ :test
+ #'(lambda (a b)
+ (equal (car a) (car b)))))))
+
+;;; org-choose-filter-tail
+(defun org-choose-filter-tail (raw)
+ "Return a translation of RAW to vanilla and set appropriate
+buffer-local variables.
+
+RAW is a list of strings representing the input text of a choose
+interpretation."
+ (let
+ ((vanilla-list nil)
+ (all-mark-texts nil)
+ (index 0)
+ bot-lower-range top-upper-range range-length static-default)
+ (dolist (i raw)
+ (destructuring-bind
+ (vanilla-text vanilla-mark &optional type)
+ (org-choose-filter-one i)
+ (cond
+ ((eq type 'bot-lower-range)
+ (setq bot-lower-range index))
+ ((eq type 'top-upper-range)
+ (setq top-upper-range index))
+ ((eq type 'default-mark)
+ (setq static-default index)))
+ (incf index)
+ (push vanilla-text all-mark-texts)
+ (push vanilla-mark vanilla-list)))
+
+ (org-choose-setup-vars bot-lower-range top-upper-range
+ static-default index (reverse all-mark-texts))
+ (nreverse vanilla-list)))
+
+;;; org-choose-setup-filter
+
+(defun org-choose-setup-filter (raw)
+ "A setup filter for choose interpretations."
+ (when (eq (car raw) 'choose)
+ (cons
+ 'choose
+ (org-choose-filter-tail (cdr raw)))))
+
+;;; org-choose-conform-after-promotion
+(defun org-choose-conform-after-promotion (entry-pos keywords highest-ok-ix)
+ "Conform the current item after another item was promoted"
+ (unless
+ ;;Skip the entry that triggered this by skipping any entry with
+ ;;the same starting position. plist uses the start of the
+ ;;header line as the position, but map no longer does, so we
+ ;;have to go back to the heading.
+ (=
+ (save-excursion
+ (org-back-to-heading)
+ (point))
+ entry-pos)
+ (let
+ ((ix
+ (org-choose-get-entry-index keywords)))
+ ;;If the index of the entry exceeds the highest allowable
+ ;;index, change it to that.
+ (when (and ix
+ (> ix highest-ok-ix))
+ (org-todo
+ (nth highest-ok-ix keywords))))))
+;;;_ . org-choose-conform-after-demotion
+(defun org-choose-conform-after-demotion (entry-pos keywords
+ raise-to-ix
+ old-highest-ok-ix)
+ "Conform the current item after another item was demoted."
+ (unless
+ ;;Skip the entry that triggered this.
+ (=
+ (save-excursion
+ (org-back-to-heading)
+ (point))
+ entry-pos)
+ (let
+ ((ix
+ (org-choose-get-entry-index keywords)))
+ ;;If the index of the entry was at or above the old allowable
+ ;;position, change it to the new mirror position if there is
+ ;;one.
+ (when (and
+ ix
+ raise-to-ix
+ (>= ix old-highest-ok-ix))
+ (org-todo
+ (nth raise-to-ix keywords))))))
+
+;;; org-choose-keep-sensible (the org-trigger-hook function)
+(defun org-choose-keep-sensible (change-plist)
+ "Bring the other items back into a sensible state after an item's
+setting was changed."
+ (let*
+ ( (from (plist-get change-plist :from))
+ (to (plist-get change-plist :to))
+ (entry-pos
+ (set-marker
+ (make-marker)
+ (plist-get change-plist :position)))
+ (kwd-data
+ (assoc to org-todo-kwd-alist)))
+ (when
+ (eq (nth 1 kwd-data) 'choose)
+ (let*
+ (
+ (data
+ (assoc to org-choose-mark-data))
+ (keywords
+ (org-choose-mark-data.-all-keywords data))
+ (old-index
+ (org-choose-get-index-in-keywords
+ from
+ keywords))
+ (new-index
+ (org-choose-get-index-in-keywords
+ to
+ keywords))
+ (highest-ok-ix
+ (org-choose-highest-other-ok
+ new-index
+ data))
+ (funcdata
+ (cond
+ ;;The entry doesn't participate in conformance,
+ ;;so give `nil' which does nothing.
+ ((not highest-ok-ix) nil)
+ ;;The entry was created or promoted
+ ((or
+ (not old-index)
+ (> new-index old-index))
+ (list
+ #'org-choose-conform-after-promotion
+ entry-pos keywords
+ highest-ok-ix))
+ (t ;;Otherwise the entry was demoted.
+ (let
+ (
+ (raise-to-ix
+ (min
+ highest-ok-ix
+ (org-choose-mark-data.-static-default
+ data)))
+ (old-highest-ok-ix
+ (org-choose-highest-other-ok
+ old-index
+ data)))
+ (list
+ #'org-choose-conform-after-demotion
+ entry-pos
+ keywords
+ raise-to-ix
+ old-highest-ok-ix))))))
+ (if funcdata
+ ;;The funny-looking names are to make variable capture
+ ;;unlikely. (Poor-man's lexical bindings).
+ (destructuring-bind (func-d473 . args-46k) funcdata
+ (let
+ ((map-over-entries
+ (org-choose-get-fn-map-group))
+ ;;We may call `org-todo', so let various hooks
+ ;;`nil' so we don't cause loops.
+ org-after-todo-state-change-hook
+ org-trigger-hook
+ org-blocker-hook
+ org-todo-get-default-hook
+ ;;Also let this alist `nil' so we don't log
+ ;;secondary transitions.
+ org-todo-log-states)
+ ;;Map over group
+ (funcall map-over-entries
+ #'(lambda ()
+ (apply func-d473 args-46k))))))))
+ ;;Remove the marker
+ (set-marker entry-pos nil)))
+
+;;; Getting the default mark
+;;; org-choose-get-index-in-keywords
+(defun org-choose-get-index-in-keywords (ix all-keywords)
+ "Return the index of the current entry."
+ (if ix
+ (position ix all-keywords
+ :test #'equal)))
+
+;;; org-choose-get-entry-index
+(defun org-choose-get-entry-index (all-keywords)
+ "Return index of current entry."
+ (let*
+ ((state (org-entry-get (point) "TODO")))
+ (org-choose-get-index-in-keywords state all-keywords)))
+
+;;; org-choose-get-fn-map-group
+
+(defun org-choose-get-fn-map-group ()
+ "Return a function to map over the group"
+ #'(lambda (fn)
+ (require 'org-agenda) ;; `org-map-entries' seems to need it.
+ (save-excursion
+ (unless (org-up-heading-safe)
+ (error "Choosing is only supported between siblings in a tree, not on top level"))
+ (let
+ ((level (org-reduced-level (org-outline-level))))
+ (save-restriction
+ (org-map-entries
+ fn
+ (format "LEVEL=%d" level)
+ 'tree))))))
+
+;;; org-choose-get-highest-mark-index
+
+(defun org-choose-get-highest-mark-index (keywords)
+ "Get the index of the highest current mark in the group.
+If there is none, return 0"
+ (let*
+ ;;Func maps over applicable entries.
+ ((map-over-entries
+ (org-choose-get-fn-map-group))
+ (indexes-list
+ (remove nil
+ (funcall map-over-entries
+ #'(lambda ()
+ (org-choose-get-entry-index keywords))))))
+ (if
+ indexes-list
+ (apply #'max indexes-list)
+ 0)))
+
+;;; org-choose-highest-ok
+
+(defun org-choose-highest-other-ok (ix data)
+ "Return the highest index that any choose mark can sensibly have,
+given that another mark has index IX.
+DATA must be a `org-choose-mark-data.'."
+ (let
+ ((bot-lower-range
+ (org-choose-mark-data.-bot-lower-range data))
+ (top-upper-range
+ (org-choose-mark-data.-top-upper-range data))
+ (range-length
+ (org-choose-mark-data.-range-length data)))
+ (when (and ix bot-lower-range)
+ (let*
+ ((delta
+ (- top-upper-range ix)))
+ (unless
+ (< range-length delta)
+ (+ bot-lower-range delta))))))
+
+;;; org-choose-get-default-mark-index
+
+(defun org-choose-get-default-mark-index (data)
+ "Return the index of the default mark in a choose interpretation.
+
+DATA must be a `org-choose-mark-data.'."
+ (or
+ (let
+ ((highest-mark-index
+ (org-choose-get-highest-mark-index
+ (org-choose-mark-data.-all-keywords data))))
+ (org-choose-highest-other-ok
+ highest-mark-index data))
+ (org-choose-mark-data.-static-default data)))
+
+;;; org-choose-get-mark-N
+(defun org-choose-get-mark-N (n data)
+ "Get the text of the nth mark in a choose interpretation."
+
+ (let*
+ ((l (org-choose-mark-data.-all-keywords data)))
+ (nth n l)))
+
+;;; org-choose-get-default-mark
+
+(defun org-choose-get-default-mark (new-mark old-mark)
+ "Get the default mark IFF in a choose interpretation.
+NEW-MARK and OLD-MARK are the text of the new and old marks."
+ (let*
+ ((old-kwd-data
+ (assoc old-mark org-todo-kwd-alist))
+ (new-kwd-data
+ (assoc new-mark org-todo-kwd-alist))
+ (becomes-choose
+ (and
+ (or
+ (not old-kwd-data)
+ (not
+ (eq (nth 1 old-kwd-data) 'choose)))
+ (eq (nth 1 new-kwd-data) 'choose))))
+ (when
+ becomes-choose
+ (let
+ ((new-mark-data
+ (assoc new-mark org-choose-mark-data)))
+ (if
+ new-mark
+ (org-choose-get-mark-N
+ (org-choose-get-default-mark-index
+ new-mark-data)
+ new-mark-data)
+ (error "Somehow got an unrecognizable mark"))))))
+
+;;; Setting it all up
+
+(eval-after-load "org"
+ '(progn
+ (add-to-list 'org-todo-setup-filter-hook
+ #'org-choose-setup-filter)
+ (add-to-list 'org-todo-get-default-hook
+ #'org-choose-get-default-mark)
+ (add-to-list 'org-trigger-hook
+ #'org-choose-keep-sensible)
+ (add-to-list 'org-todo-interpretation-widgets
+ '(:tag "Choose (to record decisions)" choose)
+ 'append)))
+
+(provide 'org-choose)
+
+;;; org-choose.el ends here
diff --git a/contrib/lisp/org-collector.el b/contrib/lisp/org-collector.el
new file mode 100644
index 0000000..10ec0cb
--- /dev/null
+++ b/contrib/lisp/org-collector.el
@@ -0,0 +1,231 @@
+;;; org-collector --- collect properties into tables
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte <schulte dot eric at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp, experimentation,
+;; organization, properties
+;; Homepage: http://orgmode.org
+;; Version: 0.01
+
+;; This file is not yet part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Pass in an alist of columns, each column can be either a single
+;; property or a function which takes column names as arguments.
+;;
+;; For example the following propview block would collect the value of
+;; the 'amount' property from each header in the current buffer
+;;
+;; #+BEGIN: propview :cols (ITEM amount)
+;; | "ITEM" | "amount" |
+;; |---------------------+----------|
+;; | "December Spending" | 0 |
+;; | "Grocery Store" | 56.77 |
+;; | "Athletic club" | 75.0 |
+;; | "Restaurant" | 30.67 |
+;; | "January Spending" | 0 |
+;; | "Athletic club" | 75.0 |
+;; | "Restaurant" | 50.00 |
+;; |---------------------+----------|
+;; | | |
+;; #+END:
+;;
+;; This slightly more selective propview block will limit those
+;; headers included to those in the subtree with the id 'december'
+;; in which the spendtype property is equal to "food"
+;;
+;; #+BEGIN: propview :id "december" :conds ((string= spendtype "food")) :cols (ITEM amount)
+;; | "ITEM" | "amount" |
+;; |-----------------+----------|
+;; | "Grocery Store" | 56.77 |
+;; | "Restaurant" | 30.67 |
+;; |-----------------+----------|
+;; | | |
+;; #+END:
+;;
+;; Org Collector allows arbitrary processing of the property values
+;; through elisp in the cols: property. This allows for both simple
+;; computations as in the following example
+;;
+;; #+BEGIN: propview :id "results" :cols (ITEM f d list (apply '+ list) (+ f d))
+;; | "ITEM" | "f" | "d" | "list" | "(apply (quote +) list)" | "(+ f d)" |
+;; |--------+-----+-----+-------------------------+--------------------------+-----------|
+;; | "run1" | 2 | 33 | (quote (9 2 3 4 5 6 7)) | 36 | 35 |
+;; | "run2" | 2 | 34 | :na | :na | 36 |
+;; | "run3" | 2 | 35 | :na | :na | 37 |
+;; | "run4" | 2 | 36 | :na | :na | 38 |
+;; | | | | | | |
+;; #+END:
+;;
+;; or more complex computations as in the following example taken from
+;; an org file where each header in "results" subtree contained a
+;; property "sorted_hits" which was passed through the
+;; "average-precision" elisp function
+;;
+;; #+BEGIN: propview :id "results" :cols (ITEM (average-precision sorted_hits))
+;; | "ITEM" | "(average-precision sorted_hits)" |
+;; |-----------+-----------------------------------|
+;; | run (80) | 0.105092 |
+;; | run (70) | 0.108142 |
+;; | run (10) | 0.111348 |
+;; | run (60) | 0.113593 |
+;; | run (50) | 0.116446 |
+;; | run (100) | 0.118863 |
+;; #+END:
+;;
+
+;;; Code:
+(require 'org)
+(require 'org-table)
+
+(defvar org-propview-default-value 0
+ "Default value to insert into the propview table when the no
+value is calculated either through lack of required variables for
+a column, or through the generation of an error.")
+
+(defun and-rest (list)
+ (if (listp list)
+ (if (> (length list) 1)
+ (and (car list) (and-rest (cdr list)))
+ (car list))
+ list))
+
+(put 'org-collector-error
+ 'error-conditions
+ '(error column-prop-error org-collector-error))
+
+(defun org-dblock-write:propview (params)
+ "collect the column specification from the #+cols line
+preceeding the dblock, then update the contents of the dblock."
+ (interactive)
+ (condition-case er
+ (let ((cols (plist-get params :cols))
+ (inherit (plist-get params :inherit))
+ (conds (plist-get params :conds))
+ (match (plist-get params :match))
+ (scope (plist-get params :scope))
+ (noquote (plist-get params :noquote))
+ (colnames (plist-get params :colnames))
+ (defaultval (plist-get params :defaultval))
+ (content-lines (org-split-string (plist-get params :content) "\n"))
+ id table line pos)
+ (save-excursion
+ (when (setq id (plist-get params :id))
+ (cond ((not id) nil)
+ ((eq id 'global) (goto-char (point-min)))
+ ((eq id 'local) nil)
+ ((setq idpos (org-find-entry-with-id id))
+ (goto-char idpos))
+ (t (error "Cannot find entry with :ID: %s" id))))
+ (unless (eq id 'global) (org-narrow-to-subtree))
+ (setq stringformat (if noquote "%s" "%S"))
+ (let ((org-propview-default-value (if defaultval defaultval org-propview-default-value)))
+ (setq table (org-propview-to-table
+ (org-propview-collect cols stringformat conds match scope inherit
+ (if colnames colnames cols)) stringformat)))
+ (widen))
+ (setq pos (point))
+ (when content-lines
+ (while (string-match "^#" (car content-lines))
+ (insert (pop content-lines) "\n")))
+ (insert table) (insert "\n|--") (org-cycle) (move-end-of-line 1)
+ (message (format "point-%d" pos))
+ (while (setq line (pop content-lines))
+ (when (string-match "^#" line)
+ (insert "\n" line)))
+ (goto-char pos)
+ (org-table-recalculate 'all))
+ (org-collector-error (widen) (error "%s" er))
+ (error (widen) (error "%s" er))))
+
+(defun org-propview-eval-w-props (props body)
+ "evaluate the BODY-FORMS binding the variables using the
+variables and values specified in props"
+ (condition-case nil ;; catch any errors
+ (eval `(let ,(mapcar
+ (lambda (pair) (list (intern (car pair)) (cdr pair)))
+ props)
+ ,body))
+ (error nil)))
+
+(defun org-propview-get-with-inherited (&optional inherit)
+ (append
+ (org-entry-properties)
+ (delq nil
+ (mapcar (lambda (i)
+ (let* ((n (symbol-name i))
+ (p (org-entry-get (point) n 'do-inherit)))
+ (when p (cons n p))))
+ inherit))))
+
+(defun org-propview-collect (cols stringformat &optional conds match scope inherit colnames)
+ (interactive)
+ ;; collect the properties from every header
+ (let* ((header-props
+ (let ((org-trust-scanner-tags t) alst)
+ (org-map-entries
+ (quote (cons (cons "ITEM" (org-get-heading t))
+ (org-propview-get-with-inherited inherit)))
+ match scope)))
+ ;; read property values
+ (header-props
+ (mapcar (lambda (props)
+ (mapcar (lambda (pair)
+ (cons (car pair) (org-babel-read (cdr pair))))
+ props))
+ header-props))
+ ;; collect all property names
+ (prop-names
+ (mapcar 'intern (delete-dups
+ (apply 'append (mapcar (lambda (header)
+ (mapcar 'car header))
+ header-props))))))
+ (append
+ (list
+ (if colnames colnames (mapcar (lambda (el) (format stringformat el)) cols))
+ 'hline) ;; ------------------------------------------------
+ (mapcar ;; calculate the value of the column for each header
+ (lambda (props) (mapcar (lambda (col)
+ (let ((result (org-propview-eval-w-props props col)))
+ (if result result org-propview-default-value)))
+ cols))
+ (if conds
+ ;; eliminate the headers which don't satisfy the property
+ (delq nil
+ (mapcar
+ (lambda (props)
+ (if (and-rest (mapcar
+ (lambda (col)
+ (org-propview-eval-w-props props col))
+ conds))
+ props))
+ header-props))
+ header-props)))))
+
+(defun org-propview-to-table (results stringformat)
+ ;; (message (format "cols:%S" cols))
+ (orgtbl-to-orgtbl
+ (mapcar
+ (lambda (row)
+ (if (equal row 'hline)
+ 'hline
+ (mapcar (lambda (el) (format stringformat el)) row)))
+ (delq nil results)) '()))
+
+(provide 'org-collector)
+;;; org-collector ends here
diff --git a/contrib/lisp/org-contacts.el b/contrib/lisp/org-contacts.el
new file mode 100644
index 0000000..2cadd1d
--- /dev/null
+++ b/contrib/lisp/org-contacts.el
@@ -0,0 +1,1150 @@
+;;; org-contacts.el --- Contacts management
+
+;; Copyright (C) 2010-2014 Julien Danjou <julien@danjou.info>
+
+;; Author: Julien Danjou <julien@danjou.info>
+;; Keywords: outlines, hypermedia, calendar
+;;
+;; This file is NOT part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code for managing your contacts into Org-mode.
+
+;; To enter new contacts, you can use `org-capture' and a minimal template just like
+;; this:
+
+;; ("c" "Contacts" entry (file "~/Org/contacts.org")
+;; "* %(org-contacts-template-name)
+;; :PROPERTIES:
+;; :EMAIL: %(org-contacts-template-email)
+;; :END:")))
+;;
+;; You can also use a complex template, for example:
+;;
+;; ("c" "Contacts" entry (file "~/Org/contacts.org")
+;; "* %(org-contacts-template-name)
+;; :PROPERTIES:
+;; :EMAIL: %(org-contacts-template-email)
+;; :PHONE:
+;; :ALIAS:
+;; :NICKNAME:
+;; :IGNORE:
+;; :ICON:
+;; :NOTE:
+;; :ADDRESS:
+;; :BIRTHDAY:
+;; :END:")))
+;;
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+(require 'gnus-util)
+(require 'gnus-art)
+(require 'mail-utils)
+(require 'org-agenda)
+(require 'org-capture)
+
+(defgroup org-contacts nil
+ "Options about contacts management."
+ :group 'org)
+
+(defcustom org-contacts-files nil
+ "List of Org files to use as contacts source.
+When set to nil, all your Org files will be used."
+ :type '(repeat file)
+ :group 'org-contacts)
+
+(defcustom org-contacts-email-property "EMAIL"
+ "Name of the property for contact email address."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-tel-property "PHONE"
+ "Name of the property for contact phone number."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-address-property "ADDRESS"
+ "Name of the property for contact address."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-birthday-property "BIRTHDAY"
+ "Name of the property for contact birthday date."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-note-property "NOTE"
+ "Name of the property for contact note."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-alias-property "ALIAS"
+ "Name of the property for contact name alias."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-ignore-property "IGNORE"
+ "Name of the property, which values will be ignored when
+completing or exporting to vcard."
+ :type 'string
+ :group 'org-contacts)
+
+
+(defcustom org-contacts-birthday-format "Birthday: %l (%Y)"
+ "Format of the anniversary agenda entry.
+The following replacements are available:
+
+ %h - Heading name
+ %l - Link to the heading
+ %y - Number of year
+ %Y - Number of year (ordinal)"
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-last-read-mail-property "LAST_READ_MAIL"
+ "Name of the property for contact last read email link storage."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-icon-property "ICON"
+ "Name of the property for contact icon."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-nickname-property "NICKNAME"
+ "Name of the property for IRC nickname match."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-icon-size 32
+ "Size of the contacts icons."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-icon-use-gravatar (fboundp 'gravatar-retrieve)
+ "Whether use Gravatar to fetch contact icons."
+ :type 'boolean
+ :group 'org-contacts)
+
+(defcustom org-contacts-completion-ignore-case t
+ "Ignore case when completing contacts."
+ :type 'boolean
+ :group 'org-contacts)
+
+(defcustom org-contacts-group-prefix "+"
+ "Group prefix."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-tags-props-prefix "#"
+ "Tags and properties prefix."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-matcher
+ (mapconcat #'identity
+ (mapcar (lambda (x) (concat x "<>\"\""))
+ (list org-contacts-email-property
+ org-contacts-alias-property
+ org-contacts-tel-property
+ org-contacts-address-property
+ org-contacts-birthday-property))
+ "|")
+ "Matching rule for finding heading that are contacts.
+This can be a tag name, or a property check."
+ :type 'string
+ :group 'org-contacts)
+
+(defcustom org-contacts-email-link-description-format "%s (%d)"
+ "Format used to store links to email.
+This overrides `org-email-link-description-format' if set."
+ :group 'org-contacts
+ :type 'string)
+
+(defcustom org-contacts-vcard-file "contacts.vcf"
+ "Default file for vcard export."
+ :group 'org-contacts
+ :type 'file)
+
+(defcustom org-contacts-enable-completion t
+ "Enable or not the completion in `message-mode' with `org-contacts'."
+ :group 'org-contacts
+ :type 'boolean)
+
+(defcustom org-contacts-complete-functions
+ '(org-contacts-complete-group org-contacts-complete-tags-props org-contacts-complete-name)
+ "List of functions used to complete contacts in `message-mode'."
+ :group 'org-contacts
+ :type 'hook)
+
+;; Decalre external functions and variables
+(declare-function org-reverse-string "org")
+(declare-function diary-ordinal-suffix "ext:diary-lib")
+(declare-function wl-summary-message-number "ext:wl-summary")
+(declare-function wl-address-header-extract-address "ext:wl-address")
+(declare-function wl-address-header-extract-realname "ext:wl-address")
+(declare-function erc-buffer-list "ext:erc")
+(declare-function erc-get-channel-user-list "ext:erc")
+(declare-function google-maps-static-show "ext:google-maps-static")
+(declare-function elmo-message-field "ext:elmo-pipe")
+(declare-function std11-narrow-to-header "ext:std11")
+(declare-function std11-fetch-field "ext:std11")
+
+(defconst org-contacts-property-values-separators "[,; \f\t\n\r\v]+"
+ "The default value of separators for `org-contacts-split-property'.
+
+A regexp matching strings of whitespace, `,' and `;'.")
+
+(defvar org-contacts-keymap
+ (let ((map (make-sparse-keymap)))
+ (define-key map "M" 'org-contacts-view-send-email)
+ (define-key map "i" 'org-contacts-view-switch-to-irc-buffer)
+ map)
+ "The keymap used in `org-contacts' result list.")
+
+(defvar org-contacts-db nil
+ "Org Contacts database.")
+
+(defvar org-contacts-last-update nil
+ "Last time the Org Contacts database has been updated.")
+
+(defun org-contacts-files ()
+ "Return list of Org files to use for contact management."
+ (or org-contacts-files (org-agenda-files t 'ifmode)))
+
+(defun org-contacts-db-need-update-p ()
+ "Determine whether `org-contacts-db' needs to be refreshed."
+ (or (null org-contacts-last-update)
+ (cl-find-if (lambda (file)
+ (or (time-less-p org-contacts-last-update
+ (elt (file-attributes file) 5))))
+ (org-contacts-files))
+ (org-contacts-db-has-dead-markers-p org-contacts-db)))
+
+(defun org-contacts-db-has-dead-markers-p (org-contacts-db)
+ "Returns t if at least one dead marker is found in
+ORG-CONTACTS-DB. A dead marker in this case is a marker pointing
+to dead or no buffer."
+ ;; Scan contacts list looking for dead markers, and return t at first found.
+ (catch 'dead-marker-found
+ (while org-contacts-db
+ (unless (marker-buffer (nth 1 (car org-contacts-db)))
+ (throw 'dead-marker-found t))
+ (setq org-contacts-db (cdr org-contacts-db)))
+ nil))
+
+(defun org-contacts-db ()
+ "Return the latest Org Contacts Database."
+ (let* ((org--matcher-tags-todo-only nil)
+ (contacts-matcher (cdr (org-make-tags-matcher org-contacts-matcher)))
+ result)
+ (when (org-contacts-db-need-update-p)
+ (let ((progress-reporter
+ (make-progress-reporter "Updating Org Contacts Database..." 0 (length org-contacts-files)))
+ (i 0))
+ (dolist (file (org-contacts-files))
+ (if (catch 'nextfile
+ ;; if file doesn't exist and the user agrees to removing it
+ ;; from org-agendas-list, 'nextfile is thrown. Catch it here
+ ;; and skip processing the file.
+ ;;
+ ;; TODO: suppose that the user has set an org-contacts-files
+ ;; list that contains an element that doesn't exist in the
+ ;; file system: in that case, the org-agenda-files list could
+ ;; be updated (and saved to the customizations of the user) if
+ ;; it contained the same file even though the org-agenda-files
+ ;; list wasn't actually used. I don't think it is normal that
+ ;; org-contacts updates org-agenda-files in this case, but
+ ;; short of duplicating org-check-agenda-files and
+ ;; org-remove-files, I don't know how to avoid it.
+ ;;
+ ;; A side effect of the TODO is that the faulty
+ ;; org-contacts-files list never gets updated and thus the
+ ;; user is always queried about the missing files when
+ ;; org-contacts-db-need-update-p returns true.
+ (org-check-agenda-file file))
+ (message "Skipped %s removed from org-agenda-files list."
+ (abbreviate-file-name file))
+ (with-current-buffer (org-get-agenda-file-buffer file)
+ (unless (eq major-mode 'org-mode)
+ (error "File %s is not in `org-mode'" file))
+ (setf result
+ (append result
+ (org-scan-tags 'org-contacts-at-point
+ contacts-matcher
+ org--matcher-tags-todo-only)))))
+ (progress-reporter-update progress-reporter (setq i (1+ i))))
+ (setf org-contacts-db result
+ org-contacts-last-update (current-time))
+ (progress-reporter-done progress-reporter)))
+ org-contacts-db))
+
+(defun org-contacts-at-point (&optional pom)
+ "Return the contacts at point-or-marker POM or current position
+if nil."
+ (setq pom (or pom (point)))
+ (org-with-point-at pom
+ (list (org-get-heading t) (set-marker (make-marker) pom) (org-entry-properties pom 'all))))
+
+(defun org-contacts-filter (&optional name-match tags-match prop-match)
+ "Search for a contact matching any of NAME-MATCH, TAGS-MATCH, PROP-MATCH.
+If all match values are nil, return all contacts.
+
+The optional PROP-MATCH argument is a single (PROP . VALUE) cons
+cell corresponding to the contact properties.
+"
+ (if (and (null name-match)
+ (null prop-match)
+ (null tags-match))
+ (org-contacts-db)
+ (cl-loop for contact in (org-contacts-db)
+ if (or
+ (and name-match
+ (string-match-p name-match
+ (first contact)))
+ (and prop-match
+ (cl-find-if (lambda (prop)
+ (and (string= (car prop-match) (car prop))
+ (string-match-p (cdr prop-match) (cdr prop))))
+ (caddr contact)))
+ (and tags-match
+ (cl-find-if (lambda (tag)
+ (string-match-p tags-match tag))
+ (org-split-string
+ (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":"))))
+ collect contact)))
+
+(when (not (fboundp 'completion-table-case-fold))
+ ;; That function is new in Emacs 24...
+ (defun completion-table-case-fold (table &optional dont-fold)
+ (lambda (string pred action)
+ (let ((completion-ignore-case (not dont-fold)))
+ (complete-with-action action table string pred)))))
+
+(defun org-contacts-try-completion-prefix (to-match collection &optional predicate)
+ "Custom implementation of `try-completion'.
+This version works only with list and alist and it looks at all
+prefixes rather than just the beginning of the string."
+ (cl-loop with regexp = (concat "\\b" (regexp-quote to-match))
+ with ret = nil
+ with ret-start = nil
+ with ret-end = nil
+
+ for el in collection
+ for string = (if (listp el) (car el) el)
+
+ for start = (when (or (null predicate) (funcall predicate string))
+ (string-match regexp string))
+
+ if start
+ do (let ((end (match-end 0))
+ (len (length string)))
+ (if (= end len)
+ (cl-return t)
+ (cl-destructuring-bind (string start end)
+ (if (null ret)
+ (values string start end)
+ (org-contacts-common-substring
+ ret ret-start ret-end
+ string start end))
+ (setf ret string
+ ret-start start
+ ret-end end))))
+
+ finally (cl-return
+ (replace-regexp-in-string "\\`[ \t\n]*" "" ret))))
+
+(defun org-contacts-compare-strings (s1 start1 end1 s2 start2 end2 &optional ignore-case)
+ "Compare the contents of two strings, using `compare-strings'.
+
+This function works like `compare-strings' excepted that it
+returns a cons.
+- The CAR is the number of characters that match at the beginning.
+- The CDR is T is the two strings are the same and NIL otherwise."
+ (let ((ret (compare-strings s1 start1 end1 s2 start2 end2 ignore-case)))
+ (if (eq ret t)
+ (cons (or end1 (length s1)) t)
+ (cons (1- (abs ret)) nil))))
+
+(defun org-contacts-common-substring (s1 start1 end1 s2 start2 end2)
+ "Extract the common substring between S1 and S2.
+
+This function extracts the common substring between S1 and S2 and
+adjust the part that remains common.
+
+START1 and END1 delimit the part in S1 that we know is common
+between the two strings. This applies to START2 and END2 for S2.
+
+This function returns a list whose contains:
+- The common substring found.
+- The new value of the start of the known inner substring.
+- The new value of the end of the known inner substring."
+ ;; Given two strings:
+ ;; s1: "foo bar baz"
+ ;; s2: "fooo bar baz"
+ ;; and the inner substring is "bar"
+ ;; then: start1 = 4, end1 = 6, start2 = 5, end2 = 7
+ ;;
+ ;; To find the common substring we will compare two substrings:
+ ;; " oof" and " ooof" to find the beginning of the common substring.
+ ;; " baz" and " baz" to find the end of the common substring.
+ (let* ((len1 (length s1))
+ (start1 (or start1 0))
+ (end1 (or end1 len1))
+
+ (len2 (length s2))
+ (start2 (or start2 0))
+ (end2 (or end2 len2))
+
+ (new-start (car (org-contacts-compare-strings
+ (substring (org-reverse-string s1) (- len1 start1)) nil nil
+ (substring (org-reverse-string s2) (- len2 start2)) nil nil)))
+
+ (new-end (+ end1 (car (org-contacts-compare-strings
+ (substring s1 end1) nil nil
+ (substring s2 end2) nil nil)))))
+ (list (substring s1 (- start1 new-start) new-end)
+ new-start
+ (+ new-start (- end1 start1)))))
+
+(defun org-contacts-all-completions-prefix (to-match collection &optional predicate)
+ "Custom version of `all-completions'.
+This version works only with list and alist and it looks at all
+prefixes rather than just the beginning of the string."
+ (cl-loop with regexp = (concat "\\b" (regexp-quote to-match))
+ for el in collection
+ for string = (if (listp el) (car el) el)
+ for match? = (when (and (or (null predicate) (funcall predicate string)))
+ (string-match regexp string))
+ if match?
+ collect (progn
+ (let ((end (match-end 0)))
+ (org-no-properties string)
+ (when (< end (length string))
+ ;; Here we add a text property that will be used
+ ;; later to highlight the character right after
+ ;; the common part between each addresses.
+ ;; See `org-contacts-display-sort-function'.
+ (put-text-property end (1+ end) 'org-contacts-prefix 't string)))
+ string)))
+
+(defun org-contacts-make-collection-prefix (collection)
+ "Make a collection function from COLLECTION which will match on prefixes."
+ (lexical-let ((collection collection))
+ (lambda (string predicate flag)
+ (cond ((eq flag nil)
+ (org-contacts-try-completion-prefix string collection predicate))
+ ((eq flag t)
+ ;; `org-contacts-all-completions-prefix' has already been
+ ;; used to compute `all-completions'.
+ collection)
+ ((eq flag 'lambda)
+ (org-contacts-test-completion-prefix string collection predicate))
+ ((and (listp flag) (eq (car flag) 'boundaries))
+ (cl-destructuring-bind (to-ignore &rest suffix)
+ flag
+ (org-contacts-boundaries-prefix string collection predicate suffix)))
+ ((eq flag 'metadata)
+ (org-contacts-metadata-prefix string collection predicate))
+ (t nil ; operation unsupported
+ )))))
+
+(defun org-contacts-display-sort-function (completions)
+ "Sort function for contacts display."
+ (mapcar (lambda (string)
+ (cl-loop with len = (1- (length string))
+ for i upfrom 0 to len
+ if (memq 'org-contacts-prefix
+ (text-properties-at i string))
+ do (set-text-properties
+ i (1+ i)
+ (list 'font-lock-face
+ (if (char-equal (aref string i)
+ (string-to-char " "))
+ ;; Spaces can't be bold.
+ 'underline
+ 'bold)) string)
+ else
+ do (set-text-properties i (1+ i) nil string)
+ finally (cl-return string)))
+ completions))
+
+(defun org-contacts-test-completion-prefix (string collection predicate)
+ (cl-find-if (lambda (el)
+ (and (or (null predicate) (funcall predicate el))
+ (string= string el)))
+ collection))
+
+(defun org-contacts-boundaries-prefix (string collection predicate suffix)
+ (list* 'boundaries (completion-boundaries string collection predicate suffix)))
+
+(defun org-contacts-metadata-prefix (string collection predicate)
+ '(metadata .
+ ((cycle-sort-function . org-contacts-display-sort-function)
+ (display-sort-function . org-contacts-display-sort-function))))
+
+(defun org-contacts-complete-group (start end string)
+ "Complete text at START from a group.
+
+A group FOO is composed of contacts with the tag FOO."
+ (let* ((completion-ignore-case org-contacts-completion-ignore-case)
+ (group-completion-p (string-match-p
+ (concat "^" org-contacts-group-prefix) string)))
+ (when group-completion-p
+ (let ((completion-list
+ (all-completions
+ string
+ (mapcar (lambda (group)
+ (propertize (concat org-contacts-group-prefix group)
+ 'org-contacts-group group))
+ (org-uniquify
+ (cl-loop for contact in (org-contacts-filter)
+ nconc (org-split-string
+ (or (cdr (assoc-string "ALLTAGS" (caddr contact))) "") ":")))))))
+ (list start end
+ (if (= (length completion-list) 1)
+ ;; We've found the correct group, returns the address
+ (lexical-let ((tag (get-text-property 0 'org-contacts-group
+ (car completion-list))))
+ (lambda (string pred &optional to-ignore)
+ (mapconcat 'identity
+ (cl-loop for contact in (org-contacts-filter
+ nil
+ tag)
+ ;; The contact name is always the car of the assoc-list
+ ;; returned by `org-contacts-filter'.
+ for contact-name = (car contact)
+ ;; Grab the first email of the contact
+ for email = (org-contacts-strip-link
+ (or (car (org-contacts-split-property
+ (or
+ (cdr (assoc-string org-contacts-email-property
+ (cl-caddr contact)))
+ ""))) ""))
+ ;; If the user has an email address, append USER <EMAIL>.
+ if email collect (org-contacts-format-email contact-name email))
+ ", ")))
+ ;; We haven't found the correct group
+ (completion-table-case-fold completion-list
+ (not org-contacts-completion-ignore-case))))))))
+
+(defun org-contacts-complete-tags-props (start end string)
+ "Insert emails that match the tags expression.
+
+For example: FOO-BAR will match entries tagged with FOO but not
+with BAR.
+
+See (org) Matching tags and properties for a complete
+description."
+ (let* ((completion-ignore-case org-contacts-completion-ignore-case)
+ (completion-p (string-match-p
+ (concat "^" org-contacts-tags-props-prefix) string)))
+ (when completion-p
+ (let ((result
+ (mapconcat
+ 'identity
+ (cl-loop for contact in (org-contacts-db)
+ for contact-name = (car contact)
+ for email = (org-contacts-strip-link (or (car (org-contacts-split-property
+ (or
+ (cdr (assoc-string org-contacts-email-property
+ (cl-caddr contact)))
+ ""))) ""))
+ for tags = (cdr (assoc "TAGS" (nth 2 contact)))
+ for tags-list = (if tags
+ (split-string (substring (cdr (assoc "TAGS" (nth 2 contact))) 1 -1) ":")
+ '())
+ for marker = (nth 1 contact)
+ if (with-current-buffer (marker-buffer marker)
+ (save-excursion
+ (goto-char marker)
+ (let (todo-only)
+ (eval (cdr (org-make-tags-matcher (cl-subseq string 1)))))))
+ collect (org-contacts-format-email contact-name email))
+ ",")))
+ (when (not (string= "" result))
+ ;; return (start end function)
+ (lexical-let* ((to-return result))
+ (list start end
+ (lambda (string pred &optional to-ignore) to-return))))))))
+
+(defun org-contacts-remove-ignored-property-values (ignore-list list)
+ "Remove all ignore-list's elements from list and you can use
+ regular expressions in the ignore list."
+ (cl-remove-if (lambda (el)
+ (cl-find-if (lambda (x)
+ (string-match-p x el))
+ ignore-list))
+ list))
+
+(defun org-contacts-complete-name (start end string)
+ "Complete text at START with a user name and email."
+ (let* ((completion-ignore-case org-contacts-completion-ignore-case)
+ (completion-list
+ (cl-loop for contact in (org-contacts-filter)
+ ;; The contact name is always the car of the assoc-list
+ ;; returned by `org-contacts-filter'.
+ for contact-name = (car contact)
+
+ ;; Build the list of the email addresses which has
+ ;; been expired
+ for ignore-list = (org-contacts-split-property
+ (or (cdr (assoc-string org-contacts-ignore-property
+ (nth 2 contact))) ""))
+ ;; Build the list of the user email addresses.
+ for email-list = (org-contacts-remove-ignored-property-values
+ ignore-list
+ (org-contacts-split-property
+ (or (cdr (assoc-string org-contacts-email-property
+ (nth 2 contact))) "")))
+ ;; If the user has email addresses…
+ if email-list
+ ;; … append a list of USER <EMAIL>.
+ nconc (cl-loop for email in email-list
+ collect (org-contacts-format-email contact-name (org-contacts-strip-link email)))))
+ (completion-list (org-contacts-all-completions-prefix
+ string
+ (org-uniquify completion-list))))
+ (when completion-list
+ (list start end
+ (org-contacts-make-collection-prefix completion-list)))))
+
+(defun org-contacts-message-complete-function (&optional start)
+ "Function used in `completion-at-point-functions' in `message-mode'."
+ ;; Avoid to complete in `post-command-hook'.
+ (when completion-in-region-mode
+ (remove-hook 'post-command-hook #'completion-in-region--postch))
+ (let ((mail-abbrev-mode-regexp
+ "^\\(Resent-To\\|To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\|Disposition-Notification-To\\|Return-Receipt-To\\):"))
+ (when (mail-abbrev-in-expansion-header-p)
+ (lexical-let*
+ ((end (point))
+ (start (or start
+ (save-excursion
+ (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
+ (goto-char (match-end 0))
+ (point))))
+ (string (buffer-substring start end)))
+ (run-hook-with-args-until-success
+ 'org-contacts-complete-functions start end string)))))
+
+(defun org-contacts-gnus-get-name-email ()
+ "Get name and email address from Gnus message."
+ (if (gnus-alive-p)
+ (gnus-with-article-headers
+ (mail-extract-address-components
+ (or (mail-fetch-field "From") "")))))
+
+(defun org-contacts-gnus-article-from-get-marker ()
+ "Return a marker for a contact based on From."
+ (let* ((address (org-contacts-gnus-get-name-email))
+ (name (car address))
+ (email (cadr address)))
+ (cl-cadar (or (org-contacts-filter
+ nil
+ nil
+ (cons org-contacts-email-property (concat "\\b" (regexp-quote email) "\\b")))
+ (when name
+ (org-contacts-filter
+ (concat "^" name "$")))))))
+
+(defun org-contacts-gnus-article-from-goto ()
+ "Go to contact in the From address of current Gnus message."
+ (interactive)
+ (let ((marker (org-contacts-gnus-article-from-get-marker)))
+ (when marker
+ (switch-to-buffer-other-window (marker-buffer marker))
+ (goto-char marker)
+ (when (eq major-mode 'org-mode) (org-show-context 'agenda)))))
+
+(with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
+(defun org-contacts-anniversaries (&optional field format)
+ "Compute FIELD anniversary for each contact, returning FORMAT.
+Default FIELD value is \"BIRTHDAY\".
+
+Format is a string matching the following format specification:
+
+ %h - Heading name
+ %l - Link to the heading
+ %y - Number of year
+ %Y - Number of year (ordinal)"
+ (let ((calendar-date-style 'american)
+ (entry ""))
+ (unless format (setq format org-contacts-birthday-format))
+ (cl-loop for contact in (org-contacts-filter)
+ for anniv = (let ((anniv (cdr (assoc-string
+ (or field org-contacts-birthday-property)
+ (nth 2 contact)))))
+ (when anniv
+ (calendar-gregorian-from-absolute
+ (org-time-string-to-absolute anniv))))
+ ;; Use `diary-anniversary' to compute anniversary.
+ if (and anniv (apply 'diary-anniversary anniv))
+ collect (format-spec format
+ `((?l . ,(org-with-point-at (cadr contact) (org-store-link nil)))
+ (?h . ,(car contact))
+ (?y . ,(- (calendar-extract-year date)
+ (calendar-extract-year anniv)))
+ (?Y . ,(let ((years (- (calendar-extract-year date)
+ (calendar-extract-year anniv))))
+ (format "%d%s" years (diary-ordinal-suffix years)))))))))
+
+(defun org-completing-read-date (prompt collection
+ &optional predicate require-match initial-input
+ hist def inherit-input-method)
+ "Like `completing-read' but reads a date.
+Only PROMPT and DEF are really used."
+ (org-read-date nil nil nil prompt nil def))
+
+(add-to-list 'org-property-set-functions-alist
+ `(,org-contacts-birthday-property . org-completing-read-date))
+
+(defun org-contacts-template-name (&optional return-value)
+ "Try to return the contact name for a template.
+If not found return RETURN-VALUE or something that would ask the user."
+ (or (car (org-contacts-gnus-get-name-email))
+ return-value
+ "%^{Name}"))
+
+(defun org-contacts-template-email (&optional return-value)
+ "Try to return the contact email for a template.
+If not found return RETURN-VALUE or something that would ask the user."
+ (or (cadr (org-contacts-gnus-get-name-email))
+ return-value
+ (concat "%^{" org-contacts-email-property "}p")))
+
+(defun org-contacts-gnus-store-last-mail ()
+ "Store a link between mails and contacts.
+
+This function should be called from `gnus-article-prepare-hook'."
+ (let ((marker (org-contacts-gnus-article-from-get-marker)))
+ (when marker
+ (with-current-buffer (marker-buffer marker)
+ (save-excursion
+ (goto-char marker)
+ (let* ((org-email-link-description-format (or org-contacts-email-link-description-format
+ org-email-link-description-format))
+ (link (gnus-with-article-buffer (org-store-link nil))))
+ (org-set-property org-contacts-last-read-mail-property link)))))))
+
+(defun org-contacts-icon-as-string ()
+ "Return the contact icon as a string."
+ (let ((image (org-contacts-get-icon)))
+ (concat
+ (propertize "-" 'display
+ (append
+ (if image
+ image
+ `'(space :width (,org-contacts-icon-size)))
+ '(:ascent center)))
+ " ")))
+
+;;;###autoload
+(defun org-contacts (name)
+ "Create agenda view for contacts matching NAME."
+ (interactive (list (read-string "Name: ")))
+ (let ((org-agenda-files (org-contacts-files))
+ (org-agenda-skip-function
+ (lambda () (org-agenda-skip-if nil `(notregexp ,name))))
+ (org-agenda-prefix-format (propertize
+ "%(org-contacts-icon-as-string)% s%(org-contacts-irc-number-of-unread-messages) "
+ 'keymap org-contacts-keymap))
+ (org-agenda-overriding-header
+ (or org-agenda-overriding-header
+ (concat "List of contacts matching `" name "':"))))
+ (setq org-agenda-skip-regexp name)
+ (org-tags-view nil org-contacts-matcher)
+ (with-current-buffer org-agenda-buffer-name
+ (setq org-agenda-redo-command
+ (list 'org-contacts name)))))
+
+(defun org-contacts-completing-read (prompt
+ &optional predicate
+ initial-input hist def inherit-input-method)
+ "Call `completing-read' with contacts name as collection."
+ (org-completing-read
+ prompt (org-contacts-filter) predicate t initial-input hist def inherit-input-method))
+
+(defun org-contacts-format-name (name)
+ "Trim any local formatting to get a bare NAME."
+ ;; Remove radio targets characters
+ (replace-regexp-in-string org-radio-target-regexp "\\1" name))
+
+(defun org-contacts-format-email (name email)
+ "Format an EMAIL address corresponding to NAME."
+ (unless email
+ (error "`email' cannot be nul"))
+ (if name
+ (concat (org-contacts-format-name name) " <" email ">")
+ email))
+
+(defun org-contacts-check-mail-address (mail)
+ "Add MAIL address to contact at point if it does not have it."
+ (let ((mails (org-entry-get (point) org-contacts-email-property)))
+ (unless (member mail (split-string mails))
+ (when (yes-or-no-p
+ (format "Do you want to add this address to %s?" (org-get-heading t)))
+ (org-set-property org-contacts-email-property (concat mails " " mail))))))
+
+(defun org-contacts-gnus-check-mail-address ()
+ "Check that contact has the current address recorded.
+This function should be called from `gnus-article-prepare-hook'."
+ (let ((marker (org-contacts-gnus-article-from-get-marker)))
+ (when marker
+ (org-with-point-at marker
+ (org-contacts-check-mail-address (cadr (org-contacts-gnus-get-name-email)))))))
+
+(defun org-contacts-gnus-insinuate ()
+ "Add some hooks for Gnus user.
+This adds `org-contacts-gnus-check-mail-address' and
+`org-contacts-gnus-store-last-mail' to
+`gnus-article-prepare-hook'. It also adds a binding on `;' in
+`gnus-summary-mode-map' to `org-contacts-gnus-article-from-goto'"
+ (require 'gnus)
+ (require 'gnus-art)
+ (define-key gnus-summary-mode-map ";" 'org-contacts-gnus-article-from-goto)
+ (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-check-mail-address)
+ (add-hook 'gnus-article-prepare-hook 'org-contacts-gnus-store-last-mail))
+
+(defun org-contacts-setup-completion-at-point ()
+ "Add `org-contacts-message-complete-function' as a new function
+to complete the thing at point."
+ (add-to-list 'completion-at-point-functions
+ 'org-contacts-message-complete-function))
+
+(defun org-contacts-unload-hook ()
+ (remove-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
+
+(when (and org-contacts-enable-completion
+ (boundp 'completion-at-point-functions))
+ (add-hook 'message-mode-hook 'org-contacts-setup-completion-at-point))
+
+(defun org-contacts-wl-get-from-header-content ()
+ "Retrieve the content of the `From' header of an email.
+Works from wl-summary-mode and mime-view-mode - that is while viewing email.
+Depends on Wanderlust been loaded."
+ (with-current-buffer (org-capture-get :original-buffer)
+ (cond
+ ((eq major-mode 'wl-summary-mode) (when (and (boundp 'wl-summary-buffer-elmo-folder)
+ wl-summary-buffer-elmo-folder)
+ (elmo-message-field
+ wl-summary-buffer-elmo-folder
+ (wl-summary-message-number)
+ 'from)))
+ ((eq major-mode 'mime-view-mode) (std11-narrow-to-header)
+ (prog1
+ (std11-fetch-field "From")
+ (widen))))))
+
+(defun org-contacts-wl-get-name-email ()
+ "Get name and email address from Wanderlust email.
+See `org-contacts-wl-get-from-header-content' for limitations."
+ (let ((from (org-contacts-wl-get-from-header-content)))
+ (when from
+ (list (wl-address-header-extract-realname from)
+ (wl-address-header-extract-address from)))))
+
+(defun org-contacts-template-wl-name (&optional return-value)
+ "Try to return the contact name for a template from wl.
+If not found, return RETURN-VALUE or something that would ask the
+user."
+ (or (car (org-contacts-wl-get-name-email))
+ return-value
+ "%^{Name}"))
+
+(defun org-contacts-template-wl-email (&optional return-value)
+ "Try to return the contact email for a template from Wanderlust.
+If not found return RETURN-VALUE or something that would ask the user."
+ (or (cadr (org-contacts-wl-get-name-email))
+ return-value
+ (concat "%^{" org-contacts-email-property "}p")))
+
+(defun org-contacts-view-send-email (&optional ask)
+ "Send email to the contact at point.
+If ASK is set, ask for the email address even if there's only one
+address."
+ (interactive "P")
+ (let ((marker (org-get-at-bol 'org-hd-marker)))
+ (org-with-point-at marker
+ (let ((emails (org-entry-get (point) org-contacts-email-property)))
+ (if emails
+ (let ((email-list (org-contacts-split-property emails)))
+ (if (and (= (length email-list) 1) (not ask))
+ (compose-mail (org-contacts-format-email
+ (org-get-heading t) emails))
+ (let ((email (completing-read "Send mail to which address: " email-list)))
+ (setq email (org-contacts-strip-link email))
+ (org-contacts-check-mail-address email)
+ (compose-mail (org-contacts-format-email (org-get-heading t) email)))))
+ (error (format "This contact has no mail address set (no %s property)"
+ org-contacts-email-property)))))))
+
+(defun org-contacts-get-icon (&optional pom)
+ "Get icon for contact at POM."
+ (setq pom (or pom (point)))
+ (catch 'icon
+ ;; Use `org-contacts-icon-property'
+ (let ((image-data (org-entry-get pom org-contacts-icon-property)))
+ (when image-data
+ (throw 'icon
+ (if (fboundp 'gnus-rescale-image)
+ (gnus-rescale-image (create-image image-data)
+ (cons org-contacts-icon-size org-contacts-icon-size))
+ (create-image image-data)))))
+ ;; Next, try Gravatar
+ (when org-contacts-icon-use-gravatar
+ (let* ((gravatar-size org-contacts-icon-size)
+ (email-list (org-entry-get pom org-contacts-email-property))
+ (gravatar
+ (when email-list
+ (loop for email in (org-contacts-split-property email-list)
+ for gravatar = (gravatar-retrieve-synchronously (org-contacts-strip-link email))
+ if (and gravatar
+ (not (eq gravatar 'error)))
+ return gravatar))))
+ (when gravatar (throw 'icon gravatar))))))
+
+(defun org-contacts-irc-buffer (&optional pom)
+ "Get the IRC buffer associated with the entry at POM."
+ (setq pom (or pom (point)))
+ (let ((nick (org-entry-get pom org-contacts-nickname-property)))
+ (when nick
+ (let ((buffer (get-buffer nick)))
+ (when buffer
+ (with-current-buffer buffer
+ (when (eq major-mode 'erc-mode)
+ buffer)))))))
+
+(defun org-contacts-irc-number-of-unread-messages (&optional pom)
+ "Return the number of unread messages for contact at POM."
+ (when (boundp 'erc-modified-channels-alist)
+ (let ((number (cadr (assoc (org-contacts-irc-buffer pom) erc-modified-channels-alist))))
+ (if number
+ (format (concat "%3d unread message" (if (> number 1) "s" " ") " ") number)
+ (make-string 21 ? )))))
+
+(defun org-contacts-view-switch-to-irc-buffer ()
+ "Switch to the IRC buffer of the current contact if it has one."
+ (interactive)
+ (let ((marker (org-get-at-bol 'org-hd-marker)))
+ (org-with-point-at marker
+ (switch-to-buffer-other-window (org-contacts-irc-buffer)))))
+
+(defun org-contacts-completing-read-nickname (prompt collection
+ &optional predicate require-match initial-input
+ hist def inherit-input-method)
+ "Like `completing-read' but reads a nickname."
+ (org-completing-read prompt (append collection (erc-nicknames-list)) predicate require-match
+ initial-input hist def inherit-input-method))
+
+(defun erc-nicknames-list ()
+ "Return all nicknames of all ERC buffers."
+ (loop for buffer in (erc-buffer-list)
+ nconc (with-current-buffer buffer
+ (loop for user-entry in (mapcar 'car (erc-get-channel-user-list))
+ collect (elt user-entry 1)))))
+
+(add-to-list 'org-property-set-functions-alist
+ `(,org-contacts-nickname-property . org-contacts-completing-read-nickname))
+
+(defun org-contacts-vcard-escape (str)
+ "Escape ; , and \n in STR for the VCard format."
+ ;; Thanks to this library for the regexp:
+ ;; http://www.emacswiki.org/cgi-bin/wiki/bbdb-vcard-export.el
+ (when str
+ (replace-regexp-in-string
+ "\n" "\\\\n"
+ (replace-regexp-in-string "\\(;\\|,\\|\\\\\\)" "\\\\\\1" str))))
+
+(defun org-contacts-vcard-encode-name (name)
+ "Try to encode NAME as VCard's N property.
+The N property expects
+
+ FamilyName;GivenName;AdditionalNames;Prefix;Postfix.
+
+Org-contacts does not specify how to encode the name. So we try
+to do our best."
+ (concat (replace-regexp-in-string "\\(\\w+\\) \\(.*\\)" "\\2;\\1" name) ";;;"))
+
+(defun org-contacts-vcard-format (contact)
+ "Formats CONTACT in VCard 3.0 format."
+ (let* ((properties (nth 2 contact))
+ (name (org-contacts-vcard-escape (car contact)))
+ (n (org-contacts-vcard-encode-name name))
+ (email (cdr (assoc-string org-contacts-email-property properties)))
+ (tel (cdr (assoc-string org-contacts-tel-property properties)))
+ (ignore-list (cdr (assoc-string org-contacts-ignore-property properties)))
+ (ignore-list (when ignore-list
+ (org-contacts-split-property ignore-list)))
+ (note (cdr (assoc-string org-contacts-note-property properties)))
+ (bday (org-contacts-vcard-escape (cdr (assoc-string org-contacts-birthday-property properties))))
+ (addr (cdr (assoc-string org-contacts-address-property properties)))
+ (nick (org-contacts-vcard-escape (cdr (assoc-string org-contacts-nickname-property properties))))
+ (head (format "BEGIN:VCARD\nVERSION:3.0\nN:%s\nFN:%s\n" n name))
+ emails-list result phones-list)
+ (concat head
+ (when email (progn
+ (setq emails-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property email)))
+ (setq result "")
+ (while emails-list
+ (setq result (concat result "EMAIL:" (org-contacts-strip-link (car emails-list)) "\n"))
+ (setq emails-list (cdr emails-list)))
+ result))
+ (when addr
+ (format "ADR:;;%s\n" (replace-regexp-in-string "\\, ?" ";" addr)))
+ (when tel (progn
+ (setq phones-list (org-contacts-remove-ignored-property-values ignore-list (org-contacts-split-property tel)))
+ (setq result "")
+ (while phones-list
+ (setq result (concat result "TEL:" (org-link-unescape (org-contacts-strip-link (car phones-list))) "\n"))
+ (setq phones-list (cdr phones-list)))
+ result))
+ (when bday
+ (let ((cal-bday (calendar-gregorian-from-absolute (org-time-string-to-absolute bday))))
+ (format "BDAY:%04d-%02d-%02d\n"
+ (calendar-extract-year cal-bday)
+ (calendar-extract-month cal-bday)
+ (calendar-extract-day cal-bday))))
+ (when nick (format "NICKNAME:%s\n" nick))
+ (when note (format "NOTE:%s\n" note))
+ "END:VCARD\n\n")))
+
+(defun org-contacts-export-as-vcard (&optional name file to-buffer)
+ "Export org contacts to V-Card 3.0.
+
+By default, all contacts are exported to `org-contacts-vcard-file'.
+
+When NAME is \\[universal-argument], prompts for a contact name.
+
+When NAME is \\[universal-argument] \\[universal-argument],
+prompts for a contact name and a file name where to export.
+
+When NAME is \\[universal-argument] \\[universal-argument]
+\\[universal-argument], prompts for a contact name and a buffer where to export.
+
+If the function is not called interactively, all parameters are
+passed to `org-contacts-export-as-vcard-internal'."
+ (interactive "P")
+ (when (called-interactively-p 'any)
+ (cl-psetf name
+ (when name
+ (read-string "Contact name: "
+ (nth 0 (org-contacts-at-point))))
+ file
+ (when (equal name '(16))
+ (read-file-name "File: " nil org-contacts-vcard-file))
+ to-buffer
+ (when (equal name '(64))
+ (read-buffer "Buffer: "))))
+ (org-contacts-export-as-vcard-internal name file to-buffer))
+
+(defun org-contacts-export-as-vcard-internal (&optional name file to-buffer)
+ "Export all contacts matching NAME as VCard 3.0.
+If TO-BUFFER is nil, the content is written to FILE or
+`org-contacts-vcard-file'. If TO-BUFFER is non-nil, the buffer
+is created and the VCard is written into that buffer."
+ (let* ((filename (or file org-contacts-vcard-file))
+ (buffer (if to-buffer
+ (get-buffer-create to-buffer)
+ (find-file-noselect filename))))
+ (message "Exporting...")
+ (set-buffer buffer)
+ (let ((inhibit-read-only t)) (erase-buffer))
+ (fundamental-mode)
+ (when (fboundp 'set-buffer-file-coding-system)
+ (set-buffer-file-coding-system coding-system-for-write))
+ (loop for contact in (org-contacts-filter name)
+ do (insert (org-contacts-vcard-format contact)))
+ (if to-buffer
+ (current-buffer)
+ (progn (save-buffer) (kill-buffer)))))
+
+(defun org-contacts-show-map (&optional name)
+ "Show contacts on a map.
+Requires google-maps-el."
+ (interactive)
+ (unless (fboundp 'google-maps-static-show)
+ (error "`org-contacts-show-map' requires `google-maps-el'"))
+ (google-maps-static-show
+ :markers
+ (cl-loop
+ for contact in (org-contacts-filter name)
+ for addr = (cdr (assoc-string org-contacts-address-property (nth 2 contact)))
+ if addr
+ collect (cons (list addr) (list :label (string-to-char (car contact)))))))
+
+(defun org-contacts-strip-link (link)
+ "Remove brackets, description, link type and colon from an org
+link string and return the pure link target."
+ (let (startpos colonpos endpos)
+ (setq startpos (string-match (regexp-opt '("[[tel:" "[[mailto:")) link))
+ (if startpos
+ (progn
+ (setq colonpos (string-match ":" link))
+ (setq endpos (string-match "\\]" link))
+ (if endpos (substring link (1+ colonpos) endpos) link))
+ (progn
+ (setq startpos (string-match "mailto:" link))
+ (setq colonpos (string-match ":" link))
+ (if startpos (substring link (1+ colonpos)) link)))))
+
+;; Add the link type supported by org-contacts-strip-link
+;; so everything is in order for its use in Org files
+(org-link-set-parameters "tel")
+
+(defun org-contacts-split-property (string &optional separators omit-nulls)
+ "Custom version of `split-string'.
+Split a property STRING into sub-strings bounded by matches
+for SEPARATORS but keep Org links intact.
+
+The beginning and end of STRING, and each match for SEPARATORS, are
+splitting points. The substrings matching SEPARATORS are removed, and
+the substrings between the splitting points are collected as a list,
+which is returned.
+
+If SEPARATORS is non-nil, it should be a regular expression
+matching text which separates, but is not part of, the
+substrings. If nil it defaults to `org-contacts-property-values-separators',
+normally \"[,; \f\t\n\r\v]+\", and OMIT-NULLS is forced to t.
+
+If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
+that for the default value of SEPARATORS leading and trailing whitespace
+are effectively trimmed). If nil, all zero-length substrings are retained."
+ (let* ((omit-nulls (if separators omit-nulls t))
+ (rexp (or separators org-contacts-property-values-separators))
+ (inputlist (split-string string rexp omit-nulls))
+ (linkstring "")
+ (bufferstring "")
+ (proplist (list "")))
+ (while inputlist
+ (setq bufferstring (pop inputlist))
+ (if (string-match "\\[\\[" bufferstring)
+ (progn
+ (setq linkstring (concat bufferstring " "))
+ (while (not (string-match "\\]\\]" bufferstring))
+ (setq bufferstring (pop inputlist))
+ (setq linkstring (concat linkstring bufferstring " ")))
+ (setq proplist (cons (org-trim linkstring) proplist)))
+ (setq proplist (cons bufferstring proplist))))
+ (cdr (reverse proplist))))
+
+(provide 'org-contacts)
+
+;;; org-contacts.el ends here
diff --git a/contrib/lisp/org-contribdir.el b/contrib/lisp/org-contribdir.el
new file mode 100644
index 0000000..4ad3116
--- /dev/null
+++ b/contrib/lisp/org-contribdir.el
@@ -0,0 +1,38 @@
+;;; org-contribdir.el --- Mark the location of the contrib directory
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 0.01
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+
+;; The sole purpose of this file is to be located in the same place
+;; as where the contributed Org files are located, typically in the
+;; contrib/lisp directory of the Org-mode distribution. This is to
+;; make sure that the command `org-reload' can reliably locate
+;; contributed org files.
+
+(provide 'org-contribdir)
+
+;;; org-contribdir.el ends here
diff --git a/contrib/lisp/org-depend.el b/contrib/lisp/org-depend.el
new file mode 100644
index 0000000..b6f3d27
--- /dev/null
+++ b/contrib/lisp/org-depend.el
@@ -0,0 +1,420 @@
+;;; org-depend.el --- TODO dependencies for Org-mode
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 0.08
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This file is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; WARNING: This file is just a PROOF OF CONCEPT, not a supported part
+;; of Org-mode.
+;;
+;; This is an example implementation of TODO dependencies in Org-mode.
+;; It uses the new hooks in version 5.13 of Org-mode,
+;; `org-trigger-hook' and `org-blocker-hook'.
+;;
+;; It implements the following:
+;;
+;; Triggering
+;; ----------
+;;
+;; 1) If an entry contains a TRIGGER property that contains the string
+;; "chain-siblings(KEYWORD)", then switching that entry to DONE does
+;; do the following:
+;; - The sibling following this entry switched to todo-state KEYWORD.
+;; - The sibling also gets a TRIGGER property "chain-sibling(KEYWORD)",
+;; property, to make sure that, when *it* is DONE, the chain will
+;; continue.
+;;
+;; 2) If an entry contains a TRIGGER property that contains the string
+;; "chain-siblings-scheduled", then switching that entry to DONE does
+;; the following actions, similarly to "chain-siblings(KEYWORD)":
+;; - The sibling receives the same scheduled time as the entry
+;; marked as DONE (or, in the case, in which there is no scheduled
+;; time, the sibling does not get any either).
+;; - The sibling also gets the same TRIGGER property
+;; "chain-siblings-scheduled", so the chain can continue.
+;;
+;; 3) If the TRIGGER property contains the string
+;; "chain-find-next(KEYWORD[,OPTIONS])", then switching that entry
+;; to DONE do the following:
+;; - All siblings are of the entry are collected into a temporary
+;; list and then filtered and sorted according to OPTIONS
+;; - The first sibling on the list is changed into KEYWORD state
+;; - The sibling also gets the same TRIGGER property
+;; "chain-find-next", so the chain can continue.
+;;
+;; OPTIONS should be a comma separated string without spaces, and
+;; can contain following options:
+;;
+;; - from-top the candidate list is all of the siblings in
+;; the current subtree
+;;
+;; - from-bottom candidate list are all siblings from bottom up
+;;
+;; - from-current candidate list are all siblings from current item
+;; until end of subtree, then wrapped around from
+;; first sibling
+;;
+;; - no-wrap candidate list are siblings from current one down
+;;
+;; - todo-only Only consider siblings that have a todo keyword
+;; -
+;; - todo-and-done-only
+;; Same as above but also include done items.
+;;
+;; - priority-up sort by highest priority
+;; - priority-down sort by lowest priority
+;; - effort-up sort by highest effort
+;; - effort-down sort by lowest effort
+;;
+;; Default OPTIONS are from-top
+;;
+;;
+;; 4) If the TRIGGER property contains any other words like
+;; XYZ(KEYWORD), these are treated as entry id's with keywords. That
+;; means Org-mode will search for an entry with the ID property XYZ
+;; and switch that entry to KEYWORD as well.
+;;
+;; Blocking
+;; --------
+;;
+;; 1) If an entry contains a BLOCKER property that contains the word
+;; "previous-sibling", the sibling above the current entry is
+;; checked when you try to mark it DONE. If it is still in a TODO
+;; state, the current state change is blocked.
+;;
+;; 2) If the BLOCKER property contains any other words, these are
+;; treated as entry id's. That means Org-mode will search for an
+;; entry with the ID property exactly equal to this word. If any
+;; of these entries is not yet marked DONE, the current state change
+;; will be blocked.
+;;
+;; 3) Whenever a state change is blocked, an org-mark is pushed, so that
+;; you can find the offending entry with `C-c &'.
+;;
+;;; Example:
+;;
+;; When trying this example, make sure that the settings for TODO keywords
+;; have been activated, i.e. include the following line and press C-c C-c
+;; on the line before working with the example:
+;;
+;; #+TYP_TODO: TODO NEXT | DONE
+;;
+;; * TODO Win a million in Las Vegas
+;; The "third" TODO (see above) cannot become a TODO without this money.
+;;
+;; :PROPERTIES:
+;; :ID: I-cannot-do-it-without-money
+;; :END:
+;;
+;; * Do this by doing a chain of TODO's
+;; ** NEXT This is the first in this chain
+;; :PROPERTIES:
+;; :TRIGGER: chain-siblings(NEXT)
+;; :END:
+;;
+;; ** This is the second in this chain
+;;
+;; ** This is the third in this chain
+;; :PROPERTIES:
+;; :BLOCKER: I-cannot-do-it-without-money
+;; :END:
+;;
+;; ** This is the forth in this chain
+;; When this is DONE, we will also trigger entry XYZ-is-my-id
+;; :PROPERTIES:
+;; :TRIGGER: XYZ-is-my-id(TODO)
+;; :END:
+;;
+;; ** This is the fifth in this chain
+;;
+;; * Start writing report
+;; :PROPERTIES:
+;; :ID: XYZ-is-my-id
+;; :END:
+;;
+;;
+
+(require 'org)
+(eval-when-compile
+ (require 'cl))
+
+(defcustom org-depend-tag-blocked t
+ "Whether to indicate blocked TODO items by a special tag."
+ :group 'org
+ :type 'boolean)
+
+(defcustom org-depend-find-next-options
+ "from-current,todo-only,priority-up"
+ "Default options for chain-find-next trigger"
+ :group 'org
+ :type 'string)
+
+(defmacro org-depend-act-on-sibling (trigger-val &rest rest)
+ "Perform a set of actions on the next sibling, if it exists,
+copying the sibling spec TRIGGER-VAL to the next sibling."
+ `(catch 'exit
+ (save-excursion
+ (goto-char pos)
+ ;; find the sibling, exit if no more siblings
+ (condition-case nil
+ (outline-forward-same-level 1)
+ (error (throw 'exit t)))
+ ;; mark the sibling TODO
+ ,@rest
+ ;; make sure the sibling will continue the chain
+ (org-entry-add-to-multivalued-property
+ nil "TRIGGER" ,trigger-val))))
+
+(defvar org-depend-doing-chain-find-next nil)
+
+(defun org-depend-trigger-todo (change-plist)
+ "Trigger new TODO entries after the current is switched to DONE.
+This does two different kinds of triggers:
+
+- If the current entry contains a TRIGGER property that contains
+ \"chain-siblings(KEYWORD)\", it goes to the next sibling, marks it
+ KEYWORD and also installs the \"chain-sibling\" trigger to continue
+ the chain.
+- If the current entry contains a TRIGGER property that contains
+ \"chain-siblings-scheduled\", we go to the next sibling and copy
+ the scheduled time from the current task, also installing the property
+ in the sibling.
+- Any other word (space-separated) like XYZ(KEYWORD) in the TRIGGER
+ property is seen as an entry id. Org-mode finds the entry with the
+ corresponding ID property and switches it to the state TODO as well."
+
+ ;; Refresh the effort text properties
+ (org-refresh-properties org-effort-property 'org-effort)
+ ;; Get information from the plist
+ (let* ((type (plist-get change-plist :type))
+ (pos (plist-get change-plist :position))
+ (from (plist-get change-plist :from))
+ (to (plist-get change-plist :to))
+ (org-log-done nil) ; IMPROTANT!: no logging during automatic trigger!
+ trigger triggers tr p1 kwd id)
+ (catch 'return
+ (unless (eq type 'todo-state-change)
+ ;; We are only handling todo-state-change....
+ (throw 'return t))
+ (unless (and (member from org-not-done-keywords)
+ (member to org-done-keywords))
+ ;; This is not a change from TODO to DONE, ignore it
+ (throw 'return t))
+
+ ;; OK, we just switched from a TODO state to a DONE state
+ ;; Lets see if this entry has a TRIGGER property.
+ ;; If yes, split it up on whitespace.
+ (setq trigger (org-entry-get pos "TRIGGER")
+ triggers (and trigger (org-split-string trigger "[ \t]+")))
+
+ ;; Go through all the triggers
+ (while (setq tr (pop triggers))
+ (cond
+ ((and (not org-depend-doing-chain-find-next)
+ (string-match "\\`chain-find-next(\\b\\(.+?\\)\\b\\(.*\\))\\'" tr))
+ ;; smarter sibling selection
+ (let* ((org-depend-doing-chain-find-next t)
+ (kwd (match-string 1 tr))
+ (options (match-string 2 tr))
+ (options (if (or (null options)
+ (equal options ""))
+ org-depend-find-next-options
+ options))
+ (todo-only (string-match "todo-only" options))
+ (todo-and-done-only (string-match "todo-and-done-only"
+ options))
+ (from-top (string-match "from-top" options))
+ (from-bottom (string-match "from-bottom" options))
+ (from-current (string-match "from-current" options))
+ (no-wrap (string-match "no-wrap" options))
+ (priority-up (string-match "priority-up" options))
+ (priority-down (string-match "priority-down" options))
+ (effort-up (string-match "effort-up" options))
+ (effort-down (string-match "effort-down" options)))
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((this-item (point)))
+ ;; go up to the parent headline, then advance to next child
+ (org-up-heading-safe)
+ (let ((end (save-excursion (org-end-of-subtree t)
+ (point)))
+ (done nil)
+ (items '()))
+ (outline-next-heading)
+ (while (not done)
+ (if (not (looking-at org-complex-heading-regexp))
+ (setq done t)
+ (let ((todo-kwd (match-string 2))
+ (tags (match-string 5))
+ (priority (org-get-priority (or (match-string 3) "")))
+ (effort (when (or effort-up effort-down)
+ (let ((effort (get-text-property (point) 'org-effort)))
+ (when effort
+ (org-duration-string-to-minutes effort))))))
+ (push (list (point) todo-kwd priority tags effort)
+ items))
+ (unless (org-goto-sibling)
+ (setq done t))))
+ ;; massage the list according to options
+ (setq items
+ (cond (from-top (nreverse items))
+ (from-bottom items)
+ ((or from-current no-wrap)
+ (let* ((items (nreverse items))
+ (pos (position this-item items :key #'first))
+ (items-before (subseq items 0 pos))
+ (items-after (subseq items pos)))
+ (if no-wrap items-after
+ (append items-after items-before))))
+ (t (nreverse items))))
+ (setq items (remove-if
+ (lambda (item)
+ (or (equal (first item) this-item)
+ (and (not todo-and-done-only)
+ (member (second item) org-done-keywords))
+ (and (or todo-only
+ todo-and-done-only)
+ (null (second item)))))
+ items))
+ (setq items
+ (sort
+ items
+ (lambda (item1 item2)
+ (let* ((p1 (third item1))
+ (p2 (third item2))
+ (e1 (fifth item1))
+ (e2 (fifth item2))
+ (p1-lt (< p1 p2))
+ (p1-gt (> p1 p2))
+ (e1-lt (and e1 (or (not e2) (< e1 e2))))
+ (e2-gt (and e2 (or (not e1) (> e1 e2)))))
+ (cond (priority-up
+ (or p1-gt
+ (and (equal p1 p2)
+ (or (and effort-up e1-lt)
+ (and effort-down e2-gt)))))
+ (priority-down
+ (or p1-lt
+ (and (equal p1 p2)
+ (or (and effort-up e1-lt)
+ (and effort-down e2-gt)))))
+ (effort-up
+ (or e2-gt (and (equal e1 e2) p1-gt)))
+ (effort-down
+ (or e1-lt (and (equal e1 e2) p1-gt))))))))
+ (when items
+ (goto-char (first (first items)))
+ (org-entry-add-to-multivalued-property nil "TRIGGER" tr)
+ (org-todo kwd)))))))
+ ((string-match "\\`chain-siblings(\\(.*?\\))\\'" tr)
+ ;; This is a TODO chain of siblings
+ (setq kwd (match-string 1 tr))
+ (org-depend-act-on-sibling (format "chain-siblings(%s)" kwd)
+ (org-todo kwd)))
+ ((string-match "\\`\\(\\S-+\\)(\\(.*?\\))\\'" tr)
+ ;; This seems to be ENTRY_ID(KEYWORD)
+ (setq id (match-string 1 tr)
+ kwd (match-string 2 tr)
+ p1 (org-find-entry-with-id id))
+ (when p1
+ ;; there is an entry with this ID, mark it TODO
+ (save-excursion
+ (goto-char p1)
+ (org-todo kwd))))
+ ((string-match "\\`chain-siblings-scheduled\\'" tr)
+ (let ((time (org-get-scheduled-time pos)))
+ (when time
+ (org-depend-act-on-sibling
+ "chain-siblings-scheduled"
+ (org-schedule nil time))))))))))
+
+(defun org-depend-block-todo (change-plist)
+ "Block turning an entry into a TODO.
+This checks for a BLOCKER property in an entry and checks
+all the entries listed there. If any of them is not done,
+block changing the current entry into a TODO entry. If the property contains
+the word \"previous-sibling\", the sibling above the current entry is checked.
+Any other words are treated as entry id's. If an entry exists with the
+this ID property, that entry is also checked."
+ ;; Get information from the plist
+ (let* ((type (plist-get change-plist :type))
+ (pos (plist-get change-plist :position))
+ (from (plist-get change-plist :from))
+ (to (plist-get change-plist :to))
+ (org-log-done nil) ; IMPROTANT!: no logging during automatic trigger
+ blocker blockers bl p1
+ (proceed-p
+ (catch 'return
+ ;; If this is not a todo state change, or if this entry is
+ ;; DONE, do not block
+ (when (or (not (eq type 'todo-state-change))
+ (member from (cons 'done org-done-keywords))
+ (member to (cons 'todo org-not-done-keywords))
+ (not to))
+ (throw 'return t))
+
+ ;; OK, the plan is to switch from nothing to TODO
+ ;; Lets see if we will allow it. Find the BLOCKER property
+ ;; and split it on whitespace.
+ (setq blocker (org-entry-get pos "BLOCKER")
+ blockers (and blocker (org-split-string blocker "[ \t]+")))
+
+ ;; go through all the blockers
+ (while (setq bl (pop blockers))
+ (cond
+ ((equal bl "previous-sibling")
+ ;; the sibling is required to be DONE.
+ (catch 'ignore
+ (save-excursion
+ (goto-char pos)
+ ;; find the older sibling, exit if no more siblings
+ (condition-case nil
+ (outline-backward-same-level 1)
+ (error (throw 'ignore t)))
+ ;; Check if this entry is not yet done and block
+ (unless (org-entry-is-done-p)
+ ;; return nil, to indicate that we block the change!
+ (org-mark-ring-push)
+ (throw 'return nil)))))
+
+ ((setq p1 (org-find-entry-with-id bl))
+ ;; there is an entry with this ID, check it out
+ (save-excursion
+ (goto-char p1)
+ (unless (org-entry-is-done-p)
+ ;; return nil, to indicate that we block the change!
+ (org-mark-ring-push)
+ (throw 'return nil))))))
+ t ; return t to indicate that we are not blocking
+ )))
+ (when org-depend-tag-blocked
+ (org-toggle-tag "blocked" (if proceed-p 'off 'on)))
+
+ proceed-p))
+
+(add-hook 'org-trigger-hook 'org-depend-trigger-todo)
+(add-hook 'org-blocker-hook 'org-depend-block-todo)
+
+(provide 'org-depend)
+
+;;; org-depend.el ends here
diff --git a/contrib/lisp/org-drill.el b/contrib/lisp/org-drill.el
new file mode 100644
index 0000000..fb578ab
--- /dev/null
+++ b/contrib/lisp/org-drill.el
@@ -0,0 +1,3367 @@
+;; -*- coding: utf-8-unix -*-
+;;; org-drill.el - Self-testing using spaced repetition
+;;;
+;;; Copyright (C) 2010-2015 Paul Sexton
+;;;
+;;; Author: Paul Sexton <eeeickythump@gmail.com>
+;;; Version: 2.4.7
+;;; Keywords: flashcards, memory, learning, memorization
+;;; Repository at http://bitbucket.org/eeeickythump/org-drill/
+;;;
+;;; This file is not part of GNU Emacs.
+;;;
+;;; This program is free software; you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; This program is distaributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+;;;
+;;;
+;;; Synopsis
+;;; ========
+;;;
+;;; Uses the SuperMemo spaced repetition algorithms to conduct interactive
+;;; "drill sessions", where the material to be remembered is presented to the
+;;; student in random order. The student rates his or her recall of each item,
+;;; and this information is used to schedule the item for later revision.
+;;;
+;;; Each drill session can be restricted to topics in the current buffer
+;;; (default), one or several files, all agenda files, or a subtree. A single
+;;; topic can also be drilled.
+;;;
+;;; Different "card types" can be defined, which present their information to
+;;; the student in different ways.
+;;;
+;;; See the file README.org for more detailed documentation.
+
+
+(eval-when-compile (require 'cl))
+(eval-when-compile (require 'hi-lock))
+(require 'cl-lib)
+(require 'hi-lock)
+(require 'org)
+(require 'org-id)
+(require 'org-learn)
+(require 'savehist)
+
+
+(defgroup org-drill nil
+ "Options concerning interactive drill sessions in Org mode (org-drill)."
+ :tag "Org-Drill"
+ :group 'org-link)
+
+
+
+(defcustom org-drill-question-tag
+ "drill"
+ "Tag which topics must possess in order to be identified as review topics
+by `org-drill'."
+ :group 'org-drill
+ :type 'string)
+
+
+(defcustom org-drill-maximum-items-per-session
+ 30
+ "Each drill session will present at most this many topics for review.
+Nil means unlimited."
+ :group 'org-drill
+ :type '(choice integer (const nil)))
+
+
+
+(defcustom org-drill-maximum-duration
+ 20
+ "Maximum duration of a drill session, in minutes.
+Nil means unlimited."
+ :group 'org-drill
+ :type '(choice integer (const nil)))
+
+
+(defcustom org-drill-failure-quality
+ 2
+ "If the quality of recall for an item is this number or lower,
+it is regarded as an unambiguous failure, and the repetition
+interval for the card is reset to 0 days. If the quality is higher
+than this number, it is regarded as successfully recalled, but the
+time interval to the next repetition will be lowered if the quality
+was near to a fail.
+
+By default this is 2, for SuperMemo-like behaviour. For
+Mnemosyne-like behaviour, set it to 1. Other values are not
+really sensible."
+ :group 'org-drill
+ :type '(choice (const 2) (const 1)))
+
+
+(defcustom org-drill-forgetting-index
+ 10
+ "What percentage of items do you consider it is 'acceptable' to
+forget each drill session? The default is 10%. A warning message
+is displayed at the end of the session if the percentage forgotten
+climbs above this number."
+ :group 'org-drill
+ :type 'integer)
+
+
+(defcustom org-drill-leech-failure-threshold
+ 15
+ "If an item is forgotten more than this many times, it is tagged
+as a 'leech' item."
+ :group 'org-drill
+ :type '(choice integer (const nil)))
+
+
+(defcustom org-drill-leech-method
+ 'skip
+ "How should 'leech items' be handled during drill sessions?
+Possible values:
+- nil :: Leech items are treated the same as normal items.
+- skip :: Leech items are not included in drill sessions.
+- warn :: Leech items are still included in drill sessions,
+ but a warning message is printed when each leech item is
+ presented."
+ :group 'org-drill
+ :type '(choice (const warn) (const skip) (const nil)))
+
+
+(defface org-drill-visible-cloze-face
+ '((t (:foreground "darkseagreen")))
+ "The face used to hide the contents of cloze phrases."
+ :group 'org-drill)
+
+
+(defface org-drill-visible-cloze-hint-face
+ '((t (:foreground "dark slate blue")))
+ "The face used to hide the contents of cloze phrases."
+ :group 'org-drill)
+
+
+(defface org-drill-hidden-cloze-face
+ '((t (:foreground "deep sky blue" :background "blue")))
+ "The face used to hide the contents of cloze phrases."
+ :group 'org-drill)
+
+
+(defcustom org-drill-use-visible-cloze-face-p
+ nil
+ "Use a special face to highlight cloze-deleted text in org mode
+buffers?"
+ :group 'org-drill
+ :type 'boolean)
+
+
+(defcustom org-drill-hide-item-headings-p
+ nil
+ "Conceal the contents of the main heading of each item during drill
+sessions? You may want to enable this behaviour if item headings or tags
+contain information that could 'give away' the answer."
+ :group 'org-drill
+ :type 'boolean)
+
+
+(defcustom org-drill-new-count-color
+ "royal blue"
+ "Foreground colour used to display the count of remaining new items
+during a drill session."
+ :group 'org-drill
+ :type 'color)
+
+(defcustom org-drill-mature-count-color
+ "green"
+ "Foreground colour used to display the count of remaining mature items
+during a drill session. Mature items are due for review, but are not new."
+ :group 'org-drill
+ :type 'color)
+
+(defcustom org-drill-failed-count-color
+ "red"
+ "Foreground colour used to display the count of remaining failed items
+during a drill session."
+ :group 'org-drill
+ :type 'color)
+
+(defcustom org-drill-done-count-color
+ "sienna"
+ "Foreground colour used to display the count of reviewed items
+during a drill session."
+ :group 'org-drill
+ :type 'color)
+
+(defcustom org-drill-left-cloze-delimiter
+ "["
+ "String used within org buffers to delimit cloze deletions."
+ :group 'org-drill
+ :type 'string)
+
+(defcustom org-drill-right-cloze-delimiter
+ "]"
+ "String used within org buffers to delimit cloze deletions."
+ :group 'org-drill
+ :type 'string)
+
+
+(setplist 'org-drill-cloze-overlay-defaults
+ `(display ,(format "%s...%s"
+ org-drill-left-cloze-delimiter
+ org-drill-right-cloze-delimiter)
+ face org-drill-hidden-cloze-face
+ window t))
+
+(setplist 'org-drill-hidden-text-overlay
+ '(invisible t))
+
+(setplist 'org-drill-replaced-text-overlay
+ '(display "Replaced text"
+ face default
+ window t))
+
+(add-hook 'org-font-lock-set-keywords-hook 'org-drill-add-cloze-fontification)
+
+
+(defvar org-drill-hint-separator "||"
+ "String which, if it occurs within a cloze expression, signifies that the
+rest of the expression after the string is a `hint', to be displayed instead of
+the hidden cloze during a test.")
+
+(defun org-drill--compute-cloze-regexp ()
+ (concat "\\("
+ (regexp-quote org-drill-left-cloze-delimiter)
+ "[[:cntrl:][:graph:][:space:]]+?\\)\\(\\|"
+ (regexp-quote org-drill-hint-separator)
+ ".+?\\)\\("
+ (regexp-quote org-drill-right-cloze-delimiter)
+ "\\)"))
+
+(defun org-drill--compute-cloze-keywords ()
+ (list (list (org-drill--compute-cloze-regexp)
+ (copy-list '(1 'org-drill-visible-cloze-face nil))
+ (copy-list '(2 'org-drill-visible-cloze-hint-face t))
+ (copy-list '(3 'org-drill-visible-cloze-face nil))
+ )))
+
+(defvar-local org-drill-cloze-regexp
+ (org-drill--compute-cloze-regexp))
+
+
+(defvar-local org-drill-cloze-keywords
+ (org-drill--compute-cloze-keywords))
+
+
+;; Variables defining what keys can be pressed during drill sessions to quit the
+;; session, edit the item, etc.
+(defvar org-drill--quit-key ?q
+ "If this character is pressed during a drill session, quit the session.")
+(defvar org-drill--edit-key ?e
+ "If this character is pressed during a drill session, suspend the session
+with the cursor at the current item..")
+(defvar org-drill--help-key ??
+ "If this character is pressed during a drill session, show help.")
+(defvar org-drill--skip-key ?s
+ "If this character is pressed during a drill session, skip to the next
+item.")
+(defvar org-drill--tags-key ?t
+ "If this character is pressed during a drill session, edit the tags for
+the current item.")
+
+
+(defcustom org-drill-card-type-alist
+ '((nil org-drill-present-simple-card)
+ ("simple" org-drill-present-simple-card)
+ ("twosided" org-drill-present-two-sided-card nil t)
+ ("multisided" org-drill-present-multi-sided-card nil t)
+ ("hide1cloze" org-drill-present-multicloze-hide1)
+ ("hide2cloze" org-drill-present-multicloze-hide2)
+ ("show1cloze" org-drill-present-multicloze-show1)
+ ("show2cloze" org-drill-present-multicloze-show2)
+ ("multicloze" org-drill-present-multicloze-hide1)
+ ("hidefirst" org-drill-present-multicloze-hide-first)
+ ("hidelast" org-drill-present-multicloze-hide-last)
+ ("hide1_firstmore" org-drill-present-multicloze-hide1-firstmore)
+ ("show1_lastmore" org-drill-present-multicloze-show1-lastmore)
+ ("show1_firstless" org-drill-present-multicloze-show1-firstless)
+ ("conjugate"
+ org-drill-present-verb-conjugation
+ org-drill-show-answer-verb-conjugation)
+ ("decline_noun"
+ org-drill-present-noun-declension
+ org-drill-show-answer-noun-declension)
+ ("spanish_verb" org-drill-present-spanish-verb)
+ ("translate_number" org-drill-present-translate-number))
+ "Alist associating card types with presentation functions. Each
+entry in the alist takes the form:
+
+;;; (CARDTYPE QUESTION-FN [ANSWER-FN DRILL-EMPTY-P])
+
+Where CARDTYPE is a string or nil (for default), and QUESTION-FN
+is a function which takes no arguments and returns a boolean
+value.
+
+When supplied, ANSWER-FN is a function that takes one argument --
+that argument is a function of no arguments, which when called,
+prompts the user to rate their recall and performs rescheduling
+of the drill item. ANSWER-FN is called with the point on the
+active item's heading, just prior to displaying the item's
+'answer'. It can therefore be used to modify the appearance of
+the answer. ANSWER-FN must call its argument before returning.
+
+When supplied, DRILL-EMPTY-P is a boolean value, default nil.
+When non-nil, cards of this type will be presented during tests
+even if their bodies are empty."
+ :group 'org-drill
+ :type '(alist :key-type (choice string (const nil))
+ :value-type function))
+
+
+(defcustom org-drill-scope
+ 'file
+ "The scope in which to search for drill items when conducting a
+drill session. This can be any of:
+
+file The current buffer, respecting the restriction if any.
+ This is the default.
+tree The subtree started with the entry at point
+file-no-restriction The current buffer, without restriction
+file-with-archives The current buffer, and any archives associated with it.
+agenda All agenda files
+agenda-with-archives All agenda files with any archive files associated
+ with them.
+directory All files with the extension '.org' in the same
+ directory as the current file (includes the current
+ file if it is an .org file.)
+ (FILE1 FILE2 ...) If this is a list, all files in the list will be scanned.
+"
+ ;; Note -- meanings differ slightly from the argument to org-map-entries:
+ ;; 'file' means current file/buffer, respecting any restriction
+ ;; 'file-no-restriction' means current file/buffer, ignoring restrictions
+ ;; 'directory' means all *.org files in current directory
+ :group 'org-drill
+ :type '(choice (const :tag "The current buffer, respecting the restriction if any." file)
+ (const :tag "The subtree started with the entry at point" tree)
+ (const :tag "The current buffer, without restriction" file-no-restriction)
+ (const :tag "The current buffer, and any archives associated with it." file-with-archives)
+ (const :tag "All agenda files" agenda)
+ (const :tag "All agenda files with any archive files associated with them." agenda-with-archives)
+ (const :tag "All files with the extension '.org' in the same directory as the current file (includes the current file if it is an .org file.)" directory)
+ (repeat :tag "List of files to scan for drill items." file)))
+
+
+(defcustom org-drill-match
+ nil
+ "If non-nil, a string specifying a tags/property/TODO query. During
+drill sessions, only items that match this query will be considered."
+ :group 'org-drill
+ :type '(choice (const nil) string))
+
+
+(defcustom org-drill-save-buffers-after-drill-sessions-p
+ t
+ "If non-nil, prompt to save all modified buffers after a drill session
+finishes."
+ :group 'org-drill
+ :type 'boolean)
+
+
+(defcustom org-drill-spaced-repetition-algorithm
+ 'sm5
+ "Which SuperMemo spaced repetition algorithm to use for scheduling items.
+Available choices are:
+- SM2 :: the SM2 algorithm, used in SuperMemo 2.0
+- SM5 :: the SM5 algorithm, used in SuperMemo 5.0
+- Simple8 :: a modified version of the SM8 algorithm. SM8 is used in
+ SuperMemo 98. The version implemented here is simplified in that while it
+ 'learns' the difficulty of each item using quality grades and number of
+ failures, it does not modify the matrix of values that
+ governs how fast the inter-repetition intervals increase. A method for
+ adjusting intervals when items are reviewed early or late has been taken
+ from SM11, a later version of the algorithm, and included in Simple8."
+ :group 'org-drill
+ :type '(choice (const sm2) (const sm5) (const simple8)))
+
+
+(defcustom org-drill-optimal-factor-matrix
+ nil
+ "Obsolete and will be removed in future. The SM5 optimal factor
+matrix data is now stored in the variable
+`org-drill-sm5-optimal-factor-matrix'."
+ :group 'org-drill
+ :type 'sexp)
+
+
+(defvar org-drill-sm5-optimal-factor-matrix
+ nil
+ "DO NOT CHANGE THE VALUE OF THIS VARIABLE.
+
+Persistent matrix of optimal factors, used by the SuperMemo SM5
+algorithm. The matrix is saved at the end of each drill session.
+
+Over time, values in the matrix will adapt to the individual user's
+pace of learning.")
+
+
+(add-to-list 'savehist-additional-variables
+ 'org-drill-sm5-optimal-factor-matrix)
+(unless savehist-mode
+ (savehist-mode 1))
+
+
+(defun org-drill--transfer-optimal-factor-matrix ()
+ (if (and org-drill-optimal-factor-matrix
+ (null org-drill-sm5-optimal-factor-matrix))
+ (setq org-drill-sm5-optimal-factor-matrix
+ org-drill-optimal-factor-matrix)))
+
+(add-hook 'after-init-hook 'org-drill--transfer-optimal-factor-matrix)
+
+
+(defcustom org-drill-sm5-initial-interval
+ 4.0
+ "In the SM5 algorithm, the initial interval after the first
+successful presentation of an item is always 4 days. If you wish to change
+this, you can do so here."
+ :group 'org-drill
+ :type 'float)
+
+
+(defcustom org-drill-add-random-noise-to-intervals-p
+ nil
+ "If true, the number of days until an item's next repetition
+will vary slightly from the interval calculated by the SM2
+algorithm. The variation is very small when the interval is
+small, but scales up with the interval."
+ :group 'org-drill
+ :type 'boolean)
+
+
+(defcustom org-drill-adjust-intervals-for-early-and-late-repetitions-p
+ nil
+ "If true, when the student successfully reviews an item 1 or more days
+before or after the scheduled review date, this will affect that date of
+the item's next scheduled review, according to the algorithm presented at
+ [[http://www.supermemo.com/english/algsm11.htm#Advanced%20repetitions]].
+
+Items that were reviewed early will have their next review date brought
+forward. Those that were reviewed late will have their next review
+date postponed further.
+
+Note that this option currently has no effect if the SM2 algorithm
+is used."
+ :group 'org-drill
+ :type 'boolean)
+
+
+(defcustom org-drill-cloze-text-weight
+ 4
+ "For card types 'hide1_firstmore', 'show1_lastmore' and 'show1_firstless',
+this number determines how often the 'less favoured' situation
+should arise. It will occur 1 in every N trials, where N is the
+value of the variable.
+
+For example, with the hide1_firstmore card type, the first piece
+of clozed text should be hidden more often than the other
+pieces. If this variable is set to 4 (default), the first item
+will only be shown 25% of the time (1 in 4 trials). Similarly for
+show1_lastmore, the last item will be shown 75% of the time, and
+for show1_firstless, the first item would only be shown 25% of the
+time.
+
+If the value of this variable is NIL, then weighting is disabled, and
+all weighted card types are treated as their unweighted equivalents."
+ :group 'org-drill
+ :type '(choice integer (const nil)))
+
+
+(defcustom org-drill-cram-hours
+ 12
+ "When in cram mode, items are considered due for review if
+they were reviewed at least this many hours ago."
+ :group 'org-drill
+ :type 'integer)
+
+
+;;; NEW items have never been presented in a drill session before.
+;;; MATURE items HAVE been presented at least once before.
+;;; - YOUNG mature items were scheduled no more than
+;;; ORG-DRILL-DAYS-BEFORE-OLD days after their last
+;;; repetition. These items will have been learned 'recently' and will have a
+;;; low repetition count.
+;;; - OLD mature items have intervals greater than
+;;; ORG-DRILL-DAYS-BEFORE-OLD.
+;;; - OVERDUE items are past their scheduled review date by more than
+;;; LAST-INTERVAL * (ORG-DRILL-OVERDUE-INTERVAL-FACTOR - 1) days,
+;;; regardless of young/old status.
+
+
+(defcustom org-drill-days-before-old
+ 10
+ "When an item's inter-repetition interval rises above this value in days,
+it is no longer considered a 'young' (recently learned) item."
+ :group 'org-drill
+ :type 'integer)
+
+
+(defcustom org-drill-overdue-interval-factor
+ 1.2
+ "An item is considered overdue if its scheduled review date is
+more than (ORG-DRILL-OVERDUE-INTERVAL-FACTOR - 1) * LAST-INTERVAL
+days in the past. For example, a value of 1.2 means an additional
+20% of the last scheduled interval is allowed to elapse before
+the item is overdue. A value of 1.0 means no extra time is
+allowed at all - items are immediately considered overdue if
+there is even one day's delay in reviewing them. This variable
+should never be less than 1.0."
+ :group 'org-drill
+ :type 'float)
+
+
+(defcustom org-drill-learn-fraction
+ 0.5
+ "Fraction between 0 and 1 that governs how quickly the spaces
+between successive repetitions increase, for all items. The
+default value is 0.5. Higher values make spaces increase more
+quickly with each successful repetition. You should only change
+this in small increments (for example 0.05-0.1) as it has an
+exponential effect on inter-repetition spacing."
+ :group 'org-drill
+ :type 'float)
+
+
+(defvar drill-answer nil
+ "Global variable that can be bound to a correct answer when an
+item is being presented. If this variable is non-nil, the default
+presentation function will show its value instead of the default
+behaviour of revealing the contents of the drilled item.
+
+This variable is useful for card types that compute their answers
+-- for example, a card type that asks the student to translate a
+random number to another language. ")
+
+
+(defvar *org-drill-session-qualities* nil)
+(defvar *org-drill-start-time* 0)
+(defvar *org-drill-new-entries* nil)
+(defvar *org-drill-dormant-entry-count* 0)
+(defvar *org-drill-due-entry-count* 0)
+(defvar *org-drill-overdue-entry-count* 0)
+(defvar *org-drill-due-tomorrow-count* 0)
+(defvar *org-drill-overdue-entries* nil
+ "List of markers for items that are considered 'overdue', based on
+the value of ORG-DRILL-OVERDUE-INTERVAL-FACTOR.")
+(defvar *org-drill-young-mature-entries* nil
+ "List of markers for mature entries whose last inter-repetition
+interval was <= ORG-DRILL-DAYS-BEFORE-OLD days.")
+(defvar *org-drill-old-mature-entries* nil
+ "List of markers for mature entries whose last inter-repetition
+interval was greater than ORG-DRILL-DAYS-BEFORE-OLD days.")
+(defvar *org-drill-failed-entries* nil)
+(defvar *org-drill-again-entries* nil)
+(defvar *org-drill-done-entries* nil)
+(defvar *org-drill-current-item* nil
+ "Set to the marker for the item currently being tested.")
+(defvar *org-drill-cram-mode* nil
+ "Are we in 'cram mode', where all items are considered due
+for review unless they were already reviewed in the recent past?")
+(defvar org-drill-scheduling-properties
+ '("LEARN_DATA" "DRILL_LAST_INTERVAL" "DRILL_REPEATS_SINCE_FAIL"
+ "DRILL_TOTAL_REPEATS" "DRILL_FAILURE_COUNT" "DRILL_AVERAGE_QUALITY"
+ "DRILL_EASE" "DRILL_LAST_QUALITY" "DRILL_LAST_REVIEWED"))
+(defvar org-drill--lapse-very-overdue-entries-p nil
+ "If non-nil, entries more than 90 days overdue are regarded as 'lapsed'.
+This means that when the item is eventually re-tested it will be
+treated as 'failed' (quality 2) for rescheduling purposes,
+regardless of whether the test was successful.")
+
+
+;;; Make the above settings safe as file-local variables.
+
+
+(put 'org-drill-question-tag 'safe-local-variable 'stringp)
+(put 'org-drill-maximum-items-per-session 'safe-local-variable
+ '(lambda (val) (or (integerp val) (null val))))
+(put 'org-drill-maximum-duration 'safe-local-variable
+ '(lambda (val) (or (integerp val) (null val))))
+(put 'org-drill-failure-quality 'safe-local-variable 'integerp)
+(put 'org-drill-forgetting-index 'safe-local-variable 'integerp)
+(put 'org-drill-leech-failure-threshold 'safe-local-variable 'integerp)
+(put 'org-drill-leech-method 'safe-local-variable
+ '(lambda (val) (memq val '(nil skip warn))))
+(put 'org-drill-use-visible-cloze-face-p 'safe-local-variable 'booleanp)
+(put 'org-drill-hide-item-headings-p 'safe-local-variable 'booleanp)
+(put 'org-drill-spaced-repetition-algorithm 'safe-local-variable
+ '(lambda (val) (memq val '(simple8 sm5 sm2))))
+(put 'org-drill-sm5-initial-interval 'safe-local-variable 'floatp)
+(put 'org-drill-add-random-noise-to-intervals-p 'safe-local-variable 'booleanp)
+(put 'org-drill-adjust-intervals-for-early-and-late-repetitions-p
+ 'safe-local-variable 'booleanp)
+(put 'org-drill-cram-hours 'safe-local-variable 'integerp)
+(put 'org-drill-learn-fraction 'safe-local-variable 'floatp)
+(put 'org-drill-days-before-old 'safe-local-variable 'integerp)
+(put 'org-drill-overdue-interval-factor 'safe-local-variable 'floatp)
+(put 'org-drill-scope 'safe-local-variable
+ '(lambda (val) (or (symbolp val) (listp val))))
+(put 'org-drill-match 'safe-local-variable
+ '(lambda (val) (or (stringp val) (null val))))
+(put 'org-drill-save-buffers-after-drill-sessions-p 'safe-local-variable 'booleanp)
+(put 'org-drill-cloze-text-weight 'safe-local-variable
+ '(lambda (val) (or (null val) (integerp val))))
+(put 'org-drill-left-cloze-delimiter 'safe-local-variable 'stringp)
+(put 'org-drill-right-cloze-delimiter 'safe-local-variable 'stringp)
+
+
+;;;; Utilities ================================================================
+
+
+(defun free-marker (m)
+ (set-marker m nil))
+
+
+(defmacro pop-random (place)
+ (let ((idx (gensym)))
+ `(if (null ,place)
+ nil
+ (let ((,idx (random* (length ,place))))
+ (prog1 (nth ,idx ,place)
+ (setq ,place (append (subseq ,place 0 ,idx)
+ (subseq ,place (1+ ,idx)))))))))
+
+
+(defmacro push-end (val place)
+ "Add VAL to the end of the sequence stored in PLACE. Return the new
+value."
+ `(setq ,place (append ,place (list ,val))))
+
+
+(defun shuffle-list (list)
+ "Randomly permute the elements of LIST (all permutations equally likely)."
+ ;; Adapted from 'shuffle-vector' in cookie1.el
+ (let ((i 0)
+ j
+ temp
+ (len (length list)))
+ (while (< i len)
+ (setq j (+ i (random* (- len i))))
+ (setq temp (nth i list))
+ (setf (nth i list) (nth j list))
+ (setf (nth j list) temp)
+ (setq i (1+ i))))
+ list)
+
+
+(defun round-float (floatnum fix)
+ "Round the floating point number FLOATNUM to FIX decimal places.
+Example: (round-float 3.56755765 3) -> 3.568"
+ (let ((n (expt 10 fix)))
+ (/ (float (round (* floatnum n))) n)))
+
+
+(defun command-keybinding-to-string (cmd)
+ "Return a human-readable description of the key/keys to which the command
+CMD is bound, or nil if it is not bound to a key."
+ (let ((key (where-is-internal cmd overriding-local-map t)))
+ (if key (key-description key))))
+
+
+(defun time-to-inactive-org-timestamp (time)
+ (format-time-string
+ (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
+ time))
+
+
+(defun time-to-active-org-timestamp (time)
+ (format-time-string
+ (concat "<" (substring (cdr org-time-stamp-formats) 1 -1) ">")
+ time))
+
+
+(defun org-map-drill-entries (func &optional scope drill-match &rest skip)
+ "Like `org-map-entries', but only drill entries are processed."
+ (let ((org-drill-scope (or scope org-drill-scope))
+ (org-drill-match (or drill-match org-drill-match)))
+ (apply 'org-map-entries func
+ (concat "+" org-drill-question-tag
+ (if (and (stringp org-drill-match)
+ (not (member '(?+ ?- ?|) (elt org-drill-match 0))))
+ "+" "")
+ (or org-drill-match ""))
+ (case org-drill-scope
+ (file nil)
+ (file-no-restriction 'file)
+ (directory
+ (directory-files (file-name-directory (buffer-file-name))
+ t "\\.org$"))
+ (t org-drill-scope))
+ skip)))
+
+
+(defmacro with-hidden-cloze-text (&rest body)
+ `(progn
+ (org-drill-hide-clozed-text)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unhide-clozed-text))))
+
+
+(defmacro with-hidden-cloze-hints (&rest body)
+ `(progn
+ (org-drill-hide-cloze-hints)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unhide-text))))
+
+
+(defmacro with-hidden-comments (&rest body)
+ `(progn
+ (if org-drill-hide-item-headings-p
+ (org-drill-hide-heading-at-point))
+ (org-drill-hide-comments)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unhide-text))))
+
+
+(defun org-drill-days-since-last-review ()
+ "Nil means a last review date has not yet been stored for
+the item.
+Zero means it was reviewed today.
+A positive number means it was reviewed that many days ago.
+A negative number means the date of last review is in the future --
+this should never happen."
+ (let ((datestr (org-entry-get (point) "DRILL_LAST_REVIEWED")))
+ (when datestr
+ (- (time-to-days (current-time))
+ (time-to-days (apply 'encode-time
+ (org-parse-time-string datestr)))))))
+
+
+(defun org-drill-hours-since-last-review ()
+ "Like `org-drill-days-since-last-review', but return value is
+in hours rather than days."
+ (let ((datestr (org-entry-get (point) "DRILL_LAST_REVIEWED")))
+ (when datestr
+ (floor
+ (/ (- (time-to-seconds (current-time))
+ (time-to-seconds (apply 'encode-time
+ (org-parse-time-string datestr))))
+ (* 60 60))))))
+
+
+(defun org-drill-entry-p (&optional marker)
+ "Is MARKER, or the point, in a 'drill item'? This will return nil if
+the point is inside a subheading of a drill item -- to handle that
+situation use `org-part-of-drill-entry-p'."
+ (save-excursion
+ (when marker
+ (org-drill-goto-entry marker))
+ (member org-drill-question-tag (org-get-local-tags))))
+
+
+(defun org-drill-goto-entry (marker)
+ (switch-to-buffer (marker-buffer marker))
+ (goto-char marker))
+
+
+(defun org-part-of-drill-entry-p ()
+ "Is the current entry either the main heading of a 'drill item',
+or a subheading within a drill item?"
+ (or (org-drill-entry-p)
+ ;; Does this heading INHERIT the drill tag
+ (member org-drill-question-tag (org-get-tags-at))))
+
+
+(defun org-drill-goto-drill-entry-heading ()
+ "Move the point to the heading which holds the :drill: tag for this
+drill entry."
+ (unless (org-at-heading-p)
+ (org-back-to-heading))
+ (unless (org-part-of-drill-entry-p)
+ (error "Point is not inside a drill entry"))
+ (while (not (org-drill-entry-p))
+ (unless (org-up-heading-safe)
+ (error "Cannot find a parent heading that is marked as a drill entry"))))
+
+
+
+(defun org-drill-entry-leech-p ()
+ "Is the current entry a 'leech item'?"
+ (and (org-drill-entry-p)
+ (member "leech" (org-get-local-tags))))
+
+
+;; (defun org-drill-entry-due-p ()
+;; (cond
+;; (*org-drill-cram-mode*
+;; (let ((hours (org-drill-hours-since-last-review)))
+;; (and (org-drill-entry-p)
+;; (or (null hours)
+;; (>= hours org-drill-cram-hours)))))
+;; (t
+;; (let ((item-time (org-get-scheduled-time (point))))
+;; (and (org-drill-entry-p)
+;; (or (not (eql 'skip org-drill-leech-method))
+;; (not (org-drill-entry-leech-p)))
+;; (or (null item-time) ; not scheduled
+;; (not (minusp ; scheduled for today/in past
+;; (- (time-to-days (current-time))
+;; (time-to-days item-time))))))))))
+
+
+(defun org-drill-entry-days-overdue ()
+ "Returns:
+- NIL if the item is not to be regarded as scheduled for review at all.
+ This is the case if it is not a drill item, or if it is a leech item
+ that we wish to skip, or if we are in cram mode and have already reviewed
+ the item within the last few hours.
+- 0 if the item is new, or if it scheduled for review today.
+- A negative integer - item is scheduled that many days in the future.
+- A positive integer - item is scheduled that many days in the past."
+ (cond
+ (*org-drill-cram-mode*
+ (let ((hours (org-drill-hours-since-last-review)))
+ (and (org-drill-entry-p)
+ (or (null hours)
+ (>= hours org-drill-cram-hours))
+ 0)))
+ (t
+ (let ((item-time (org-get-scheduled-time (point))))
+ (cond
+ ((or (not (org-drill-entry-p))
+ (and (eql 'skip org-drill-leech-method)
+ (org-drill-entry-leech-p)))
+ nil)
+ ((null item-time) ; not scheduled -> due now
+ 0)
+ (t
+ (- (time-to-days (current-time))
+ (time-to-days item-time))))))))
+
+
+(defun org-drill-entry-overdue-p (&optional days-overdue last-interval)
+ "Returns true if entry that is scheduled DAYS-OVERDUE dasy in the past,
+and whose last inter-repetition interval was LAST-INTERVAL, should be
+considered 'overdue'. If the arguments are not given they are extracted
+from the entry at point."
+ (unless days-overdue
+ (setq days-overdue (org-drill-entry-days-overdue)))
+ (unless last-interval
+ (setq last-interval (org-drill-entry-last-interval 1)))
+ (and (numberp days-overdue)
+ (> days-overdue 1) ; enforce a sane minimum 'overdue' gap
+ ;;(> due org-drill-days-before-overdue)
+ (> (/ (+ days-overdue last-interval 1.0) last-interval)
+ org-drill-overdue-interval-factor)))
+
+
+
+(defun org-drill-entry-due-p ()
+ (let ((due (org-drill-entry-days-overdue)))
+ (and (not (null due))
+ (not (minusp due)))))
+
+
+(defun org-drill-entry-new-p ()
+ (and (org-drill-entry-p)
+ (let ((item-time (org-get-scheduled-time (point))))
+ (null item-time))))
+
+
+(defun org-drill-entry-last-quality (&optional default)
+ (let ((quality (org-entry-get (point) "DRILL_LAST_QUALITY")))
+ (if quality
+ (string-to-number quality)
+ default)))
+
+
+(defun org-drill-entry-failure-count ()
+ (let ((quality (org-entry-get (point) "DRILL_FAILURE_COUNT")))
+ (if quality
+ (string-to-number quality)
+ 0)))
+
+
+(defun org-drill-entry-average-quality (&optional default)
+ (let ((val (org-entry-get (point) "DRILL_AVERAGE_QUALITY")))
+ (if val
+ (string-to-number val)
+ (or default nil))))
+
+(defun org-drill-entry-last-interval (&optional default)
+ (let ((val (org-entry-get (point) "DRILL_LAST_INTERVAL")))
+ (if val
+ (string-to-number val)
+ (or default 0))))
+
+(defun org-drill-entry-repeats-since-fail (&optional default)
+ (let ((val (org-entry-get (point) "DRILL_REPEATS_SINCE_FAIL")))
+ (if val
+ (string-to-number val)
+ (or default 0))))
+
+(defun org-drill-entry-total-repeats (&optional default)
+ (let ((val (org-entry-get (point) "DRILL_TOTAL_REPEATS")))
+ (if val
+ (string-to-number val)
+ (or default 0))))
+
+(defun org-drill-entry-ease (&optional default)
+ (let ((val (org-entry-get (point) "DRILL_EASE")))
+ (if val
+ (string-to-number val)
+ default)))
+
+
+;;; From http://www.supermemo.com/english/ol/sm5.htm
+(defun org-drill-random-dispersal-factor ()
+ "Returns a random number between 0.5 and 1.5."
+ (let ((a 0.047)
+ (b 0.092)
+ (p (- (random* 1.0) 0.5)))
+ (cl-flet ((sign (n)
+ (cond ((zerop n) 0)
+ ((plusp n) 1)
+ (t -1))))
+ (/ (+ 100 (* (* (/ -1 b) (log (- 1 (* (/ b a ) (abs p)))))
+ (sign p)))
+ 100.0))))
+
+(defun pseudonormal (mean variation)
+ "Random numbers in a pseudo-normal distribution with mean MEAN, range
+ MEAN-VARIATION to MEAN+VARIATION"
+ (+ (random* variation)
+ (random* variation)
+ (- variation)
+ mean))
+
+
+(defun org-drill-early-interval-factor (optimal-factor
+ optimal-interval
+ days-ahead)
+ "Arguments:
+- OPTIMAL-FACTOR: interval-factor if the item had been tested
+exactly when it was supposed to be.
+- OPTIMAL-INTERVAL: interval for next repetition (days) if the item had been
+tested exactly when it was supposed to be.
+- DAYS-AHEAD: how many days ahead of time the item was reviewed.
+
+Returns an adjusted optimal factor which should be used to
+calculate the next interval, instead of the optimal factor found
+in the matrix."
+ (let ((delta-ofmax (* (1- optimal-factor)
+ (/ (+ optimal-interval
+ (* 0.6 optimal-interval) -1) (1- optimal-interval)))))
+ (- optimal-factor
+ (* delta-ofmax (/ days-ahead (+ days-ahead (* 0.6 optimal-interval)))))))
+
+
+(defun org-drill-get-item-data ()
+ "Returns a list of 6 items, containing all the stored recall
+ data for the item at point:
+- LAST-INTERVAL is the interval in days that was used to schedule the item's
+ current review date.
+- REPEATS is the number of items the item has been successfully recalled without
+ without any failures. It is reset to 0 upon failure to recall the item.
+- FAILURES is the total number of times the user has failed to recall the item.
+- TOTAL-REPEATS includes both successful and unsuccessful repetitions.
+- AVERAGE-QUALITY is the mean quality of recall of the item over
+ all its repetitions, successful and unsuccessful.
+- EASE is a number reflecting how easy the item is to learn. Higher is easier.
+"
+ (let ((learn-str (org-entry-get (point) "LEARN_DATA"))
+ (repeats (org-drill-entry-total-repeats :missing)))
+ (cond
+ (learn-str
+ (let ((learn-data (or (and learn-str
+ (read learn-str))
+ (copy-list initial-repetition-state))))
+ (list (nth 0 learn-data) ; last interval
+ (nth 1 learn-data) ; repetitions
+ (org-drill-entry-failure-count)
+ (nth 1 learn-data)
+ (org-drill-entry-last-quality)
+ (nth 2 learn-data) ; EF
+ )))
+ ((not (eql :missing repeats))
+ (list (org-drill-entry-last-interval)
+ (org-drill-entry-repeats-since-fail)
+ (org-drill-entry-failure-count)
+ (org-drill-entry-total-repeats)
+ (org-drill-entry-average-quality)
+ (org-drill-entry-ease)))
+ (t ; virgin item
+ (list 0 0 0 0 nil nil)))))
+
+
+(defun org-drill-store-item-data (last-interval repeats failures
+ total-repeats meanq
+ ease)
+ "Stores the given data in the item at point."
+ (org-entry-delete (point) "LEARN_DATA")
+ (org-set-property "DRILL_LAST_INTERVAL"
+ (number-to-string (round-float last-interval 4)))
+ (org-set-property "DRILL_REPEATS_SINCE_FAIL" (number-to-string repeats))
+ (org-set-property "DRILL_TOTAL_REPEATS" (number-to-string total-repeats))
+ (org-set-property "DRILL_FAILURE_COUNT" (number-to-string failures))
+ (org-set-property "DRILL_AVERAGE_QUALITY"
+ (number-to-string (round-float meanq 3)))
+ (org-set-property "DRILL_EASE"
+ (number-to-string (round-float ease 3))))
+
+
+
+;;; SM2 Algorithm =============================================================
+
+
+(defun determine-next-interval-sm2 (last-interval n ef quality
+ failures meanq total-repeats)
+ "Arguments:
+- LAST-INTERVAL -- the number of days since the item was last reviewed.
+- REPEATS -- the number of times the item has been successfully reviewed
+- EF -- the 'easiness factor'
+- QUALITY -- 0 to 5
+
+Returns a list: (INTERVAL REPEATS EF FAILURES MEAN TOTAL-REPEATS OFMATRIX), where:
+- INTERVAL is the number of days until the item should next be reviewed
+- REPEATS is incremented by 1.
+- EF is modified based on the recall quality for the item.
+- OF-MATRIX is not modified."
+ (assert (> n 0))
+ (assert (and (>= quality 0) (<= quality 5)))
+ (if (<= quality org-drill-failure-quality)
+ ;; When an item is failed, its interval is reset to 0,
+ ;; but its EF is unchanged
+ (list -1 1 ef (1+ failures) meanq (1+ total-repeats)
+ org-drill-sm5-optimal-factor-matrix)
+ ;; else:
+ (let* ((next-ef (modify-e-factor ef quality))
+ (interval
+ (cond
+ ((<= n 1) 1)
+ ((= n 2)
+ (cond
+ (org-drill-add-random-noise-to-intervals-p
+ (case quality
+ (5 6)
+ (4 4)
+ (3 3)
+ (2 1)
+ (t -1)))
+ (t 6)))
+ (t (* last-interval next-ef)))))
+ (list (if org-drill-add-random-noise-to-intervals-p
+ (+ last-interval (* (- interval last-interval)
+ (org-drill-random-dispersal-factor)))
+ interval)
+ (1+ n)
+ next-ef
+ failures meanq (1+ total-repeats)
+ org-drill-sm5-optimal-factor-matrix))))
+
+
+;;; SM5 Algorithm =============================================================
+
+
+
+(defun initial-optimal-factor-sm5 (n ef)
+ (if (= 1 n)
+ org-drill-sm5-initial-interval
+ ef))
+
+(defun get-optimal-factor-sm5 (n ef of-matrix)
+ (let ((factors (assoc n of-matrix)))
+ (or (and factors
+ (let ((ef-of (assoc ef (cdr factors))))
+ (and ef-of (cdr ef-of))))
+ (initial-optimal-factor-sm5 n ef))))
+
+
+(defun inter-repetition-interval-sm5 (last-interval n ef &optional of-matrix)
+ (let ((of (get-optimal-factor-sm5 n ef (or of-matrix
+ org-drill-sm5-optimal-factor-matrix))))
+ (if (= 1 n)
+ of
+ (* of last-interval))))
+
+
+(defun determine-next-interval-sm5 (last-interval n ef quality
+ failures meanq total-repeats
+ of-matrix &optional delta-days)
+ (if (zerop n) (setq n 1))
+ (if (null ef) (setq ef 2.5))
+ (assert (> n 0))
+ (assert (and (>= quality 0) (<= quality 5)))
+ (unless of-matrix
+ (setq of-matrix org-drill-sm5-optimal-factor-matrix))
+ (setq of-matrix (cl-copy-tree of-matrix))
+
+ (setq meanq (if meanq
+ (/ (+ quality (* meanq total-repeats 1.0))
+ (1+ total-repeats))
+ quality))
+
+ (let ((next-ef (modify-e-factor ef quality))
+ (old-ef ef)
+ (new-of (modify-of (get-optimal-factor-sm5 n ef of-matrix)
+ quality org-drill-learn-fraction))
+ (interval nil))
+ (when (and org-drill-adjust-intervals-for-early-and-late-repetitions-p
+ delta-days (minusp delta-days))
+ (setq new-of (org-drill-early-interval-factor
+ (get-optimal-factor-sm5 n ef of-matrix)
+ (inter-repetition-interval-sm5
+ last-interval n ef of-matrix)
+ delta-days)))
+
+ (setq of-matrix
+ (set-optimal-factor n next-ef of-matrix
+ (round-float new-of 3))) ; round OF to 3 d.p.
+
+ (setq ef next-ef)
+
+ (cond
+ ;; "Failed" -- reset repetitions to 0,
+ ((<= quality org-drill-failure-quality)
+ (list -1 1 old-ef (1+ failures) meanq (1+ total-repeats)
+ of-matrix)) ; Not clear if OF matrix is supposed to be
+ ; preserved
+ ;; For a zero-based quality of 4 or 5, don't repeat
+ ;; ((and (>= quality 4)
+ ;; (not org-learn-always-reschedule))
+ ;; (list 0 (1+ n) ef failures meanq
+ ;; (1+ total-repeats) of-matrix)) ; 0 interval = unschedule
+ (t
+ (setq interval (inter-repetition-interval-sm5
+ last-interval n ef of-matrix))
+ (if org-drill-add-random-noise-to-intervals-p
+ (setq interval (* interval (org-drill-random-dispersal-factor))))
+ (list interval
+ (1+ n)
+ ef
+ failures
+ meanq
+ (1+ total-repeats)
+ of-matrix)))))
+
+
+;;; Simple8 Algorithm =========================================================
+
+
+(defun org-drill-simple8-first-interval (failures)
+ "Arguments:
+- FAILURES: integer >= 0. The total number of times the item has
+ been forgotten, ever.
+
+Returns the optimal FIRST interval for an item which has previously been
+forgotten on FAILURES occasions."
+ (* 2.4849 (exp (* -0.057 failures))))
+
+
+(defun org-drill-simple8-interval-factor (ease repetition)
+ "Arguments:
+- EASE: floating point number >= 1.2. Corresponds to `AF' in SM8 algorithm.
+- REPETITION: the number of times the item has been tested.
+1 is the first repetition (ie the second trial).
+Returns:
+The factor by which the last interval should be
+multiplied to give the next interval. Corresponds to `RF' or `OF'."
+ (+ 1.2 (* (- ease 1.2) (expt org-drill-learn-fraction (log repetition 2)))))
+
+
+(defun org-drill-simple8-quality->ease (quality)
+ "Returns the ease (`AF' in the SM8 algorithm) which corresponds
+to a mean item quality of QUALITY."
+ (+ (* 0.0542 (expt quality 4))
+ (* -0.4848 (expt quality 3))
+ (* 1.4916 (expt quality 2))
+ (* -1.2403 quality)
+ 1.4515))
+
+
+(defun determine-next-interval-simple8 (last-interval repeats quality
+ failures meanq totaln
+ &optional delta-days)
+ "Arguments:
+- LAST-INTERVAL -- the number of days since the item was last reviewed.
+- REPEATS -- the number of times the item has been successfully reviewed
+- EASE -- the 'easiness factor'
+- QUALITY -- 0 to 5
+- DELTA-DAYS -- how many days overdue was the item when it was reviewed.
+ 0 = reviewed on the scheduled day. +N = N days overdue.
+ -N = reviewed N days early.
+
+Returns the new item data, as a list of 6 values:
+- NEXT-INTERVAL
+- REPEATS
+- EASE
+- FAILURES
+- AVERAGE-QUALITY
+- TOTAL-REPEATS.
+See the documentation for `org-drill-get-item-data' for a description of these."
+ (assert (>= repeats 0))
+ (assert (and (>= quality 0) (<= quality 5)))
+ (assert (or (null meanq) (and (>= meanq 0) (<= meanq 5))))
+ (let ((next-interval nil))
+ (setf meanq (if meanq
+ (/ (+ quality (* meanq totaln 1.0)) (1+ totaln))
+ quality))
+ (cond
+ ((<= quality org-drill-failure-quality)
+ (incf failures)
+ (setf repeats 0
+ next-interval -1))
+ ((or (zerop repeats)
+ (zerop last-interval))
+ (setf next-interval (org-drill-simple8-first-interval failures))
+ (incf repeats)
+ (incf totaln))
+ (t
+ (let* ((use-n
+ (if (and
+ org-drill-adjust-intervals-for-early-and-late-repetitions-p
+ (numberp delta-days) (plusp delta-days)
+ (plusp last-interval))
+ (+ repeats (min 1 (/ delta-days last-interval 1.0)))
+ repeats))
+ (factor (org-drill-simple8-interval-factor
+ (org-drill-simple8-quality->ease meanq) use-n))
+ (next-int (* last-interval factor)))
+ (when (and org-drill-adjust-intervals-for-early-and-late-repetitions-p
+ (numberp delta-days) (minusp delta-days))
+ ;; The item was reviewed earlier than scheduled.
+ (setf factor (org-drill-early-interval-factor
+ factor next-int (abs delta-days))
+ next-int (* last-interval factor)))
+ (setf next-interval next-int)
+ (incf repeats)
+ (incf totaln))))
+ (list
+ (if (and org-drill-add-random-noise-to-intervals-p
+ (plusp next-interval))
+ (* next-interval (org-drill-random-dispersal-factor))
+ next-interval)
+ repeats
+ (org-drill-simple8-quality->ease meanq)
+ failures
+ meanq
+ totaln
+ )))
+
+
+
+
+;;; Essentially copied from `org-learn.el', but modified to
+;;; optionally call the SM2 or simple8 functions.
+(defun org-drill-smart-reschedule (quality &optional days-ahead)
+ "If DAYS-AHEAD is supplied it must be a positive integer. The
+item will be scheduled exactly this many days into the future."
+ (let ((delta-days (- (time-to-days (current-time))
+ (time-to-days (or (org-get-scheduled-time (point))
+ (current-time)))))
+ (ofmatrix org-drill-sm5-optimal-factor-matrix)
+ ;; Entries can have weights, 1 by default. Intervals are divided by the
+ ;; item's weight, so an item with a weight of 2 will have all intervals
+ ;; halved, meaning you will end up reviewing it twice as often.
+ ;; Useful for entries which randomly present any of several facts.
+ (weight (org-entry-get (point) "DRILL_CARD_WEIGHT")))
+ (if (stringp weight)
+ (setq weight (read weight)))
+ (destructuring-bind (last-interval repetitions failures
+ total-repeats meanq ease)
+ (org-drill-get-item-data)
+ (destructuring-bind (next-interval repetitions ease
+ failures meanq total-repeats
+ &optional new-ofmatrix)
+ (case org-drill-spaced-repetition-algorithm
+ (sm5 (determine-next-interval-sm5 last-interval repetitions
+ ease quality failures
+ meanq total-repeats ofmatrix))
+ (sm2 (determine-next-interval-sm2 last-interval repetitions
+ ease quality failures
+ meanq total-repeats))
+ (simple8 (determine-next-interval-simple8 last-interval repetitions
+ quality failures meanq
+ total-repeats
+ delta-days)))
+ (if (numberp days-ahead)
+ (setq next-interval days-ahead))
+
+ (if (and (null days-ahead)
+ (numberp weight) (plusp weight)
+ (not (minusp next-interval)))
+ (setq next-interval
+ (max 1.0 (+ last-interval
+ (/ (- next-interval last-interval) weight)))))
+
+ (org-drill-store-item-data next-interval repetitions failures
+ total-repeats meanq ease)
+
+ (if (eql 'sm5 org-drill-spaced-repetition-algorithm)
+ (setq org-drill-sm5-optimal-factor-matrix new-ofmatrix))
+
+ (cond
+ ((= 0 days-ahead)
+ (org-schedule '(4)))
+ ((minusp days-ahead)
+ (org-schedule nil (current-time)))
+ (t
+ (org-schedule nil (time-add (current-time)
+ (days-to-time
+ (round next-interval))))))))))
+
+
+(defun org-drill-hypothetical-next-review-date (quality)
+ "Returns an integer representing the number of days into the future
+that the current item would be scheduled, based on a recall quality
+of QUALITY."
+ (let ((weight (org-entry-get (point) "DRILL_CARD_WEIGHT")))
+ (destructuring-bind (last-interval repetitions failures
+ total-repeats meanq ease)
+ (org-drill-get-item-data)
+ (if (stringp weight)
+ (setq weight (read weight)))
+ (destructuring-bind (next-interval repetitions ease
+ failures meanq total-repeats
+ &optional ofmatrix)
+ (case org-drill-spaced-repetition-algorithm
+ (sm5 (determine-next-interval-sm5 last-interval repetitions
+ ease quality failures
+ meanq total-repeats
+ org-drill-sm5-optimal-factor-matrix))
+ (sm2 (determine-next-interval-sm2 last-interval repetitions
+ ease quality failures
+ meanq total-repeats))
+ (simple8 (determine-next-interval-simple8 last-interval repetitions
+ quality failures meanq
+ total-repeats)))
+ (cond
+ ((not (plusp next-interval))
+ 0)
+ ((and (numberp weight) (plusp weight))
+ (+ last-interval
+ (max 1.0 (/ (- next-interval last-interval) weight))))
+ (t
+ next-interval))))))
+
+
+(defun org-drill-hypothetical-next-review-dates ()
+ (let ((intervals nil))
+ (dotimes (q 6)
+ (push (max (or (car intervals) 0)
+ (org-drill-hypothetical-next-review-date q))
+ intervals))
+ (reverse intervals)))
+
+
+(defun org-drill-reschedule ()
+ "Returns quality rating (0-5), or nil if the user quit."
+ (let ((ch nil)
+ (input nil)
+ (next-review-dates (org-drill-hypothetical-next-review-dates))
+ (key-prompt (format "(0-5, %c=help, %c=edit, %c=tags, %c=quit)"
+ org-drill--help-key
+ org-drill--edit-key
+ org-drill--tags-key
+ org-drill--quit-key)))
+ (save-excursion
+ (while (not (memq ch (list org-drill--quit-key
+ org-drill--edit-key
+ 7 ; C-g
+ ?0 ?1 ?2 ?3 ?4 ?5)))
+ (setq input (read-key-sequence
+ (if (eq ch org-drill--help-key)
+ (format "0-2 Means you have forgotten the item.
+3-5 Means you have remembered the item.
+
+0 - Completely forgot.
+1 - Even after seeing the answer, it still took a bit to sink in.
+2 - After seeing the answer, you remembered it.
+3 - It took you awhile, but you finally remembered. (+%s days)
+4 - After a little bit of thought you remembered. (+%s days)
+5 - You remembered the item really easily. (+%s days)
+
+How well did you do? %s"
+ (round (nth 3 next-review-dates))
+ (round (nth 4 next-review-dates))
+ (round (nth 5 next-review-dates))
+ key-prompt)
+ (format "How well did you do? %s" key-prompt))))
+ (cond
+ ((stringp input)
+ (setq ch (elt input 0)))
+ ((and (vectorp input) (symbolp (elt input 0)))
+ (case (elt input 0)
+ (up (ignore-errors (forward-line -1)))
+ (down (ignore-errors (forward-line 1)))
+ (left (ignore-errors (backward-char)))
+ (right (ignore-errors (forward-char)))
+ (prior (ignore-errors (scroll-down))) ; pgup
+ (next (ignore-errors (scroll-up))))) ; pgdn
+ ((and (vectorp input) (listp (elt input 0))
+ (eventp (elt input 0)))
+ (case (car (elt input 0))
+ (wheel-up (ignore-errors (mwheel-scroll (elt input 0))))
+ (wheel-down (ignore-errors (mwheel-scroll (elt input 0)))))))
+ (if (eql ch org-drill--tags-key)
+ (org-set-tags-command))))
+ (cond
+ ((and (>= ch ?0) (<= ch ?5))
+ (let ((quality (- ch ?0))
+ (failures (org-drill-entry-failure-count)))
+ (unless *org-drill-cram-mode*
+ (save-excursion
+ (let ((quality (if (org-drill--entry-lapsed-p) 2 quality)))
+ (org-drill-smart-reschedule quality
+ (nth quality next-review-dates))))
+ (push quality *org-drill-session-qualities*)
+ (cond
+ ((<= quality org-drill-failure-quality)
+ (when org-drill-leech-failure-threshold
+ ;;(setq failures (if failures (string-to-number failures) 0))
+ ;; (org-set-property "DRILL_FAILURE_COUNT"
+ ;; (format "%d" (1+ failures)))
+ (if (> (1+ failures) org-drill-leech-failure-threshold)
+ (org-toggle-tag "leech" 'on))))
+ (t
+ (let ((scheduled-time (org-get-scheduled-time (point))))
+ (when scheduled-time
+ (message "Next review in %d days"
+ (- (time-to-days scheduled-time)
+ (time-to-days (current-time))))
+ (sit-for 0.5)))))
+ (org-set-property "DRILL_LAST_QUALITY" (format "%d" quality))
+ (org-set-property "DRILL_LAST_REVIEWED"
+ (time-to-inactive-org-timestamp (current-time))))
+ quality))
+ ((= ch org-drill--edit-key)
+ 'edit)
+ (t
+ nil))))
+
+
+;; (defun org-drill-hide-all-subheadings-except (heading-list)
+;; "Returns a list containing the position of each immediate subheading of
+;; the current topic."
+;; (let ((drill-entry-level (org-current-level))
+;; (drill-sections nil)
+;; (drill-heading nil))
+;; (org-show-subtree)
+;; (save-excursion
+;; (org-map-entries
+;; (lambda ()
+;; (when (and (not (org-invisible-p))
+;; (> (org-current-level) drill-entry-level))
+;; (setq drill-heading (org-get-heading t))
+;; (unless (and (= (org-current-level) (1+ drill-entry-level))
+;; (member drill-heading heading-list))
+;; (hide-subtree))
+;; (push (point) drill-sections)))
+;; "" 'tree))
+;; (reverse drill-sections)))
+
+
+
+(defun org-drill-hide-subheadings-if (test)
+ "TEST is a function taking no arguments. TEST will be called for each
+of the immediate subheadings of the current drill item, with the point
+on the relevant subheading. TEST should return nil if the subheading is
+to be revealed, non-nil if it is to be hidden.
+Returns a list containing the position of each immediate subheading of
+the current topic."
+ (let ((drill-entry-level (org-current-level))
+ (drill-sections nil))
+ (org-show-subtree)
+ (save-excursion
+ (org-map-entries
+ (lambda ()
+ (when (and (not (org-invisible-p))
+ (> (org-current-level) drill-entry-level))
+ (when (or (/= (org-current-level) (1+ drill-entry-level))
+ (funcall test))
+ (hide-subtree))
+ (push (point) drill-sections)))
+ "" 'tree))
+ (reverse drill-sections)))
+
+
+(defun org-drill-hide-all-subheadings-except (heading-list)
+ (org-drill-hide-subheadings-if
+ (lambda () (let ((drill-heading (org-get-heading t)))
+ (not (member drill-heading heading-list))))))
+
+
+(defun org-drill-presentation-prompt (&rest fmt-and-args)
+ (let* ((item-start-time (current-time))
+ (input nil)
+ (ch nil)
+ (last-second 0)
+ (mature-entry-count (+ (length *org-drill-young-mature-entries*)
+ (length *org-drill-old-mature-entries*)
+ (length *org-drill-overdue-entries*)))
+ (status (first (org-drill-entry-status)))
+ (prompt
+ (if fmt-and-args
+ (apply 'format
+ (first fmt-and-args)
+ (rest fmt-and-args))
+ (format (concat "Press key for answer, "
+ "%c=edit, %c=tags, %c=skip, %c=quit.")
+ org-drill--edit-key
+ org-drill--tags-key
+ org-drill--skip-key
+ org-drill--quit-key))))
+ (setq prompt
+ (format "%s %s %s %s %s %s"
+ (propertize
+ (char-to-string
+ (cond
+ ((eql status :failed) ?F)
+ (*org-drill-cram-mode* ?C)
+ (t
+ (case status
+ (:new ?N) (:young ?Y) (:old ?o) (:overdue ?!)
+ (t ??)))))
+ 'face `(:foreground
+ ,(case status
+ (:new org-drill-new-count-color)
+ ((:young :old) org-drill-mature-count-color)
+ ((:overdue :failed) org-drill-failed-count-color)
+ (t org-drill-done-count-color))))
+ (propertize
+ (number-to-string (length *org-drill-done-entries*))
+ 'face `(:foreground ,org-drill-done-count-color)
+ 'help-echo "The number of items you have reviewed this session.")
+ (propertize
+ (number-to-string (+ (length *org-drill-again-entries*)
+ (length *org-drill-failed-entries*)))
+ 'face `(:foreground ,org-drill-failed-count-color)
+ 'help-echo (concat "The number of items that you failed, "
+ "and need to review again."))
+ (propertize
+ (number-to-string mature-entry-count)
+ 'face `(:foreground ,org-drill-mature-count-color)
+ 'help-echo "The number of old items due for review.")
+ (propertize
+ (number-to-string (length *org-drill-new-entries*))
+ 'face `(:foreground ,org-drill-new-count-color)
+ 'help-echo (concat "The number of new items that you "
+ "have never reviewed."))
+ prompt))
+ (if (and (eql 'warn org-drill-leech-method)
+ (org-drill-entry-leech-p))
+ (setq prompt (concat
+ (propertize "!!! LEECH ITEM !!!
+You seem to be having a lot of trouble memorising this item.
+Consider reformulating the item to make it easier to remember.\n"
+ 'face '(:foreground "red"))
+ prompt)))
+ (while (memq ch '(nil org-drill--tags-key))
+ (setq ch nil)
+ (while (not (input-pending-p))
+ (let ((elapsed (time-subtract (current-time) item-start-time)))
+ (message (concat (if (>= (time-to-seconds elapsed) (* 60 60))
+ "++:++ "
+ (format-time-string "%M:%S " elapsed))
+ prompt))
+ (sit-for 1)))
+ (setq input (read-key-sequence nil))
+ (if (stringp input) (setq ch (elt input 0)))
+ (if (eql ch org-drill--tags-key)
+ (org-set-tags-command)))
+ (case ch
+ (org-drill--quit-key nil)
+ (org-drill--edit-key 'edit)
+ (org-drill--skip-key 'skip)
+ (otherwise t))))
+
+
+(defun org-pos-in-regexp (pos regexp &optional nlines)
+ (save-excursion
+ (goto-char pos)
+ (org-in-regexp regexp nlines)))
+
+
+(defun org-drill-hide-region (beg end &optional text)
+ "Hide the buffer region between BEG and END with an 'invisible text'
+visual overlay, or with the string TEXT if it is supplied."
+ (let ((ovl (make-overlay beg end)))
+ (overlay-put ovl 'category
+ 'org-drill-hidden-text-overlay)
+ (overlay-put ovl 'priority 9999)
+ (when (stringp text)
+ (overlay-put ovl 'invisible nil)
+ (overlay-put ovl 'face 'default)
+ (overlay-put ovl 'display text))))
+
+
+(defun org-drill-hide-heading-at-point (&optional text)
+ (unless (org-at-heading-p)
+ (error "Point is not on a heading."))
+ (save-excursion
+ (let ((beg (point)))
+ (end-of-line)
+ (org-drill-hide-region beg (point) text))))
+
+
+(defun org-drill-hide-comments ()
+ (save-excursion
+ (while (re-search-forward "^#.*$" nil t)
+ (org-drill-hide-region (match-beginning 0) (match-end 0)))))
+
+
+(defun org-drill-unhide-text ()
+ ;; This will also unhide the item's heading.
+ (save-excursion
+ (dolist (ovl (overlays-in (point-min) (point-max)))
+ (when (eql 'org-drill-hidden-text-overlay (overlay-get ovl 'category))
+ (delete-overlay ovl)))))
+
+
+(defun org-drill-hide-clozed-text ()
+ (save-excursion
+ (while (re-search-forward org-drill-cloze-regexp nil t)
+ ;; Don't hide:
+ ;; - org links, partly because they might contain inline
+ ;; images which we want to keep visible.
+ ;; - LaTeX math fragments
+ ;; - the contents of SRC blocks
+ (unless (save-match-data
+ (or (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1)
+ (org-in-src-block-p)
+ (org-inside-LaTeX-fragment-p)))
+ (org-drill-hide-matched-cloze-text)))))
+
+
+(defun org-drill-hide-matched-cloze-text ()
+ "Hide the current match with a 'cloze' visual overlay."
+ (let ((ovl (make-overlay (match-beginning 0) (match-end 0)))
+ (hint-sep-pos (string-match-p (regexp-quote org-drill-hint-separator)
+ (match-string 0))))
+ (overlay-put ovl 'category
+ 'org-drill-cloze-overlay-defaults)
+ (overlay-put ovl 'priority 9999)
+ (when (and hint-sep-pos
+ (> hint-sep-pos 1))
+ (let ((hint (substring-no-properties
+ (match-string 0)
+ (+ hint-sep-pos (length org-drill-hint-separator))
+ (1- (length (match-string 0))))))
+ (overlay-put
+ ovl 'display
+ ;; If hint is like `X...' then display [X...]
+ ;; otherwise display [...X]
+ (format (if (string-match-p (regexp-quote "...") hint) "[%s]" "[%s...]")
+ hint))))))
+
+
+(defun org-drill-hide-cloze-hints ()
+ (save-excursion
+ (while (re-search-forward org-drill-cloze-regexp nil t)
+ (unless (or (save-match-data
+ (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1))
+ (null (match-beginning 2))) ; hint subexpression matched
+ (org-drill-hide-region (match-beginning 2) (match-end 2))))))
+
+
+(defmacro with-replaced-entry-text (text &rest body)
+ "During the execution of BODY, the entire text of the current entry is
+concealed by an overlay that displays the string TEXT."
+ `(progn
+ (org-drill-replace-entry-text ,text)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unreplace-entry-text))))
+
+
+(defmacro with-replaced-entry-text-multi (replacements &rest body)
+ "During the execution of BODY, the entire text of the current entry is
+concealed by an overlay that displays the overlays in REPLACEMENTS."
+ `(progn
+ (org-drill-replace-entry-text ,replacements t)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unreplace-entry-text))))
+
+
+(defun org-drill-replace-entry-text (text &optional multi-p)
+ "Make an overlay that conceals the entire text of the item, not
+including properties or the contents of subheadings. The overlay shows
+the string TEXT.
+If MULTI-P is non-nil, TEXT must be a list of values which are legal
+for the `display' text property. The text of the item will be temporarily
+replaced by all of these items, in the order in which they appear in
+the list.
+Note: does not actually alter the item."
+ (cond
+ ((and multi-p
+ (listp text))
+ (org-drill-replace-entry-text-multi text))
+ (t
+ (let ((ovl (make-overlay (point-min)
+ (save-excursion
+ (outline-next-heading)
+ (point)))))
+ (overlay-put ovl 'priority 9999)
+ (overlay-put ovl 'category
+ 'org-drill-replaced-text-overlay)
+ (overlay-put ovl 'display text)))))
+
+
+(defun org-drill-unreplace-entry-text ()
+ (save-excursion
+ (dolist (ovl (overlays-in (point-min) (point-max)))
+ (when (eql 'org-drill-replaced-text-overlay (overlay-get ovl 'category))
+ (delete-overlay ovl)))))
+
+
+(defun org-drill-replace-entry-text-multi (replacements)
+ "Make overlays that conceal the entire text of the item, not
+including properties or the contents of subheadings. The overlay shows
+the string TEXT.
+Note: does not actually alter the item."
+ (let ((ovl nil)
+ (p-min (point-min))
+ (p-max (save-excursion
+ (outline-next-heading)
+ (point))))
+ (assert (>= (- p-max p-min) (length replacements)))
+ (dotimes (i (length replacements))
+ (setq ovl (make-overlay (+ p-min (* 2 i))
+ (if (= i (1- (length replacements)))
+ p-max
+ (+ p-min (* 2 i) 1))))
+ (overlay-put ovl 'priority 9999)
+ (overlay-put ovl 'category
+ 'org-drill-replaced-text-overlay)
+ (overlay-put ovl 'display (nth i replacements)))))
+
+
+(defmacro with-replaced-entry-heading (heading &rest body)
+ `(progn
+ (org-drill-replace-entry-heading ,heading)
+ (unwind-protect
+ (progn
+ ,@body)
+ (org-drill-unhide-text))))
+
+
+(defun org-drill-replace-entry-heading (heading)
+ "Make an overlay that conceals the heading of the item. The overlay shows
+the string TEXT.
+Note: does not actually alter the item."
+ (org-drill-hide-heading-at-point heading))
+
+
+(defun org-drill-unhide-clozed-text ()
+ (save-excursion
+ (dolist (ovl (overlays-in (point-min) (point-max)))
+ (when (eql 'org-drill-cloze-overlay-defaults (overlay-get ovl 'category))
+ (delete-overlay ovl)))))
+
+
+(defun org-drill-get-entry-text (&optional keep-properties-p)
+ (let ((text (org-agenda-get-some-entry-text (point-marker) 100)))
+ (if keep-properties-p
+ text
+ (substring-no-properties text))))
+
+
+;; (defun org-entry-empty-p ()
+;; (zerop (length (org-drill-get-entry-text))))
+
+;; This version is about 5x faster than the old version, above.
+(defun org-entry-empty-p ()
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((lim (save-excursion
+ (outline-next-heading) (point))))
+ (if (fboundp 'org-end-of-meta-data-and-drawers)
+ (org-end-of-meta-data-and-drawers) ; function removed Feb 2015
+ (org-end-of-meta-data t))
+ (or (>= (point) lim)
+ (null (re-search-forward "[[:graph:]]" lim t))))))
+
+(defun org-drill-entry-empty-p () (org-entry-empty-p))
+
+
+;;; Presentation functions ====================================================
+;;
+;; Each of these is called with point on topic heading. Each needs to show the
+;; topic in the form of a 'question' or with some information 'hidden', as
+;; appropriate for the card type. The user should then be prompted to press a
+;; key. The function should then reveal either the 'answer' or the entire
+;; topic, and should return t if the user chose to see the answer and rate their
+;; recall, nil if they chose to quit.
+
+
+(defun org-drill-present-simple-card ()
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (with-hidden-cloze-text
+ (org-drill-hide-all-subheadings-except nil)
+ (org-drill--show-latex-fragments) ; overlay all LaTeX fragments with images
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p))))))
+
+
+(defun org-drill-present-default-answer (reschedule-fn)
+ (cond
+ (drill-answer
+ (with-replaced-entry-text
+ (format "\nAnswer:\n\n %s\n" drill-answer)
+ (prog1
+ (funcall reschedule-fn)
+ (setq drill-answer nil))))
+ (t
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)
+ (org-drill-unhide-clozed-text)
+ (org-drill--show-latex-fragments)
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (with-hidden-cloze-hints
+ (funcall reschedule-fn)))))
+
+
+(defun org-drill--show-latex-fragments ()
+ (org-remove-latex-fragment-image-overlays)
+ (if (fboundp 'org-toggle-latex-fragment)
+ (org-toggle-latex-fragment '(4))
+ (org-preview-latex-fragment '(4))))
+
+
+(defun org-drill-present-two-sided-card ()
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (with-hidden-cloze-text
+ (let ((drill-sections (org-drill-hide-all-subheadings-except nil)))
+ (when drill-sections
+ (save-excursion
+ (goto-char (nth (random* (min 2 (length drill-sections)))
+ drill-sections))
+ (org-show-subtree)))
+ (org-drill--show-latex-fragments)
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
+
+
+
+(defun org-drill-present-multi-sided-card ()
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (with-hidden-cloze-text
+ (let ((drill-sections (org-drill-hide-all-subheadings-except nil)))
+ (when drill-sections
+ (save-excursion
+ (goto-char (nth (random* (length drill-sections)) drill-sections))
+ (org-show-subtree)))
+ (org-drill--show-latex-fragments)
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
+
+
+(defun org-drill-present-multicloze-hide-n (number-to-hide
+ &optional
+ force-show-first
+ force-show-last
+ force-hide-first)
+ "Hides NUMBER-TO-HIDE pieces of text that are marked for cloze deletion,
+chosen at random.
+If NUMBER-TO-HIDE is negative, show only (ABS NUMBER-TO-HIDE) pieces,
+hiding all the rest.
+If FORCE-HIDE-FIRST is non-nil, force the first piece of text to be one of
+the hidden items.
+If FORCE-SHOW-FIRST is non-nil, never hide the first piece of text.
+If FORCE-SHOW-LAST is non-nil, never hide the last piece of text.
+If the number of text pieces in the item is less than
+NUMBER-TO-HIDE, then all text pieces will be hidden (except the first or last
+items if FORCE-SHOW-FIRST or FORCE-SHOW-LAST is non-nil)."
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (let ((item-end nil)
+ (match-count 0)
+ (body-start (or (cdr (org-get-property-block))
+ (point))))
+ (if (and force-hide-first force-show-first)
+ (error "FORCE-HIDE-FIRST and FORCE-SHOW-FIRST are mutually exclusive"))
+ (org-drill-hide-all-subheadings-except nil)
+ (save-excursion
+ (outline-next-heading)
+ (setq item-end (point)))
+ (save-excursion
+ (goto-char body-start)
+ (while (re-search-forward org-drill-cloze-regexp item-end t)
+ (let ((in-regexp? (save-match-data
+ (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1))))
+ (unless (or in-regexp?
+ (org-inside-LaTeX-fragment-p))
+ (incf match-count)))))
+ (if (minusp number-to-hide)
+ (setq number-to-hide (+ match-count number-to-hide)))
+ (when (plusp match-count)
+ (let* ((positions (shuffle-list (loop for i from 1
+ to match-count
+ collect i)))
+ (match-nums nil)
+ (cnt nil))
+ (if force-hide-first
+ ;; Force '1' to be in the list, and to be the first item
+ ;; in the list.
+ (setq positions (cons 1 (remove 1 positions))))
+ (if force-show-first
+ (setq positions (remove 1 positions)))
+ (if force-show-last
+ (setq positions (remove match-count positions)))
+ (setq match-nums
+ (subseq positions
+ 0 (min number-to-hide (length positions))))
+ ;; (dolist (pos-to-hide match-nums)
+ (save-excursion
+ (goto-char body-start)
+ (setq cnt 0)
+ (while (re-search-forward org-drill-cloze-regexp item-end t)
+ (unless (save-match-data
+ (or (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1)
+ (org-inside-LaTeX-fragment-p)))
+ (incf cnt)
+ (if (memq cnt match-nums)
+ (org-drill-hide-matched-cloze-text)))))))
+ ;; (loop
+ ;; do (re-search-forward org-drill-cloze-regexp
+ ;; item-end t pos-to-hide)
+ ;; while (org-pos-in-regexp (match-beginning 0)
+ ;; org-bracket-link-regexp 1))
+ ;; (org-drill-hide-matched-cloze-text)))))
+ (org-drill--show-latex-fragments)
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)
+ (org-drill-unhide-clozed-text))))))
+
+
+(defun org-drill-present-multicloze-hide-nth (to-hide)
+ "Hide the TO-HIDE'th piece of clozed text. 1 is the first piece. If
+TO-HIDE is negative, count backwards, so -1 means the last item, -2
+the second to last, etc."
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (let ((item-end nil)
+ (match-count 0)
+ (body-start (or (cdr (org-get-property-block))
+ (point)))
+ (cnt 0))
+ (org-drill-hide-all-subheadings-except nil)
+ (save-excursion
+ (outline-next-heading)
+ (setq item-end (point)))
+ (save-excursion
+ (goto-char body-start)
+ (while (re-search-forward org-drill-cloze-regexp item-end t)
+ (let ((in-regexp? (save-match-data
+ (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1))))
+ (unless (or in-regexp?
+ (org-inside-LaTeX-fragment-p))
+ (incf match-count)))))
+ (if (minusp to-hide)
+ (setq to-hide (+ 1 to-hide match-count)))
+ (cond
+ ((or (not (plusp match-count))
+ (> to-hide match-count))
+ nil)
+ (t
+ (save-excursion
+ (goto-char body-start)
+ (setq cnt 0)
+ (while (re-search-forward org-drill-cloze-regexp item-end t)
+ (unless (save-match-data
+ ;; Don't consider this a cloze region if it is part of an
+ ;; org link, or if it occurs inside a LaTeX math
+ ;; fragment
+ (or (org-pos-in-regexp (match-beginning 0)
+ org-bracket-link-regexp 1)
+ (org-inside-LaTeX-fragment-p)))
+ (incf cnt)
+ (if (= cnt to-hide)
+ (org-drill-hide-matched-cloze-text)))))))
+ (org-drill--show-latex-fragments)
+ (ignore-errors
+ (org-display-inline-images t))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)
+ (org-drill-unhide-clozed-text))))))
+
+
+(defun org-drill-present-multicloze-hide1 ()
+ "Hides one of the pieces of text that are marked for cloze deletion,
+chosen at random."
+ (org-drill-present-multicloze-hide-n 1))
+
+
+(defun org-drill-present-multicloze-hide2 ()
+ "Hides two of the pieces of text that are marked for cloze deletion,
+chosen at random."
+ (org-drill-present-multicloze-hide-n 2))
+
+
+(defun org-drill-present-multicloze-hide-first ()
+ "Hides the first piece of text that is marked for cloze deletion."
+ (org-drill-present-multicloze-hide-nth 1))
+
+
+(defun org-drill-present-multicloze-hide-last ()
+ "Hides the last piece of text that is marked for cloze deletion."
+ (org-drill-present-multicloze-hide-nth -1))
+
+
+(defun org-drill-present-multicloze-hide1-firstmore ()
+ "Commonly, hides the FIRST piece of text that is marked for
+cloze deletion. Uncommonly, hide one of the other pieces of text,
+chosen at random.
+
+The definitions of 'commonly' and 'uncommonly' are determined by
+the value of `org-drill-cloze-text-weight'."
+ ;; The 'firstmore' and 'lastmore' functions used to randomly choose whether
+ ;; to hide the 'favoured' piece of text. However even when the chance of
+ ;; hiding it was set quite high (80%), the outcome was too unpredictable over
+ ;; the small number of repetitions where most learning takes place for each
+ ;; item. In other words, the actual frequency during the first 10 repetitions
+ ;; was often very different from 80%. Hence we use modulo instead.
+ (cond
+ ((null org-drill-cloze-text-weight)
+ ;; Behave as hide1cloze
+ (org-drill-present-multicloze-hide1))
+ ((not (and (integerp org-drill-cloze-text-weight)
+ (plusp org-drill-cloze-text-weight)))
+ (error "Illegal value for org-drill-cloze-text-weight: %S"
+ org-drill-cloze-text-weight))
+ ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
+ org-drill-cloze-text-weight))
+ ;; Uncommonly, hide any item except the first
+ (org-drill-present-multicloze-hide-n 1 t))
+ (t
+ ;; Commonly, hide first item
+ (org-drill-present-multicloze-hide-first))))
+
+
+(defun org-drill-present-multicloze-show1-lastmore ()
+ "Commonly, hides all pieces except the last. Uncommonly, shows
+any random piece. The effect is similar to 'show1cloze' except
+that the last item is much less likely to be the item that is
+visible.
+
+The definitions of 'commonly' and 'uncommonly' are determined by
+the value of `org-drill-cloze-text-weight'."
+ (cond
+ ((null org-drill-cloze-text-weight)
+ ;; Behave as show1cloze
+ (org-drill-present-multicloze-show1))
+ ((not (and (integerp org-drill-cloze-text-weight)
+ (plusp org-drill-cloze-text-weight)))
+ (error "Illegal value for org-drill-cloze-text-weight: %S"
+ org-drill-cloze-text-weight))
+ ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
+ org-drill-cloze-text-weight))
+ ;; Uncommonly, show any item except the last
+ (org-drill-present-multicloze-hide-n -1 nil nil t))
+ (t
+ ;; Commonly, show the LAST item
+ (org-drill-present-multicloze-hide-n -1 nil t))))
+
+
+(defun org-drill-present-multicloze-show1-firstless ()
+ "Commonly, hides all pieces except one, where the shown piece
+is guaranteed NOT to be the first piece. Uncommonly, shows any
+random piece. The effect is similar to 'show1cloze' except that
+the first item is much less likely to be the item that is
+visible.
+
+The definitions of 'commonly' and 'uncommonly' are determined by
+the value of `org-drill-cloze-text-weight'."
+ (cond
+ ((null org-drill-cloze-text-weight)
+ ;; Behave as show1cloze
+ (org-drill-present-multicloze-show1))
+ ((not (and (integerp org-drill-cloze-text-weight)
+ (plusp org-drill-cloze-text-weight)))
+ (error "Illegal value for org-drill-cloze-text-weight: %S"
+ org-drill-cloze-text-weight))
+ ((zerop (mod (1+ (org-drill-entry-total-repeats 0))
+ org-drill-cloze-text-weight))
+ ;; Uncommonly, show the first item
+ (org-drill-present-multicloze-hide-n -1 t))
+ (t
+ ;; Commonly, show any item, except the first
+ (org-drill-present-multicloze-hide-n -1 nil nil t))))
+
+
+(defun org-drill-present-multicloze-show1 ()
+ "Similar to `org-drill-present-multicloze-hide1', but hides all
+the pieces of text that are marked for cloze deletion, except for one
+piece which is chosen at random."
+ (org-drill-present-multicloze-hide-n -1))
+
+
+(defun org-drill-present-multicloze-show2 ()
+ "Similar to `org-drill-present-multicloze-show1', but reveals two
+pieces rather than one."
+ (org-drill-present-multicloze-hide-n -2))
+
+
+(defun org-drill-present-card-using-text (question &optional answer)
+ "Present the string QUESTION as the only visible content of the card.
+If ANSWER is supplied, set the global variable `drill-answer' to its value."
+ (if answer (setq drill-answer answer))
+ (with-hidden-comments
+ (with-replaced-entry-text
+ (concat "\n" question)
+ (org-drill-hide-all-subheadings-except nil)
+ (org-cycle-hide-drawers 'all)
+ (ignore-errors
+ (org-display-inline-images t))
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)))))
+
+
+(defun org-drill-present-card-using-multiple-overlays (replacements &optional answer)
+ "TEXTS is a list of valid values for the 'display' text property.
+Present these overlays, in sequence, as the only
+visible content of the card.
+If ANSWER is supplied, set the global variable `drill-answer' to its value."
+ (if answer (setq drill-answer answer))
+ (with-hidden-comments
+ (with-replaced-entry-text-multi
+ replacements
+ (org-drill-hide-all-subheadings-except nil)
+ (org-cycle-hide-drawers 'all)
+ (ignore-errors
+ (org-display-inline-images t))
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)))))
+
+
+(defun org-drill-entry ()
+ "Present the current topic for interactive review, as in `org-drill'.
+Review will occur regardless of whether the topic is due for review or whether
+it meets the definition of a 'review topic' used by `org-drill'.
+
+Returns a quality rating from 0 to 5, or nil if the user quit, or the symbol
+EDIT if the user chose to exit the drill and edit the current item. Choosing
+the latter option leaves the drill session suspended; it can be resumed
+later using `org-drill-resume'.
+
+See `org-drill' for more details."
+ (interactive)
+ (org-drill-goto-drill-entry-heading)
+ ;;(unless (org-part-of-drill-entry-p)
+ ;; (error "Point is not inside a drill entry"))
+ ;;(unless (org-at-heading-p)
+ ;; (org-back-to-heading))
+ (let ((card-type (org-entry-get (point) "DRILL_CARD_TYPE" t))
+ (answer-fn 'org-drill-present-default-answer)
+ (present-empty-cards nil)
+ (cont nil)
+ ;; fontification functions in `outline-view-change-hook' can cause big
+ ;; slowdowns, so we temporarily bind this variable to nil here.
+ (outline-view-change-hook nil))
+ (setq drill-answer nil)
+ (org-save-outline-visibility t
+ (save-restriction
+ (org-narrow-to-subtree)
+ (org-show-subtree)
+ (org-cycle-hide-drawers 'all)
+
+ (let ((presentation-fn
+ (cdr (assoc card-type org-drill-card-type-alist))))
+ (if (listp presentation-fn)
+ (psetq answer-fn (or (second presentation-fn)
+ 'org-drill-present-default-answer)
+ present-empty-cards (third presentation-fn)
+ presentation-fn (first presentation-fn)))
+ (prog1
+ (cond
+ ((null presentation-fn)
+ (message "%s:%d: Unrecognised card type '%s', skipping..."
+ (buffer-name) (point) card-type)
+ (sit-for 0.5)
+ 'skip)
+ (t
+ (setq cont (funcall presentation-fn))
+ (cond
+ ((not cont)
+ (message "Quit")
+ nil)
+ ((eql cont 'edit)
+ 'edit)
+ ((eql cont 'skip)
+ 'skip)
+ (t
+ (save-excursion
+ (funcall answer-fn
+ (lambda () (org-drill-reschedule))))))))
+ (org-remove-latex-fragment-image-overlays)))))))
+
+
+(defun org-drill-entries-pending-p ()
+ (or *org-drill-again-entries*
+ *org-drill-current-item*
+ (and (not (org-drill-maximum-item-count-reached-p))
+ (not (org-drill-maximum-duration-reached-p))
+ (or *org-drill-new-entries*
+ *org-drill-failed-entries*
+ *org-drill-young-mature-entries*
+ *org-drill-old-mature-entries*
+ *org-drill-overdue-entries*
+ *org-drill-again-entries*))))
+
+
+(defun org-drill-pending-entry-count ()
+ (+ (if (markerp *org-drill-current-item*) 1 0)
+ (length *org-drill-new-entries*)
+ (length *org-drill-failed-entries*)
+ (length *org-drill-young-mature-entries*)
+ (length *org-drill-old-mature-entries*)
+ (length *org-drill-overdue-entries*)
+ (length *org-drill-again-entries*)))
+
+
+(defun org-drill-maximum-duration-reached-p ()
+ "Returns true if the current drill session has continued past its
+maximum duration."
+ (and org-drill-maximum-duration
+ (not *org-drill-cram-mode*)
+ *org-drill-start-time*
+ (> (- (float-time (current-time)) *org-drill-start-time*)
+ (* org-drill-maximum-duration 60))))
+
+
+(defun org-drill-maximum-item-count-reached-p ()
+ "Returns true if the current drill session has reached the
+maximum number of items."
+ (and org-drill-maximum-items-per-session
+ (not *org-drill-cram-mode*)
+ (>= (length *org-drill-done-entries*)
+ org-drill-maximum-items-per-session)))
+
+
+(defun org-drill-pop-next-pending-entry ()
+ (block org-drill-pop-next-pending-entry
+ (let ((m nil))
+ (while (or (null m)
+ (not (org-drill-entry-p m)))
+ (setq
+ m
+ (cond
+ ;; First priority is items we failed in a prior session.
+ ((and *org-drill-failed-entries*
+ (not (org-drill-maximum-item-count-reached-p))
+ (not (org-drill-maximum-duration-reached-p)))
+ (pop-random *org-drill-failed-entries*))
+ ;; Next priority is overdue items.
+ ((and *org-drill-overdue-entries*
+ (not (org-drill-maximum-item-count-reached-p))
+ (not (org-drill-maximum-duration-reached-p)))
+ ;; We use `pop', not `pop-random', because we have already
+ ;; sorted overdue items into a random order which takes
+ ;; number of days overdue into account.
+ (pop *org-drill-overdue-entries*))
+ ;; Next priority is 'young' items.
+ ((and *org-drill-young-mature-entries*
+ (not (org-drill-maximum-item-count-reached-p))
+ (not (org-drill-maximum-duration-reached-p)))
+ (pop-random *org-drill-young-mature-entries*))
+ ;; Next priority is newly added items, and older entries.
+ ;; We pool these into a single group.
+ ((and (or *org-drill-new-entries*
+ *org-drill-old-mature-entries*)
+ (not (org-drill-maximum-item-count-reached-p))
+ (not (org-drill-maximum-duration-reached-p)))
+ (cond
+ ((< (random* (+ (length *org-drill-new-entries*)
+ (length *org-drill-old-mature-entries*)))
+ (length *org-drill-new-entries*))
+ (pop-random *org-drill-new-entries*))
+ (t
+ (pop-random *org-drill-old-mature-entries*))))
+ ;; After all the above are done, last priority is items
+ ;; that were failed earlier THIS SESSION.
+ (*org-drill-again-entries*
+ (pop *org-drill-again-entries*))
+ (t ; nothing left -- return nil
+ (return-from org-drill-pop-next-pending-entry nil)))))
+ m)))
+
+
+(defun org-drill-entries (&optional resuming-p)
+ "Returns nil, t, or a list of markers representing entries that were
+'failed' and need to be presented again before the session ends.
+
+RESUMING-P is true if we are resuming a suspended drill session."
+ (block org-drill-entries
+ (while (org-drill-entries-pending-p)
+ (let ((m (cond
+ ((or (not resuming-p)
+ (null *org-drill-current-item*)
+ (not (org-drill-entry-p *org-drill-current-item*)))
+ (org-drill-pop-next-pending-entry))
+ (t ; resuming a suspended session.
+ (setq resuming-p nil)
+ *org-drill-current-item*))))
+ (setq *org-drill-current-item* m)
+ (unless m
+ (error "Unexpectedly ran out of pending drill items"))
+ (save-excursion
+ (org-drill-goto-entry m)
+ (cond
+ ((not (org-drill-entry-due-p))
+ ;; The entry is not due anymore. This could arise if the user
+ ;; suspends a drill session, then drills an individual entry,
+ ;; then resumes the session.
+ (message "Entry no longer due, skipping...")
+ (sit-for 0.3)
+ nil)
+ (t
+ (setq result (org-drill-entry))
+ (cond
+ ((null result)
+ (message "Quit")
+ (setq end-pos :quit)
+ (return-from org-drill-entries nil))
+ ((eql result 'edit)
+ (setq end-pos (point-marker))
+ (return-from org-drill-entries nil))
+ ((eql result 'skip)
+ (setq *org-drill-current-item* nil)
+ nil) ; skip this item
+ (t
+ (cond
+ ((<= result org-drill-failure-quality)
+ (if *org-drill-again-entries*
+ (setq *org-drill-again-entries*
+ (shuffle-list *org-drill-again-entries*)))
+ (push-end m *org-drill-again-entries*))
+ (t
+ (push m *org-drill-done-entries*)))
+ (setq *org-drill-current-item* nil))))))))))
+
+
+
+(defun org-drill-final-report ()
+ (let ((pass-percent
+ (round (* 100 (count-if (lambda (qual)
+ (> qual org-drill-failure-quality))
+ *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*))))
+ (prompt nil)
+ (max-mini-window-height 0.6))
+ (setq prompt
+ (format
+ "%d items reviewed. Session duration %s.
+Recall of reviewed items:
+ Excellent (5): %3d%% | Near miss (2): %3d%%
+ Good (4): %3d%% | Failure (1): %3d%%
+ Hard (3): %3d%% | Abject failure (0): %3d%%
+
+You successfully recalled %d%% of reviewed items (quality > %s)
+%d/%d items still await review (%s, %s, %s, %s, %s).
+Tomorrow, %d more items will become due for review.
+Session finished. Press a key to continue..."
+ (length *org-drill-done-entries*)
+ (format-seconds "%h:%.2m:%.2s"
+ (- (float-time (current-time)) *org-drill-start-time*))
+ (round (* 100 (count 5 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ (round (* 100 (count 2 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ (round (* 100 (count 4 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ (round (* 100 (count 1 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ (round (* 100 (count 3 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ (round (* 100 (count 0 *org-drill-session-qualities*))
+ (max 1 (length *org-drill-session-qualities*)))
+ pass-percent
+ org-drill-failure-quality
+ (org-drill-pending-entry-count)
+ (+ (org-drill-pending-entry-count)
+ *org-drill-dormant-entry-count*)
+ (propertize
+ (format "%d failed"
+ (+ (length *org-drill-failed-entries*)
+ (length *org-drill-again-entries*)))
+ 'face `(:foreground ,org-drill-failed-count-color))
+ (propertize
+ (format "%d overdue"
+ (length *org-drill-overdue-entries*))
+ 'face `(:foreground ,org-drill-failed-count-color))
+ (propertize
+ (format "%d new"
+ (length *org-drill-new-entries*))
+ 'face `(:foreground ,org-drill-new-count-color))
+ (propertize
+ (format "%d young"
+ (length *org-drill-young-mature-entries*))
+ 'face `(:foreground ,org-drill-mature-count-color))
+ (propertize
+ (format "%d old"
+ (length *org-drill-old-mature-entries*))
+ 'face `(:foreground ,org-drill-mature-count-color))
+ *org-drill-due-tomorrow-count*
+ ))
+
+ (while (not (input-pending-p))
+ (message "%s" prompt)
+ (sit-for 0.5))
+ (read-char-exclusive)
+
+ (if (and *org-drill-session-qualities*
+ (< pass-percent (- 100 org-drill-forgetting-index)))
+ (read-char-exclusive
+ (format
+ "%s
+You failed %d%% of the items you reviewed during this session.
+%d (%d%%) of all items scanned were overdue.
+
+Are you keeping up with your items, and reviewing them
+when they are scheduled? If so, you may want to consider
+lowering the value of `org-drill-learn-fraction' slightly in
+order to make items appear more frequently over time."
+ (propertize "WARNING!" 'face 'org-warning)
+ (- 100 pass-percent)
+ *org-drill-overdue-entry-count*
+ (round (* 100 *org-drill-overdue-entry-count*)
+ (+ *org-drill-dormant-entry-count*
+ *org-drill-due-entry-count*)))
+ ))))
+
+
+
+(defun org-drill-free-markers (markers)
+ "MARKERS is a list of markers, all of which will be freed (set to
+point nowhere). Alternatively, MARKERS can be 't', in which case
+all the markers used by Org-Drill will be freed."
+ (dolist (m (if (eql t markers)
+ (append *org-drill-done-entries*
+ *org-drill-new-entries*
+ *org-drill-failed-entries*
+ *org-drill-again-entries*
+ *org-drill-overdue-entries*
+ *org-drill-young-mature-entries*
+ *org-drill-old-mature-entries*)
+ markers))
+ (free-marker m)))
+
+
+;;; overdue-data is a list of entries, each entry has the form (POS DUE AGE)
+;;; where POS is a marker pointing to the start of the entry, and
+;;; DUE is a number indicating how many days ago the entry was due.
+;;; AGE is the number of days elapsed since item creation (nil if unknown).
+;;; if age > lapse threshold (default 90), sort by age (oldest first)
+;;; if age < lapse threshold, sort by due (biggest first)
+
+
+(defun org-drill-order-overdue-entries (overdue-data)
+ (let* ((lapsed-days (if org-drill--lapse-very-overdue-entries-p
+ 90 most-positive-fixnum))
+ (not-lapsed (remove-if (lambda (a) (> (or (second a) 0) lapsed-days))
+ overdue-data))
+ (lapsed (remove-if-not (lambda (a) (> (or (second a) 0)
+ lapsed-days)) overdue-data)))
+ (setq *org-drill-overdue-entries*
+ (mapcar 'first
+ (append
+ (sort (shuffle-list not-lapsed)
+ (lambda (a b) (> (second a) (second b))))
+ (sort lapsed
+ (lambda (a b) (> (third a) (third b)))))))))
+
+
+(defun org-drill--entry-lapsed-p ()
+ (let ((lapsed-days 90))
+ (and org-drill--lapse-very-overdue-entries-p
+ (> (or (org-drill-entry-days-overdue) 0) lapsed-days))))
+
+
+
+
+(defun org-drill-entry-days-since-creation (&optional use-last-interval-p)
+ "If USE-LAST-INTERVAL-P is non-nil, and DATE_ADDED is missing, use the
+value of DRILL_LAST_INTERVAL instead (as the item's age must be at least
+that many days)."
+ (let ((timestamp (org-entry-get (point) "DATE_ADDED")))
+ (cond
+ (timestamp
+ (- (org-time-stamp-to-now timestamp)))
+ (use-last-interval-p
+ (+ (or (org-drill-entry-days-overdue) 0)
+ (read (or (org-entry-get (point) "DRILL_LAST_INTERVAL") "0"))))
+ (t nil))))
+
+
+(defun org-drill-entry-status ()
+ "Returns a list (STATUS DUE AGE) where DUE is the number of days overdue,
+zero being due today, -1 being scheduled 1 day in the future.
+AGE is the number of days elapsed since the item was created (nil if unknown).
+STATUS is one of the following values:
+- nil, if the item is not a drill entry, or has an empty body
+- :unscheduled
+- :future
+- :new
+- :failed
+- :overdue
+- :young
+- :old
+"
+ (save-excursion
+ (unless (org-at-heading-p)
+ (org-back-to-heading))
+ (let ((due (org-drill-entry-days-overdue))
+ (age (org-drill-entry-days-since-creation t))
+ (last-int (org-drill-entry-last-interval 1)))
+ (list
+ (cond
+ ((not (org-drill-entry-p))
+ nil)
+ ((and (org-entry-empty-p)
+ (let* ((card-type (org-entry-get (point) "DRILL_CARD_TYPE" nil))
+ (dat (cdr (assoc card-type org-drill-card-type-alist))))
+ (or (null card-type)
+ (not (third dat)))))
+ ;; body is empty, and this is not a card type where empty bodies are
+ ;; meaningful, so skip it.
+ nil)
+ ((null due) ; unscheduled - usually a skipped leech
+ :unscheduled)
+ ;; ((eql -1 due)
+ ;; :tomorrow)
+ ((minusp due) ; scheduled in the future
+ :future)
+ ;; The rest of the stati all denote 'due' items ==========================
+ ((<= (org-drill-entry-last-quality 9999)
+ org-drill-failure-quality)
+ ;; Mature entries that were failed last time are
+ ;; FAILED, regardless of how young, old or overdue
+ ;; they are.
+ :failed)
+ ((org-drill-entry-new-p)
+ :new)
+ ((org-drill-entry-overdue-p due last-int)
+ ;; Overdue status overrides young versus old
+ ;; distinction.
+ ;; Store marker + due, for sorting of overdue entries
+ :overdue)
+ ((<= (org-drill-entry-last-interval 9999)
+ org-drill-days-before-old)
+ :young)
+ (t
+ :old))
+ due age))))
+
+
+(defun org-drill-progress-message (collected scanned)
+ (when (zerop (% scanned 50))
+ (let* ((meter-width 40)
+ (sym1 (if (oddp (floor scanned (* 50 meter-width))) ?| ?.))
+ (sym2 (if (eql sym1 ?.) ?| ?.)))
+ (message "Collecting due drill items:%4d %s%s"
+ collected
+ (make-string (% (ceiling scanned 50) meter-width)
+ sym2)
+ (make-string (- meter-width (% (ceiling scanned 50) meter-width))
+ sym1)))))
+
+
+(defun org-map-drill-entry-function ()
+ (org-drill-progress-message
+ (+ (length *org-drill-new-entries*)
+ (length *org-drill-overdue-entries*)
+ (length *org-drill-young-mature-entries*)
+ (length *org-drill-old-mature-entries*)
+ (length *org-drill-failed-entries*))
+ (incf cnt))
+ (cond
+ ((not (org-drill-entry-p))
+ nil) ; skip
+ (t
+ (when (and (not warned-about-id-creation)
+ (null (org-id-get)))
+ (message (concat "Creating unique IDs for items "
+ "(slow, but only happens once)"))
+ (sit-for 0.5)
+ (setq warned-about-id-creation t))
+ (org-id-get-create) ; ensure drill entry has unique ID
+ (destructuring-bind (status due age)
+ (org-drill-entry-status)
+ (case status
+ (:unscheduled
+ (incf *org-drill-dormant-entry-count*))
+ ;; (:tomorrow
+ ;; (incf *org-drill-dormant-entry-count*)
+ ;; (incf *org-drill-due-tomorrow-count*))
+ (:future
+ (incf *org-drill-dormant-entry-count*)
+ (if (eq -1 due)
+ (incf *org-drill-due-tomorrow-count*)))
+ (:new
+ (push (point-marker) *org-drill-new-entries*))
+ (:failed
+ (push (point-marker) *org-drill-failed-entries*))
+ (:young
+ (push (point-marker) *org-drill-young-mature-entries*))
+ (:overdue
+ (push (list (point-marker) due age) overdue-data))
+ (:old
+ (push (point-marker) *org-drill-old-mature-entries*))
+ )))))
+
+
+(defun org-drill (&optional scope drill-match resume-p)
+ "Begin an interactive 'drill session'. The user is asked to
+review a series of topics (headers). Each topic is initially
+presented as a 'question', often with part of the topic content
+hidden. The user attempts to recall the hidden information or
+answer the question, then presses a key to reveal the answer. The
+user then rates his or her recall or performance on that
+topic. This rating information is used to reschedule the topic
+for future review.
+
+Org-drill proceeds by:
+
+- Finding all topics (headings) in SCOPE which have either been
+ used and rescheduled before, or which have a tag that matches
+ `org-drill-question-tag'.
+
+- All matching topics which are either unscheduled, or are
+ scheduled for the current date or a date in the past, are
+ considered to be candidates for the drill session.
+
+- If `org-drill-maximum-items-per-session' is set, a random
+ subset of these topics is presented. Otherwise, all of the
+ eligible topics will be presented.
+
+SCOPE determines the scope in which to search for
+questions. It accepts the same values as `org-drill-scope',
+which see.
+
+DRILL-MATCH, if supplied, is a string specifying a tags/property/
+todo query. Only items matching the query will be considered.
+It accepts the same values as `org-drill-match', which see.
+
+If RESUME-P is non-nil, resume a suspended drill session rather
+than starting a new one."
+
+ (interactive)
+ ;; Check org version. Org 7.9.3f introduced a backwards-incompatible change
+ ;; to the arguments accepted by `org-schedule'. At the time of writing there
+ ;; are still lots of people using versions of org older than this.
+ (let ((majorv (first (mapcar 'string-to-number (split-string (org-release) "[.]")))))
+ (if (and (< majorv 8)
+ (not (string-match-p "universal prefix argument" (documentation 'org-schedule))))
+ (read-char-exclusive
+ (format "Warning: org-drill requires org mode 7.9.3f or newer. Scheduling of failed cards will not
+work correctly with older versions of org mode. Your org mode version (%s) appears to be older than
+7.9.3f. Please consider installing a more recent version of org mode." (org-release)))))
+ (let ((end-pos nil)
+ (overdue-data nil)
+ (cnt 0))
+ (block org-drill
+ (unless resume-p
+ (org-drill-free-markers t)
+ (setq *org-drill-current-item* nil
+ *org-drill-done-entries* nil
+ *org-drill-dormant-entry-count* 0
+ *org-drill-due-entry-count* 0
+ *org-drill-due-tomorrow-count* 0
+ *org-drill-overdue-entry-count* 0
+ *org-drill-new-entries* nil
+ *org-drill-overdue-entries* nil
+ *org-drill-young-mature-entries* nil
+ *org-drill-old-mature-entries* nil
+ *org-drill-failed-entries* nil
+ *org-drill-again-entries* nil)
+ (setq *org-drill-session-qualities* nil)
+ (setq *org-drill-start-time* (float-time (current-time))))
+ (setq *random-state* (make-random-state t)) ; reseed RNG
+ (unwind-protect
+ (save-excursion
+ (unless resume-p
+ (let ((org-trust-scanner-tags t)
+ (warned-about-id-creation nil))
+ (org-map-drill-entries
+ 'org-map-drill-entry-function
+ scope drill-match)
+ (org-drill-order-overdue-entries overdue-data)
+ (setq *org-drill-overdue-entry-count*
+ (length *org-drill-overdue-entries*))))
+ (setq *org-drill-due-entry-count* (org-drill-pending-entry-count))
+ (cond
+ ((and (null *org-drill-current-item*)
+ (null *org-drill-new-entries*)
+ (null *org-drill-failed-entries*)
+ (null *org-drill-overdue-entries*)
+ (null *org-drill-young-mature-entries*)
+ (null *org-drill-old-mature-entries*))
+ (message "I did not find any pending drill items."))
+ (t
+ (org-drill-entries resume-p)
+ (message "Drill session finished!"))))
+ (progn
+ (unless end-pos
+ (setq *org-drill-cram-mode* nil)
+ (org-drill-free-markers *org-drill-done-entries*)))))
+ (cond
+ (end-pos
+ (when (markerp end-pos)
+ (org-drill-goto-entry end-pos)
+ (org-reveal)
+ (org-show-entry))
+ (let ((keystr (command-keybinding-to-string 'org-drill-resume)))
+ (message
+ "You can continue the drill session with the command `org-drill-resume'.%s"
+ (if keystr (format "\nYou can run this command by pressing %s." keystr)
+ ""))))
+ (t
+ (org-drill-final-report)
+ (if (eql 'sm5 org-drill-spaced-repetition-algorithm)
+ (org-drill-save-optimal-factor-matrix))
+ (if org-drill-save-buffers-after-drill-sessions-p
+ (save-some-buffers))
+ (message "Drill session finished!")
+ ))))
+
+
+(defun org-drill-save-optimal-factor-matrix ()
+ (savehist-autosave))
+
+
+(defun org-drill-cram (&optional scope drill-match)
+ "Run an interactive drill session in 'cram mode'. In cram mode,
+all drill items are considered to be due for review, unless they
+have been reviewed within the last `org-drill-cram-hours'
+hours."
+ (interactive)
+ (setq *org-drill-cram-mode* t)
+ (org-drill scope drill-match))
+
+
+(defun org-drill-tree ()
+ "Run an interactive drill session using drill items within the
+subtree at point."
+ (interactive)
+ (org-drill 'tree))
+
+
+(defun org-drill-directory ()
+ "Run an interactive drill session using drill items from all org
+files in the same directory as the current file."
+ (interactive)
+ (org-drill 'directory))
+
+
+(defun org-drill-again (&optional scope drill-match)
+ "Run a new drill session, but try to use leftover due items that
+were not reviewed during the last session, rather than scanning for
+unreviewed items. If there are no leftover items in memory, a full
+scan will be performed."
+ (interactive)
+ (setq *org-drill-cram-mode* nil)
+ (cond
+ ((plusp (org-drill-pending-entry-count))
+ (org-drill-free-markers *org-drill-done-entries*)
+ (if (markerp *org-drill-current-item*)
+ (free-marker *org-drill-current-item*))
+ (setq *org-drill-start-time* (float-time (current-time))
+ *org-drill-done-entries* nil
+ *org-drill-current-item* nil)
+ (org-drill scope drill-match t))
+ (t
+ (org-drill scope drill-match))))
+
+
+
+(defun org-drill-resume ()
+ "Resume a suspended drill session. Sessions are suspended by
+exiting them with the `edit' or `quit' options."
+ (interactive)
+ (cond
+ ((org-drill-entries-pending-p)
+ (org-drill nil nil t))
+ ((and (plusp (org-drill-pending-entry-count))
+ ;; Current drill session is finished, but there are still
+ ;; more items which need to be reviewed.
+ (y-or-n-p (format
+ "You have finished the drill session. However, %d items still
+need reviewing. Start a new drill session? "
+ (org-drill-pending-entry-count))))
+ (org-drill-again))
+ (t
+ (message "You have finished the drill session."))))
+
+
+(defun org-drill-relearn-item ()
+ "Make the current item due for revision, and set its last interval to 0.
+Makes the item behave as if it has been failed, without actually recording a
+failure. This command can be used to 'reset' repetitions for an item."
+ (interactive)
+ (org-drill-smart-reschedule 4 0))
+
+
+(defun org-drill-strip-entry-data ()
+ (dolist (prop org-drill-scheduling-properties)
+ (org-delete-property prop))
+ (org-schedule '(4)))
+
+
+(defun org-drill-strip-all-data (&optional scope)
+ "Delete scheduling data from every drill entry in scope. This
+function may be useful if you want to give your collection of
+entries to someone else. Scope defaults to the current buffer,
+and is specified by the argument SCOPE, which accepts the same
+values as `org-drill-scope'."
+ (interactive)
+ (when (yes-or-no-p
+ "Delete scheduling data from ALL items in scope: are you sure?")
+ (cond
+ ((null scope)
+ ;; Scope is the current buffer. This means we can use
+ ;; `org-delete-property-globally', which is faster.
+ (dolist (prop org-drill-scheduling-properties)
+ (org-delete-property-globally prop))
+ (org-map-drill-entries (lambda () (org-schedule '(4))) scope))
+ (t
+ (org-map-drill-entries 'org-drill-strip-entry-data scope)))
+ (message "Done.")))
+
+
+(defun org-drill-add-cloze-fontification ()
+ ;; Compute local versions of the regexp for cloze deletions, in case
+ ;; the left and right delimiters are redefined locally.
+ (setq-local org-drill-cloze-regexp (org-drill--compute-cloze-regexp))
+ (setq-local org-drill-cloze-keywords (org-drill--compute-cloze-keywords))
+ (when org-drill-use-visible-cloze-face-p
+ (add-to-list 'org-font-lock-extra-keywords
+ (first org-drill-cloze-keywords))))
+
+
+;; Can't add to org-mode-hook, because local variables won't have been loaded
+;; yet.
+
+;; (defun org-drill-add-cloze-fontification ()
+;; (when (eql major-mode 'org-mode)
+;; ;; Compute local versions of the regexp for cloze deletions, in case
+;; ;; the left and right delimiters are redefined locally.
+;; (setq-local org-drill-cloze-regexp (org-drill--compute-cloze-regexp))
+;; (setq-local org-drill-cloze-keywords (org-drill--compute-cloze-keywords))
+;; (when org-drill-use-visible-cloze-face-p
+;; (font-lock-add-keywords nil ;'org-mode
+;; org-drill-cloze-keywords
+;; nil))))
+
+;; XXX
+;; (add-hook 'hack-local-variables-hook
+;; 'org-drill-add-cloze-fontification)
+;;
+;; (org-drill-add-cloze-fontification)
+
+
+;;; Synching card collections =================================================
+
+
+(defvar *org-drill-dest-id-table* (make-hash-table :test 'equal))
+
+
+(defun org-drill-copy-entry-to-other-buffer (dest &optional path)
+ "Copy the subtree at point to the buffer DEST. The copy will receive
+the tag 'imported'."
+ (block org-drill-copy-entry-to-other-buffer
+ (save-excursion
+ (let ((src (current-buffer))
+ (m nil))
+ (cl-flet ((paste-tree-here (&optional level)
+ (org-paste-subtree level)
+ (org-drill-strip-entry-data)
+ (org-toggle-tag "imported" 'on)
+ (org-map-drill-entries
+ (lambda ()
+ (let ((id (org-id-get)))
+ (org-drill-strip-entry-data)
+ (unless (gethash id *org-drill-dest-id-table*)
+ (puthash id (point-marker)
+ *org-drill-dest-id-table*))))
+ 'tree)))
+ (unless path
+ (setq path (org-get-outline-path)))
+ (org-copy-subtree)
+ (switch-to-buffer dest)
+ (setq m
+ (condition-case nil
+ (org-find-olp path t)
+ (error ; path does not exist in DEST
+ (return-from org-drill-copy-entry-to-other-buffer
+ (cond
+ ((cdr path)
+ (org-drill-copy-entry-to-other-buffer
+ dest (butlast path)))
+ (t
+ ;; We've looked all the way up the path
+ ;; Default to appending to the end of DEST
+ (goto-char (point-max))
+ (newline)
+ (paste-tree-here)))))))
+ (goto-char m)
+ (outline-next-heading)
+ (newline)
+ (forward-line -1)
+ (paste-tree-here (1+ (or (org-current-level) 0)))
+ )))))
+
+
+
+(defun org-drill-merge-buffers (src &optional dest ignore-new-items-p)
+ "SRC and DEST are two org mode buffers containing drill items.
+For each drill item in DEST that shares an ID with an item in SRC,
+overwrite scheduling data in DEST with data taken from the item in SRC.
+This is intended for use when two people are sharing a set of drill items,
+one person has made some updates to the item set, and the other person
+wants to migrate to the updated set without losing their scheduling data.
+
+By default, any drill items in SRC which do not exist in DEST are
+copied into DEST. We attempt to place the copied item in the
+equivalent location in DEST to its location in SRC, by matching
+the heading hierarchy. However if IGNORE-NEW-ITEMS-P is non-nil,
+we simply ignore any items that do not exist in DEST, and do not
+copy them across."
+ (interactive "bImport scheduling info from which buffer?")
+ (unless dest
+ (setq dest (current-buffer)))
+ (setq src (get-buffer src)
+ dest (get-buffer dest))
+ (when (yes-or-no-p
+ (format
+ (concat "About to overwrite all scheduling data for drill items in `%s' "
+ "with information taken from matching items in `%s'. Proceed? ")
+ (buffer-name dest) (buffer-name src)))
+ ;; Compile list of all IDs in the destination buffer.
+ (clrhash *org-drill-dest-id-table*)
+ (with-current-buffer dest
+ (org-map-drill-entries
+ (lambda ()
+ (let ((this-id (org-id-get)))
+ (when this-id
+ (puthash this-id (point-marker) *org-drill-dest-id-table*))))
+ 'file))
+ ;; Look through all entries in source buffer.
+ (with-current-buffer src
+ (org-map-drill-entries
+ (lambda ()
+ (let ((id (org-id-get))
+ (last-quality nil) (last-reviewed nil)
+ (scheduled-time nil))
+ (cond
+ ((or (null id)
+ (not (org-drill-entry-p)))
+ nil)
+ ((gethash id *org-drill-dest-id-table*)
+ ;; This entry matches an entry in dest. Retrieve all its
+ ;; scheduling data, then go to the matching location in dest
+ ;; and write the data.
+ (let ((marker (gethash id *org-drill-dest-id-table*)))
+ (destructuring-bind (last-interval repetitions failures
+ total-repeats meanq ease)
+ (org-drill-get-item-data)
+ (setq last-reviewed (org-entry-get (point) "DRILL_LAST_REVIEWED")
+ last-quality (org-entry-get (point) "DRILL_LAST_QUALITY")
+ scheduled-time (org-get-scheduled-time (point)))
+ (save-excursion
+ ;; go to matching entry in destination buffer
+ (switch-to-buffer (marker-buffer marker))
+ (goto-char marker)
+ (org-drill-strip-entry-data)
+ (unless (zerop total-repeats)
+ (org-drill-store-item-data last-interval repetitions failures
+ total-repeats meanq ease)
+ (if last-quality
+ (org-set-property "LAST_QUALITY" last-quality)
+ (org-delete-property "LAST_QUALITY"))
+ (if last-reviewed
+ (org-set-property "LAST_REVIEWED" last-reviewed)
+ (org-delete-property "LAST_REVIEWED"))
+ (if scheduled-time
+ (org-schedule nil scheduled-time)))))
+ (remhash id *org-drill-dest-id-table*)
+ (free-marker marker)))
+ (t
+ ;; item in SRC has ID, but no matching ID in DEST.
+ ;; It must be a new item that does not exist in DEST.
+ ;; Copy the entire item to the *end* of DEST.
+ (unless ignore-new-items-p
+ (org-drill-copy-entry-to-other-buffer dest))))))
+ 'file))
+ ;; Finally: there may be some items in DEST which are not in SRC, and
+ ;; which have been scheduled by another user of DEST. Clear out the
+ ;; scheduling info from all the unmatched items in DEST.
+ (with-current-buffer dest
+ (maphash (lambda (id m)
+ (goto-char m)
+ (org-drill-strip-entry-data)
+ (free-marker m))
+ *org-drill-dest-id-table*))))
+
+
+
+;;; Card types for learning languages =========================================
+
+;;; Get spell-number.el from:
+;;; http://www.emacswiki.org/emacs/spell-number.el
+(autoload 'spelln-integer-in-words "spell-number")
+
+
+;;; `conjugate' card type =====================================================
+;;; See spanish.org for usage
+
+(defvar org-drill-verb-tense-alist
+ '(("present" "tomato")
+ ("simple present" "tomato")
+ ("present indicative" "tomato")
+ ;; past tenses
+ ("past" "purple")
+ ("simple past" "purple")
+ ("preterite" "purple")
+ ("imperfect" "darkturquoise")
+ ("present perfect" "royalblue")
+ ;; future tenses
+ ("future" "green")
+ ;; moods (backgrounds).
+ ("indicative" nil) ; default
+ ("subjunctive" "medium blue")
+ ("conditional" "grey30")
+ ("negative imperative" "red4")
+ ("positive imperative" "darkgreen")
+ )
+ "Alist where each entry has the form (TENSE COLOUR), where
+TENSE is a string naming a tense in which verbs can be
+conjugated, and COLOUR is a string specifying a foreground colour
+which will be used by `org-drill-present-verb-conjugation' and
+`org-drill-show-answer-verb-conjugation' to fontify the verb and
+the name of the tense.")
+
+
+(defun org-drill-get-verb-conjugation-info ()
+ "Auxiliary function used by `org-drill-present-verb-conjugation' and
+`org-drill-show-answer-verb-conjugation'."
+ (let ((infinitive (org-entry-get (point) "VERB_INFINITIVE" t))
+ (inf-hint (org-entry-get (point) "VERB_INFINITIVE_HINT" t))
+ (translation (org-entry-get (point) "VERB_TRANSLATION" t))
+ (tense (org-entry-get (point) "VERB_TENSE" nil))
+ (mood (org-entry-get (point) "VERB_MOOD" nil))
+ (highlight-face nil))
+ (unless (and infinitive translation (or tense mood))
+ (error "Missing information for verb conjugation card (%s, %s, %s, %s) at %s"
+ infinitive translation tense mood (point)))
+ (setq tense (if tense (downcase (car (read-from-string tense))))
+ mood (if mood (downcase (car (read-from-string mood))))
+ infinitive (car (read-from-string infinitive))
+ inf-hint (if inf-hint (car (read-from-string inf-hint)))
+ translation (car (read-from-string translation)))
+ (setq highlight-face
+ (list :foreground
+ (or (second (assoc-string tense org-drill-verb-tense-alist t))
+ "hotpink")
+ :background
+ (second (assoc-string mood org-drill-verb-tense-alist t))))
+ (setq infinitive (propertize infinitive 'face highlight-face))
+ (setq translation (propertize translation 'face highlight-face))
+ (if tense (setq tense (propertize tense 'face highlight-face)))
+ (if mood (setq mood (propertize mood 'face highlight-face)))
+ (list infinitive inf-hint translation tense mood)))
+
+
+(defun org-drill-present-verb-conjugation ()
+ "Present a drill entry whose card type is 'conjugate'."
+ (cl-flet ((tense-and-mood-to-string
+ (tense mood)
+ (cond
+ ((and tense mood)
+ (format "%s tense, %s mood" tense mood))
+ (tense
+ (format "%s tense" tense))
+ (mood
+ (format "%s mood" mood)))))
+ (destructuring-bind (infinitive inf-hint translation tense mood)
+ (org-drill-get-verb-conjugation-info)
+ (org-drill-present-card-using-text
+ (cond
+ ((zerop (random* 2))
+ (format "\nTranslate the verb\n\n%s\n\nand conjugate for the %s.\n\n"
+ infinitive (tense-and-mood-to-string tense mood)))
+
+ (t
+ (format "\nGive the verb that means\n\n%s %s\n
+and conjugate for the %s.\n\n"
+ translation
+ (if inf-hint (format " [HINT: %s]" inf-hint) "")
+ (tense-and-mood-to-string tense mood))))))))
+
+
+(defun org-drill-show-answer-verb-conjugation (reschedule-fn)
+ "Show the answer for a drill item whose card type is 'conjugate'.
+RESCHEDULE-FN must be a function that calls `org-drill-reschedule' and
+returns its return value."
+ (destructuring-bind (infinitive inf-hint translation tense mood)
+ (org-drill-get-verb-conjugation-info)
+ (with-replaced-entry-heading
+ (format "%s of %s ==> %s\n\n"
+ (capitalize
+ (cond
+ ((and tense mood)
+ (format "%s tense, %s mood" tense mood))
+ (tense
+ (format "%s tense" tense))
+ (mood
+ (format "%s mood" mood))))
+ infinitive translation)
+ (org-cycle-hide-drawers 'all)
+ (funcall reschedule-fn))))
+
+
+;;; `decline_noun' card type ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+
+(defvar org-drill-noun-gender-alist
+ '(("masculine" "dodgerblue")
+ ("masc" "dodgerblue")
+ ("male" "dodgerblue")
+ ("m" "dodgerblue")
+ ("feminine" "orchid")
+ ("fem" "orchid")
+ ("female" "orchid")
+ ("f" "orchid")
+ ("neuter" "green")
+ ("neutral" "green")
+ ("neut" "green")
+ ("n" "green")
+ ))
+
+
+(defun org-drill-get-noun-info ()
+ "Auxiliary function used by `org-drill-present-noun-declension' and
+`org-drill-show-answer-noun-declension'."
+ (let ((noun (org-entry-get (point) "NOUN" t))
+ (noun-hint (org-entry-get (point) "NOUN_HINT" t))
+ (noun-root (org-entry-get (point) "NOUN_ROOT" t))
+ (noun-gender (org-entry-get (point) "NOUN_GENDER" t))
+ (translation (org-entry-get (point) "NOUN_TRANSLATION" t))
+ (highlight-face nil))
+ (unless (and noun translation)
+ (error "Missing information for `decline_noun' card (%s, %s, %s, %s) at %s"
+ noun translation noun-hint noun-root (point)))
+ (setq noun-root (if noun-root (car (read-from-string noun-root)))
+ noun (car (read-from-string noun))
+ noun-gender (downcase (car (read-from-string noun-gender)))
+ noun-hint (if noun-hint (car (read-from-string noun-hint)))
+ translation (car (read-from-string translation)))
+ (setq highlight-face
+ (list :foreground
+ (or (second (assoc-string noun-gender
+ org-drill-noun-gender-alist t))
+ "red")))
+ (setq noun (propertize noun 'face highlight-face))
+ (setq translation (propertize translation 'face highlight-face))
+ (list noun noun-root noun-gender noun-hint translation)))
+
+
+(defun org-drill-present-noun-declension ()
+ "Present a drill entry whose card type is 'decline_noun'."
+ (destructuring-bind (noun noun-root noun-gender noun-hint translation)
+ (org-drill-get-noun-info)
+ (let* ((props (org-entry-properties (point)))
+ (definite
+ (cond
+ ((assoc "DECLINE_DEFINITE" props)
+ (propertize (if (org-entry-get (point) "DECLINE_DEFINITE")
+ "definite" "indefinite")
+ 'face 'warning))
+ (t nil)))
+ (plural
+ (cond
+ ((assoc "DECLINE_PLURAL" props)
+ (propertize (if (org-entry-get (point) "DECLINE_PLURAL")
+ "plural" "singular")
+ 'face 'warning))
+ (t nil))))
+ (org-drill-present-card-using-text
+ (cond
+ ((zerop (random* 2))
+ (format "\nTranslate the noun\n\n%s (%s)\n\nand list its declensions%s.\n\n"
+ noun noun-gender
+ (if (or plural definite)
+ (format " for the %s %s form" definite plural)
+ "")))
+ (t
+ (format "\nGive the noun that means\n\n%s %s\n
+and list its declensions%s.\n\n"
+ translation
+ (if noun-hint (format " [HINT: %s]" noun-hint) "")
+ (if (or plural definite)
+ (format " for the %s %s form" definite plural)
+ ""))))))))
+
+
+(defun org-drill-show-answer-noun-declension (reschedule-fn)
+ "Show the answer for a drill item whose card type is 'decline_noun'.
+RESCHEDULE-FN must be a function that calls `org-drill-reschedule' and
+returns its return value."
+ (destructuring-bind (noun noun-root noun-gender noun-hint translation)
+ (org-drill-get-noun-info)
+ (with-replaced-entry-heading
+ (format "Declensions of %s (%s) ==> %s\n\n"
+ noun noun-gender translation)
+ (org-cycle-hide-drawers 'all)
+ (funcall reschedule-fn))))
+
+
+;;; `translate_number' card type ==============================================
+;;; See spanish.org for usage
+
+
+(defun spelln-integer-in-language (n lang)
+ (let ((spelln-language lang))
+ (spelln-integer-in-words n)))
+
+(defun org-drill-present-translate-number ()
+ (let ((num-min (read (org-entry-get (point) "DRILL_NUMBER_MIN")))
+ (num-max (read (org-entry-get (point) "DRILL_NUMBER_MAX")))
+ (language (read (org-entry-get (point) "DRILL_LANGUAGE" t)))
+ (drilled-number 0)
+ (drilled-number-direction 'to-english)
+ (highlight-face 'font-lock-warning-face))
+ (cond
+ ((not (fboundp 'spelln-integer-in-words))
+ (message "`spell-number.el' not loaded, skipping 'translate_number' card...")
+ (sit-for 0.5)
+ 'skip)
+ ((not (and (numberp num-min) (numberp num-max) language))
+ (error "Missing language or minimum or maximum numbers for number card"))
+ (t
+ (if (> num-min num-max)
+ (psetf num-min num-max
+ num-max num-min))
+ (setq drilled-number
+ (+ num-min (random* (abs (1+ (- num-max num-min))))))
+ (setq drilled-number-direction
+ (if (zerop (random* 2)) 'from-english 'to-english))
+ (cond
+ ((eql 'to-english drilled-number-direction)
+ (org-drill-present-card-using-text
+ (format "\nTranslate into English:\n\n%s\n"
+ (propertize
+ (spelln-integer-in-language drilled-number language)
+ 'face highlight-face))
+ (spelln-integer-in-language drilled-number 'english-gb)))
+ (t
+ (org-drill-present-card-using-text
+ (format "\nTranslate into %s:\n\n%s\n"
+ (capitalize (format "%s" language))
+ (propertize
+ (spelln-integer-in-language drilled-number 'english-gb)
+ 'face highlight-face))
+ (spelln-integer-in-language drilled-number language))))))))
+
+
+;; (defun org-drill-show-answer-translate-number (reschedule-fn)
+;; (let* ((language (read (org-entry-get (point) "DRILL_LANGUAGE" t)))
+;; (highlight-face 'font-lock-warning-face)
+;; (non-english
+;; (let ((spelln-language language))
+;; (propertize (spelln-integer-in-words *drilled-number*)
+;; 'face highlight-face)))
+;; (english
+;; (let ((spelln-language 'english-gb))
+;; (propertize (spelln-integer-in-words *drilled-number*)
+;; 'face 'highlight-face))))
+;; (with-replaced-entry-text
+;; (cond
+;; ((eql 'to-english *drilled-number-direction*)
+;; (format "\nThe English translation of %s is:\n\n%s\n"
+;; non-english english))
+;; (t
+;; (format "\nThe %s translation of %s is:\n\n%s\n"
+;; (capitalize (format "%s" language))
+;; english non-english)))
+;; (funcall reschedule-fn))))
+
+
+;;; `spanish_verb' card type ==================================================
+;;; Not very interesting, but included to demonstrate how a presentation
+;;; function can manipulate which subheading are hidden versus shown.
+
+
+(defun org-drill-present-spanish-verb ()
+ (let ((prompt nil)
+ (reveal-headings nil))
+ (with-hidden-comments
+ (with-hidden-cloze-hints
+ (with-hidden-cloze-text
+ (case (random* 6)
+ (0
+ (org-drill-hide-all-subheadings-except '("Infinitive"))
+ (setq prompt
+ (concat "Translate this Spanish verb, and conjugate it "
+ "for the *present* tense.")
+ reveal-headings '("English" "Present Tense" "Notes")))
+ (1
+ (org-drill-hide-all-subheadings-except '("English"))
+ (setq prompt (concat "For the *present* tense, conjugate the "
+ "Spanish translation of this English verb.")
+ reveal-headings '("Infinitive" "Present Tense" "Notes")))
+ (2
+ (org-drill-hide-all-subheadings-except '("Infinitive"))
+ (setq prompt (concat "Translate this Spanish verb, and "
+ "conjugate it for the *past* tense.")
+ reveal-headings '("English" "Past Tense" "Notes")))
+ (3
+ (org-drill-hide-all-subheadings-except '("English"))
+ (setq prompt (concat "For the *past* tense, conjugate the "
+ "Spanish translation of this English verb.")
+ reveal-headings '("Infinitive" "Past Tense" "Notes")))
+ (4
+ (org-drill-hide-all-subheadings-except '("Infinitive"))
+ (setq prompt (concat "Translate this Spanish verb, and "
+ "conjugate it for the *future perfect* tense.")
+ reveal-headings '("English" "Future Perfect Tense" "Notes")))
+ (5
+ (org-drill-hide-all-subheadings-except '("English"))
+ (setq prompt (concat "For the *future perfect* tense, conjugate the "
+ "Spanish translation of this English verb.")
+ reveal-headings '("Infinitive" "Future Perfect Tense" "Notes"))))
+ (org-cycle-hide-drawers 'all)
+ (prog1 (org-drill-presentation-prompt)
+ (org-drill-hide-subheadings-if 'org-drill-entry-p)))))))
+
+
+(provide 'org-drill)
diff --git a/contrib/lisp/org-ebib.el b/contrib/lisp/org-ebib.el
new file mode 100644
index 0000000..4ed5e50
--- /dev/null
+++ b/contrib/lisp/org-ebib.el
@@ -0,0 +1,47 @@
+;;; org-ebib.el - Support for links to Ebib's entries in Org
+;;
+;; Author: Grégoire Jadi <daimrod@gmail.com>
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+(require 'org)
+
+(org-link-set-parameters "ebib"
+ :follow #'org-ebib-open
+ :store #'org-ebib-store-link)
+
+(defun org-ebib-open (key)
+ "Open Ebib and jump to KEY."
+ (ebib nil key))
+
+(defun org-ebib-store-link ()
+ "Store a key to an Ebib entry."
+ (when (memq major-mode '(ebib-index-mode ebib-entry-mode))
+ ;; This is an Ebib entry
+ (let* ((key (ebib-cur-entry-key))
+ (link (concat "ebib:" key))
+ (description (ignore-errors (ebib-db-get-field-value 'title key ebib-cur-db))))
+ (org-store-link-props
+ :type "ebib"
+ :link link
+ :description description))))
+
+(provide 'org-ebib)
+
+;;; org-ebib.el ends here
diff --git a/contrib/lisp/org-effectiveness.el b/contrib/lisp/org-effectiveness.el
new file mode 100644
index 0000000..a07084c
--- /dev/null
+++ b/contrib/lisp/org-effectiveness.el
@@ -0,0 +1,369 @@
+;;; org-effectiveness.el --- Measuring the personal effectiveness
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: David Arroyo Menéndez <davidam@es.gnu.org>
+;; Keywords: effectiveness, plot
+;; Homepage: http://orgmode.org
+;;
+;; This file is not part of GNU Emacs, yet.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements functions to measure the effectiveness in org.
+;; Org-mode doesn't load this module by default - if this is not what
+;; you want, configure the variable `org-modules'. Thanks to #emacs-es
+;; irc channel for your support.
+
+;;; Code:
+
+(require 'org)
+
+(defcustom org-effectiveness-max-todo 50
+ "This variable is useful to advice to the user about
+many TODO pending"
+ :type 'integer
+ :group 'org-effectiveness)
+
+(defun org-effectiveness-advice()
+ "Advicing about a possible excess of TODOS"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (if (< org-effectiveness-max-todo (count-matches "* TODO"))
+ (message "An excess of TODOS!"))))
+
+;; Check advice starting an org file
+(add-hook 'org-mode-hook 'org-effectiveness-advice)
+
+(defun org-effectiveness-count-keyword(keyword)
+ "Print a message with the number of keyword outline in the current buffer"
+ (interactive "sKeyword: ")
+ (save-excursion
+ (goto-char (point-min))
+ (message "Number of %s: %d" keyword (count-matches (concat "* " keyword)))))
+
+(defun org-effectiveness-count-todo()
+ "Print a message with the number of todo tasks in the current buffer"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (message "Number of TODO: %d" (count-matches "* TODO"))))
+
+(defun org-effectiveness-count-done()
+ "Print a message with the number of done tasks in the current buffer"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (message "Number of DONE: %d" (count-matches "* DONE"))))
+
+(defun org-effectiveness-count-canceled()
+ "Print a message with the number of canceled tasks in the current buffer"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (message "Number of Canceled: %d" (count-matches "* CANCEL+ED"))))
+
+(defun org-effectiveness-count-task()
+ "Print a message with the number of tasks and subtasks in the current buffer"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (message "Number of tasks: %d" (count-matches "^*"))))
+
+(defun org-effectiveness()
+ "Returns the effectiveness in the current org buffer"
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (let ((done (float (count-matches "* DONE.*\n.*")))
+ (canc (float (count-matches "* CANCEL+ED.*\n.*"))))
+ (if (and (= done canc) (zerop done))
+ (setq effectiveness 0)
+ (setq effectiveness (* 100 (/ done (+ done canc)))))
+ (message "Effectiveness: %f" effectiveness))))
+
+
+(defun org-effectiveness-keywords-in-date(keyword date)
+ (interactive "sKeyword: \nsDate: " keyword date)
+ (setq count (count-matches (concat keyword ".*\n.*" date)))
+ (message (concat "%sS: %d" keyword count)))
+
+(defun org-effectiveness-dones-in-date(date &optional notmessage)
+ (interactive "sGive me a date: " date)
+ (save-excursion
+ (goto-char (point-min))
+ (let ((count (count-matches (concat "DONE.*\n.*" date))))
+ (if (eq notmessage 1)
+ (message "%d" count)
+ (message "DONES: %d " count)))))
+
+(defun org-effectiveness-todos-in-date(date)
+ (interactive "sGive me a date: " date)
+ (save-excursion
+ (goto-char (point-min))
+ (setq count (count-matches (concat "TODO.*\n.*" date)))
+ (message "TODOS: %d" count)))
+
+(defun org-effectiveness-canceled-in-date(date)
+ (interactive "sGive me a date: " date)
+ (save-excursion
+ (goto-char (point-min))
+ (setq count (count-matches (concat "CANCEL+ED.*\n.*" date)))
+ (message "CANCELEDS: %d" count)))
+
+(defun org-effectiveness-ntasks-in-date(date &optional notmessage)
+ (interactive "sGive me a date: " date)
+ (save-excursion
+ (goto-char (point-min))
+ (let ((tasks (float (count-matches (concat "^*.*\n.*" date)))))
+ (message "%d" tasks))))
+
+(defun org-effectiveness-in-date(date &optional notmessage)
+ (interactive "sGive me a date: " date)
+ (save-excursion
+ (goto-char (point-min))
+ (let ((done (float (count-matches (concat "* DONE.*\n.*" date))))
+ (canc (float (count-matches (concat "* CANCEL+ED.*\n.*" date)))))
+ (if (and (= done canc) (zerop done))
+ (setq effectiveness 0)
+ (setq effectiveness (* 100 (/ done (+ done canc)))))
+ (if (eq notmessage 1)
+ (message "%d" effectiveness)
+ (message "Effectiveness: %d " effectiveness)))))
+
+(defun org-effectiveness-month-to-string (m)
+ (if (< m 10)
+ (concat "0" (number-to-string m))
+ (number-to-string m)))
+
+(defun org-effectiveness-plot(startdate enddate &optional save)
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (setq dates (org-effectiveness-check-dates startdate enddate))
+ (setq syear (cadr (assq 'startyear dates)))
+ (setq smonth (cadr (assq 'startmonth dates)))
+ (setq eyear (cadr (assq 'endyear dates)))
+ (setq emonth (assq 'endmonth dates))
+;; Checking the format of the dates
+ (if (not (string-match "[0-9][0-9][0-9][0-9]-[0-9][0-9]" startdate))
+ (message "The start date must have the next format YYYY-MM"))
+ (if (not (string-match "[0-9][0-9][0-9][0-9]-[0-9][0-9]" enddate))
+ (message "The end date must have the next format YYYY-MM"))
+;; Checking if startdate < enddate
+ (if (string-match "^[0-9][0-9][0-9][0-9]" startdate)
+ (setq startyear (string-to-number (match-string 0 startdate))))
+ (if (string-match "[0-9][0-9]$" startdate)
+ (setq startmonth (string-to-number (match-string 0 startdate))))
+ (if (string-match "^[0-9][0-9][0-9][0-9]" enddate)
+ (setq endyear (string-to-number (match-string 0 enddate))))
+ (if (string-match "[0-9][0-9]$" enddate)
+ (setq endmonth (string-to-number (match-string 0 enddate))))
+ (if (> startyear endyear)
+ (message "The start date must be before that end date"))
+ (if (and (= startyear endyear) (> startmonth endmonth))
+ (message "The start date must be before that end date"))
+;; Create a file
+ (let ((month startmonth)
+ (year startyear)
+ (str ""))
+ (while (or (> endyear year) (and (= endyear year) (>= endmonth month)))
+ (setq str (concat str (number-to-string year) "-" (org-effectiveness-month-to-string month) " " (org-effectiveness-in-date (concat (number-to-string year) "-" (org-effectiveness-month-to-string month)) 1) "\n"))
+ (if (= month 12)
+ (progn
+ (setq year (+ 1 year))
+ (setq month 1))
+ (setq month (+ 1 month))))
+ (write-region str nil "/tmp/org-effectiveness"))
+;; Create the bar graph
+ (if (eq save t)
+ (setq strplot "/usr/bin/gnuplot -e 'set term png; set output \"/tmp/org-effectiveness.png\"; plot \"/tmp/org-effectiveness\" using 2:xticlabels(1) with histograms' -p")
+ (setq strplot "/usr/bin/gnuplot -e 'plot \"/tmp/org-effectiveness\" using 2:xticlabels(1) with histograms' -p"))
+ (if (file-exists-p "/usr/bin/gnuplot")
+ (call-process "/bin/bash" nil t nil "-c" strplot)
+ (message "gnuplot is not installed")))
+
+(defun org-effectiveness-plot-save(startdate enddate &optional save)
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (org-effectiveness-plot startdate enddate t))
+
+;; (defun org-effectiveness-plot(startdate enddate)
+
+
+(defun org-effectiveness-ascii-bar(n &optional label)
+ "Print a bar with the percentage from 0 to 100 printed in ascii"
+ (interactive "nPercentage: \nsLabel: ")
+ (if (or (< n 0) (> n 100))
+ (message "The percentage must be between 0 to 100")
+ (let ((x 0)
+ (y 0)
+ (z 0))
+ (insert (format "\n### %s ###" label))
+ (insert "\n-")
+ (while (< x n)
+ (insert "-")
+ (setq x (+ x 1)))
+ (insert "+\n")
+ (insert (format "%d" n))
+ (if (> n 10)
+ (setq y (+ y 1)))
+ (while (< y n)
+ (insert " ")
+ (setq y (+ y 1)))
+ (insert "|\n")
+ (insert "-")
+ (while (< z n)
+ (insert "-")
+ (setq z (+ z 1)))
+ (insert "+"))))
+
+(defun org-effectiveness-html-bar(n &optional label)
+ "Print a bar with the percentage from 0 to 100 printed in html"
+ (interactive "nPercentage: \nsLabel: ")
+ (if (or (< n 0) (> n 100))
+ (message "The percentage must be between 0 to 100")
+ (let ((x 0)
+ (y 0)
+ (z 0))
+ (insert (format "\n<div class='percentage-%d'>%d</div>" n n))
+)))
+
+
+(defun org-effectiveness-check-dates (startdate enddate)
+ "Generate a list with ((startyear startmonth) (endyear endmonth))"
+ (setq str nil)
+ (if (not (string-match "[0-9][0-9][0-9][0-9]-[0-9][0-9]" startdate))
+ (setq str "The start date must have the next format YYYY-MM"))
+ (if (not (string-match "[0-9][0-9][0-9][0-9]-[0-9][0-9]" enddate))
+ (setq str "The end date must have the next format YYYY-MM"))
+;; Checking if startdate < enddate
+ (if (string-match "^[0-9][0-9][0-9][0-9]" startdate)
+ (setq startyear (string-to-number (match-string 0 startdate))))
+ (if (string-match "[0-9][0-9]$" startdate)
+ (setq startmonth (string-to-number (match-string 0 startdate))))
+ (if (string-match "^[0-9][0-9][0-9][0-9]" enddate)
+ (setq endyear (string-to-number (match-string 0 enddate))))
+ (if (string-match "[0-9][0-9]$" enddate)
+ (setq endmonth (string-to-number (match-string 0 enddate))))
+ (if (> startyear endyear)
+ (setq str "The start date must be before that end date"))
+ (if (and (= startyear endyear) (> startmonth endmonth))
+ (setq str "The start date must be before that end date"))
+ (if str
+ (message str)
+;; (list (list startyear startmonth) (list endyear endmonth))))
+ (list (list 'startyear startyear) (list 'startmonth startmonth) (list 'endyear endyear) (list 'endmonth endmonth))))
+
+(defun org-effectiveness-plot-ascii (startdate enddate)
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (setq dates (org-effectiveness-check-dates startdate enddate))
+ (let ((syear (cadr (assq 'startyear dates)))
+ (smonth (cadr (assq 'startmonth dates)))
+ (year (cadr (assq 'startyear dates)))
+ (month (cadr (assq 'startmonth dates)))
+ (emonth (cadr (assq 'endmonth dates)))
+ (eyear (cadr (assq 'endyear dates)))
+ (buffer (current-buffer))
+ (str ""))
+ (while (or (> eyear year) (and (= eyear year) (>= emonth month)))
+ (setq str (org-effectiveness-in-date (concat (number-to-string year) "-" (org-effectiveness-month-to-string month)) 1))
+ (switch-to-buffer "*org-effectiveness*")
+ (org-effectiveness-ascii-bar (string-to-number str) (format "%s-%s" year month))
+ (switch-to-buffer buffer)
+ (if (eq month 12)
+ (progn
+ (setq year (+ 1 year))
+ (setq month 1))
+ (setq month (+ 1 month)))))
+ (switch-to-buffer "*org-effectiveness*"))
+
+
+(defun org-effectiveness-plot-ascii-ntasks (startdate enddate)
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (setq dates (org-effectiveness-check-dates startdate enddate))
+ (let ((syear (cadr (assq 'startyear dates)))
+ (smonth (cadr (assq 'startmonth dates)))
+ (year (cadr (assq 'startyear dates)))
+ (month (cadr (assq 'startmonth dates)))
+ (emonth (cadr (assq 'endmonth dates)))
+ (eyear (cadr (assq 'endyear dates)))
+ (buffer (current-buffer))
+ (str ""))
+ (while (or (> eyear year) (and (= eyear year) (>= emonth month)))
+ (setq str (org-effectiveness-ntasks-in-date (concat (number-to-string year) "-" (org-effectiveness-month-to-string month)) 1))
+ (switch-to-buffer "*org-effectiveness*")
+ (org-effectiveness-ascii-bar (string-to-number str) (format "%s-%s" year month))
+ (switch-to-buffer buffer)
+ (if (eq month 12)
+ (progn
+ (setq year (+ 1 year))
+ (setq month 1))
+ (setq month (+ 1 month)))))
+ (switch-to-buffer "*org-effectiveness*"))
+
+(defun org-effectiveness-plot-ascii-dones (startdate enddate)
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (setq dates (org-effectiveness-check-dates startdate enddate))
+ (let ((syear (cadr (assq 'startyear dates)))
+ (smonth (cadr (assq 'startmonth dates)))
+ (year (cadr (assq 'startyear dates)))
+ (month (cadr (assq 'startmonth dates)))
+ (emonth (cadr (assq 'endmonth dates)))
+ (eyear (cadr (assq 'endyear dates)))
+ (buffer (current-buffer))
+ (str ""))
+ (while (or (> eyear year) (and (= eyear year) (>= emonth month)))
+ (setq str (org-effectiveness-dones-in-date (concat (number-to-string year) "-" (org-effectiveness-month-to-string month)) 1))
+ (switch-to-buffer "*org-effectiveness*")
+ (org-effectiveness-ascii-bar (string-to-number str) (format "%s-%s" year month))
+ (switch-to-buffer buffer)
+ (if (eq month 12)
+ (progn
+ (setq year (+ 1 year))
+ (setq month 1))
+ (setq month (+ 1 month)))))
+ (switch-to-buffer "*org-effectiveness*"))
+
+
+(defun org-effectiveness-plot-html (startdate enddate)
+ "Print html bars about the effectiveness in a buffer"
+ (interactive "sGive me the start date: \nsGive me the end date: " startdate enddate)
+ (setq dates (org-effectiveness-check-dates startdate enddate))
+ (let ((syear (cadr (assq 'startyear dates)))
+ (smonth (cadr (assq 'startmonth dates)))
+ (year (cadr (assq 'startyear dates)))
+ (month (cadr (assq 'startmonth dates)))
+ (emonth (cadr (assq 'endmonth dates)))
+ (eyear (cadr (assq 'endyear dates)))
+ (buffer (current-buffer))
+ (str ""))
+ (switch-to-buffer "*org-effectiveness-html*")
+ (insert "<html><head><title>Graphbar</title><meta http-equiv='Content-type' content='text/html; charset=utf-8'><link rel='stylesheet' type='text/css' href='graphbar.css' title='graphbar'></head><body>")
+ (while (or (> eyear year) (and (= eyear year) (>= emonth month)))
+ (setq str (org-effectiveness-in-date (concat (number-to-string year) "-" (org-effectiveness-month-to-string month)) 1))
+ (switch-to-buffer "*org-effectiveness-html*")
+ (org-effectiveness-html-bar (string-to-number str) (format "%s-%s" year month))
+ (switch-to-buffer buffer)
+ (format "%s-%s" year month)
+ (if (eq month 12)
+ (progn
+ (setq year (+ 1 year))
+ (setq month 1))
+ (setq month (+ 1 month))))
+ (switch-to-buffer "*org-effectiveness-html*")
+ (insert "</body></html>")))
+
+(provide 'org-effectiveness)
diff --git a/contrib/lisp/org-eldoc.el b/contrib/lisp/org-eldoc.el
new file mode 100644
index 0000000..74dc69b
--- /dev/null
+++ b/contrib/lisp/org-eldoc.el
@@ -0,0 +1,173 @@
+;;; org-eldoc.el --- display org header and src block info using eldoc
+
+;; Copyright (c) 2014-2017 Free Software Foundation, Inc.
+
+;; Author: Łukasz Gruner <lukasz@gruner.lu>
+;; Maintainer: Łukasz Gruner <lukasz@gruner.lu>
+;; Version: 6
+;; Package-Requires: ((org "8"))
+;; URL: https://bitbucket.org/ukaszg/org-eldoc
+;; Created: 25/05/2014
+;; Keywords: eldoc, outline, breadcrumb, org, babel, minibuffer
+
+;; This file is not part of Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Changelog:
+
+;; As of 01/11/14 switching license to GPL3 to allow submission to org-mode.
+;; 08/11/14 switch code to automatically define eldoc-documentation-function, but don't autostart eldoc-mode.
+
+;;; Code:
+
+(require 'org)
+(require 'ob-core)
+(require 'eldoc)
+
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+
+(defgroup org-eldoc nil "" :group 'org)
+
+(defcustom org-eldoc-breadcrumb-separator "/"
+ "Breadcrumb separator."
+ :group 'org-eldoc
+ :type 'string)
+
+(defcustom org-eldoc-test-buffer-name " *Org-eldoc test buffer*"
+ "Name of the buffer used while testing for mode-local variable values."
+ :group 'org-eldoc
+ :type 'string)
+
+(defun org-eldoc-get-breadcrumb ()
+ "Return breadcrumb if on a headline or nil."
+ (let ((case-fold-search t) cur)
+ (save-excursion
+ (beginning-of-line)
+ (save-match-data
+ (when (looking-at org-complex-heading-regexp)
+ (setq cur (match-string 4))
+ (org-format-outline-path
+ (append (org-get-outline-path) (list cur))
+ (frame-width) "" org-eldoc-breadcrumb-separator))))))
+
+(defun org-eldoc-get-src-header ()
+ "Returns lang and list of header properties if on src definition line and nil otherwise."
+ (let ((case-fold-search t) info lang hdr-args)
+ (save-excursion
+ (beginning-of-line)
+ (save-match-data
+ (when (looking-at "^[ \t]*#\\+\\(begin\\|end\\)_src")
+ (setq info (org-babel-get-src-block-info 'light)
+ lang (propertize (or (nth 0 info) "no lang") 'face 'font-lock-string-face)
+ hdr-args (nth 2 info))
+ (concat
+ lang
+ ": "
+ (mapconcat
+ (lambda (elem)
+ (when (and (cdr elem) (not (string= "" (cdr elem))))
+ (concat
+ (propertize (symbol-name (car elem)) 'face 'org-list-dt)
+ " "
+ (propertize (cdr elem) 'face 'org-verbatim)
+ " ")))
+ hdr-args " ")))))))
+
+(defun org-eldoc-get-src-lang ()
+ "Return value of lang for the current block if in block body and nil otherwise."
+ (let ((element (save-match-data (org-element-at-point))))
+ (and (eq (org-element-type element) 'src-block)
+ (>= (line-beginning-position)
+ (org-element-property :post-affiliated element))
+ (<=
+ (line-end-position)
+ (org-with-wide-buffer
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \t\n")
+ (line-end-position)))
+ (org-element-property :language element))))
+
+(defvar org-eldoc-local-functions-cache (make-hash-table :size 40 :test 'equal)
+ "Cache of major-mode's eldoc-documentation-functions,
+ used by \\[org-eldoc-get-mode-local-documentation-function].")
+
+(defun org-eldoc-get-mode-local-documentation-function (lang)
+ "Check if LANG-mode sets eldoc-documentation-function and return its value."
+ (let ((cached-func (gethash lang org-eldoc-local-functions-cache 'empty))
+ (mode-func (intern-soft (format "%s-mode" lang)))
+ doc-func)
+ (if (eq 'empty cached-func)
+ (when (fboundp mode-func)
+ (with-temp-buffer
+ (funcall mode-func)
+ (setq doc-func (and eldoc-documentation-function
+ (symbol-value 'eldoc-documentation-function)))
+ (puthash lang doc-func org-eldoc-local-functions-cache))
+ doc-func)
+ cached-func)))
+
+(declare-function c-eldoc-print-current-symbol-info "c-eldoc" ())
+(declare-function css-eldoc-function "css-eldoc" ())
+(declare-function php-eldoc-function "php-eldoc" ())
+(declare-function go-eldoc--documentation-function "go-eldoc" ())
+
+(defun org-eldoc-documentation-function ()
+ "Return breadcrumbs when on a headline, args for src block header-line,
+ calls other documentation functions depending on lang when inside src body."
+ (or
+ (org-eldoc-get-breadcrumb)
+ (org-eldoc-get-src-header)
+ (let ((lang (org-eldoc-get-src-lang)))
+ (cond ((or
+ (string= lang "emacs-lisp")
+ (string= lang "elisp")) (if (fboundp 'elisp-eldoc-documentation-function)
+ (elisp-eldoc-documentation-function)
+ (let (eldoc-documentation-function)
+ (eldoc-print-current-symbol-info))))
+ ((or
+ (string= lang "c") ;; http://github.com/nflath/c-eldoc
+ (string= lang "C")) (when (require 'c-eldoc nil t)
+ (c-eldoc-print-current-symbol-info)))
+ ;; https://github.com/zenozeng/css-eldoc
+ ((string= lang "css") (when (require 'css-eldoc nil t)
+ (css-eldoc-function)))
+ ;; https://github.com/zenozeng/php-eldoc
+ ((string= lang "php") (when (require 'php-eldoc nil t)
+ (php-eldoc-function)))
+ ((or
+ (string= lang "go")
+ (string= lang "golang")) (when (require 'go-eldoc nil t)
+ (go-eldoc--documentation-function)))
+ (t (let ((doc-fun (org-eldoc-get-mode-local-documentation-function lang)))
+ (when (functionp doc-fun) (funcall doc-fun))))))))
+
+;;;###autoload
+(defun org-eldoc-load ()
+ "Set up org-eldoc documentation function."
+ (interactive)
+ (setq-local eldoc-documentation-function #'org-eldoc-documentation-function))
+
+;;;###autoload
+(add-hook 'org-mode-hook #'org-eldoc-load)
+
+(provide 'org-eldoc)
+
+;; -*- coding: utf-8-emacs; -*-
+
+;;; org-eldoc.el ends here
diff --git a/contrib/lisp/org-elisp-symbol.el b/contrib/lisp/org-elisp-symbol.el
new file mode 100644
index 0000000..a089914
--- /dev/null
+++ b/contrib/lisp/org-elisp-symbol.el
@@ -0,0 +1,161 @@
+;;; org-elisp-symbol.el --- Org links to emacs-lisp symbols
+;;
+;; Copyright 2007-2017 Free Software Foundation, Inc.
+;;
+;; Author: Bastien Guerry
+;; Version: 0.2
+;; Keywords: org, remember, lisp
+;; URL: http://www.cognition.ens.fr/~guerry/u/org-elisp-symbol.el
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+;; Org-mode already lets you store/insert links to emacs-lisp files,
+;; just like any other file. This package lets you precisely link to
+;; any emacs-lisp symbol and access useful information about the symbol.
+;;
+;; Here is the list of available properties when linking from a elisp-symbol:
+;;
+;; :name The symbol's name.
+;; :stype The symbol's type (commandp, function, etc.)
+;; :def The function used to set the symbol's value (defun, etc.)
+;; :keys The keys associated with the command.
+;; :args The arguments of the function.
+;; :docstring The docstring of the symbol.
+;; :doc The first line of the dostring.
+;; :comment A comment line just above the sexp, if any.
+;; :fixme A FIXME comment line just above the sexp, if any.
+;;
+;; Let's say we have a defun like this one:
+;;
+;; ;; FIXME update docstring
+;; (defun org-export-latex-lists ()
+;; "Convert lists to LaTeX."
+;; (goto-char (point-min))
+;; (while (re-search-forward org-export-latex-list-beginning-re nil t)
+;; (beginning-of-line)
+;; (insert (org-list-to-latex (org-list-parse-list t)) "\n")))
+;;
+;; And a remember template like:
+;;
+;; (setq org-remember-templates
+;; '((?s "* DEBUG `%:name' (%:args)\n\n%?\n\nFixme: %:fixme\n \
+;; Doc: \"%:doc\"\n\n%a")))
+;;
+;; Then M-x `org-remember' on this sexp will produce this buffer:
+;;
+;; =====================================================================
+;; * DEBUG `org-export-latex-lists' ()
+;;
+;; <== point
+;;
+;; Fixme: update the docstring
+;; Doc: "Convert lists to LaTeX."
+;;
+;; [[file:~/path/file.el::defun%20my-func][Function: my-func]]
+;; =====================================================================
+;;
+;; Put this file into your load-path and the following into your ~/.emacs:
+;; (require 'org-elisp-symbol)
+
+;;; Code:
+
+(provide 'org-elisp-symbol)
+
+(require 'org)
+
+(org-link-set-parameters "elisp-symbol"
+ :follow #'org-elisp-symbol-open
+ :store #'org-elisp-symbol-store-link)
+
+(defun org-elisp-symbol-open (path)
+ "Visit the emacs-lisp elisp-symbol at PATH."
+ (let* ((search (when (string-match "::\\(.+\\)\\'" path)
+ (match-string 1 path)))
+ (path (substring path 0 (match-beginning 0))))
+ (org-open-file path t nil search)))
+
+(defun org-elisp-symbol-store-link ()
+ "Store a link to an emacs-lisp elisp-symbol."
+ (when (eq major-mode 'emacs-lisp-mode)
+ (save-excursion
+ (or (looking-at "^(") (beginning-of-defun))
+ (looking-at "^(\\([a-z]+\\) \\([^)\n ]+\\) ?\n?[ \t]*\\(?:(\\(.*\\))\\)?")
+ (let* ((end (save-excursion
+ (save-match-data
+ (end-of-defun) (point))))
+ (def (match-string 1))
+ (name (match-string 2))
+ (sym-name (intern-soft name))
+ (stype (cond ((commandp sym-name) "Command")
+ ((functionp sym-name) "Function")
+ ((user-variable-p sym-name) "User variable")
+ ((string= def "defvar") "Variable")
+ ((string= def "defmacro") "Macro")
+ ((string= def "defun") "Function or command")
+ (t "Symbol")))
+ (args (if (match-string 3)
+ (mapconcat (lambda (a) (unless (string-match "^&" a) a))
+ (split-string (match-string 3)) " ")
+ "no arg"))
+ (docstring (cond ((functionp sym-name)
+ (or (documentation sym-name)
+ "[no documentation]"))
+ ((string-match "[Vv]ariable" stype)
+ (documentation-property sym-name
+ 'variable-documentation))
+ (t "no documentation")))
+ (doc (and (string-match "^\\([^\n]+\\)$" docstring)
+ (match-string 1 docstring)))
+ (fixme (save-excursion
+ (beginning-of-defun) (end-of-defun)
+ (if (re-search-forward "^;+ ?FIXME[ :]*\\(.*\\)$" end t)
+ (match-string 1) "nothing to fix")))
+ (comment (save-excursion
+ (beginning-of-defun) (end-of-defun)
+ (if (re-search-forward "^;;+ ?\\(.*\\)$" end t)
+ (match-string 1) "no comment")))
+ keys keys-desc link description)
+ (if (equal stype "Command")
+ (setq keys (where-is-internal sym-name)
+ keys-desc
+ (if keys (mapconcat 'key-description keys " ") "none")))
+ (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
+ "::" def " " name))
+ (setq description (concat stype ": " name))
+ (org-store-link-props
+ :type "elisp-symbol"
+ :link link
+ :description description
+ :def def
+ :name name
+ :stype stype
+ :args args
+ :keys keys-desc
+ :docstring docstring
+ :doc doc
+ :fixme fixme
+ :comment comment)))))
+
+(provide 'org-elisp-symbol)
+
+
+;;;;##########################################################################
+;;;; User Options, Variables
+;;;;##########################################################################
+
+;;; org-elisp-symbol.el ends here
diff --git a/contrib/lisp/org-eval-light.el b/contrib/lisp/org-eval-light.el
new file mode 100644
index 0000000..57ac290
--- /dev/null
+++ b/contrib/lisp/org-eval-light.el
@@ -0,0 +1,199 @@
+;;; org-eval-light.el --- Display result of evaluating code in various languages (light)
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>,
+;; Eric Schulte <schulte dot eric at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp, literate programming,
+;; reproducible research
+;; Homepage: http://orgmode.org
+;; Version: 0.04
+
+;; This file is not yet part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file is based off of org-eval, with the following changes.
+;;
+;; 1) forms are only executed manually, (allowing for the execution of
+;; an entire subtree of forms)
+;; 2) use the org-mode style src blocks, rather than the muse style
+;; <code></code> blocks
+;; 3) forms are not replaced by their outputs, but rather the output
+;; is placed in the buffer immediately following the src block
+;; commented by `org-eval-light-make-region-example' (when
+;; evaluated with a prefix argument no output is placed in the
+;; buffer)
+;; 4) add defadvice to org-ctrl-c-ctrl-c so that when called inside of
+;; a source block it will call `org-eval-light-current-snippet'
+
+;;; Code:
+(require 'org)
+
+(defgroup org-eval-light nil
+ "Options concerning including output from commands into the Org-mode buffer."
+ :tag "Org Eval"
+ :group 'org)
+
+(defvar org-eval-light-example-size-cutoff 10
+ "The number of lines under which an example is considered
+'small', and is exported with the '^:' syntax instead of in a
+large example block")
+
+(defvar org-eval-light-regexp nil)
+
+(defun org-eval-light-set-interpreters (var value)
+ (set-default var value)
+ (setq org-eval-light-regexp
+ (concat "#\\+begin_src \\("
+ (mapconcat 'regexp-quote value "\\|")
+ "\\)\\([^\000]+?\\)#\\+end_src")))
+
+(defcustom org-eval-light-interpreters '("lisp" "emacs-lisp" "ruby" "shell")
+ "Interpreters allows for evaluation tags.
+This is a list of program names (as strings) that can evaluate code and
+insert the output into an Org-mode buffer. Valid choices are
+
+lisp Interpret Emacs Lisp code and display the result
+shell Pass command to the shell and display the result
+perl The perl interpreter
+python Thy python interpreter
+ruby The ruby interpreter"
+ :group 'org-eval-light
+ :set 'org-eval-light-set-interpreters
+ :type '(set :greedy t
+ (const "lisp")
+ (const "emacs-lisp")
+ (const "perl")
+ (const "python")
+ (const "ruby")
+ (const "shell")))
+
+;;; functions
+(defun org-eval-light-inside-snippet ()
+ (interactive)
+ (save-excursion
+ (let ((case-fold-search t)
+ (start-re "^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n")
+ (end-re "\n#\\+end_src")
+ (pos (point))
+ beg end)
+ (if (and (setq beg (re-search-backward start-re nil t))
+ (setq end (re-search-forward end-re nil t))
+ (<= beg pos) (>= end pos))
+ t))))
+
+(defun org-eval-light-make-region-example (beg end)
+ "Comment out region using either the '^:' or the BEGIN_EXAMPLE
+syntax based on the size of the region as compared to
+`org-eval-light-example-size-cutoff'."
+ (interactive "*r")
+ (let ((size (abs (- (line-number-at-pos end)
+ (line-number-at-pos beg)))))
+ (if (= size 0)
+ (let ((result (buffer-substring beg end)))
+ (delete-region beg end)
+ (insert (concat ": " result)))
+ (if (<= size org-eval-light-example-size-cutoff)
+ (save-excursion
+ (goto-char beg)
+ (dotimes (n size)
+ (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
+ (let ((result (buffer-substring beg end)))
+ (delete-region beg end)
+ (insert (concat "#+BEGIN_EXAMPLE\n" result "#+END_EXAMPLE\n")))))))
+
+(defun org-eval-light-current-snippet (&optional arg)
+ "Execute the current #+begin_src #+end_src block, and dump the
+results into the buffer immediately following the src block,
+commented by `org-eval-light-make-region-example'."
+ (interactive "P")
+ (let ((line (org-current-line))
+ (case-fold-search t)
+ (info (org-edit-src-find-region-and-lang))
+ beg end lang result)
+ (setq beg (nth 0 info)
+ end (nth 1 info)
+ lang (nth 2 info))
+ (unless (member lang org-eval-light-interpreters)
+ (error "Language is not in `org-eval-light-interpreters': %s" lang))
+ (goto-line line)
+ (setq result (org-eval-light-code lang (buffer-substring beg end)))
+ (unless arg
+ (save-excursion
+ (re-search-forward "^#\\+end_src" nil t) (open-line 1) (forward-char 2)
+ (let ((beg (point))
+ (end (progn (insert result)
+ (point))))
+ (message (format "from %S %S" beg end))
+ (org-eval-light-make-region-example beg end))))))
+
+(defun org-eval-light-eval-subtree (&optional arg)
+ "Replace EVAL snippets in the entire subtree."
+ (interactive "P")
+ (save-excursion
+ (org-narrow-to-subtree)
+ (goto-char (point-min))
+ (while (re-search-forward org-eval-light-regexp nil t)
+ (org-eval-light-current-snippet arg))
+ (widen)))
+
+(defun org-eval-light-code (interpreter code)
+ (cond
+ ((member interpreter '("lisp" "emacs-lisp"))
+ (org-eval-light-lisp (concat "(progn\n" code "\n)")))
+ ((equal interpreter "shell")
+ (shell-command-to-string code))
+ ((member interpreter '("perl" "python" "ruby"))
+ (org-eval-light-run (executable-find interpreter) code))
+ (t (error "Cannot evaluate code type %s" interpreter))))
+
+(defun org-eval-light-lisp (form)
+ "Evaluate the given form and return the result as a string."
+ (require 'pp)
+ (save-match-data
+ (condition-case err
+ (let ((object (eval (read form))))
+ (cond
+ ((stringp object) object)
+ ((and (listp object)
+ (not (eq object nil)))
+ (let ((string (pp-to-string object)))
+ (substring string 0 (1- (length string)))))
+ ((numberp object)
+ (number-to-string object))
+ ((eq object nil) "")
+ (t
+ (pp-to-string object))))
+ (error
+ (org-display-warning (format "%s: Error evaluating %s: %s"
+ "???" form err))
+ "; INVALID LISP CODE"))))
+
+(defun org-eval-light-run (cmd code)
+ (with-temp-buffer
+ (insert code)
+ (shell-command-on-region (point-min) (point-max) cmd nil 'replace)
+ (buffer-string)))
+
+(defadvice org-ctrl-c-ctrl-c (around org-cc-eval-source activate)
+ (if (org-eval-light-inside-snippet)
+ (call-interactively 'org-eval-light-current-snippet)
+ ad-do-it))
+
+(provide 'org-eval-light)
+
+;;; org-eval-light.el ends here
diff --git a/contrib/lisp/org-eval.el b/contrib/lisp/org-eval.el
new file mode 100644
index 0000000..ecea46a
--- /dev/null
+++ b/contrib/lisp/org-eval.el
@@ -0,0 +1,216 @@
+;;; org-eval.el --- Display result of evaluating code in various languages
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 0.04
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This modules allows to include output from various commands into an
+;; Org-mode buffer, both for live display, and for export.
+;; This technique has been copied from emacs-wiki and Emacs Muse, and
+;; we try to make it work here in a way as similar as possible to
+;; Muse, so that people who move between both worlds don't need to learn
+;; new syntax.
+;;
+;; Basically it works like this:
+;;
+;; <lisp>(concat "aaa" "bbb")</lisp>
+;;
+;; will display "aaabbb" in the buffer and export like that as well.
+;; The leading lisp tag will also accept the attributes "markup" and
+;; "lang", to specify how the text should be formatted during export.
+;; For example,
+;;
+;; <lisp markup="src" lang="emacs-lisp"> .... </lisp>
+;;
+;; will format the result of the lisp form as if it was lisp source
+;; code. Internally, it will wrap the text into a
+;;
+;; #+begin_src emacs-lisp
+;; #+end_src
+;;
+;; structure so that the right things happen when the exporter is running.
+;;
+;; By default, only the <lisp> tag is turned on, but you can configure
+;; the variable `org-eval-interpreters' to add more interpreters like
+;; `perl', `python', or the `shell'.
+;;
+;; You can edit the code snippets with "C-c '" (org-edit-src-code).
+;;
+;; Please note that this mechanism is potentially dangerous, because it
+;; executes code that you don't even see. This gives you great power,
+;; but also enough rope to hang yourself. And, it gives your friends
+;; who send you Org files plenty of opportunity for good and bad jokes.
+;; This is also why this module is not turned on by default, but only
+;; available as a contributed package.
+;;
+;;
+;;
+(require 'org)
+
+;;; Customization
+
+(defgroup org-eval nil
+ "Options concerning including output from commands into the Org-mode buffer."
+ :tag "Org Eval"
+ :group 'org)
+
+(defface org-eval
+ (org-compatible-face nil
+ '((((class color grayscale) (min-colors 88) (background light))
+ (:foreground "grey40"))
+ (((class color grayscale) (min-colors 88) (background dark))
+ (:foreground "grey60"))
+ (((class color) (min-colors 8) (background light))
+ (:foreground "green"))
+ (((class color) (min-colors 8) (background dark))
+ (:foreground "yellow"))))
+ "Face for command output that is included into an Org-mode buffer."
+ :group 'org-eval
+ :group 'org-faces)
+
+(defvar org-eval-regexp nil)
+
+(defun org-eval-set-interpreters (var value)
+ (set-default var value)
+ (setq org-eval-regexp
+ (concat "<\\("
+ (mapconcat 'regexp-quote value "\\|")
+ "\\)"
+ "\\([^>]\\{0,50\\}?\\)>"
+ "\\([^\000]+?\\)</\\1>")))
+
+(defcustom org-eval-interpreters '("lisp")
+ "Interpreters allows for evaluation tags.
+This is a list of program names (as strings) that can evaluate code and
+insert the output into an Org-mode buffer. Valid choices are
+
+lisp Interpret Emacs Lisp code and display the result
+shell Pass command to the shell and display the result
+perl The perl interpreter
+python Thy python interpreter
+ruby The ruby interpreter"
+ :group 'org-eval
+ :set 'org-eval-set-interpreters
+ :type '(set :greedy t
+ (const "lisp")
+ (const "perl")
+ (const "python")
+ (const "ruby")
+ (const "shell")))
+
+(defun org-eval-handle-snippets (limit &optional replace)
+ "Evaluate code snippets and display the results as display property.
+When REPLACE is non-nil, replace the code region with the result (used
+for export)."
+ (let (a)
+ (while (setq a (text-property-any (point) (or limit (point-max))
+ 'org-eval t))
+ (remove-text-properties
+ a (next-single-property-change a 'org-eval nil limit)
+ '(display t intangible t org-eval t))))
+ (while (re-search-forward org-eval-regexp limit t)
+ (let* ((beg (match-beginning 0))
+ (end (match-end 0))
+ (kind (match-string 1))
+ (attr (match-string 2))
+ (code (match-string 3))
+ (value (org-eval-code kind code))
+ markup lang)
+ (if replace
+ (progn
+ (setq attr (save-match-data (org-eval-get-attributes attr))
+ markup (cdr (assoc "markup" attr))
+ lang (cdr (assoc "lang" attr)))
+ (replace-match
+ (concat (if markup (format "#+BEGIN_%s" (upcase markup)))
+ (if (and markup (equal (downcase markup) "src"))
+ (concat " " (or lang "fundamental")))
+ "\n"
+ value
+ (if markup (format "\n#+END_%s\n" (upcase markup))))
+ t t))
+ (add-text-properties
+ beg end
+ (list 'display value 'intangible t 'font-lock-multiline t
+ 'face 'org-eval
+ 'org-eval t))))))
+
+(defun org-eval-replace-snippts ()
+ "Replace EVAL snippets in the entire buffer.
+This should go into the `org-export-preprocess-hook'."
+ (goto-char (point-min))
+ (org-eval-handle-snippets nil 'replace))
+
+(add-hook 'org-export-preprocess-hook 'org-eval-replace-snippts)
+(add-hook 'org-font-lock-hook 'org-eval-handle-snippets)
+
+(defun org-eval-get-attributes (str)
+ (let ((start 0) key value rtn)
+ (while (string-match "\\<\\([a-zA-Z]+\\)\\>=\"\\([^\"]+\\)\"" str start)
+ (setq key (match-string 1 str)
+ value (match-string 2 str)
+ start (match-end 0))
+ (push (cons key value) rtn))
+ rtn))
+
+(defun org-eval-code (interpreter code)
+ (cond
+ ((equal interpreter "lisp")
+ (org-eval-lisp (concat "(progn\n" code "\n)")))
+ ((equal interpreter "shell")
+ (shell-command-to-string code))
+ ((member interpreter '("perl" "python" "ruby"))
+ (org-eval-run (executable-find interpreter) code))
+ (t (error "Cannot evaluate code type %s" interpreter))))
+
+(defun org-eval-lisp (form)
+ "Evaluate the given form and return the result as a string."
+ (require 'pp)
+ (save-match-data
+ (condition-case err
+ (let ((object (eval (read form))))
+ (cond
+ ((stringp object) object)
+ ((and (listp object)
+ (not (eq object nil)))
+ (let ((string (pp-to-string object)))
+ (substring string 0 (1- (length string)))))
+ ((numberp object)
+ (number-to-string object))
+ ((eq object nil) "")
+ (t
+ (pp-to-string object))))
+ (error
+ (org-display-warning (format "%s: Error evaluating %s: %s"
+ "???" form err))
+ "; INVALID LISP CODE"))))
+
+(defun org-eval-run (cmd code)
+ (with-temp-buffer
+ (insert code)
+ (shell-command-on-region (point-min) (point-max) cmd nil 'replace)
+ (buffer-string)))
+
+(provide 'org-eval)
+
+;;; org-eval.el ends here
diff --git a/contrib/lisp/org-expiry.el b/contrib/lisp/org-expiry.el
new file mode 100644
index 0000000..2b8c050
--- /dev/null
+++ b/contrib/lisp/org-expiry.el
@@ -0,0 +1,361 @@
+;;; org-expiry.el --- expiry mechanism for Org entries
+;;
+;; Copyright 2007-2017 Free Software Foundation, Inc.
+;;
+;; Author: Bastien Guerry
+;; Version: 0.2
+;; Keywords: org expiry
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+;; This gives you a chance to get rid of old entries in your Org files
+;; by expiring them.
+;;
+;; By default, entries that have no EXPIRY property are considered to be
+;; new (i.e. 0 day old) and only entries older than one year go to the
+;; expiry process, which consist in adding the ARCHIVE tag. None of
+;; your tasks will be deleted with the default settings.
+;;
+;; When does an entry expires?
+;;
+;; Consider this entry:
+;;
+;; * Stop watching TV
+;; :PROPERTIES:
+;; :CREATED: <2008-01-07 lun 08:01>
+;; :EXPIRY: <2008-01-09 08:01>
+;; :END:
+;;
+;; This entry will expire on the 9th, january 2008.
+
+;; * Stop watching TV
+;; :PROPERTIES:
+;; :CREATED: <2008-01-07 lun 08:01>
+;; :EXPIRY: +1w
+;; :END:
+;;
+;; This entry will expire on the 14th, january 2008, one week after its
+;; creation date.
+;;
+;; What happen when an entry is expired? Nothing until you explicitely
+;; M-x org-expiry-process-entries When doing this, org-expiry will check
+;; for expired entries and request permission to process them.
+;;
+;; Processing an expired entries means calling the function associated
+;; with `org-expiry-handler-function'; the default is to add the tag
+;; :ARCHIVE:, but you can also add a EXPIRED keyword or even archive
+;; the subtree.
+;;
+;; Is this useful? Well, when you're in a brainstorming session, it
+;; might be useful to know about the creation date of an entry, and be
+;; able to archive those entries that are more than xxx days/weeks old.
+;;
+;; When you're in such a session, you can insinuate org-expiry like
+;; this: M-x org-expiry-insinuate
+;;
+;; Then, each time you're pressing M-RET to insert an item, the CREATION
+;; property will be automatically added. Same when you're scheduling or
+;; deadlining items. You can deinsinuate: M-x org-expiry-deinsinuate
+
+;;; Code:
+
+;;; User variables:
+
+(defgroup org-expiry nil
+ "Org expiry process."
+ :tag "Org Expiry"
+ :group 'org)
+
+(defcustom org-expiry-inactive-timestamps nil
+ "Insert inactive timestamps for created/expired properties."
+ :type 'boolean
+ :group 'org-expiry)
+
+(defcustom org-expiry-created-property-name "CREATED"
+ "The name of the property for setting the creation date."
+ :type 'string
+ :group 'org-expiry)
+
+(defcustom org-expiry-expiry-property-name "EXPIRY"
+ "The name of the property for setting the expiry date/delay."
+ :type 'string
+ :group 'org-expiry)
+
+(defcustom org-expiry-keyword "EXPIRED"
+ "The default keyword for `org-expiry-add-keyword'."
+ :type 'string
+ :group 'org-expiry)
+
+(defcustom org-expiry-wait "+1y"
+ "Time span between the creation date and the expiry.
+The default value for this variable (\"+1y\") means that entries
+will expire if there are at least one year old.
+
+If the expiry delay cannot be retrieved from the entry or the
+subtree above, the expiry process compares the expiry delay with
+`org-expiry-wait'. This can be either an ISO date or a relative
+time specification. See `org-read-date' for details."
+ :type 'string
+ :group 'org-expiry)
+
+(defcustom org-expiry-created-date "+0d"
+ "The default creation date.
+The default value of this variable (\"+0d\") means that entries
+without a creation date will be handled as if they were created
+today.
+
+If the creation date cannot be retrieved from the entry or the
+subtree above, the expiry process will compare the expiry delay
+with this date. This can be either an ISO date or a relative
+time specification. See `org-read-date' for details on relative
+time specifications."
+ :type 'string
+ :group 'org-expiry)
+
+(defcustom org-expiry-handler-function 'org-toggle-archive-tag
+ "Function to process expired entries.
+Possible candidates for this function are:
+
+`org-toggle-archive-tag'
+`org-expiry-add-keyword'
+`org-expiry-archive-subtree'"
+ :type 'function
+ :group 'org-expiry)
+
+(defcustom org-expiry-confirm-flag t
+ "Non-nil means confirm expiration process."
+ :type '(choice
+ (const :tag "Always require confirmation" t)
+ (const :tag "Do not require confirmation" nil)
+ (const :tag "Require confirmation in interactive expiry process"
+ interactive))
+ :group 'org-expiry)
+
+(defcustom org-expiry-advised-functions
+ '(org-scheduled org-deadline org-time-stamp)
+ "A list of advised functions.
+`org-expiry-insinuate' will activate the expiry advice for these
+functions. `org-expiry-deinsinuate' will deactivate them."
+ :type 'boolean
+ :group 'list)
+
+;;; Advices and insinuation:
+
+(defadvice org-schedule (after org-schedule-update-created)
+ "Update the creation-date property when calling `org-schedule'."
+ (org-expiry-insert-created))
+
+(defadvice org-deadline (after org-deadline-update-created)
+ "Update the creation-date property when calling `org-deadline'."
+ (org-expiry-insert-created))
+
+(defadvice org-time-stamp (after org-time-stamp-update-created)
+ "Update the creation-date property when calling `org-time-stamp'."
+ (org-expiry-insert-created))
+
+(defun org-expiry-insinuate (&optional arg)
+ "Add hooks and activate advices for org-expiry.
+If ARG, also add a hook to `before-save-hook' in `org-mode' and
+restart `org-mode' if necessary."
+ (interactive "P")
+ (ad-activate 'org-schedule)
+ (ad-activate 'org-time-stamp)
+ (ad-activate 'org-deadline)
+ (add-hook 'org-insert-heading-hook 'org-expiry-insert-created)
+ (add-hook 'org-after-todo-state-change-hook 'org-expiry-insert-created)
+ (add-hook 'org-after-tags-change-hook 'org-expiry-insert-created)
+ (when arg
+ (add-hook 'org-mode-hook
+ (lambda() (add-hook 'before-save-hook
+ 'org-expiry-process-entries t t)))
+ ;; need this to refresh org-mode hooks
+ (when (eq major-mode 'org-mode)
+ (org-mode)
+ (if (called-interactively-p 'any)
+ (message "Org-expiry insinuated, `org-mode' restarted.")))))
+
+(defun org-expiry-deinsinuate (&optional arg)
+ "Remove hooks and deactivate advices for org-expiry.
+If ARG, also remove org-expiry hook in Org's `before-save-hook'
+and restart `org-mode' if necessary."
+ (interactive "P")
+ (ad-deactivate 'org-schedule)
+ (ad-deactivate 'org-time-stamp)
+ (ad-deactivate 'org-deadline)
+ (remove-hook 'org-insert-heading-hook 'org-expiry-insert-created)
+ (remove-hook 'org-after-todo-state-change-hook 'org-expiry-insert-created)
+ (remove-hook 'org-after-tags-change-hook 'org-expiry-insert-created)
+ (remove-hook 'org-mode-hook
+ (lambda() (add-hook 'before-save-hook
+ 'org-expiry-process-entries t t)))
+ (when arg
+ ;; need this to refresh org-mode hooks
+ (when (eq major-mode 'org-mode)
+ (org-mode)
+ (if (called-interactively-p 'any)
+ (message "Org-expiry de-insinuated, `org-mode' restarted.")))))
+
+;;; org-expiry-expired-p:
+
+(defun org-expiry-expired-p ()
+ "Check if the entry at point is expired.
+Return nil if the entry is not expired. Otherwise return the
+amount of time between today and the expiry date.
+
+If there is no creation date, use `org-expiry-created-date'.
+If there is no expiry date, use `org-expiry-wait'."
+ (let* ((ex-prop org-expiry-expiry-property-name)
+ (cr-prop org-expiry-created-property-name)
+ (ct (current-time))
+ (cr (org-read-date nil t (or (org-entry-get (point) cr-prop t)
+ org-expiry-created-date)))
+ (ex-field (or (org-entry-get (point) ex-prop t) org-expiry-wait))
+ (ex (if (string-match "^[ \t]?[+-]" ex-field)
+ (time-add cr (time-subtract (org-read-date nil t ex-field) ct))
+ (org-read-date nil t ex-field))))
+ (if (time-less-p ex ct)
+ (time-subtract ct ex))))
+
+;;; Expire an entry or a region/buffer:
+
+(defun org-expiry-process-entry (&optional force)
+ "Call `org-expiry-handler-function' on entry.
+If FORCE is non-nil, don't require confirmation from the user.
+Otherwise rely on `org-expiry-confirm-flag' to decide."
+ (interactive "P")
+ (save-excursion
+ (when (called-interactively-p) (org-reveal))
+ (when (org-expiry-expired-p)
+ (org-back-to-heading)
+ (looking-at org-complex-heading-regexp)
+ (let* ((ov (make-overlay (point) (match-end 0)))
+ (e (org-expiry-expired-p))
+ (d (time-to-number-of-days e)))
+ (overlay-put ov 'face 'secondary-selection)
+ (if (or force
+ (null org-expiry-confirm-flag)
+ (and (eq org-expiry-confirm-flag 'interactive)
+ (not (interactive)))
+ (and org-expiry-confirm-flag
+ (y-or-n-p (format "Entry expired by %d days. Process? " d))))
+ (funcall org-expiry-handler-function))
+ (delete-overlay ov)))))
+
+(defun org-expiry-process-entries (beg end)
+ "Process all expired entries between BEG and END.
+The expiry process will run the function defined by
+`org-expiry-handler-functions'."
+ (interactive "r")
+ (save-excursion
+ (let ((beg (if (org-region-active-p)
+ (region-beginning) (point-min)))
+ (end (if (org-region-active-p)
+ (region-end) (point-max))))
+ (goto-char beg)
+ (let ((expired 0) (processed 0))
+ (while (and (outline-next-heading) (< (point) end))
+ (when (org-expiry-expired-p)
+ (setq expired (1+ expired))
+ (if (if (called-interactively-p 'any)
+ (call-interactively 'org-expiry-process-entry)
+ (org-expiry-process-entry))
+ (setq processed (1+ processed)))))
+ (if (equal expired 0)
+ (message "No expired entry")
+ (message "Processed %d on %d expired entries"
+ processed expired))))))
+
+;;; Insert created/expiry property:
+
+(defun org-expiry-insert-created (&optional arg)
+ "Insert or update a property with the creation date.
+If ARG, always update it. With one `C-u' prefix, silently update
+to today's date. With two `C-u' prefixes, prompt the user for to
+update the date."
+ (interactive "P")
+ (let* ((d (org-entry-get (point) org-expiry-created-property-name))
+ d-time d-hour timestr)
+ (when (or (null d) arg)
+ ;; update if no date or non-nil prefix argument
+ ;; FIXME Use `org-time-string-to-time'
+ (setq d-time (if d (org-time-string-to-time d)
+ (current-time)))
+ (setq d-hour (format-time-string "%H:%M" d-time))
+ (setq timestr
+ ;; two C-u prefixes will call org-read-date
+ (if (equal arg '(16))
+ (concat "<" (org-read-date
+ nil nil nil nil d-time d-hour) ">")
+ (format-time-string (cdr org-time-stamp-formats))))
+ ;; maybe transform to inactive timestamp
+ (if org-expiry-inactive-timestamps
+ (setq timestr (concat "[" (substring timestr 1 -1) "]")))
+ (save-excursion
+ (org-entry-put
+ (point) org-expiry-created-property-name timestr)))))
+
+(defun org-expiry-insert-expiry (&optional today)
+ "Insert a property with the expiry date.
+With one `C-u' prefix, don't prompt interactively for the date
+and insert today's date."
+ (interactive "P")
+ (let* ((d (org-entry-get (point) org-expiry-expiry-property-name))
+ d-time d-hour)
+ (setq d-time (if d (org-time-string-to-time d)
+ (current-time)))
+ (setq d-hour (format-time-string "%H:%M" d-time))
+ (setq timestr (if today
+ (format-time-string (cdr org-time-stamp-formats))
+ (concat "<" (org-read-date
+ nil nil nil nil d-time d-hour) ">")))
+ ;; maybe transform to inactive timestamp
+ (if org-expiry-inactive-timestamps
+ (setq timestr (concat "[" (substring timestr 1 -1) "]")))
+
+ (save-excursion
+ (org-entry-put
+ (point) org-expiry-expiry-property-name timestr))))
+
+;;; Functions to process expired entries:
+
+(defun org-expiry-archive-subtree ()
+ "Archive the entry at point if it is expired."
+ (interactive)
+ (save-excursion
+ (if (org-expiry-expired-p)
+ (org-archive-subtree)
+ (if (called-interactively-p 'any)
+ (message "Entry at point is not expired.")))))
+
+(defun org-expiry-add-keyword (&optional keyword)
+ "Add KEYWORD to the entry at point if it is expired."
+ (interactive "sKeyword: ")
+ (if (or (member keyword org-todo-keywords-1)
+ (setq keyword org-expiry-keyword))
+ (save-excursion
+ (if (org-expiry-expired-p)
+ (org-todo keyword)
+ (if (called-interactively-p 'any)
+ (message "Entry at point is not expired."))))
+ (error "\"%s\" is not a to-do keyword in this buffer" keyword)))
+
+;; FIXME what about using org-refile ?
+
+(provide 'org-expiry)
+
+;;; org-expiry.el ends here
diff --git a/contrib/lisp/org-git-link.el b/contrib/lisp/org-git-link.el
new file mode 100644
index 0000000..0028daf
--- /dev/null
+++ b/contrib/lisp/org-git-link.el
@@ -0,0 +1,229 @@
+;;; org-git-link.el --- Provide org links to specific file version
+
+;; Copyright (C) 2009-2014 Reimar Finken
+
+;; Author: Reimar Finken <reimar.finken@gmx.de>
+;; Keywords: files, calendar, hypermedia
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distaributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; `org-git-link.el' defines two new link types. The `git' link
+;; type is meant to be used in the typical scenario and mimics the
+;; `file' link syntax as closely as possible. The `gitbare' link
+;; type exists mostly for debugging reasons, but also allows e.g.
+;; linking to files in a bare git repository for the experts.
+
+;; * User friendy form
+;; [[git:/path/to/file::searchstring]]
+
+;; This form is the familiar from normal org file links
+;; including search options. However, its use is
+;; restricted to files in a working directory and does not
+;; handle bare repositories on purpose (see the bare form for
+;; that).
+
+;; The search string references a commit (a tree-ish in Git
+;; terminology). The two most useful types of search strings are
+
+;; - A symbolic ref name, usually a branch or tag name (e.g.
+;; master or nobelprize).
+;; - A ref followed by the suffix @ with a date specification
+;; enclosed in a brace pair (e.g. {yesterday}, {1 month 2
+;; weeks 3 days 1 hour 1 second ago} or {1979-02-26 18:30:00})
+;; to specify the value of the ref at a prior point in time
+;;
+;; * Bare git form
+;; [[gitbare:$GIT_DIR::$OBJECT]]
+;;
+;; This is the more bare metal version, which gives the user most
+;; control. It directly translates to the git command
+;; git --no-pager --git-dir=$GIT_DIR show $OBJECT
+;; Using this version one can also view files from a bare git
+;; repository. For detailed information on how to specify an
+;; object, see the man page of `git-rev-parse' (section
+;; SPECIFYING REVISIONS). A specific blob (file) can be
+;; specified by a suffix clolon (:) followed by a path.
+
+;;; Code:
+
+(require 'org)
+(defcustom org-git-program "git"
+ "Name of the git executable used to follow git links."
+ :type '(string)
+ :group 'org)
+
+;; org link functions
+;; bare git link
+(org-link-set-parameters "gitbare" :follow #'org-gitbare-open)
+
+(defun org-gitbare-open (str)
+ (let* ((strlist (org-git-split-string str))
+ (gitdir (nth 0 strlist))
+ (object (nth 1 strlist)))
+ (org-git-open-file-internal gitdir object)))
+
+
+(defun org-git-open-file-internal (gitdir object)
+ (let* ((sha (org-git-blob-sha gitdir object))
+ (tmpdir (concat temporary-file-directory "org-git-" sha))
+ (filename (org-git-link-filename object))
+ (tmpfile (expand-file-name filename tmpdir)))
+ (unless (file-readable-p tmpfile)
+ (make-directory tmpdir)
+ (with-temp-file tmpfile
+ (org-git-show gitdir object (current-buffer))))
+ (org-open-file tmpfile)
+ (set-buffer (get-file-buffer tmpfile))
+ (setq buffer-read-only t)))
+
+;; user friendly link
+(org-link-set-parameters "git" :follow #'org-git-open :store #'org-git-store-link)
+
+(defun org-git-open (str)
+ (let* ((strlist (org-git-split-string str))
+ (filepath (nth 0 strlist))
+ (commit (nth 1 strlist))
+ (line (nth 2 strlist))
+ (dirlist (org-git-find-gitdir (file-truename filepath)))
+ (gitdir (nth 0 dirlist))
+ (relpath (nth 1 dirlist)))
+ (org-git-open-file-internal gitdir (concat commit ":" relpath))
+ (when line
+ (save-restriction
+ (widen)
+ (goto-char (point-min))
+ (forward-line (1- (string-to-number line)))))))
+
+
+;; Utility functions (file names etc)
+
+(defun org-git-split-dirpath (dirpath)
+ "Given a directory name, return '(dirname basname)"
+ (let ((dirname (file-name-directory (directory-file-name dirpath)))
+ (basename (file-name-nondirectory (directory-file-name dirpath))))
+ (list dirname basename)))
+
+;; finding the git directory
+(defun org-git-find-gitdir (path)
+ "Given a file (not necessarily existing) file path, return the
+ a pair (gitdir relpath), where gitdir is the path to the first
+ .git subdirectory found updstream and relpath is the rest of
+ the path. Example: (org-git-find-gitdir
+ \"~/gitrepos/foo/bar.txt\") returns
+ '(\"/home/user/gitrepos/.git\" \"foo/bar.txt\"). When not in a git repository, return nil."
+ (let ((dir (expand-file-name (file-name-directory path)))
+ (relpath (file-name-nondirectory path)))
+ (catch 'toplevel
+ (while (not (file-exists-p (expand-file-name ".git" dir)))
+ (let ((dirlist (org-git-split-dirpath dir)))
+ (when (string= (nth 1 dirlist) "") ; at top level
+ (throw 'toplevel nil))
+ (setq dir (nth 0 dirlist)
+ relpath (concat (file-name-as-directory (nth 1 dirlist)) relpath))))
+ (list (expand-file-name ".git" dir) relpath))))
+
+
+(eval-and-compile
+ (defalias 'org-git-gitrepos-p 'org-git-find-gitdir
+ "Return non-nil if path is in git repository"))
+
+;; splitting the link string
+
+;; Both link open functions are called with a string of
+;; consisting of three parts separated by a double colon (::).
+(defun org-git-split-string (str)
+ "Given a string of the form \"str1::str2::str3\", return a list of
+ three substrings \'(\"str1\" \"str2\" \"str3\"). If there are less
+than two double colons, str2 and/or str3 may be set the empty string."
+ (let ((strlist (split-string str "::")))
+ (cond ((= 1 (length strlist))
+ (list (car strlist) "" ""))
+ ((= 2 (length strlist))
+ (append strlist (list "")))
+ ((= 3 (length strlist))
+ strlist)
+ (t (error "org-git-split-string: only one or two :: allowed: %s" str)))))
+
+;; finding the file name part of a commit
+(defun org-git-link-filename (str)
+ "Given an object description (see the man page of
+ git-rev-parse), return the nondirectory part of the referenced
+ filename, if it can be extracted. Otherwise, return a valid
+ filename."
+ (let* ((match (and (string-match "[^:]+$" str)
+ (match-string 0 str)))
+ (filename (and match (file-name-nondirectory match)))) ;extract the final part without slash
+ filename))
+
+;; creating a link
+(defun org-git-create-searchstring (branch timestring)
+ (concat branch "@{" timestring "}"))
+
+
+(defun org-git-create-git-link (file &optional line)
+ "Create git link part to file at specific time"
+ (interactive "FFile: ")
+ (let* ((gitdir (nth 0 (org-git-find-gitdir (file-truename file))))
+ (branchname (org-git-get-current-branch gitdir))
+ (timestring (format-time-string "%Y-%m-%d" (current-time))))
+ (concat "git:" file "::" (org-git-create-searchstring branchname timestring)
+ (if line (format "::%s" line) ""))))
+
+(defun org-git-store-link ()
+ "Store git link to current file."
+ (when (buffer-file-name)
+ (let ((file (abbreviate-file-name (buffer-file-name)))
+ (line (line-number-at-pos)))
+ (when (org-git-gitrepos-p file)
+ (org-store-link-props
+ :type "git"
+ :link (org-git-create-git-link file line))))))
+
+(defun org-git-insert-link-interactively (file searchstring &optional description)
+ (interactive "FFile: \nsSearch string: \nsDescription: ")
+ (insert (org-make-link-string (concat "git:" file "::" searchstring) description)))
+
+;; Calling git
+(defun org-git-show (gitdir object buffer)
+ "Show the output of git --git-dir=gitdir show object in buffer."
+ (unless
+ (zerop (call-process org-git-program nil buffer nil
+ "--no-pager" (concat "--git-dir=" gitdir) "show" object))
+ (error "git error: %s " (with-current-buffer buffer (buffer-string)))))
+
+(defun org-git-blob-sha (gitdir object)
+ "Return sha of the referenced object"
+ (with-temp-buffer
+ (if (zerop (call-process org-git-program nil t nil
+ "--no-pager" (concat "--git-dir=" gitdir) "rev-parse" object))
+ (buffer-substring (point-min) (1- (point-max))) ; to strip off final newline
+ (error "git error: %s " (buffer-string)))))
+
+(defun org-git-get-current-branch (gitdir)
+ "Return the name of the current branch."
+ (with-temp-buffer
+ (if (not (zerop (call-process org-git-program nil t nil
+ "--no-pager" (concat "--git-dir=" gitdir) "symbolic-ref" "-q" "HEAD")))
+ (error "git error: %s " (buffer-string))
+ (goto-char (point-min))
+ (if (looking-at "^refs/heads/") ; 11 characters
+ (buffer-substring 12 (1- (point-max))))))) ; to strip off final newline
+
+(provide 'org-git-link)
+
+;;; org-git-link.el ends here
diff --git a/contrib/lisp/org-index.el b/contrib/lisp/org-index.el
new file mode 100644
index 0000000..9efa510
--- /dev/null
+++ b/contrib/lisp/org-index.el
@@ -0,0 +1,3006 @@
+;;; org-index.el --- A personal adaptive index for org
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Marc Ihm <org-index@2484.de>
+;; Version: 5.1.3
+;; Keywords: outlines index
+
+;; This file is not part of GNU Emacs.
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Purpose:
+;;
+;; Fast search for selected org nodes and things outside of org.
+;;
+;; org-index creates and updates an index table with keywords; each line
+;; either points to a heading in org, references something outside or
+;; carries a snippet of text to yank. When searching the index, the set
+;; of matching lines is updated with every keystroke; results are sorted
+;; by usage count and date, so that frequently used entries appear first
+;; in the list of results.
+;;
+;; References are decorated numbers (e.g. 'R237' or '--455--'); they are
+;; well suited to be used outside of org, e.g. in folder names, ticket
+;; systems or on printed documents.
+;;
+;; On first invocation org-index will assist you in creating the index
+;; table.
+;;
+;; To start using your index, invoke subcommands 'add', 'ref' and 'yank'
+;; to create entries and 'occur' to find them.
+;;
+;;
+;; Setup:
+;;
+;; - Place this file in a directory from your load-path,
+;; e.g. org-mode/contrib/lisp.
+;;
+;; - Add these lines to your .emacs:
+;;
+;; (require 'org-index)
+;; (global-set-key (kbd "C-c i") 'org-index-dispatch) ; this is optional
+;;
+;; - Restart your Emacs to make these lines effective.
+;;
+;; - Invoke `org-index'; on first run it will assist in creating your
+;; index table.
+;;
+;; - Optionally invoke `M-x org-customize' to tune some settings (choose
+;; group org-index).
+;;
+;;
+;; Further information:
+;;
+;; - Watch the screencast at http://2484.de/org-index.html.
+;;
+;; - See the documentation of `org-index', which can also be read by
+;; invoking `org-index' and choosing the command help or '?'.
+;;
+;;
+;; Updates:
+;;
+;; The latest published version of this file can always be found at:
+;;
+;; http://orgmode.org/w/?p=org-mode.git;a=blob_plain;f=contrib/lisp/org-index.el;hb=HEAD
+;;
+;; Development version under:
+;;
+;; https://github.com/marcIhm/org-index
+
+;;; Change Log:
+
+;; [2016-08-26 Fr] Version 5.1.3
+;; - Offering help during query for subcommands
+;; - Removed org-index-default-keybindings
+;; - Renamed subcommand multi-occur to find-ref
+;; - Subcommands add and need no longer be invoked from heading
+;; - Many Bugfixes
+;;
+;; [2015-12-29 Tu] Version 5.0.2
+;; - New commands yank, column and edit
+;; - New column tags
+;; - All columns are now required
+;; - References are now optional
+;; - Subcommand enter has been renamed to index
+;; - Subcommands kill and edit can be invoked from an occur buffer
+;; - Many Bugfixes
+;; - Added link to screencast
+;;
+;; [2015-08-20 Th] Version 4.3.0
+;; - Configuration is done now via standard customize
+;; - New sorting strategy 'mixed'
+;; - Silenced some compiler warnings
+;;
+;; [2015-03-18 We] Version 4.2.1
+;; - No garbage in kill-ring
+;; - No recentering after add
+;;
+;; [2015-03-08 Su] Version 4.2.0
+;; - Reference numbers for subcommands can be passed as a prefix argument
+;; - New variable org-index-default-keybindings-list with a list of
+;; default keybindings for org-index-default-keybindings
+;; - Added new column level
+;; - removed flags get-category-on-add and get-heading-on-add
+;;
+;; [2015-02-26 Th] to [2015-03-05 Th] Version 4.0.0 to 4.1.2
+;; - Removed command "leave"; rather go back with org-mark-ring-goto
+;; - Renamed column "link" to "id"
+;; - Added maintainance options to find duplicate rows, to check ids,
+;; update index or remove property org-index-ref from nodes
+;; - Shortened versin history
+;;
+;; [2014-12-08 Mo] to [2015-01-31 Sa] Version 3.0.0 to 3.2.0:
+;; - Complete sorting of index only occurs in idle-timer
+;; - New command "maintain" with some subcommands
+;; - Rewrote command "occur" with overlays in an indirect buffer
+;; - Command "add" updates index, if node is already present
+;; - New commands "add" and "delete" to easily add and remove
+;; the current node to or from your index.
+;; - New command "example" to create an example index.
+;; - Several new flags that are explained within index node.
+;; - Removed commands "reuse", "missing", "put", "goto",
+;; "update", "link", "fill", "unhighlight"
+;; - New function `org-index-default-keybindings'
+;;
+;; [2012-12-07 Fr] to [2014-04-26 Sa] Version 2.0.0 to 2.4.3:
+;; - New functions org-index-new-line and org-index-get-line
+;; offer access to org-index from other lisp programs
+;; - Regression tests with ert
+;; - Renamed from "org-favtable" to "org-index"
+;; - Added an assistant to set up the index table
+;; - occur is now incremental, searching as you type
+;; - Integrated with org-mark-ring-goto
+;; - Added full support for ids
+;; - Renamed the package from "org-reftable" to "org-favtable"
+;; - Additional columns are required (e.g. "link"). Error messages will
+;; guide you
+;; - Ask user explicitly, which command to invoke
+;; - Renamed the package from "org-refer-by-number" to "org-reftable"
+;;
+;; [2011-12-10 Sa] to [2012-09-22 Sa] Version Version 1.2.0 to 1.5.0:
+;; - New command "sort" to sort a buffer or region by reference number
+;; - New commands "highlight" and "unhighlight" to mark references
+;; - New command "head" to find a headline with a reference number
+;; - New commands occur and multi-occur
+;; - Started this Change Log
+
+;;; Code:
+
+(require 'org-table)
+(require 'cl-lib)
+(require 'widget)
+
+;; Version of this package
+(defvar org-index-version "5.1.3" "Version of `org-index', format is major.minor.bugfix, where \"major\" are incompatible changes and \"minor\" are new features.")
+
+;; customizable options
+(defgroup org-index nil
+ "Options concerning the optional index for org."
+ :tag "Org Index"
+ :group 'org)
+
+(defcustom org-index-id nil
+ "Id of the Org-mode node, which contains the index table."
+ :group 'org-index)
+
+(defcustom org-index-sort-by 'mixed
+ "Strategy for sorting index table (and whence entries in occur).
+Valid values are:
+
+last-access Sort index by date and time of last access; show
+ more recent entries first.
+count Sort by usage count; more often used entries first.
+mixed First, show all index entries, which have been
+ used today; sort them by last access. Then show
+ older entries sorted by usage count."
+ :group 'org-index
+ :set (lambda (s v)
+ (set-default s v)
+ (if (and org-index-id
+ org-index--buffer
+ (functionp 'org-index--sort-silent))
+ (org-index--sort-silent)))
+ :initialize 'custom-initialize-default
+ :type '(choice
+ (const last-accessed)
+ (const count)
+ (const mixed)))
+
+(defcustom org-index-yank-after-add 'ref
+ "Specifies which column should be yanked after adding a new index row.
+Valid values are some columns of index table."
+ :group 'org-index
+ :type '(choice
+ (const ref)
+ (const category)
+ (const keywords)))
+
+(defcustom org-index-point-on-add 'keywords
+ "Specifies in which column point will land when adding a new index row.
+Valid values are some columns of index table."
+ :group 'org-index
+ :type '(choice
+ (const category)
+ (const keywords)))
+
+(defcustom org-index-copy-heading-to-keywords t
+ "When adding a new node to index: Copy heading to keywords-column ?"
+ :group 'org-index
+ :type '(choice (const :tag "Yes" t)
+ (const :tag "No" nil)))
+
+(defcustom org-index-strip-ref-and-date-from-heading t
+ "When adding a node to index: strip leading ref or timestamps ?
+
+This can be useful, if you have the habit of adding refs and
+dates to the start of your headings; then, if you change your
+heading and want to update your index, you do not need to remove
+those pieces."
+ :group 'org-index
+ :type '(choice (const :tag "Yes" t)
+ (const :tag "No" nil)))
+
+(defcustom org-index-edit-on-add '(category keywords)
+ "List of columns to edit when adding a new row."
+ :group 'org-index
+ :type '(repeat (choice
+ (const category)
+ (const keywords))))
+
+(defcustom org-index-edit-on-yank '(yank keywords)
+ "List of columns to edit when adding new text to yank."
+ :group 'org-index
+ :type '(repeat (choice
+ (const yank)
+ (const category)
+ (const keywords))))
+
+(defcustom org-index-edit-on-ref '(category keywords)
+ "List of columns to edit when adding new ref."
+ :group 'org-index
+ :type '(repeat (choice
+ (const category)
+ (const keywords))))
+
+;; Variables to hold the configuration of the index table
+(defvar org-index--maxrefnum nil "Maximum number from reference table, e.g. 153.")
+(defvar org-index--nextref nil "Next reference, that can be used, e.g. 'R154'.")
+(defvar org-index--head nil "Header before number (e.g. 'R').")
+(defvar org-index--tail nil "Tail after number (e.g. '}' or ')'.")
+(defvar org-index--numcols nil "Number of columns in index table.")
+(defvar org-index--ref-regex nil "Regular expression to match a reference.")
+(defvar org-index--ref-format nil "Format, that can print a reference.")
+(defvar org-index--columns nil "Columns of index-table.")
+(defvar org-index--buffer nil "Buffer of index table.")
+(defvar org-index--point nil "Position at start of headline of index table.")
+(defvar org-index--below-hline nil "Position of first cell in first line below hline.")
+(defvar org-index--saved-positions nil "Saved positions within current buffer and index buffer; filled by ‘org-index--save-positions’.")
+(defvar org-index--headings nil "Headlines of index-table as a string.")
+(defvar org-index--headings-visible nil "Visible part of headlines of index-table as a string.")
+
+;; Variables to hold context and state
+(defvar org-index--last-fingerprint nil "Fingerprint of last line created.")
+(defvar org-index--category-before nil "Category of node before.")
+(defvar org-index--active-region nil "Active region, initially. I.e. what has been marked.")
+(defvar org-index--below-cursor nil "Word below cursor.")
+(defvar org-index--within-index-node nil "True, if we are within node of the index table.")
+(defvar org-index--within-occur nil "True, if we are within the occur-buffer.")
+(defvar org-index--message-text nil "Text that was issued as an explanation; helpful for regression tests.")
+(defvar org-index--occur-help-text nil "Text for help in occur buffer.")
+(defvar org-index--occur-help-overlay nil "Overlay for help in occur buffer.")
+(defvar org-index--occur-stack nil "Stack with overlays for hiding lines.")
+(defvar org-index--occur-tail-overlay nil "Overlay to cover invisible lines.")
+(defvar org-index--occur-lines-collected 0 "Number of lines collected in occur buffer; helpful for tests.")
+(defvar org-index--last-sort nil "Last column, the index has been sorted after.")
+(defvar org-index--sort-timer nil "Timer to sort index in correct order.")
+(defvar org-index--aligned nil "Remember for this Emacs session, if table has been aligned at least once.")
+(defvar org-index--edit-widgets nil "List of widgets used to edit.")
+(defvar org-index--context-index nil "Position and line used for index in edit buffer.")
+(defvar org-index--context-occur nil "Position and line used for occur in edit buffer.")
+(defvar org-index--context-node nil "Buffer and position for node in edit buffer.")
+(defvar org-index--short-help-buffer-name "*org-index commands*" "Name of buffer to display short help.")
+(defvar org-index--display-short-help nil "True, if short help should be displayed.")
+(defvar org-index--short-help-displayed nil "True, if short help message has been displayed.")
+(defvar org-index--minibuffer-saved-key nil "Temporarily save entry of minibuffer keymap.")
+
+;; static information for this program package
+(defconst org-index--commands '(occur add kill head ping index ref yank column edit help short-help example sort find-ref highlight maintain) "List of commands available.")
+(defconst org-index--valid-headings '(ref id created last-accessed count keywords category level yank tags) "All valid headings.")
+(defconst org-index--occur-buffer-name "*org-index-occur*" "Name of occur buffer.")
+(defconst org-index--edit-buffer-name "*org-index-edit*" "Name of edit buffer.")
+(defconst org-index--sort-idle-delay 300 "Delay in seconds after which buffer will sorted.")
+(defvar org-index--short-help-text nil "Cache for result of `org-index--get-short-help-text.")
+(defvar org-index--shortcut-chars nil "Cache for result of `org-index--get-shortcut-chars.")
+
+
+(defmacro org-index--on (column value &rest body)
+ "Execute the forms in BODY with point on index line whose COLUMN is VALUE.
+The value returned is the value of the last form in BODY or nil,
+if VALUE cannot be found."
+ (declare (indent 2) (debug t))
+ (let ((pointvar (make-symbol "point")) ; avoid clash with same-named variables in body
+ (foundvar (make-symbol "found"))
+ (retvar (make-symbol "ret")))
+ `(save-current-buffer
+ (let ((,pointvar (point))
+ ,foundvar
+ ,retvar)
+
+ (set-buffer org-index--buffer)
+
+ (setq ,foundvar (org-index--go ,column ,value))
+ (when ,foundvar
+ (setq ,retvar (progn ,@body)))
+
+ (goto-char ,pointvar)
+
+ ,retvar))))
+
+
+(defun org-index (&optional command search-ref arg)
+ "Fast search-index for selected org nodes and things outside of org.
+
+org-index creates and updates an index table with keywords; each line
+either points to a heading in org, references something outside or
+carries a snippet of text to yank. The index table is searched for
+keywords through an incremental occur; results are sorted by usage
+count and date, so that frequently used entries appear first among
+the results.
+
+References are decorated numbers (e.g. 'R237' or '--455--'); they are
+well suited to be used outside of org, e.g. in folder names, ticket
+systems or on printed documents.
+
+On first invocation org-index will help to create a dedicated node
+for its index table.
+
+To start building up your index, use subcommands 'add', 'ref' and
+'yank' to create entries and use 'occur' to find them.
+
+This is version 5.1.3 of org-index.el.
+
+
+The function `org-index' is the only interactive function of this
+package and its main entry point; it will present you with a list
+of subcommands to choose from:
+
+\(Note the one-letter shortcuts, e.g. [o]; used like 'C-c i o'.)
+
+ occur: [o] Incrementally show matching lines from index.
+ Result is updated after every keystroke. You may enter a
+ list of words seperated by space or comma (`,'), to select
+ lines that contain all of the given words.
+
+ add: [a] Add the current node to index.
+ So that (e.g.) it can be found through the subcommand
+ 'occur'. Update index, if node is already present.
+
+ kill: [k] Kill (delete) the current node from index.
+ Can be invoked from index, from occur or from a headline.
+
+ head: [h] Search for heading, by ref or from index line.
+ If invoked from within index table, go to associated
+ node (if any), otherwise ask for ref to search.
+
+ index: [i] Enter index table and maybe go to a specific reference.
+ Use `org-mark-ring-goto' (\\[org-mark-ring-goto]) to go back.
+
+ ping: [p] Echo line from index table for current node.
+ If current node is not in index, than search among its
+ parents.
+
+ ref: [r] Create a new index line with a reference.
+ This line will not be associated with a node.
+
+ yank: [y] Store a new string, that can be yanked from occur.
+ The index line will not be associated with a node.
+
+ column: [c] From within index table: read char and jump to column.
+ Shortcut for column movement; stays within one index line.
+
+ edit: [e] Present current line in edit buffer.
+ Can be invoked from index, from occur or from a headline.
+
+ help: Show complete help text of org-index.
+
+ short-help: [?] Show one-line description of each subcommand.
+ I.e. show this list but only first sentence each.
+
+ example: Create an example index, that will not be saved.
+ May serve as an example.
+
+ sort: Sort lines in index, in region or buffer.
+ Region or buffer can be sorted by contained reference; Index
+ by count, reference or last access.
+
+ find-ref: Search for given reference in all org-buffers.
+ A wrapper to employ emacs standard `multi-occur' function;
+ asks for reference.
+
+ highlight: Highlight or unhighlight all references.
+ Operates on active region or whole buffer. Call with prefix
+ argument (`C-u') to remove highlights.
+
+ maintain: Index maintainance.
+ Offers some choices to check, update or fix your index.
+
+If you invoke `org-index' for the first time, an assistant will be
+invoked, that helps you to create your own index.
+
+Invoke `org-customize' to tweak the behaviour of org-index.
+
+Optionally bind `org-index-dispatch' to a key, e.g. 'C-c i' in
+the global keymap to invoke the most important subcommands with
+a single key.
+
+A numeric prefix argument is used as a reference number for
+commands, that need one (e.g. 'head').
+
+Use from elisp: Optional argument COMMAND is a symbol naming the
+command to execute. SEARCH-REF specifies a reference to search
+for, if needed. ARG allows passing in a prefix argument as in
+interactive calls."
+
+ (interactive "i\ni\nP")
+
+ (let (search-id ; id to search for
+ search-fingerprint ; fingerprint to search for
+ sort-what ; sort what ?
+ kill-new-text ; text that will be appended to kill ring
+ message-text) ; text that will be issued as an explanation
+
+ (catch 'new-index
+
+ ;;
+ ;; Initialize and parse
+ ;;
+
+ ;; creates index table, if necessary
+ (org-index--verify-id)
+
+ ;; Get configuration of index table
+ (org-index--parse-table)
+
+ ;; store context information
+ (org-index--retrieve-context)
+
+
+ ;;
+ ;; Arrange for proper sorting of index
+ ;;
+
+ ;; lets assume, that it has been sorted this way (we try hard to make sure)
+ (unless org-index--last-sort (setq org-index--last-sort org-index-sort-by))
+ ;; rearrange for index beeing sorted into default sort order after 300 secs of idle time
+ (unless org-index--sort-timer
+ (setq org-index--sort-timer
+ (run-with-idle-timer org-index--sort-idle-delay t 'org-index--sort-silent)))
+
+
+ ;;
+ ;; Find out, what we are supposed to do
+ ;;
+
+ ;; Check or read command
+ (if (and command (not (eq command 'short-help)))
+ (unless (memq command org-index--commands)
+ (error "Unknown command '%s' passed as argument, valid choices are any of these symbols: %s"
+ command (mapconcat 'symbol-name org-index--commands ",")))
+
+ ;; read command; if requested display help in read-loop
+ (setq org-index--display-short-help (eq command 'short-help))
+ (setq command (org-index--read-command))
+ (setq org-index--display-short-help nil))
+
+ ;;
+ ;; Get search string, if required; process possible sources one after
+ ;; another (lisp argument, prefix argument, user input).
+ ;;
+
+ ;; Try prefix, if no lisp argument given
+ (if (and (not search-ref)
+ (numberp arg))
+ (setq search-ref (format "%s%d%s" org-index--head arg org-index--tail)))
+
+ ;; These actions really need a search string and may even prompt for it
+ (when (memq command '(index head find-ref))
+
+ ;; search from surrounding text ?
+ (unless search-ref
+ (if org-index--within-index-node
+
+ (if (org-at-table-p)
+ (setq search-ref (org-index--get-or-set-field 'ref)))
+
+ (if (and org-index--below-cursor
+ (string-match (concat "\\(" org-index--ref-regex "\\)")
+ org-index--below-cursor))
+ (setq search-ref (match-string 1 org-index--below-cursor)))))
+
+ ;; If we still do not have a search string, ask user explicitly
+ (unless search-ref
+ (if (eq command 'index)
+ (let ((r (org-index--read-search-for-index)))
+ (setq search-ref (first r))
+ (setq search-id (second r))
+ (setq search-fingerprint (third r)))
+ (unless (and (eq command 'head)
+ org-index--within-index-node
+ (org-at-table-p))
+ (setq search-ref (read-from-minibuffer "Search reference number: ")))))
+
+ ;; Clean up search string
+ (when search-ref
+ (setq search-ref (org-trim search-ref))
+ (if (string-match "^[0-9]+$" search-ref)
+ (setq search-ref (concat org-index--head search-ref org-index--tail)))
+ (if (string= search-ref "") (setq search-ref nil)))
+
+ (if (and (not search-ref)
+ (not (eq command 'index))
+ (not (and (eq command 'head)
+ org-index--within-index-node
+ (org-at-table-p))))
+ (error "Command %s needs a reference number" command)))
+
+
+ ;;
+ ;; Command sort needs to know in advance, what to sort for
+ ;;
+
+ (when (eq command 'sort)
+ (setq sort-what (intern (org-completing-read "You may sort:\n - index : your index table by various columns\n - region : the active region by contained reference\n - buffer : the whole current buffer\nPlease choose what to sort: " (list "index" "region" "buffer") nil t))))
+
+
+ ;;
+ ;; Enter table
+ ;;
+
+ ;; Arrange for beeing able to return
+ (when (and (memq command '(occur head index example sort maintain))
+ (not (string= (buffer-name) org-index--occur-buffer-name)))
+ (org-mark-ring-push))
+
+ ;; These commands will leave user in index table after they are finished
+ (when (or (memq command '(index maintain))
+ (and (eq command 'sort)
+ (eq sort-what 'index)))
+
+ (pop-to-buffer-same-window org-index--buffer)
+ (goto-char org-index--point)
+ (org-index--unfold-buffer))
+
+
+ ;;
+ ;; Actually do, what is requested
+ ;;
+
+ (cond
+
+ ((eq command 'help)
+
+ ;; bring up help-buffer for this function
+ (describe-function 'org-index))
+
+
+ ((eq command 'short-help)
+
+ (org-index--display-short-help))
+
+
+ ((eq command 'find-ref)
+
+ ;; Construct list of all org-buffers
+ (let (org-buffers)
+ (dolist (buff (buffer-list))
+ (set-buffer buff)
+ (if (string= major-mode "org-mode")
+ (setq org-buffers (cons buff org-buffers))))
+
+ ;; Do multi-occur
+ (multi-occur org-buffers (org-index--make-guarded-search search-ref))
+
+ ;; Present results
+ (if (get-buffer "*Occur*")
+ (progn
+ (setq message-text (format "Found '%s'" search-ref))
+ (other-window 1)
+ (toggle-truncate-lines 1))
+ (setq message-text (format "Did not find '%s'" search-ref)))))
+
+
+ ((eq command 'add)
+
+ (let ((r (org-index--do-add-or-update (if (equal arg '(4)) t nil)
+ (if (numberp arg) arg nil))))
+ (setq message-text (car r))
+ (setq kill-new-text (cdr r))))
+
+
+ ((eq command 'kill)
+ (setq message-text (org-index--do-kill)))
+
+
+ ((eq command 'head)
+
+ (if (and org-index--within-index-node
+ (org-at-table-p))
+ (setq search-id (org-index--get-or-set-field 'id)))
+
+ (if (and (not search-id) search-ref)
+ (setq search-id (org-index--id-from-ref search-ref)))
+
+ (setq message-text
+ (if search-id
+ (org-index--find-id search-id)
+ "Current line has no id")))
+
+
+ ((eq command 'index)
+
+ (goto-char org-index--below-hline)
+
+ (setq message-text
+
+ (if search-ref
+ (if (org-index--go 'ref search-ref)
+ (progn
+ (org-index--update-current-line)
+ (org-table-goto-column (org-index--column-num 'ref))
+ (format "Found index line '%s'" search-ref))
+ (format "Did not find index line with reference '%s'" search-ref))
+
+ (if search-id
+ (if (org-index--go 'id search-id)
+ (progn
+ (org-index--update-current-line)
+ (org-table-goto-column (org-index--column-num 'ref))
+ (format "Found index line '%s'" (org-index--get-or-set-field 'ref)))
+ (format "Did not find index line with id '%s'" search-id))
+
+ (if search-fingerprint
+ (if (org-index--go 'fingerprint org-index--last-fingerprint)
+ (progn
+ (org-index--update-current-line)
+ (beginning-of-line)
+ (format "Found latest index line"))
+ (format "Did not find index line"))
+
+ ;; simply go into table
+ "At index table"))))
+
+ (recenter))
+
+
+ ((eq command 'ping)
+
+ (let ((moved-up 0) id info reached-top)
+
+ (unless (string= major-mode "org-mode") (error "No node at point"))
+ ;; take id from current node or reference
+ (setq id (if search-ref
+ (org-index--id-from-ref search-ref)
+ (org-id-get)))
+
+ ;; move up until we find a node in index
+ (save-excursion
+ (outline-back-to-heading)
+ (while (not (or info
+ reached-top))
+ (if id
+ (setq info (org-index--on 'id id
+ (mapcar (lambda (x) (org-index--get-or-set-field x))
+ (list 'ref 'count 'created 'last-accessed 'category 'keywords 'ref)))))
+
+ (setq reached-top (= (org-outline-level) 1))
+
+ (unless (or info
+ reached-top)
+ (outline-up-heading 1 t)
+ (cl-incf moved-up))
+
+ (setq id (org-id-get))))
+
+ (if info
+ (progn
+ (setq message-text
+ (apply 'format
+ (append (list "'%s'%shas been accessed %s times between %s and %s; category is '%s', keywords are '%s'"
+ (pop info)
+ (if (> moved-up 0) (format " (parent node, %d level up) " moved-up) " "))
+ info)))
+ (setq kill-new-text (car (last info))))
+ (setq message-text "Neither this node nor any of its parents is part of index"))))
+
+
+ ((eq command 'occur)
+
+ (set-buffer org-index--buffer)
+ (org-index--do-occur))
+
+
+ ((eq command 'ref)
+
+ (let (args)
+
+ (setq args (org-index--collect-values-from-user org-index-edit-on-ref))
+ (setq args (plist-put args 'category "yank"))
+ (setq args (plist-put args 'ref org-index--nextref))
+ (apply 'org-index--do-new-line args)
+
+ (setq kill-new-text org-index--nextref)
+
+ (setq message-text (format "Added new row with ref '%s'" org-index--nextref))))
+
+
+ ((eq command 'yank)
+
+ (let (args)
+
+ (setq args (org-index--collect-values-from-user org-index-edit-on-yank))
+ (if (plist-get args 'yank)
+ (plist-put args 'yank (replace-regexp-in-string "|" "\\vert" (plist-get args 'yank) nil 'literal)))
+ (setq args (plist-put args 'category "yank"))
+ (apply 'org-index--do-new-line args)
+
+ (setq message-text "Added new row with text to yank")))
+
+
+ ((eq command 'column)
+
+ (if (and org-index--within-index-node
+ (org-at-table-p))
+ (let (char col num)
+ (setq char (read-char "Please specify, which column to go to (r=ref, k=keywords, c=category, y=yank): "))
+ (unless (memq char (list ?r ?k ?c ?y))
+ (error (format "Invalid char '%c', cannot goto this column" char)))
+ (setq col (cdr (assoc char '((?r . ref) (?k . keywords) (?c . category) (?y . yank)))))
+ (setq num (org-index--column-num col))
+ (if num
+ (progn
+ (org-table-goto-column num)
+ (setq message-text (format "At column %s" (symbol-name col))))
+
+ (error (format "Column '%s' is not present" col))))
+ (error "Need to be in index table to go to a specific column")))
+
+
+ ((eq command 'edit)
+
+ (setq message-text (org-index--do-edit)))
+
+
+ ((eq command 'sort)
+
+ (let ((sorts (list "count" "last-accessed" "mixed" "id" "ref"))
+ sort groups-and-counts)
+
+ (cond
+ ((eq sort-what 'index)
+ (setq sort
+ (intern
+ (completing-read
+ "Please choose column to sort index table: "
+ (cl-copy-list sorts)
+ nil t nil nil (symbol-name org-index-sort-by))))
+
+ (org-index--do-sort-index sort)
+ (org-table-goto-column (org-index--column-num (if (eq sort 'mixed) 'last-access sort)))
+ ;; When saving index, it should again be sorted correctly
+ (with-current-buffer org-index--buffer
+ (add-hook 'before-save-hook 'org-index--sort-silent t))
+
+ (setq message-text
+ (format
+ (concat "Your index has been sorted temporarily by %s and will be sorted again by %s after %d seconds of idle time"
+ (if groups-and-counts
+ "; %d groups with equal %s and a total of %d lines have been found"
+ ""))
+ (symbol-name sort)
+ org-index-sort-by
+ org-index--sort-idle-delay
+ (second groups-and-counts)
+ (symbol-name sort)
+ (third groups-and-counts))))
+
+ ((memq sort-what '(region buffer))
+ (org-index--do-sort-lines sort-what)
+ (setq message-text (format "Sorted %s by contained references" sort-what))))))
+
+
+ ((eq command 'highlight)
+
+ (let ((where "buffer"))
+ (save-excursion
+ (save-restriction
+ (when (and transient-mark-mode
+ mark-active)
+ (narrow-to-region (region-beginning) (region-end))
+ (setq where "region"))
+
+ (if arg
+ (progn
+ (unhighlight-regexp org-index--ref-regex)
+ (setq message-text (format "Removed highlights for references in %s" where)))
+ (highlight-regexp org-index--ref-regex 'isearch)
+ (setq message-text (format "Highlighted references in %s" where)))))))
+
+
+ ((eq command 'maintain)
+ (setq message-text (org-index--do-maintain)))
+
+
+ ((eq command 'example)
+
+ (if (y-or-n-p "This assistant will help you to create a temporary index with detailed comments.\nDo you want to proceed ? ")
+ (org-index--create-index t)))
+
+
+ ((not command) (setq message-text "No command given"))
+
+
+ (t (error "Unknown subcommand '%s'" command)))
+
+
+ ;; tell, what we have done and what can be yanked
+ (if kill-new-text (setq kill-new-text
+ (substring-no-properties kill-new-text)))
+ (if (string= kill-new-text "") (setq kill-new-text nil))
+ (let ((m (concat
+ message-text
+ (if (and message-text kill-new-text)
+ " and r"
+ (if kill-new-text "R" ""))
+ (if kill-new-text (format "eady to yank '%s'." kill-new-text) (if message-text "." "")))))
+ (unless (string= m "")
+ (message m)
+ (setq org-index--message-text m)))
+ (if kill-new-text (kill-new kill-new-text)))))
+
+
+(defun org-index-dispatch (&optional arg)
+ "Read additional chars and call subcommands of `org-index'.
+Can be bound in global keyboard map as central entry point.
+Optional argument ARG is passed on."
+ (interactive "P")
+ (let (char command)
+ (if (sit-for 1)
+ (message "org-index (? for detailed prompt) -"))
+ (setq char (key-description (read-key-sequence nil)))
+ (if (string= char "C-g") (keyboard-quit))
+ (if (string= char "SPC") (setq char "?"))
+ (setq command (cdr (assoc char (org-index--get-shortcut-chars))))
+ (unless command
+ (message "No subcommand for '%s'; switching to detailed prompt" char)
+ (sit-for 1)
+ (setq command 'short-help))
+ (org-index command nil arg)))
+
+
+(defun org-index-new-line (&rest keys-values)
+ "Create a new line within the index table, returning its reference.
+
+The function takes a varying number of argument pairs; each pair
+is a symbol for an existing column heading followed by its value.
+The return value is the new reference.
+
+Example:
+
+ (message \"Created reference %s\"
+ (org-index-new-line 'keywords \"foo bar\" 'category \"baz\"))
+
+Optional argument KEYS-VALUES specifies content of new line."
+
+ (let ((ref (plist-get keys-values 'ref)))
+ (org-index--verify-id)
+ (org-index--parse-table)
+ (if (not (memq ref '(t nil)))
+ (error "Column 'ref' accepts only 't' or 'nil'"))
+ (when ref
+ (setq ref org-index--nextref)
+ (setq keys-values (plist-put keys-values 'ref ref)))
+
+ (apply 'org-index--do-new-line keys-values)
+ ref))
+
+
+(defun org-index--read-command (&optional with-short-help)
+ "Read subcommand for ‘org-index’ from minibuffer.
+Optional argument WITH-SHORT-HELP displays help screen upfront."
+ (let (minibuffer-scroll-window
+ minibuffer-setup-fun
+ command)
+ (setq org-index--short-help-displayed nil)
+ (add-hook 'minibuffer-setup-hook 'org-index--minibuffer-setup-function)
+ (add-hook 'minibuffer-exit-hook 'org-index--minibuffer-exit-function)
+ (unwind-protect
+ (setq command
+ (intern
+ (completing-read
+ (concat
+ "Please choose"
+ (if org-index--display-short-help "" " (? for short help)")
+ ": ")
+ (mapcar 'symbol-name org-index--commands) nil t)))
+ (remove-hook 'minibuffer-setup-hook 'org-index--minibuffer-setup-function)
+ (remove-hook 'minibuffer-exit-hook 'org-index--minibuffer-exit-function)
+ (when org-index--short-help-displayed
+ (quit-windows-on org-index--short-help-buffer-name)))
+ command))
+
+
+(defun org-index--minibuffer-setup-function ()
+ "Prepare minibuffer for `org-index--read-command'."
+ (setq org-index--minibuffer-saved-key (local-key-binding (kbd "?")))
+ (local-set-key (kbd "?") 'org-index--display-short-help)
+ (if org-index--display-short-help (org-index--display-short-help)))
+
+
+(defun org-index--minibuffer-exit-function ()
+ "Restore minibuffer after `org-index--read-command'."
+ (local-set-key (kbd "?") org-index--minibuffer-saved-key)
+ (setq org-index--minibuffer-saved-key nil))
+
+
+(defun org-index--display-short-help ()
+ "Helper function to show help in minibuffer."
+ (interactive)
+
+ (with-temp-buffer-window
+ org-index--short-help-buffer-name nil nil
+ (setq org-index--short-help-displayed t)
+ (princ "Short help; all subcommands of `org-index', shortcuts in []\n")
+ (princ (org-index--get-short-help-text)))
+ (with-current-buffer org-index--short-help-buffer-name
+ (let ((inhibit-read-only t)
+ height-before height-after win)
+ (setq win (get-buffer-window))
+ (setq height-before (window-height win))
+ (shrink-window-if-larger-than-buffer win)
+ (setq height-after (window-height win))
+ (goto-char (point-min))
+ (end-of-line)
+ (insert
+ (if (> height-before height-after)
+ "."
+ (concat ", "
+ (substitute-command-keys "\\[scroll-other-window]")
+ " to scroll:")))
+ (goto-char (point-min)))))
+
+
+(defun org-index--get-short-help-text ()
+ "Extract text for short help message from long help."
+ (or org-index--short-help-text
+ (with-temp-buffer
+ (insert (documentation 'org-index))
+ (goto-char (point-min))
+ (search-forward (concat " " (symbol-name (first org-index--commands)) ": "))
+ (forward-line 0)
+ (kill-region (point-min) (point))
+ (search-forward (concat " " (symbol-name (car (last org-index--commands))) ": "))
+ (forward-line 1)
+ (kill-region (point) (point-max))
+ (keep-lines "^ [-a-z]+:" (point-min) (point-max))
+ (align-regexp (point-min) (point-max) "\\(\\s-*\\):")
+ (goto-char (point-min))
+ (while (re-search-forward "\\. *$" nil t)
+ (replace-match "" nil nil))
+ (goto-char (point-min))
+ (re-search-forward "short-help")
+ (end-of-line)
+ (insert " (this text)")
+ (goto-char (point-min))
+ (unless (= (line-number-at-pos (point-max)) (1+ (length org-index--commands)))
+ (error "Internal error, unable to properly extract one-line descriptions of subcommands"))
+ (setq org-index--short-help-text (buffer-string)))))
+
+
+(defun org-index--get-shortcut-chars ()
+ "Collect shortcut chars from short help message."
+ (or org-index--shortcut-chars
+ (with-temp-buffer
+ (insert (org-index--get-short-help-text))
+ (goto-char (point-min))
+ (while (< (point) (point-max))
+ (when (looking-at "^ \\([-a-z]+\\) +: +\\[\\([a-z?]\\)\\] ")
+ (setq org-index--shortcut-chars
+ (cons (cons (match-string 2) (intern (match-string 1)))
+ org-index--shortcut-chars)))
+ (forward-line 1))
+ (unless (> (length org-index--shortcut-chars) 0)
+ (error "Internal error, did not find shortcut chars"))
+ org-index--shortcut-chars)))
+
+
+(defun org-index--do-edit ()
+ "Perform command edit."
+ (let ((maxlen 0) cols-vals buffer-keymap field-keymap keywords-pos val)
+
+ (setq org-index--context-node nil)
+ (setq org-index--context-occur nil)
+
+ ;; change to index, if whithin occur
+ (if org-index--within-occur
+ (let ((pos (get-text-property (point) 'org-index-lbp)))
+ (org-index--occur-test-stale pos)
+ (setq org-index--context-occur (cons (point) (org-index--line-in-canonical-form)))
+ (set-buffer org-index--buffer)
+ (goto-char pos))
+
+ ;; change to index, if still not within
+ (if (not org-index--within-index-node)
+ (let ((id (org-id-get)))
+ (setq org-index--context-node (cons (current-buffer) (point)))
+ (set-buffer org-index--buffer)
+ (unless (and id (org-index--go 'id id))
+ (setq org-index--context-node nil)
+ (error "This node is not in index")))))
+
+ ;; retrieve current content of index line
+ (dolist (col (mapcar 'car (reverse org-index--columns)))
+ (if (> (length (symbol-name col)) maxlen)
+ (setq maxlen (length (symbol-name col))))
+ (setq val (org-index--get-or-set-field col))
+ (if (and val (eq col 'yank)) (setq val (replace-regexp-in-string (regexp-quote "\\vert") "|" val nil 'literal)))
+ (setq cols-vals (cons (cons col val)
+ cols-vals)))
+
+ ;; we need two different keymaps
+ (setq buffer-keymap (make-sparse-keymap))
+ (set-keymap-parent buffer-keymap widget-keymap)
+ (define-key buffer-keymap (kbd "C-c C-c") 'org-index--edit-c-c-c-c)
+ (define-key buffer-keymap (kbd "C-c C-k") 'org-index--edit-c-c-c-k)
+
+ (setq field-keymap (make-sparse-keymap))
+ (set-keymap-parent field-keymap widget-field-keymap)
+ (define-key field-keymap (kbd "C-c C-c") 'org-index--edit-c-c-c-c)
+ (define-key field-keymap (kbd "C-c C-k") 'org-index--edit-c-c-c-k)
+
+ ;; prepare buffer
+ (setq org-index--context-index (cons (point) (org-index--line-in-canonical-form)))
+ (if (get-buffer org-index--edit-buffer-name) (kill-buffer org-index--edit-buffer-name))
+ (switch-to-buffer (get-buffer-create org-index--edit-buffer-name))
+
+ ;; create and fill widgets
+ (setq org-index--edit-widgets nil)
+ (widget-insert "Edit this line from index; type C-c C-c when done, C-c C-k to abort.\n\n")
+ (dolist (col-val cols-vals)
+ (if (eq (car col-val) 'keywords) (setq keywords-pos (point)))
+ (setq org-index--edit-widgets (cons
+ (cons (car col-val)
+ (widget-create 'editable-field
+ :format (format (format "%%%ds: %%%%v" maxlen) (symbol-name (car col-val)))
+ :keymap field-keymap
+ (or (cdr col-val) "")))
+ org-index--edit-widgets)))
+
+ (widget-setup)
+ (goto-char keywords-pos)
+ (beginning-of-line)
+ (forward-char (+ maxlen 2))
+ (use-local-map buffer-keymap)
+ "Editing a single line from index"))
+
+
+(defun org-index--edit-c-c-c-c ()
+ "Function to invoked on C-c C-c in Edit buffer."
+ (interactive)
+
+ (let ((obuf (get-buffer org-index--occur-buffer-name))
+ val line)
+
+ ;; Time might have passed
+ (org-index--refresh-parse-table)
+
+ (with-current-buffer org-index--buffer
+
+ ;; check, if buffer has become stale
+ (save-excursion
+ (goto-char (car org-index--context-index))
+ (unless (string= (cdr org-index--context-index)
+ (org-index--line-in-canonical-form))
+ (switch-to-buffer org-index--edit-buffer-name)
+ (error "Index table has changed: Cannot find line, that this buffer is editing")))
+
+ (pop-to-buffer-same-window org-index--buffer)
+ (goto-char (car org-index--context-index))
+
+ ;; write back line to index
+ (dolist (col-widget org-index--edit-widgets)
+ (setq val (widget-value (cdr col-widget)))
+ (if (eq (car col-widget) 'yank) (setq val (replace-regexp-in-string "|" (regexp-quote "\\vert") val)))
+ (org-index--get-or-set-field (car col-widget) val))
+
+ (setq line (org-index--align-and-fontify-current-line))
+ (beginning-of-line))
+
+ ;; write line to occur if appropriate
+ (if org-index--context-occur
+ (if obuf
+ (if (string= (cdr org-index--context-index)
+ (cdr org-index--context-occur))
+ (progn
+ (pop-to-buffer-same-window obuf)
+ (goto-char (car org-index--context-occur))
+ (beginning-of-line)
+ (let ((inhibit-read-only t))
+ (delete-region (line-beginning-position) (line-end-position))
+ (insert line)
+ (put-text-property (line-beginning-position) (line-end-position)
+ 'org-index-lbp (cdr org-index--context-index))))
+ (error "Occur buffer and index buffer do not match any longer"))
+ (message "Occur buffer has gone, cannot switch back."))
+ (setq org-index--context-occur nil))
+
+ ;; return to node, if invoked from there
+ (when org-index--context-node
+ (pop-to-buffer-same-window (car org-index--context-node))
+ (goto-char (cdr org-index--context-node)))
+
+ ;; clean up
+ (kill-buffer org-index--edit-buffer-name)
+ (setq org-index--context-index nil)
+ (setq org-index--edit-widgets nil)
+ (beginning-of-line)
+ (message "Index line has been edited.")))
+
+
+(defun org-index--edit-c-c-c-k ()
+ "Function invoked on C-c C-k in Edit buffer."
+ (interactive)
+ (kill-buffer org-index--edit-buffer-name)
+ (setq org-index--context-index nil)
+ (setq org-index--edit-widgets nil)
+ (beginning-of-line)
+ (message "Edit aborted."))
+
+
+(defun org-index--do-new-line (&rest keys-values)
+ "Do the work for `org-index-new-line'.
+Optional argument KEYS-VALUES specifies content of new line."
+
+ (org-index--retrieve-context)
+ (with-current-buffer org-index--buffer
+ (goto-char org-index--point)
+
+ ;; check arguments early; they might come from userland
+ (let ((kvs keys-values)
+ k v)
+ (while kvs
+ (setq k (car kvs))
+ (setq v (cadr kvs))
+ (if (or (not (symbolp k))
+ (and (symbolp v) (not (eq v t)) (not (eq v nil))))
+ (error "Arguments must be alternation of key and value"))
+ (unless (org-index--column-num k)
+ (error "Unknown column or column not defined in table: '%s'" (symbol-name k)))
+ (setq kvs (cddr kvs))))
+
+ (let (yank)
+ ;; create new line
+ (org-index--create-new-line)
+
+ ;; fill columns
+ (let ((kvs keys-values)
+ k v)
+ (while kvs
+ (setq k (car kvs))
+ (setq v (cadr kvs))
+ (org-table-goto-column (org-index--column-num k))
+ (insert (org-trim (or v "")))
+ (setq kvs (cddr kvs))))
+
+ ;; align and fontify line
+ (org-index--promote-current-line)
+ (org-index--align-and-fontify-current-line)
+
+ ;; remember fingerprint to be able to return
+ (setq org-index--last-fingerprint (org-index--get-or-set-field 'fingerprint))
+
+ ;; get column to yank
+ (setq yank (org-index--get-or-set-field org-index-yank-after-add))
+
+ yank)))
+
+
+(defun org-index-get-line (column value)
+ "Retrieve an existing line within the index table by ref or id.
+Return its contents as a property list.
+
+The function `plist-get' may be used to retrieve specific elements
+from the result.
+
+Example:
+
+ (plist-get (org-index-get-line 'ref \"R12\") 'count)
+
+retrieves the value of the count-column for reference number 12.
+
+Argument COLUMN is a symbol, either ref or id,
+argument VALUE specifies the value to search for."
+ ;; check arguments
+ (unless (memq column '(ref id))
+ (error "Argument column can only be 'ref' or 'id'"))
+
+ (unless value
+ (error "Need a value to search for"))
+
+ (org-index--verify-id)
+ (org-index--parse-table)
+
+ (org-index--get-line column value))
+
+
+(defun org-index--get-line (column value)
+ "Find a line by ID, return its contents.
+Argument COLUMN and VALUE specify line to get."
+ (let (content)
+ (org-index--on
+ column value
+ (mapc (lambda (x)
+ (if (and (numberp (cdr x))
+ (> (cdr x) 0))
+ (setq content (cons (car x) (cons (or (org-index--get-or-set-field (car x)) "") content)))))
+ (reverse org-index--columns)))
+ content))
+
+
+(defun org-index--ref-from-id (id)
+ "Get reference from line ID."
+ (org-index--on 'id id (org-index--get-or-set-field 'ref)))
+
+
+(defun org-index--id-from-ref (ref)
+ "Get id from line REF."
+ (org-index--on 'ref ref (org-index--get-or-set-field 'id)))
+
+
+(defun org-index--get-fingerprint ()
+ "Get fingerprint of current line."
+ (replace-regexp-in-string
+ "\\s " ""
+ (mapconcat (lambda (x) (org-index--get-or-set-field x)) '(id ref yank keywords created) "")))
+
+
+(defun org-index--read-search-for-index ()
+ "Special input routine for command index."
+
+ ;; Accept single char commands or switch to reading a sequence of digits
+ (let (char prompt search-ref search-id search-fingerprint)
+
+ ;; start with short prompt but give more help on next iteration
+ (setq prompt "Please specify, where to go in index (0-9,.,space,backspace,return or ? for short help) - ")
+
+ ;; read one character
+ (while (not (memq char (append (number-sequence ?0 ?9) (list ?\d ?\b ?\r ?\j ?\s ?.))))
+ (setq char (read-char prompt))
+ (setq prompt "Go to specific position in index table. Digits specify a reference number, <space> goes to top of index, <backspace> or <delete> to last line created and <return> or `.' to index line of current node. Please choose - "))
+
+ (if (memq char (number-sequence ?0 ?9))
+ ;; read rest of digits
+ (setq search-ref (read-from-minibuffer "Search reference number: " (char-to-string char))))
+ ;; decode single chars
+ (if (memq char '(?\r ?\n ?.)) (setq search-id (org-id-get)))
+ (if (memq char '(?\d ?\b)) (setq search-fingerprint org-index--last-fingerprint))
+
+ (list search-ref search-id search-fingerprint)))
+
+
+(defun org-index--verify-id ()
+ "Check, that we have a valid id."
+
+ ;; Check id
+ (unless org-index-id
+ (let ((answer (org-completing-read "Cannot find an index (org-index-id is not set). You may:\n - read-help : to learn more about org-index\n - create-index : invoke an assistant to create an initial index\nPlease choose: " (list "read-help" "create-index") nil t nil nil "read-help")))
+ (if (string= answer "create-index")
+ (org-index--create-missing-index "Variable org-index-id is not set, so probably no index table has been created yet.")
+ (describe-function 'org-index)
+ (throw 'new-index nil))))
+
+ ;; Find node
+ (let (marker)
+ (setq marker (org-id-find org-index-id 'marker))
+ (unless marker (org-index--create-missing-index "Cannot find the node with id \"%s\" (as specified by variable org-index-id)." org-index-id))
+ ; Try again with new node
+ (setq marker (org-id-find org-index-id 'marker))
+ (unless marker (error "Could not create node"))
+ (setq org-index--buffer (marker-buffer marker)
+ org-index--point (marker-position marker))
+ (move-marker marker nil)))
+
+
+(defun org-index--retrieve-context ()
+ "Collect context information before starting with command."
+
+ ;; Get the content of the active region or the word under cursor
+ (setq org-index--active-region
+ (if (and transient-mark-mode mark-active)
+ (buffer-substring (region-beginning) (region-end))
+ nil))
+ (setq org-index--below-cursor (thing-at-point 'symbol))
+
+ ;; get category of current node
+ (setq org-index--category-before
+ (save-excursion ; workaround: org-get-category does not give category when at end of buffer
+ (beginning-of-line)
+ (org-get-category (point) t)))
+
+ ;; Find out, if we are within index table or occur buffer
+ (setq org-index--within-index-node (string= (org-id-get) org-index-id))
+ (setq org-index--within-occur (string= (buffer-name) org-index--occur-buffer-name)))
+
+
+(defun org-index--parse-table ()
+ "Parse content of index table."
+
+ (let (ref-field
+ id-field
+ initial-point
+ end-of-headings
+ start-of-headings)
+
+ (with-current-buffer org-index--buffer
+
+ (setq org-index--maxrefnum 0)
+ (setq initial-point (point))
+
+ (org-index--go-below-hline)
+
+ ;; align and fontify table once for this emacs session
+ (unless org-index--aligned
+ (org-table-align) ; needs to happen before fontification to be effective ?
+ (let ((is-modified (buffer-modified-p))
+ (below (point)))
+ (while (org-at-table-p)
+ (forward-line))
+ (font-lock-fontify-region below (point))
+ (org-index--go-below-hline)
+ (setq org-index--aligned t)
+ (set-buffer-modified-p is-modified)))
+
+ (org-index--go-below-hline)
+ (beginning-of-line)
+
+ ;; get headings to display during occur
+ (setq end-of-headings (point))
+ (while (org-at-table-p) (forward-line -1))
+ (forward-line)
+ (setq start-of-headings (point))
+ (setq org-index--headings-visible (substring-no-properties (org-index--copy-visible start-of-headings end-of-headings)))
+ (setq org-index--headings (buffer-substring start-of-headings end-of-headings))
+
+ ;; count columns
+ (org-table-goto-column 100)
+ (setq org-index--numcols (- (org-table-current-column) 1))
+
+ ;; go to top of table
+ (while (org-at-table-p)
+ (forward-line -1))
+ (forward-line)
+
+ ;; parse line of headings
+ (org-index--parse-headings)
+
+ ;; parse list of flags
+ (goto-char org-index--point)
+
+ ;; Retrieve any decorations around the number within the first nonempty ref-field
+ (goto-char org-index--below-hline)
+ (while (and (org-at-table-p)
+ (not (setq ref-field (org-index--get-or-set-field 'ref))))
+ (forward-line))
+
+ ;; Some Checking
+ (unless ref-field
+ (org-index--report-index-error "Reference column is empty"))
+
+ (unless (string-match "^\\([^0-9]*\\)\\([0-9]+\\)\\([^0-9]*\\)$" ref-field)
+ (org-index--report-index-error
+ "First reference in index table ('%s') does not contain a number" ref-field))
+
+ ;; These are the decorations used within the first ref of index
+ (setq org-index--head (match-string 1 ref-field))
+ (setq org-index--tail (match-string 3 ref-field))
+ (setq org-index--ref-regex (concat (regexp-quote org-index--head)
+ "\\([0-9]+\\)"
+ (regexp-quote org-index--tail)))
+ (setq org-index--ref-format (concat org-index--head "%d" org-index--tail))
+
+ ;; check if the table still seems to be sorted mixed
+ (goto-char org-index--below-hline)
+ (when (eq org-index-sort-by 'mixed)
+ (org-index--go-below-hline)
+ (if (string< (org-index--get-or-set-field 'last-accessed)
+ (org-index--get-mixed-time))
+ (org-index--do-sort-index org-index-sort-by)))
+
+ ;; Go through table to find maximum number and do some checking
+ (let ((refnum 0))
+
+ (while (org-at-table-p)
+
+ (setq ref-field (org-index--get-or-set-field 'ref))
+ (setq id-field (org-index--get-or-set-field 'id))
+
+ (if ref-field
+ (if (string-match org-index--ref-regex ref-field)
+ ;; grab number
+ (setq refnum (string-to-number (match-string 1 ref-field)))
+ (kill-whole-line)
+ (message "Removing line from index-table whose ref does not contain a number")))
+
+ ;; check, if higher ref
+ (if (> refnum org-index--maxrefnum) (setq org-index--maxrefnum refnum))
+
+ (forward-line 1)))
+
+ (setq org-index--nextref (format "%s%d%s" org-index--head (1+ org-index--maxrefnum) org-index--tail))
+ ;; go back to initial position
+ (goto-char initial-point))))
+
+
+(defun org-index--refresh-parse-table ()
+ "Fast refresh of selected results of parsing index table."
+
+ (setq org-index--point (marker-position (org-id-find org-index-id 'marker)))
+ (with-current-buffer org-index--buffer
+ (save-excursion
+ (org-index--go-below-hline))))
+
+
+(defun org-index--do-maintain ()
+ "Choose among and perform some tasks to maintain index."
+ (let ((check-what) (max-mini-window-height 1.0) message-text)
+ (setq check-what (intern (org-completing-read "These checks and fixes are available:\n - statistics : compute statistics about index table\n - check : check ids by visiting their nodes\n - duplicates : check index for duplicate rows (ref or id)\n - clean : remove obsolete property org-index-id\n - update : update content of index lines, with an id \nPlease choose: " (list "statistics" "check" "duplicates" "clean" "update") nil t nil nil "statistics")))
+ (message nil)
+
+ (cond
+ ((eq check-what 'check)
+ (setq message-text (or (org-index--check-ids)
+ "No problems found")))
+
+ ((eq check-what 'statistics)
+ (setq message-text (org-index--do-statistics)))
+
+ ((eq check-what 'duplicates)
+ (setq message-text (org-index--find-duplicates)))
+
+ ((eq check-what 'clean)
+ (let ((lines 0))
+ (org-map-entries
+ (lambda ()
+ (when (org-entry-get (point) "org-index-ref")
+ (cl-incf lines)
+ (org-entry-delete (point) "org-index-ref")))
+ nil 'agenda)
+ (setq message-text (format "Removed property 'org-index-ref' from %d lines" lines))))
+
+ ((eq check-what 'update)
+ (if (y-or-n-p "Updating your index will overwrite certain columns with content from the associated heading and category. If unsure, you may try this for a single, already existing line of your index by invoking `add'. Are you SURE to proceed for ALL INDEX LINES ? ")
+ (setq message-text (org-index--update-all-lines))
+ (setq message-text "Canceled."))))
+ message-text))
+
+
+(defun org-index--get-mixed-time ()
+ "Get timestamp for sorting order mixed."
+ (format-time-string
+ (org-time-stamp-format t t)
+ (apply 'encode-time (append '(0 0 0) (nthcdr 3 (decode-time))))))
+
+
+(defun org-index--do-sort-index (sort)
+ "Sort index table according to SORT."
+
+ (let ((is-modified (buffer-modified-p))
+ top
+ bottom
+ mixed-time)
+
+ (unless buffer-read-only
+
+ (message "Sorting index table for %s..." (symbol-name sort))
+ (undo-boundary)
+
+ (let ((message-log-max nil)) ; we have just issued a message, dont need those of sort-subr
+
+ ;; if needed for mixed sort
+ (if (eq sort 'mixed)
+ (setq mixed-time (org-index--get-mixed-time)))
+
+ ;; get boundaries of table
+ (org-index--go-below-hline)
+ (forward-line 0)
+ (setq top (point))
+ (while (org-at-table-p) (forward-line))
+
+ ;; kill all empty rows at bottom
+ (while (progn
+ (forward-line -1)
+ (org-table-goto-column 1)
+ (and
+ (not (org-index--get-or-set-field 'ref))
+ (not (org-index--get-or-set-field 'id))
+ (not (org-index--get-or-set-field 'yank))))
+ (org-table-kill-row))
+ (forward-line 1)
+ (setq bottom (point))
+
+ ;; sort lines
+ (save-restriction
+ (narrow-to-region top bottom)
+ (goto-char top)
+ (sort-subr t
+ 'forward-line
+ 'end-of-line
+ (lambda ()
+ (org-index--get-sort-key sort t mixed-time))
+ nil
+ 'string<)
+ (goto-char (point-min))
+
+ ;; restore modification state
+ (set-buffer-modified-p is-modified)))
+
+ (setq org-index--last-sort sort))))
+
+
+(defun org-index--do-sort-lines (what)
+ "Sort lines in WHAT according to contained reference."
+ (save-restriction
+ (cond
+ ((eq what 'region)
+ (if (region-active-p)
+ (narrow-to-region (region-beginning) (region-end))
+ (error "No active region, cannot sort")))
+ ((eq what 'buffer)
+ (unless (y-or-n-p "Sort whole current buffer ? ")
+ (error "Canceled"))
+ (narrow-to-region (point-min) (point-max))))
+
+ (goto-char (point-min))
+ (sort-subr nil 'forward-line 'end-of-line
+ (lambda ()
+ (if (looking-at (concat ".*"
+ (org-index--make-guarded-search org-index--ref-regex 'dont-quote)))
+ (string-to-number (match-string 1))
+ 0)))))
+
+
+(defun org-index--go-below-hline ()
+ "Move below hline in index-table."
+
+ (let ((errstring (format "index table within node %s" org-index-id)))
+
+ (goto-char org-index--point)
+
+ ;; go to heading of node
+ (while (not (org-at-heading-p)) (forward-line -1))
+ (forward-line 1)
+
+ ;; go to first table, but make sure we do not get into another node
+ (while (and (not (org-at-table-p))
+ (not (org-at-heading-p))
+ (not (eobp)))
+ (forward-line))
+
+ ;; check, if there really is a table
+ (unless (org-at-table-p)
+ (org-index--create-missing-index "Cannot find %s." errstring))
+
+ ;; go just after hline
+ (while (and (not (org-at-table-hline-p))
+ (org-at-table-p))
+ (forward-line))
+ (forward-line)
+
+ ;; and check
+ (unless (org-at-table-p)
+ (org-index--report-index-error "Cannot find a hline within %s" errstring))
+
+ (org-table-goto-column 1)
+ (setq org-index--below-hline (point))))
+
+
+(defun org-index--parse-headings ()
+ "Parse headings of index table."
+
+ (let (field ;; field content
+ field-symbol) ;; and as a symbol
+
+ (setq org-index--columns nil)
+
+ ;; For each column
+ (dotimes (col org-index--numcols)
+
+ (setq field (substring-no-properties (downcase (org-trim (org-table-get-field (+ col 1))))))
+
+ (if (string= field "")
+ (error "Heading of column cannot be empty"))
+ (if (and (not (string= (substring field 0 1) "."))
+ (not (member (intern field) org-index--valid-headings)))
+ (error "Column name '%s' is not a valid heading (custom headings may start with a dot, e.g. '.foo')" field))
+
+ (setq field-symbol (intern field))
+
+ ;; check if heading has already appeared
+ (if (assoc field-symbol org-index--columns)
+ (org-index--report-index-error
+ "'%s' appears two times as column heading" (downcase field))
+ ;; add it to list at front, reverse later
+ (setq org-index--columns (cons (cons field-symbol (+ col 1)) org-index--columns)))))
+
+ (setq org-index--columns (reverse org-index--columns))
+
+ ;; check if all necessary headings have appeared
+ (mapc (lambda (head)
+ (unless (cdr (assoc head org-index--columns))
+ (org-index--report-index-error "No column has heading '%s'" head)))
+ org-index--valid-headings))
+
+
+(defun org-index--create-missing-index (&rest reasons)
+ "Create a new empty index table with detailed explanation. Argument REASONS explains why."
+
+ (org-index--ask-before-create-index "Cannot find index table: "
+ "new permanent" "."
+ reasons)
+ (org-index--create-index))
+
+
+(defun org-index--report-index-error (&rest reasons)
+ "Report an error (explained by REASONS) with the existing index and offer to create a valid one to compare with."
+
+ (when org-index--buffer
+ (pop-to-buffer-same-window org-index--buffer)
+ (goto-char org-index--below-hline)
+ (org-reveal t))
+ (org-index--ask-before-create-index "The existing index contains this error: "
+ "temporary" ", to compare with."
+ reasons)
+ (org-index--create-index t t))
+
+
+(defun org-index--ask-before-create-index (explanation type for-what reasons)
+ ; checkdoc-params: (explanation type for-what reasons)
+ "Ask the user before creating an index or throw error. Arguments specify bits of issued message."
+ (let (reason prompt)
+
+ (setq reason (apply 'format reasons))
+
+ (setq prompt (concat explanation reason "\n"
+ "However, this assistant can help you to create a "
+ type " index with detailed comments" for-what "\n\n"
+ "Do you want to proceed ?"))
+
+ (unless (let ((max-mini-window-height 1.0))
+ (y-or-n-p prompt))
+ (error (concat explanation reason)))))
+
+
+(defun org-index--create-index (&optional temporary compare)
+ "Create a new empty index table with detailed explanation.
+specify flag TEMPORARY for th new table temporary, maybe COMPARE it with existing index."
+ (let (buffer
+ title
+ firstref
+ id)
+
+ (if temporary
+ (let ((file-name (concat temporary-file-directory "org-index--example-index.org"))
+ (buffer-name "*org-index-example-index*"))
+ (setq buffer (get-buffer-create buffer-name))
+ (with-current-buffer buffer
+ ;; but it needs a file for its index to be found
+ (unless (string= (buffer-file-name) file-name)
+ (set-visited-file-name file-name))
+ (rename-buffer buffer-name) ; name is change by line above
+
+ (erase-buffer)
+ (org-mode)))
+
+ (setq buffer (get-buffer (org-completing-read "Please choose the buffer, where the new node for the index table should be created; the new node will be inserted at its end.\n\nBuffer: " (mapcar 'buffer-name (org-buffer-list))))))
+
+ (setq title (read-from-minibuffer "Please enter the title of the index node (leave empty for default 'index'): "))
+ (if (string= title "") (setq title "index"))
+
+ (while (progn
+ (setq firstref (read-from-minibuffer "Please enter your first reference-number. This is an integer number preceeded by some and optionally followed by some non-numeric chars; e.g. 'R1', '-1-' or '#1#' (and your initial number does not need to be '1'). The format of your reference-numbers only needs to make sense for yourself, so that you can spot it easily in your texts or write it on a piece of paper; it should however not already appear frequently within your existing notes, to avoid too many false hits when searching.\n\nPlease choose (leave empty for default 'R1'): "))
+ (if (string= firstref "") (setq firstref "R1"))
+ (let (desc)
+ (when (string-match "[[:blank:]]" firstref)
+ (setq desc "Contains whitespace"))
+ (when (string-match "[[:cntrl:]]" firstref)
+ (setq desc "Contains control characters"))
+ (unless (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)
+ ;; firstref not okay, report details
+ (setq desc
+ (cond ((string= firstref "") "is empty")
+ ((not (string-match "^[^0-9]+" firstref)) "starts with a digit")
+ ((not (string-match "^[^0-9]+[0-9]+" firstref)) "does not contain a number")
+ ((not (string-match "^[^0-9]+[0-9]+[^0-9]*$" firstref)) "contains more than one sequence of digits")
+
+ )))
+ (if desc
+ (progn
+ (read-from-minibuffer (format "Your input '%s' does not meet the requirements because it %s.\nPlease hit RET and try again: " firstref desc))
+ t)
+ nil))))
+
+ (with-current-buffer buffer
+ (goto-char (point-max))
+ (insert (format "* %s %s\n" firstref title))
+ (if temporary
+ (insert "
+ Below you find your temporary index table, which WILL NOT LAST LONGER
+ THAN YOUR CURRENT EMACS SESSION; please use it only for evaluation.
+")
+ (insert "
+ Below you find your initial index table, which will grow over time.
+"))
+ (insert " You may start using it by adding some lines. Just
+ move to another heading within org, invoke `org-index' and
+ choose the command 'add'. After adding a few nodes, try the
+ command 'occur' to search among them.
+
+ To gain further insight you may invoke the subcommand 'help', or
+ (same content) read the help of `org-index'.
+
+ Within the index table below, the sequence of columns does not
+ matter. You may reorder them in any way you like. You may also
+ add your own columns, which should start with a dot
+ (e.g. '.my-column').
+
+ Invoke `org-customize' to tweak the behaviour of org-index
+ (see the group org-index).
+
+ This node needs not be a top level node; its name is completely
+ at your choice; it is found through its ID only.
+")
+ (unless temporary
+ (insert "
+ Remark: These lines of explanation can be removed at any time.
+"))
+
+ (setq id (org-id-get-create))
+ (insert (format "
+
+ | ref | category | keywords | tags | count | level | last-accessed | created | id | yank |
+ | | | | | | | | | <4> | <4> |
+ |-----+----------+----------+------+-------+-------+---------------+---------+-----+------|
+ | %s | | %s | | | | | %s | %s | |
+
+"
+ firstref
+ title
+ (with-temp-buffer (org-insert-time-stamp nil nil t))
+ id))
+
+ ;; make sure, that node can be found
+ (org-id-add-location id (buffer-file-name))
+ (setq buffer-save-without-query t)
+ (basic-save-buffer)
+
+ (while (not (org-at-table-p)) (forward-line -1))
+ (unless buffer-read-only (org-table-align))
+ (while (not (org-at-heading-p)) (forward-line -1))
+
+ ;; read back some info about new index
+ (let ((org-index-id id))
+ (org-index--verify-id))
+
+ ;; remember at least for this session
+ (setq org-index-id id)
+
+ ;; present results to user
+ (if temporary
+ (progn
+ ;; Present existing and temporary index together
+ (when compare
+ (pop-to-buffer-same-window org-index--buffer)
+ (goto-char org-index--point)
+ (org-index--unfold-buffer)
+ (delete-other-windows)
+ (select-window (split-window-vertically)))
+ ;; show new index
+ (pop-to-buffer-same-window buffer)
+ (org-id-goto id)
+ (org-index--unfold-buffer)
+ (if compare
+ (progn
+ (message "Please compare your existing index (upper window) and a temporary new one (lower window) to fix your index")
+ (throw 'new-index nil))
+ (message "This is your new temporary index, use command add to populate, occur to search.")))
+ (progn
+ ;; Only show the new index
+ (pop-to-buffer-same-window buffer)
+ (delete-other-windows)
+ (org-id-goto id)
+ (org-index--unfold-buffer)
+ (if (y-or-n-p "This is your new index table. It is already set for this Emacs session, so you may try it out. Do you want to save its id to make it available for future Emacs sessions too ? ")
+ (progn
+ (customize-save-variable 'org-index-id id)
+ (message "Saved org-index-id '%s' to %s." id (or custom-file
+ user-init-file))
+ (throw 'new-index nil))
+ (let (sq)
+ (setq sq (format "(setq org-index-id \"%s\")" id))
+ (kill-new sq)
+ (message "Did not make the id of this new index permanent; you may want to put\n\n %s\n\ninto your own initialization; it is copied already, just yank it." sq)
+ (throw 'new-index nil))))))))
+
+
+(defun org-index--unfold-buffer ()
+ "Helper function to unfold buffer."
+ (org-show-context)
+ (org-show-subtree)
+ (recenter 1)
+ (save-excursion
+ (org-back-to-heading)
+ (forward-line) ;; on property drawer
+ (org-cycle)))
+
+
+(defun org-index--update-line (&optional ref-or-id-or-pos)
+ "Update columns count and last-accessed in line REF-OR-ID-OR-POS."
+
+ (let (initial)
+
+ (with-current-buffer org-index--buffer
+ (unless buffer-read-only
+
+ ;; search reference or id, if given (or assume, that we are already positioned right)
+ (when ref-or-id-or-pos
+ (setq initial (point))
+ (goto-char org-index--below-hline)
+ (while (and (org-at-table-p)
+ (not (if (integerp ref-or-id-or-pos)
+ (and (>= ref-or-id-or-pos (line-beginning-position))
+ (< ref-or-id-or-pos (line-end-position)))
+ (or (string= ref-or-id-or-pos (org-index--get-or-set-field 'ref))
+ (string= ref-or-id-or-pos (org-index--get-or-set-field 'id))))))
+ (forward-line)))
+
+ (if (not (org-at-table-p))
+ (error "Did not find reference or id '%s'" ref-or-id-or-pos)
+ (org-index--update-current-line))
+
+ (if initial (goto-char initial))))))
+
+
+(defun org-index--update-current-line ()
+ "Update current lines columns count and last-accessed."
+ (let (newcount (count-field (org-index--get-or-set-field 'count)))
+
+ ;; update count field only if number or empty
+ (when (or (not count-field)
+ (string-match "^[0-9]+$" count-field))
+ (setq newcount (+ 1 (string-to-number (or count-field "0"))))
+ (org-index--get-or-set-field 'count
+ (number-to-string newcount)))
+
+ ;; update timestamp
+ (org-table-goto-column (org-index--column-num 'last-accessed))
+ (org-table-blank-field)
+ (org-insert-time-stamp nil t t)
+
+ ;; move line according to new content
+ (org-index--promote-current-line)
+ (org-index--align-and-fontify-current-line)))
+
+
+(defun org-index--align-and-fontify-current-line (&optional num)
+ "Make current line (or NUM lines) blend well among others."
+ (let (lines)
+ ;; get current content
+ (unless num (setq num 1))
+ (setq lines (delete-and-extract-region (line-beginning-position) (line-end-position num)))
+ ;; create minimum table with fixed-width columns to align and fontify new line
+ (insert (with-temp-buffer
+ (org-set-font-lock-defaults)
+ (insert org-index--headings-visible)
+ ;; fill columns, so that aligning cannot shrink them
+ (goto-char (point-min))
+ (search-forward "|")
+ (while (search-forward " " (line-end-position) t)
+ (replace-match "." nil t))
+ (goto-char (point-min))
+ (while (search-forward ".|." (line-end-position) t)
+ (replace-match " | " nil t))
+ (goto-char (point-min))
+ (while (search-forward "|." (line-end-position) t)
+ (replace-match "| " nil t))
+ (goto-char (point-max))
+ (insert lines)
+ (forward-line 0)
+ (let ((start (point)))
+ (while (re-search-forward "^\s +|-" nil t)
+ (replace-match "| -"))
+ (goto-char start))
+ (org-mode)
+ (org-table-align)
+ (font-lock-fontify-region (point-min) (point-max))
+ (goto-char (point-max))
+ (if (eq -1 (skip-chars-backward "\n"))
+ (delete-char 1))
+ (forward-line (- 1 num))
+ (buffer-substring (line-beginning-position) (line-end-position num))))
+ lines))
+
+
+(defun org-index--promote-current-line ()
+ "Move current line up in table according to changed sort fields."
+ (let (begin end key
+ (to-skip 0))
+
+ (forward-line 0) ; stay at beginning of line
+
+ (setq key (org-index--get-sort-key))
+ (setq begin (point))
+ (setq end (line-beginning-position 2))
+
+ (forward-line -1)
+ (while (and (org-at-table-p)
+ (not (org-at-table-hline-p))
+ (string< (org-index--get-sort-key) key))
+
+ (cl-incf to-skip)
+ (forward-line -1))
+ (forward-line 1)
+
+ ;; insert line at new position
+ (when (> to-skip 0)
+ (insert (delete-and-extract-region begin end))
+ (forward-line -1))))
+
+
+(defun org-index--get-sort-key (&optional sort with-ref mixed-time)
+ "Get value for sorting from column SORT, optional WITH-REF; if mixes use MIXED-TIME."
+ (let (ref
+ ref-field
+ key)
+
+ (unless sort (setq sort org-index--last-sort)) ; use default value
+
+ (when (or with-ref
+ (eq sort 'ref))
+ ;; get reference with leading zeroes, so it can be
+ ;; sorted as text
+ (setq ref-field (org-index--get-or-set-field 'ref))
+ (if ref-field
+ (progn
+ (string-match org-index--ref-regex ref-field)
+ (setq ref (format
+ "%06d"
+ (string-to-number
+ (match-string 1 ref-field)))))
+ (setq ref "000000")))
+
+ (setq key
+ (cond
+ ((eq sort 'count)
+ (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))
+ ((eq sort 'mixed)
+ (let ((last-accessed (org-index--get-or-set-field 'last-accessed)))
+ (unless mixed-time (setq mixed-time (org-index--get-mixed-time)))
+ (concat
+ (if (string< mixed-time last-accessed) last-accessed mixed-time)
+ (format "%08d" (string-to-number (or (org-index--get-or-set-field 'count) ""))))))
+ ((eq sort 'ref)
+ ref)
+ ((memq sort '(id last-accessed created))
+ (org-index--get-or-set-field sort))
+ (t (error "This is a bug: unmatched case '%s'" sort))))
+
+ (if with-ref (setq key (concat key ref)))
+
+ key))
+
+
+(defun org-index--get-or-set-field (key &optional value)
+ "Retrieve field KEY from index table or set it to VALUE."
+ (let (field)
+ (save-excursion
+ (if (eq key 'fingerprint)
+ (progn
+ (if value (error "Internal error, pseudo-column fingerprint cannot be set"))
+ (setq field (org-index--get-fingerprint)))
+ (setq field (org-trim (org-table-get-field (cdr (assoc key org-index--columns)) value))))
+ (if (string= field "") (setq field nil))
+
+ (org-no-properties field))))
+
+
+(defun org-index--column-num (key)
+ "Return number of column KEY."
+ (if (numberp key)
+ key
+ (cdr (assoc key org-index--columns))))
+
+
+(defun org-index--make-guarded-search (ref &optional dont-quote)
+ "Make robust search string from REF; DONT-QUOTE it, if requested."
+ (concat "\\_<" (if dont-quote ref (regexp-quote ref)) "\\_>"))
+
+
+(defun org-index--find-duplicates ()
+ "Find duplicate references or ids in index table."
+ (let (ref-duplicates id-duplicates)
+
+ (setq ref-duplicates (org-index--find-duplicates-helper 'ref))
+ (setq id-duplicates (org-index--find-duplicates-helper 'id))
+ (goto-char org-index--below-hline)
+ (if (or ref-duplicates id-duplicates)
+ (progn
+ ;; show results
+ (pop-to-buffer-same-window
+ (get-buffer-create "*org-index-duplicates*"))
+ (when ref-duplicates
+ (insert "These references appear more than once:\n")
+ (mapc (lambda (x) (insert " " x "\n")) ref-duplicates)
+ (insert "\n\n"))
+ (when id-duplicates
+ (insert "These ids appear more than once:\n")
+ (mapc (lambda (x) (insert " " x "\n")) id-duplicates))
+
+ "Some references or ids are duplicates")
+ "No duplicate references or ids found")))
+
+
+(defun org-index--find-duplicates-helper (column)
+ "Helper for `org-index--find-duplicates': Go through table and count given COLUMN."
+ (let (counts duplicates field found)
+
+ ;; go through table
+ (goto-char org-index--below-hline)
+ (while (org-at-table-p)
+
+ ;; get column
+ (setq field (org-index--get-or-set-field column))
+
+ ;; and increment
+ (setq found (assoc field counts))
+ (if found
+ (cl-incf (cdr found))
+ (setq counts (cons (cons field 1) counts)))
+
+ (forward-line))
+
+ (mapc (lambda (x) (if (and (> (cdr x) 1)
+ (car x))
+ (setq duplicates (cons (car x) duplicates)))) counts)
+
+ duplicates))
+
+
+(defun org-index--do-statistics ()
+ "Compute statistics about index table."
+ (let ((total-lines 0) (total-refs 0)
+ ref ref-field min max message)
+
+ ;; go through table
+ (goto-char org-index--below-hline)
+ (while (org-at-table-p)
+
+ ;; get ref
+ (setq ref-field (org-index--get-or-set-field 'ref))
+
+ (when ref-field
+ (string-match org-index--ref-regex ref-field)
+ (setq ref (string-to-number (match-string 1 ref-field)))
+
+ ;; record min and max
+ (if (or (not min) (< ref min)) (setq min ref))
+ (if (or (not max) (> ref max)) (setq max ref))
+
+ (setq total-refs (1+ total-refs)))
+
+ ;; count
+ (setq total-lines (1+ total-lines))
+
+ (forward-line))
+
+ (setq message (format "%d Lines in index table. First reference is %s, last %s; %d of them are used (%d percent)"
+ total-lines
+ (format org-index--ref-format min)
+ (format org-index--ref-format max)
+ total-refs
+ (truncate (* 100 (/ (float total-refs) (1+ (- max min)))))))
+
+ (goto-char org-index--below-hline)
+ message))
+
+
+(defun org-index--do-add-or-update (&optional create-ref tag-with-ref)
+ "For current node or current line in index, add or update in index table.
+CREATE-REF and TAG-WITH-REF if given."
+
+ (let* (id id-from-index ref args yank ret)
+
+ (org-index--save-positions)
+ (unless (or org-index--within-index-node
+ org-index--within-occur)
+ (org-back-to-heading))
+
+ ;; try to do the same things from within index and from outside
+ (if org-index--within-index-node
+
+ (progn
+ (unless (org-at-table-p)
+ (error "Within index node but not on table"))
+
+ (setq id (org-index--get-or-set-field 'id))
+ (setq ref (org-index--get-or-set-field 'ref))
+ (setq args (org-index--collect-values-for-add-update-remote id))
+ (org-index--write-fields args)
+ (setq yank (org-index--get-or-set-field org-index-yank-after-add))
+
+ (setq ret
+ (if ref
+ (cons (format "Updated index line %s" ref) yank)
+ (cons "Updated index line" nil))))
+
+ (setq id (org-id-get-create))
+ (org-index--refresh-parse-table)
+ (setq id-from-index (org-index--on 'id id id))
+ (setq ref (org-index--on 'id id (org-index--get-or-set-field 'ref)))
+
+ (if tag-with-ref
+ (org-toggle-tag (format "%s%d%s" org-index--head tag-with-ref org-index--tail) 'on))
+ (setq args (org-index--collect-values-for-add-update id))
+
+ (when (and create-ref
+ (not ref))
+ (setq ref org-index--nextref)
+ (setq args (plist-put args 'ref ref)))
+
+
+ (if id-from-index
+ ;; already have an id in index, find it and update fields
+ (progn
+
+ (org-index--on
+ 'id id
+ (org-index--write-fields args)
+ (setq yank (org-index--get-or-set-field org-index-yank-after-add)))
+
+ (setq ret
+ (if ref
+ (cons (format "Updated index line %s" ref) yank)
+ (cons "Updated index line" nil))))
+
+ ;; no id here, create new line in index
+ (if ref (setq ref (plist-put args 'ref org-index--nextref)))
+ (setq yank (apply 'org-index--do-new-line args))
+
+ (setq ret
+ (if ref
+ (cons
+ (format "Added new index line %s" ref)
+ (concat yank " "))
+ (cons
+ "Added new index line"
+ nil)))))
+
+ (org-index--restore-positions)
+
+ ret))
+
+
+(defun org-index--check-ids ()
+ "Check, that ids really point to a node."
+
+ (let ((lines 0)
+ id ids marker)
+
+ (goto-char org-index--below-hline)
+
+ (catch 'problem
+ (while (org-at-table-p)
+
+ (when (setq id (org-index--get-or-set-field 'id))
+
+ ;; check for double ids
+ (when (member id ids)
+ (org-table-goto-column (org-index--column-num 'id))
+ (throw 'problem "This id appears twice in index; please use command 'maintain' to check for duplicate ids"))
+ (cl-incf lines)
+ (setq ids (cons id ids))
+
+ ;; check, if id is valid
+ (setq marker (org-id-find id t))
+ (unless marker
+ (org-table-goto-column (org-index--column-num 'id))
+ (throw 'problem "This id cannot be found")))
+
+ (forward-line))
+
+ (goto-char org-index--below-hline)
+ nil)))
+
+
+(defun org-index--update-all-lines ()
+ "Update all lines of index at once."
+
+ (let ((lines 0)
+ id ref kvs)
+
+ ;; check for double ids
+ (or
+ (org-index--check-ids)
+
+ (progn
+ (goto-char org-index--below-hline)
+ (while (org-at-table-p)
+
+ ;; update single line
+ (when (setq id (org-index--get-or-set-field 'id))
+ (setq ref (org-index--get-or-set-field 'ref))
+ (setq kvs (org-index--collect-values-for-add-update-remote id))
+ (org-index--write-fields kvs)
+ (cl-incf lines))
+ (forward-line))
+
+ (goto-char org-index--below-hline)
+ (org-table-align)
+ (format "Updated %d lines" lines)))))
+
+
+(defun org-index--collect-values-for-add-update (id &optional silent category)
+ "Collect values for adding or updating line specified by ID, do not ask if SILENT, use CATEGORY, if given."
+
+ (let ((args (list 'id id))
+ content)
+
+ (dolist (col (mapcar 'car org-index--columns))
+
+ (setq content "")
+
+ (cond
+ ((eq col 'keywords)
+ (if org-index-copy-heading-to-keywords
+ (setq content (nth 4 (org-heading-components))))
+
+ ;; Shift ref and timestamp ?
+ (if org-index-strip-ref-and-date-from-heading
+ (dotimes (i 2)
+ (if (or (string-match (concat "^\\s-*" org-index--ref-regex) content)
+ (string-match (concat "^\\s-*" org-ts-regexp-both) content))
+ (setq content (substring content (match-end 0)))))))
+
+ ((eq col 'category)
+ (setq content (or category org-index--category-before)))
+
+ ((eq col 'level)
+ (setq content (number-to-string (org-outline-level))))
+
+ ((eq col 'tags)
+ (setq content (org-get-tags-string))))
+
+ (unless (string= content "")
+ (setq args (plist-put args col content))))
+
+ (if (not silent)
+ (let ((args-edited (org-index--collect-values-from-user org-index-edit-on-add args)))
+ (setq args (append args-edited args))))
+
+ args))
+
+
+(defun org-index--collect-values-for-add-update-remote (id)
+ "Wrap `org-index--collect-values-for-add-update' by prior moving to remote node identified by ID."
+
+ (let (marker point args)
+
+ (setq marker (org-id-find id t))
+ ;; enter buffer and collect information
+ (with-current-buffer (marker-buffer marker)
+ (setq point (point))
+ (goto-char marker)
+ (setq args (org-index--collect-values-for-add-update id t (org-get-category (point) t)))
+ (goto-char point))
+
+ args))
+
+
+(defun org-index--collect-values-from-user (cols &optional defaults)
+ "Collect values for adding a new yank-line.
+Argument COLS gives list of columns to edit.
+Optional argument DEFAULTS gives default values."
+
+ (let (content args)
+
+ (dolist (col cols)
+
+ (setq content "")
+
+ (setq content (read-from-minibuffer
+ (format "Enter text for column '%s': " (symbol-name col))
+ (plist-get col defaults)))
+
+ (unless (string= content "")
+ (setq args (plist-put args col content))))
+ args))
+
+
+(defun org-index--write-fields (kvs)
+ "Update current line with values from KVS (keys-values)."
+ (while kvs
+ (org-index--get-or-set-field (car kvs) (org-trim (cadr kvs)))
+ (setq kvs (cddr kvs))))
+
+
+(defun org-index--do-kill ()
+ "Perform command kill from within occur, index or node."
+
+ (let (id ref chars-deleted-index text-deleted-from pos-in-index)
+
+ (org-index--save-positions)
+ (unless (or org-index--within-index-node
+ org-index--within-occur)
+ (org-back-to-heading))
+
+ ;; Collect information: What should be deleted ?
+ (if (or org-index--within-occur
+ org-index--within-index-node)
+
+ (progn
+ (if org-index--within-index-node
+ ;; In index
+ (setq pos-in-index (point))
+ ;; In occur
+ (setq pos-in-index (get-text-property (point) 'org-index-lbp))
+ (org-index--occur-test-stale pos-in-index)
+ (set-buffer org-index--buffer)
+ (goto-char pos-in-index))
+ ;; In Index (maybe moved there)
+ (setq id (org-index--get-or-set-field 'id))
+ (setq ref (org-index--get-or-set-field 'ref)))
+
+ ;; At a headline
+ (setq id (org-entry-get (point) "ID"))
+ (setq ref (org-index--ref-from-id id))
+ (setq pos-in-index (org-index--on 'id id (point)))
+ (unless pos-in-index (error "This node is not in index")))
+
+ ;; Remark: Current buffer is not certain here, but we have all the information to delete
+
+ ;; Delete from node
+ (when id
+ (let ((m (org-id-find id 'marker)))
+ (set-buffer (marker-buffer m))
+ (goto-char m)
+ (move-marker m nil)
+ (unless (string= (org-id-get) id)
+ (error "Could not find node with id %s" id)))
+
+ (org-index--delete-any-ref-from-tags)
+ (if ref (org-index--delete-ref-from-heading ref))
+ (setq text-deleted-from (cons "node" text-deleted-from)))
+
+ ;; Delete from index
+ (set-buffer org-index--buffer)
+ (unless pos-in-index "Internal error, pos-in-index should be defined here")
+ (goto-char pos-in-index)
+ (setq chars-deleted-index (length (delete-and-extract-region (line-beginning-position) (line-beginning-position 2))))
+ (setq text-deleted-from (cons "index" text-deleted-from))
+
+ ;; Delete from occur only if we started there, accept that it will be stale otherwise
+ (if org-index--within-occur
+ (let ((inhibit-read-only t))
+ (set-buffer org-index--occur-buffer-name)
+ (delete-region (line-beginning-position) (line-beginning-position 2))
+ ;; correct positions
+ (while (org-at-table-p)
+ (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp
+ (- (get-text-property (point) 'org-index-lbp) chars-deleted-index))
+ (forward-line))
+ (setq text-deleted-from (cons "occur" text-deleted-from))))
+
+ (org-index--restore-positions)
+ (concat "Deleted from: " (mapconcat 'identity (sort text-deleted-from 'string<) ","))))
+
+
+(defun org-index--save-positions ()
+ "Save current buffer and positions in index- and current buffer; not in occur-buffer."
+
+ (let (cur-buf cur-mrk idx-pnt idx-mrk)
+ (setq cur-buf (current-buffer))
+ (setq cur-mrk (point-marker))
+ (set-buffer org-index--buffer)
+ (if (string= (org-id-get) org-index-id)
+ (setq idx-pnt (point))
+ (setq idx-mrk (point-marker)))
+ (set-buffer cur-buf)
+ (setq org-index--saved-positions (list cur-buf cur-mrk idx-pnt idx-mrk))))
+
+
+(defun org-index--restore-positions ()
+ "Restore positions as saved by `org-index--save-positions'."
+
+ (cl-multiple-value-bind
+ (cur-buf cur-mrk idx-pnt idx-mrk buf)
+ org-index--saved-positions
+ (setq buf (current-buffer))
+ (set-buffer cur-buf)
+ (goto-char cur-mrk)
+ (set-buffer org-index--buffer)
+ (goto-char (or idx-pnt idx-mrk))
+ (set-buffer buf))
+ (setq org-index--saved-positions nil))
+
+
+(defun org-index--delete-ref-from-heading (ref)
+ "Delete given REF from current heading."
+ (save-excursion
+ (end-of-line)
+ (let ((end (point)))
+ (beginning-of-line)
+ (when (search-forward ref end t)
+ (delete-char (- (length ref)))
+ (just-one-space)))))
+
+
+(defun org-index--delete-any-ref-from-tags ()
+ "Delete any reference from list of tags."
+ (let (new-tags)
+ (mapc (lambda (tag)
+ (unless (string-match org-index--ref-regex tag)
+ (setq new-tags (cons tag new-tags) )))
+ (org-get-tags))
+ (org-set-tags-to new-tags)))
+
+
+(defun org-index--go (&optional column value)
+ "Position cursor on index line where COLUMN equals VALUE.
+Return t or nil, leave point on line or at top of table, needs to be in buffer initially."
+ (let (found)
+
+ (unless (eq (current-buffer) org-index--buffer)
+ (error "This is a bug: Not in index buffer"))
+
+ ;; loop over lines
+ (goto-char org-index--below-hline)
+ (if column
+ (progn
+ (forward-line -1)
+ (while (and (not found)
+ (forward-line)
+ (org-at-table-p))
+ (setq found (string= value (org-index--get-or-set-field column)))))
+ (setq found t))
+
+ ;; return value
+ (if found
+ t
+ (goto-char org-index--below-hline)
+ nil)))
+
+
+(defun org-index--find-id (id &optional other)
+ "Perform command head: Find node with REF or ID and present it.
+If OTHER in separate window."
+
+ (let (message marker)
+
+ (setq marker (org-id-find id t))
+
+ (if marker
+ (progn
+ (org-index--update-line id)
+ (if other
+ (progn
+ (pop-to-buffer (marker-buffer marker)))
+ (pop-to-buffer-same-window (marker-buffer marker)))
+
+ (goto-char marker)
+ (org-reveal t)
+ (org-show-entry)
+ (recenter)
+ (unless (string= (org-id-get) id)
+ (setq message (format "Could not go to node with id %s (narrowed ?)" id)))
+ (setq message "Found headline"))
+ (setq message (format "Did not find node with %s" id)))
+ message))
+
+
+(defun org-index--do-occur ()
+ "Perform command occur."
+ (let ((word "") ; last word to search for growing and shrinking on keystrokes
+ (prompt "Search for: ")
+ (these-commands " NOTE: If you invoke the org-index subcommands edit or kill from within the occur buffer, the index is updated accordingly.")
+ (lines-wanted (window-body-height))
+ (lines-found 0) ; number of lines found
+ words ; list words that should match
+ occur-buffer
+ begin ; position of first line
+ narrow ; start of narrowed buffer
+ help-text ; cons with help text short and long
+ search-text ; description of text to search for
+ done ; true, if loop is done
+ in-c-backspace ; true, while processing C-backspace
+ help-overlay ; Overlay with help text
+ last-point ; Last position before end of search
+ initial-frame ; Frame when starting occur
+ key ; input from user in various forms
+ key-sequence
+ key-sequence-raw)
+
+
+ ;; make and show buffer
+ (if (get-buffer org-index--occur-buffer-name)
+ (kill-buffer org-index--occur-buffer-name))
+ (setq occur-buffer (make-indirect-buffer org-index--buffer org-index--occur-buffer-name))
+ (pop-to-buffer-same-window occur-buffer)
+ (setq initial-frame (selected-frame))
+
+ ;; avoid modifying direct buffer
+ (setq buffer-read-only t)
+ (toggle-truncate-lines 1)
+ (setq font-lock-keywords-case-fold-search t)
+ (setq case-fold-search t)
+
+ ;; reset stack and overlays
+ (setq org-index--occur-stack nil)
+ (setq org-index--occur-tail-overlay nil)
+
+ ;; narrow to table rows and one line before
+ (goto-char org-index--below-hline)
+ (forward-line 0)
+ (setq begin (point))
+ (forward-line -1)
+ (setq narrow (point))
+ (while (org-at-table-p)
+ (forward-line))
+ (narrow-to-region narrow (point))
+ (goto-char (point-min))
+ (forward-line)
+
+ ;; initialize help text
+ (setq help-text (cons
+ (concat
+ (propertize "Incremental occur" 'face 'org-todo)
+ (propertize "; ? toggles help and headlines.\n" 'face 'org-agenda-dimmed-todo-face))
+ (concat
+ (propertize
+ (org-index--wrap
+ (concat
+ "Normal keys add to search word; <space> or <comma> start additional word; <backspace> erases last char, <C-backspace> last word; <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index; all other keys end search." these-commands "\n"))
+ 'face 'org-agenda-dimmed-todo-face)
+ org-index--headings)))
+
+ ;; insert overlays for help text and to cover unsearched lines
+ (setq help-overlay (make-overlay (point-min) begin))
+ (overlay-put help-overlay 'display (car help-text))
+ (setq org-index--occur-tail-overlay (make-overlay (point-max) (point-max)))
+ (overlay-put org-index--occur-tail-overlay 'invisible t)
+
+ (while (not done)
+
+ (if in-c-backspace
+ (setq key "<backspace>")
+ (setq search-text (mapconcat 'identity (reverse (cons word words)) ","))
+ (message "foo")
+
+ ;; read key, if selected frame has not changed
+ (if (eq initial-frame (selected-frame))
+ (progn
+ (setq key-sequence
+ (let ((echo-keystrokes 0)
+ (full-prompt (format "%s%s%s"
+ prompt
+ search-text
+ (if (string= search-text "") "" " "))))
+ (read-key-sequence full-prompt nil nil t t)))
+ (setq key (key-description key-sequence))
+ (setq key-sequence-raw (this-single-command-raw-keys)))
+ (setq done t)
+ (setq key-sequence nil)
+ (setq key nil)
+ (setq key-sequence-raw nil)))
+
+
+ (cond
+
+
+ ((string= key "<C-backspace>")
+ (setq in-c-backspace t))
+
+
+ ((member key (list "<backspace>" "DEL")) ; erase last char
+
+ (if (= (length word) 0)
+
+ ;; nothing more to delete from current word; try next
+ (progn
+ (setq word (car words))
+ (setq words (cdr words))
+ (setq in-c-backspace nil))
+
+ ;; unhighlight longer match
+ (unhighlight-regexp (regexp-quote word))
+
+ ;; some chars are left; shorten word
+ (setq word (substring word 0 -1))
+ (when (= (length word) 0) ; when nothing left, use next word from list
+ (setq word (car words))
+ (setq words (cdr words))
+ (setq in-c-backspace nil))
+
+ ;; free top list of overlays and remove list
+ (setq lines-found (or (org-index--unhide) lines-wanted))
+ (move-overlay org-index--occur-tail-overlay
+ (if org-index--occur-stack (cdr (assq :end-of-visible (car org-index--occur-stack)))
+ (point-max))
+ (point-max))
+
+
+ ;; highlight shorter word
+ (unless (= (length word) 0)
+ (highlight-regexp (regexp-quote word) 'isearch))
+
+ ;; make sure, point is still visible
+ (goto-char begin)))
+
+
+ ((member key (list "SPC" ",")) ; space or comma: enter an additional search word
+
+ ;; push current word and clear, no need to change display
+ (unless (string= word "")
+ (setq words (cons word words))
+ (setq word "")))
+
+
+ ((string= key "?") ; question mark: toggle display of headlines and help
+ (setq help-text (cons (cdr help-text) (car help-text)))
+ (overlay-put help-overlay 'display (car help-text)))
+
+ ((and (= (length key) 1)
+ (aref printable-chars (elt key 0))) ; any printable char: add to current search word
+
+ ;; unhighlight short word
+ (unless (= (length word) 0)
+ (unhighlight-regexp (regexp-quote word)))
+
+ ;; add to word
+ (setq word (concat word key))
+
+ ;; make overlays to hide lines, that do not match longer word any more
+ (goto-char begin)
+ (setq lines-found (org-index--hide-with-overlays (cons word words) lines-wanted))
+ (move-overlay org-index--occur-tail-overlay
+ (if org-index--occur-stack (cdr (assq :end-of-visible (car org-index--occur-stack)))
+ (point-max))
+ (point-max))
+
+ (goto-char begin)
+
+ ;; highlight longer word
+ (highlight-regexp (regexp-quote word) 'isearch)
+
+ ;; make sure, point is on a visible line
+ (line-move -1 t)
+ (line-move 1 t))
+
+ ;; anything else terminates loop
+ (t (setq done t))))
+
+ ;; put back input event, that caused the loop to end
+ (unless (string= key "C-g")
+ (setq unread-command-events (listify-key-sequence key-sequence-raw))
+ (message key))
+
+ ;; postprocessing
+ (setq last-point (point))
+
+ ;; For performance reasons do not show matching lines for rest of table. So no code here.
+
+ ;; make permanent copy
+ ;; copy visible lines
+ (let ((lines-collected 0)
+ keymap line all-lines all-lines-lbp header-lines lbp)
+
+ (setq cursor-type t)
+ (goto-char begin)
+
+ ;; collect all visible lines
+ (while (and (not (eobp))
+ (< lines-collected lines-wanted))
+ ;; skip over invisible lines
+ (while (and (invisible-p (point))
+ (not (eobp)))
+ (goto-char (1+ (overlay-end (car (overlays-at (point)))))))
+ (setq lbp (line-beginning-position))
+ (setq line (buffer-substring-no-properties lbp (line-end-position)))
+ (unless (string= line "")
+ (cl-incf lines-collected)
+ (setq all-lines (cons (concat line
+ "\n")
+ all-lines))
+ (setq all-lines-lbp (cons lbp all-lines-lbp)))
+ (forward-line 1))
+
+ (kill-buffer org-index--occur-buffer-name) ; cannot keep this buffer; might become stale soon
+
+ ;; create new buffer
+ (setq occur-buffer (get-buffer-create org-index--occur-buffer-name))
+ (pop-to-buffer-same-window occur-buffer)
+ (insert org-index--headings)
+ (setq header-lines (line-number-at-pos))
+
+ ;; insert into new buffer
+ (save-excursion
+ (apply 'insert (reverse all-lines))
+ (if (= lines-collected lines-wanted)
+ (insert "\n(more lines omitted)\n")))
+ (setq org-index--occur-lines-collected lines-collected)
+
+ (org-mode)
+ (setq truncate-lines t)
+ (if all-lines (org-index--align-and-fontify-current-line (length all-lines)))
+ (font-lock-ensure)
+ (font-lock-flush)
+ (when all-lines-lbp
+ (while (not (org-at-table-p))
+ (forward-line -1))
+ (while all-lines-lbp
+ (put-text-property (line-beginning-position) (line-end-position) 'org-index-lbp (car all-lines-lbp))
+ (setq all-lines-lbp (cdr all-lines-lbp))
+ (forward-line -1)))
+
+ ;; prepare help text
+ (goto-char (point-min))
+ (forward-line (1- header-lines))
+ (setq org-index--occur-help-overlay (make-overlay (point-min) (point)))
+ (setq org-index--occur-help-text
+ (cons
+ (org-index--wrap
+ (propertize "Search is done; ? toggles help and headlines.\n" 'face 'org-agenda-dimmed-todo-face))
+ (concat
+ (org-index--wrap
+ (propertize
+ (format
+ (concat "Search is done."
+ (if (< lines-collected lines-wanted)
+ " Showing all %d matches for "
+ " Showing one window of matches for ")
+ "\"" search-text
+ "\". <return> jumps to heading, <tab> jumps to heading in other window, <S-return> jumps to matching line in index, <space> increments count.\n" these-commands "\n")
+ (length all-lines))
+ 'face 'org-agenda-dimmed-todo-face))
+ org-index--headings)))
+
+ (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))
+
+ ;; highlight words
+ (setq case-fold-search t)
+ (setq font-lock-keywords-case-fold-search t)
+ (mapc (lambda (w) (unless (or (not w) (string= w "")) (highlight-regexp (regexp-quote w) 'isearch)))
+ (cons word words))
+
+ (setq buffer-read-only t)
+
+ ;; install keyboard-shortcuts
+ (setq keymap (make-sparse-keymap))
+ (set-keymap-parent keymap org-mode-map)
+
+ (mapc (lambda (x) (define-key keymap (kbd x)
+ (lambda () (interactive)
+ (message "%s" (org-index--occur-action)))))
+ (list "<return>" "RET"))
+
+ (define-key keymap (kbd "<tab>")
+ (lambda () (interactive)
+ (message (org-index--occur-action t))))
+
+ (define-key keymap (kbd "SPC")
+ (lambda () (interactive)
+ (org-index--refresh-parse-table)
+ ;; increment in index
+ (let ((ref (org-index--get-or-set-field 'ref))
+ count)
+ (org-index--on
+ 'ref ref
+ (setq count (+ 1 (string-to-number (org-index--get-or-set-field 'count))))
+ (org-index--get-or-set-field 'count (number-to-string count))
+ (org-index--promote-current-line)
+ (org-index--align-and-fontify-current-line))
+ ;; increment in this buffer
+ (let ((inhibit-read-only t))
+ (org-index--get-or-set-field 'count (number-to-string count)))
+ (message "Incremented count to %d" count))))
+
+ (define-key keymap (kbd "<S-return>")
+ (lambda () (interactive)
+ (let ((pos (get-text-property (point) 'org-index-lbp)))
+ (org-index--refresh-parse-table)
+ (org-index--occur-test-stale pos)
+ (pop-to-buffer org-index--buffer)
+ (goto-char pos)
+ (org-reveal t)
+ (org-index--update-current-line)
+ (beginning-of-line))))
+
+ (define-key keymap (kbd "?")
+ (lambda () (interactive)
+ (org-index--refresh-parse-table)
+ (setq-local org-index--occur-help-text (cons (cdr org-index--occur-help-text) (car org-index--occur-help-text)))
+ (overlay-put org-index--occur-help-overlay 'display (car org-index--occur-help-text))))
+
+ (use-local-map keymap))))
+
+
+(defun org-index--occur-test-stale (pos)
+ "Test, if current line in occur buffer has become stale at POS."
+ (let (here there)
+ (org-index--refresh-parse-table)
+ (setq here (org-index--line-in-canonical-form))
+ (with-current-buffer org-index--buffer
+ (goto-char pos)
+ (setq there (org-index--line-in-canonical-form)))
+ (unless (string= here there)
+ (error "Occur buffer has become stale"))))
+
+
+(defun org-index--line-in-canonical-form ()
+ "Return current line in its canonical form."
+ (org-trim (substring-no-properties (replace-regexp-in-string "\s +" " " (buffer-substring (line-beginning-position) (line-beginning-position 2))))))
+
+
+(defun org-index--wrap (text)
+ "Wrap TEXT at fill column."
+ (with-temp-buffer
+ (insert text)
+ (fill-region (point-min) (point-max) nil t)
+ (buffer-string)))
+
+
+(defun org-index--occur-action (&optional other)
+ "Helper for `org-index--occur', find heading with ref or id; if OTHER, in other window; or copy yank column."
+ (if (org-at-table-p)
+ (let ((id (org-index--get-or-set-field 'id))
+ (ref (org-index--get-or-set-field 'ref))
+ (yank (org-index--get-or-set-field 'yank)))
+ (if id
+ (org-index--find-id id other)
+ (if ref
+ (progn
+ (org-mark-ring-goto)
+ (format "Found reference %s (no node is associated)" ref))
+ (if yank
+ (progn
+ (org-index--update-line (get-text-property (point) 'org-index-lbp))
+ (setq yank (replace-regexp-in-string (regexp-quote "\\vert") "|" yank nil 'literal))
+ (kill-new yank)
+ (org-mark-ring-goto)
+ (format "Copied '%s' (no node is associated)" yank))
+ (error "Internal error, this line contains neither id, nor reference, nor text to yank")))))
+ (message "Not at table")))
+
+
+(defun org-index--hide-with-overlays (words lines-wanted)
+ "Hide text that is currently visible and does not match WORDS by creating overlays; leave LINES-WANTED lines visible."
+ (let ((lines-found 0)
+ (end-of-visible (point))
+ overlay overlays start matched)
+
+ ;; main loop
+ (while (and (not (eobp))
+ (< lines-found lines-wanted))
+
+ ;; skip invisible lines
+ (while (and (not (eobp))
+ (and
+ (invisible-p (point))
+ (< (point) (overlay-start org-index--occur-tail-overlay))))
+ (goto-char (overlay-end (car (overlays-at (point))))))
+
+ ;; find stretch of lines, that are currently visible but should be invisible now
+ (setq matched nil)
+ (setq start (point))
+ (while (and (not (eobp))
+ (not
+ (and
+ (invisible-p (point))
+ (< (point) (overlay-start org-index--occur-tail-overlay))))
+ (not (and (org-index--test-words words)
+ (setq matched t)))) ; for its side effect
+ (forward-line 1))
+
+ ;; create overlay to hide this stretch
+ (when (< start (point)) ; avoid creating an empty overlay
+ (setq overlay (make-overlay start (point)))
+ (overlay-put overlay 'invisible t)
+ (setq overlays (cons overlay overlays)))
+
+ ;; skip and count line, that matched
+ (when matched
+ (forward-line 1)
+ (setq end-of-visible (point))
+ (cl-incf lines-found)))
+
+ ;; put new list on top of stack
+ (setq org-index--occur-stack
+ (cons (list (cons :overlays overlays)
+ (cons :end-of-visible end-of-visible)
+ (cons :lines lines-found))
+ org-index--occur-stack))
+
+ lines-found))
+
+
+(defun org-index--unhide ()
+ "Unhide text that does has been hidden by `org-index--hide-with-overlays'."
+ (when org-index--occur-stack
+ ;; delete overlays and make visible again
+ (mapc (lambda (y)
+ (delete-overlay y))
+ (cdr (assq :overlays (car org-index--occur-stack))))
+ ;; remove from stack
+ (setq org-index--occur-stack (cdr org-index--occur-stack))
+ ;; return number of lines, that are now visible
+ (if org-index--occur-stack (cdr (assq :lines (car org-index--occur-stack))))))
+
+
+(defun org-index--test-words (words)
+ "Test current line for match against WORDS."
+ (let (line)
+ (setq line (downcase (buffer-substring (line-beginning-position) (line-beginning-position 2))))
+ (catch 'not-found
+ (dolist (w words)
+ (or (cl-search w line)
+ (throw 'not-found nil)))
+ t)))
+
+
+(defun org-index--create-new-line ()
+ "Do the common work for `org-index-new-line' and `org-index'."
+
+ ;; insert ref or id as last or first line, depending on sort-column
+ (goto-char org-index--below-hline)
+ (if (eq org-index-sort-by 'count)
+ (progn
+ (while (org-at-table-p)
+ (forward-line))
+ (forward-line -1)
+ (org-table-insert-row t))
+ (org-table-insert-row))
+
+ ;; insert some of the standard values
+ (org-table-goto-column (org-index--column-num 'created))
+ (org-insert-time-stamp nil nil t)
+ (org-table-goto-column (org-index--column-num 'count))
+ (insert "1"))
+
+
+(defun org-index--sort-silent ()
+ "Sort index for default column to remove any effects of temporary sorting."
+ (save-excursion
+ (org-index--verify-id)
+ (org-index--parse-table)
+ (org-index--on nil nil
+ (org-index--do-sort-index org-index-sort-by)
+ (org-table-align)
+ (remove-hook 'before-save-hook 'org-index--sort-silent))))
+
+
+(defun org-index--copy-visible (beg end)
+ "Copy the visible parts of the region between BEG and END without adding it to `kill-ring'; copy of `org-copy-visible'."
+ (let (snippets s)
+ (save-excursion
+ (save-restriction
+ (narrow-to-region beg end)
+ (setq s (goto-char (point-min)))
+ (while (not (= (point) (point-max)))
+ (goto-char (org-find-invisible))
+ (push (buffer-substring s (point)) snippets)
+ (setq s (goto-char (org-find-visible))))))
+ (apply 'concat (nreverse snippets))))
+
+
+(provide 'org-index)
+
+;; Local Variables:
+;; fill-column: 75
+;; comment-column: 50
+;; End:
+
+;;; org-index.el ends here
diff --git a/contrib/lisp/org-interactive-query.el b/contrib/lisp/org-interactive-query.el
new file mode 100644
index 0000000..147ddae
--- /dev/null
+++ b/contrib/lisp/org-interactive-query.el
@@ -0,0 +1,311 @@
+;;; org-interactive-query.el --- Interactive modification of agenda query
+;;
+;; Copyright 2007-2017 Free Software Foundation, Inc.
+;;
+;; Author: Christopher League <league at contrapunctus dot net>
+;; Version: 1.0
+;; Keywords: org, wp
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+
+;; This library implements interactive modification of a tags/todo query
+;; in the org-agenda. It adds 4 keys to the agenda
+;;
+;; / add a keyword as a positive selection criterion
+;; \ add a keyword as a newgative selection criterion
+;; = clear a keyword from the selection string
+;; ;
+
+(require 'org)
+
+(org-defkey org-agenda-mode-map "=" 'org-agenda-query-clear-cmd)
+(org-defkey org-agenda-mode-map "/" 'org-agenda-query-and-cmd)
+(org-defkey org-agenda-mode-map ";" 'org-agenda-query-or-cmd)
+(org-defkey org-agenda-mode-map "\\" 'org-agenda-query-not-cmd)
+
+;;; Agenda interactive query manipulation
+
+(defcustom org-agenda-query-selection-single-key t
+ "Non-nil means query manipulation exits after first change.
+When nil, you have to press RET to exit it.
+During query selection, you can toggle this flag with `C-c'.
+This variable can also have the value `expert'. In this case, the window
+displaying the tags menu is not even shown, until you press C-c again."
+ :group 'org-agenda
+ :type '(choice
+ (const :tag "No" nil)
+ (const :tag "Yes" t)
+ (const :tag "Expert" expert)))
+
+(defun org-agenda-query-selection (current op table &optional todo-table)
+ "Fast query manipulation with single keys.
+CURRENT is the current query string, OP is the initial
+operator (one of \"+|-=\"), TABLE is an alist of tags and
+corresponding keys, possibly with grouping information.
+TODO-TABLE is a similar table with TODO keywords, should these
+have keys assigned to them. If the keys are nil, a-z are
+automatically assigned. Returns the new query string, or nil to
+not change the current one."
+ (let* ((fulltable (append table todo-table))
+ (maxlen (apply 'max (mapcar
+ (lambda (x)
+ (if (stringp (car x)) (string-width (car x)) 0))
+ fulltable)))
+ (fwidth (+ maxlen 3 1 3))
+ (ncol (/ (- (window-width) 4) fwidth))
+ (expert (eq org-agenda-query-selection-single-key 'expert))
+ (exit-after-next org-agenda-query-selection-single-key)
+ (done-keywords org-done-keywords)
+ tbl char cnt e groups ingroup
+ tg c2 c c1 ntable rtn)
+ (save-window-excursion
+ (if expert
+ (set-buffer (get-buffer-create " *Org tags*"))
+ (delete-other-windows)
+ (split-window-vertically)
+ (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
+ (erase-buffer)
+ (setq-local org-done-keywords done-keywords)
+ (insert "Query: " current "\n")
+ (org-agenda-query-op-line op)
+ (insert "\n\n")
+ (org-fast-tag-show-exit exit-after-next)
+ (setq tbl fulltable char ?a cnt 0)
+ (while (setq e (pop tbl))
+ (cond
+ ((equal e '(:startgroup))
+ (push '() groups) (setq ingroup t)
+ (when (not (= cnt 0))
+ (setq cnt 0)
+ (insert "\n"))
+ (insert "{ "))
+ ((equal e '(:endgroup))
+ (setq ingroup nil cnt 0)
+ (insert "}\n"))
+ (t
+ (setq tg (car e) c2 nil)
+ (if (cdr e)
+ (setq c (cdr e))
+ ;; automatically assign a character.
+ (setq c1 (string-to-char
+ (downcase (substring
+ tg (if (= (string-to-char tg) ?@) 1 0)))))
+ (if (or (rassoc c1 ntable) (rassoc c1 table))
+ (while (or (rassoc char ntable) (rassoc char table))
+ (setq char (1+ char)))
+ (setq c2 c1))
+ (setq c (or c2 char)))
+ (if ingroup (push tg (car groups)))
+ (setq tg (org-add-props tg nil 'face
+ (cond
+ ((not (assoc tg table))
+ (org-get-todo-face tg))
+ (t nil))))
+ (if (and (= cnt 0) (not ingroup)) (insert " "))
+ (insert "[" c "] " tg (make-string
+ (- fwidth 4 (length tg)) ?\ ))
+ (push (cons tg c) ntable)
+ (when (= (setq cnt (1+ cnt)) ncol)
+ (insert "\n")
+ (if ingroup (insert " "))
+ (setq cnt 0)))))
+ (setq ntable (nreverse ntable))
+ (insert "\n")
+ (goto-char (point-min))
+ (if (and (not expert) (fboundp 'fit-window-to-buffer))
+ (fit-window-to-buffer))
+ (setq rtn
+ (catch 'exit
+ (while t
+ (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
+ (if groups " [!] no groups" " [!]groups")
+ (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
+ (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
+ (cond
+ ((= c ?\r) (throw 'exit t))
+ ((= c ?!)
+ (setq groups (not groups))
+ (goto-char (point-min))
+ (while (re-search-forward "[{}]" nil t) (replace-match " ")))
+ ((= c ?\C-c)
+ (if (not expert)
+ (org-fast-tag-show-exit
+ (setq exit-after-next (not exit-after-next)))
+ (setq expert nil)
+ (delete-other-windows)
+ (split-window-vertically)
+ (org-switch-to-buffer-other-window " *Org tags*")
+ (and (fboundp 'fit-window-to-buffer)
+ (fit-window-to-buffer))))
+ ((or (= c ?\C-g)
+ (and (= c ?q) (not (rassoc c ntable))))
+ (setq quit-flag t))
+ ((= c ?\ )
+ (setq current "")
+ (if exit-after-next (setq exit-after-next 'now)))
+ ((= c ?\[) ; clear left
+ (org-agenda-query-decompose current)
+ (setq current (concat "/" (match-string 2 current)))
+ (if exit-after-next (setq exit-after-next 'now)))
+ ((= c ?\]) ; clear right
+ (org-agenda-query-decompose current)
+ (setq current (match-string 1 current))
+ (if exit-after-next (setq exit-after-next 'now)))
+ ((= c ?\t)
+ (condition-case nil
+ (setq current (read-string "Query: " current))
+ (quit))
+ (if exit-after-next (setq exit-after-next 'now)))
+ ;; operators
+ ((or (= c ?/) (= c ?+)) (setq op "+"))
+ ((or (= c ?\;) (= c ?|)) (setq op "|"))
+ ((or (= c ?\\) (= c ?-)) (setq op "-"))
+ ((= c ?=) (setq op "="))
+ ;; todos
+ ((setq e (rassoc c todo-table) tg (car e))
+ (setq current (org-agenda-query-manip
+ current op groups 'todo tg))
+ (if exit-after-next (setq exit-after-next 'now)))
+ ;; tags
+ ((setq e (rassoc c ntable) tg (car e))
+ (setq current (org-agenda-query-manip
+ current op groups 'tag tg))
+ (if exit-after-next (setq exit-after-next 'now))))
+ (if (eq exit-after-next 'now) (throw 'exit t))
+ (goto-char (point-min))
+ (beginning-of-line 1)
+ (delete-region (point) (point-at-eol))
+ (insert "Query: " current)
+ (beginning-of-line 2)
+ (delete-region (point) (point-at-eol))
+ (org-agenda-query-op-line op)
+ (goto-char (point-min)))))
+ (if rtn current nil))))
+
+(defun org-agenda-query-op-line (op)
+ (insert "Operator: "
+ (org-agenda-query-op-entry (equal op "+") "/+" "and")
+ (org-agenda-query-op-entry (equal op "|") ";|" "or")
+ (org-agenda-query-op-entry (equal op "-") "\\-" "not")
+ (org-agenda-query-op-entry (equal op "=") "=" "clear")))
+
+(defun org-agenda-query-op-entry (matchp chars str)
+ (if matchp
+ (org-add-props (format "[%s %s] " chars (upcase str))
+ nil 'face 'org-todo)
+ (format "[%s]%s " chars str)))
+
+(defun org-agenda-query-decompose (current)
+ (string-match "\\([^/]*\\)/?\\(.*\\)" current))
+
+(defun org-agenda-query-clear (current prefix tag)
+ (if (string-match (concat prefix "\\b" (regexp-quote tag) "\\b") current)
+ (replace-match "" t t current)
+ current))
+
+(defun org-agenda-query-manip (current op groups kind tag)
+ "Apply an operator to a query string and a tag.
+CURRENT is the current query string, OP is the operator, GROUPS is a
+list of lists of tags that are mutually exclusive. KIND is 'tag for a
+regular tag, or 'todo for a TODO keyword, and TAG is the tag or
+keyword string."
+ ;; If this tag is already in query string, remove it.
+ (setq current (org-agenda-query-clear current "[-\\+&|]?" tag))
+ (if (equal op "=") current
+ ;; When using AND, also remove mutually exclusive tags.
+ (if (equal op "+")
+ (loop for g in groups do
+ (if (member tag g)
+ (mapc (lambda (x)
+ (setq current
+ (org-agenda-query-clear current "\\+" x)))
+ g))))
+ ;; Decompose current query into q1 (tags) and q2 (TODOs).
+ (org-agenda-query-decompose current)
+ (let* ((q1 (match-string 1 current))
+ (q2 (match-string 2 current)))
+ (cond
+ ((eq kind 'tag)
+ (concat q1 op tag "/" q2))
+ ;; It's a TODO; when using AND, drop all other TODOs.
+ ((equal op "+")
+ (concat q1 "/+" tag))
+ (t
+ (concat q1 "/" q2 op tag))))))
+
+(defun org-agenda-query-global-todo-keys (&optional files)
+ "Return alist of all TODO keywords and their fast keys, in all FILES."
+ (let (alist)
+ (unless (and files (car files))
+ (setq files (org-agenda-files)))
+ (save-excursion
+ (loop for f in files do
+ (set-buffer (find-file-noselect f))
+ (loop for k in org-todo-key-alist do
+ (setq alist (org-agenda-query-merge-todo-key
+ alist k)))))
+ alist))
+
+(defun org-agenda-query-merge-todo-key (alist entry)
+ (let (e)
+ (cond
+ ;; if this is not a keyword (:startgroup, etc), ignore it
+ ((not (stringp (car entry))))
+ ;; if keyword already exists, replace char if it's null
+ ((setq e (assoc (car entry) alist))
+ (when (null (cdr e)) (setcdr e (cdr entry))))
+ ;; if char already exists, prepend keyword but drop char
+ ((rassoc (cdr entry) alist)
+ (message "TRACE POSITION 2")
+ (setq alist (cons (cons (car entry) nil) alist)))
+ ;; else, prepend COPY of entry
+ (t
+ (setq alist (cons (cons (car entry) (cdr entry)) alist)))))
+ alist)
+
+(defun org-agenda-query-generic-cmd (op)
+ "Activate query manipulation with OP as initial operator."
+ (let ((q (org-agenda-query-selection org-agenda-query-string op
+ org-tag-alist
+ (org-agenda-query-global-todo-keys))))
+ (when q
+ (setq org-agenda-query-string q)
+ (org-agenda-redo))))
+
+(defun org-agenda-query-clear-cmd ()
+ "Activate query manipulation, to clear a tag from the string."
+ (interactive)
+ (org-agenda-query-generic-cmd "="))
+
+(defun org-agenda-query-and-cmd ()
+ "Activate query manipulation, initially using the AND (+) operator."
+ (interactive)
+ (org-agenda-query-generic-cmd "+"))
+
+(defun org-agenda-query-or-cmd ()
+ "Activate query manipulation, initially using the OR (|) operator."
+ (interactive)
+ (org-agenda-query-generic-cmd "|"))
+
+(defun org-agenda-query-not-cmd ()
+ "Activate query manipulation, initially using the NOT (-) operator."
+ (interactive)
+ (org-agenda-query-generic-cmd "-"))
+
+(provide 'org-interactive-query)
diff --git a/contrib/lisp/org-invoice.el b/contrib/lisp/org-invoice.el
new file mode 100644
index 0000000..4c83d2e
--- /dev/null
+++ b/contrib/lisp/org-invoice.el
@@ -0,0 +1,401 @@
+;;; org-invoice.el --- Help manage client invoices in OrgMode
+;;
+;; Copyright (C) 2008-2014 pmade inc. (Peter Jones pjones@pmade.com)
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; Permission is hereby granted, free of charge, to any person obtaining
+;; a copy of this software and associated documentation files (the
+;; "Software"), to deal in the Software without restriction, including
+;; without limitation the rights to use, copy, modify, merge, publish,
+;; distribute, sublicense, and/or sell copies of the Software, and to
+;; permit persons to whom the Software is furnished to do so, subject to
+;; the following conditions:
+;;
+;; The above copyright notice and this permission notice shall be
+;; included in all copies or substantial portions of the Software.
+;;
+;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+;;
+;;; Commentary:
+;;
+;; Building on top of the terrific OrgMode, org-invoice tries to
+;; provide functionality for managing invoices. Currently, it does
+;; this by implementing an OrgMode dynamic block where invoice
+;; information is aggregated so that it can be exported.
+;;
+;; It also provides a library of functions that can be used to collect
+;; this invoice information and use it in other ways, such as
+;; submitting it to on-line invoicing tools.
+;;
+;; I'm already working on an elisp package to submit this invoice data
+;; to the FreshBooks on-line accounting tool.
+;;
+;; Usage:
+;;
+;; In your ~/.emacs:
+;; (autoload 'org-invoice-report "org-invoice")
+;; (autoload 'org-dblock-write:invoice "org-invoice")
+;;
+;; See the documentation in the following functions:
+;;
+;; `org-invoice-report'
+;; `org-dblock-write:invoice'
+;;
+;; Latest version:
+;;
+;; git clone git://pmade.com/elisp
+(eval-when-compile
+ (require 'cl)
+ (require 'org))
+
+(defgroup org-invoice nil
+ "OrgMode Invoice Helper"
+ :tag "Org-Invoice" :group 'org)
+
+(defcustom org-invoice-long-date-format "%A, %B %d, %Y"
+ "The format string for long dates."
+ :type 'string :group 'org-invoice)
+
+(defcustom org-invoice-strip-ts t
+ "Remove org timestamps that appear in headings."
+ :type 'boolean :group 'org-invoice)
+
+(defcustom org-invoice-default-level 2
+ "The heading level at which a new invoice starts. This value
+is used if you don't specify a scope option to the invoice block,
+and when other invoice helpers are trying to find the heading
+that starts an invoice.
+
+The default is 2, assuming that you structure your invoices so
+that they fall under a single heading like below:
+
+* Invoices
+** This is invoice number 1...
+** This is invoice number 2...
+
+If you don't structure your invoices using those conventions,
+change this setting to the number that corresponds to the heading
+at which an invoice begins."
+ :type 'integer :group 'org-invoice)
+
+(defcustom org-invoice-start-hook nil
+ "Hook called when org-invoice is about to collect data from an
+invoice heading. When this hook is called, point will be on the
+heading where the invoice begins.
+
+When called, `org-invoice-current-invoice' will be set to the
+alist that represents the info for this invoice."
+ :type 'hook :group 'org-invoice)
+
+ (defcustom org-invoice-heading-hook nil
+ "Hook called when org-invoice is collecting data from a
+heading. You can use this hook to add additional information to
+the alist that represents the heading.
+
+When this hook is called, point will be on the current heading
+being processed, and `org-invoice-current-item' will contain the
+alist for the current heading.
+
+This hook is called repeatedly for each invoice item processed."
+ :type 'hook :group 'org-invoice)
+
+(defvar org-invoice-current-invoice nil
+ "Information about the current invoice.")
+
+(defvar org-invoice-current-item nil
+ "Information about the current invoice item.")
+
+(defvar org-invoice-table-params nil
+ "The table parameters currently being used.")
+
+(defvar org-invoice-total-time nil
+ "The total invoice time for the summary line.")
+
+(defvar org-invoice-total-price nil
+ "The total invoice price for the summary line.")
+
+(defconst org-invoice-version "1.0.0"
+ "The org-invoice version number.")
+
+(defun org-invoice-goto-tree (&optional tree)
+ "Move point to the heading that represents the head of the
+current invoice. The heading level will be taken from
+`org-invoice-default-level' unless tree is set to a string that
+looks like tree2, where the level is 2."
+ (let ((level org-invoice-default-level))
+ (save-match-data
+ (when (and tree (string-match "^tree\\([0-9]+\\)$" tree))
+ (setq level (string-to-number (match-string 1 tree)))))
+ (org-back-to-heading)
+ (while (and (> (org-reduced-level (org-outline-level)) level)
+ (org-up-heading-safe)))))
+
+(defun org-invoice-heading-info ()
+ "Return invoice information from the current heading."
+ (let ((title (org-no-properties (org-get-heading t)))
+ (date (org-entry-get nil "TIMESTAMP" 'selective))
+ (work (org-entry-get nil "WORK" nil))
+ (rate (or (org-entry-get nil "RATE" t) "0"))
+ (level (org-outline-level))
+ raw-date long-date)
+ (unless date (setq date (org-entry-get nil "TIMESTAMP_IA" 'selective)))
+ (unless date (setq date (org-entry-get nil "TIMESTAMP" t)))
+ (unless date (setq date (org-entry-get nil "TIMESTAMP_IA" t)))
+ (unless work (setq work (org-entry-get nil "CLOCKSUM" nil)))
+ (unless work (setq work "00:00"))
+ (when date
+ (setq raw-date (apply 'encode-time (org-parse-time-string date)))
+ (setq long-date (format-time-string org-invoice-long-date-format raw-date)))
+ (when (and org-invoice-strip-ts (string-match org-ts-regexp-both title))
+ (setq title (replace-match "" nil nil title)))
+ (when (string-match "^[ \t]+" title)
+ (setq title (replace-match "" nil nil title)))
+ (when (string-match "[ \t]+$" title)
+ (setq title (replace-match "" nil nil title)))
+ (setq work (org-hh:mm-string-to-minutes work))
+ (setq rate (string-to-number rate))
+ (setq org-invoice-current-item (list (cons 'title title)
+ (cons 'date date)
+ (cons 'raw-date raw-date)
+ (cons 'long-date long-date)
+ (cons 'work work)
+ (cons 'rate rate)
+ (cons 'level level)
+ (cons 'price (* rate (/ work 60.0)))))
+ (run-hook-with-args 'org-invoice-heading-hook)
+ org-invoice-current-item))
+
+(defun org-invoice-level-min-max (ls)
+ "Return a list where the car is the min level, and the cdr the max."
+ (let ((max 0) min level)
+ (dolist (info ls)
+ (when (cdr (assq 'date info))
+ (setq level (cdr (assq 'level info)))
+ (when (or (not min) (< level min)) (setq min level))
+ (when (> level max) (setq max level))))
+ (cons (or min 0) max)))
+
+(defun org-invoice-collapse-list (ls)
+ "Reorganize the given list by dates."
+ (let ((min-max (org-invoice-level-min-max ls)) new)
+ (dolist (info ls)
+ (let* ((date (cdr (assq 'date info)))
+ (work (cdr (assq 'work info)))
+ (price (cdr (assq 'price info)))
+ (long-date (cdr (assq 'long-date info)))
+ (level (cdr (assq 'level info)))
+ (bucket (cdr (assoc date new))))
+ (if (and (/= (car min-max) (cdr min-max))
+ (= (car min-max) level)
+ (= work 0) (not bucket) date)
+ (progn
+ (setq info (assq-delete-all 'work info))
+ (push (cons 'total-work 0) info)
+ (push (cons date (list info)) new)
+ (setq bucket (cdr (assoc date new))))
+ (when (and date (not bucket))
+ (setq bucket (list (list (cons 'date date)
+ (cons 'title long-date)
+ (cons 'total-work 0)
+ (cons 'price 0))))
+ (push (cons date bucket) new)
+ (setq bucket (cdr (assoc date new))))
+ (when (and date bucket)
+ (setcdr (assq 'total-work (car bucket))
+ (+ work (cdr (assq 'total-work (car bucket)))))
+ (setcdr (assq 'price (car bucket))
+ (+ price (cdr (assq 'price (car bucket)))))
+ (nconc bucket (list info))))))
+ (nreverse new)))
+
+(defun org-invoice-info-to-table (info)
+ "Create a single org table row from the given info alist."
+ (let ((title (cdr (assq 'title info)))
+ (total (cdr (assq 'total-work info)))
+ (work (cdr (assq 'work info)))
+ (price (cdr (assq 'price info)))
+ (with-price (plist-get org-invoice-table-params :price)))
+ (unless total
+ (setq
+ org-invoice-total-time (+ org-invoice-total-time work)
+ org-invoice-total-price (+ org-invoice-total-price price)))
+ (setq total (and total (org-minutes-to-clocksum-string total)))
+ (setq work (and work (org-minutes-to-clocksum-string work)))
+ (insert-before-markers
+ (concat "|" title
+ (cond
+ (total (concat "|" total))
+ (work (concat "|" work)))
+ (and with-price price (concat "|" (format "%.2f" price)))
+ "|" "\n"))))
+
+(defun org-invoice-list-to-table (ls)
+ "Convert a list of heading info to an org table"
+ (let ((with-price (plist-get org-invoice-table-params :price))
+ (with-summary (plist-get org-invoice-table-params :summary))
+ (with-header (plist-get org-invoice-table-params :headers))
+ (org-invoice-total-time 0)
+ (org-invoice-total-price 0))
+ (insert-before-markers
+ (concat "| Task / Date | Time" (and with-price "| Price") "|\n"))
+ (dolist (info ls)
+ (insert-before-markers "|-\n")
+ (mapc 'org-invoice-info-to-table (if with-header (cdr info) (cdr (cdr info)))))
+ (when with-summary
+ (insert-before-markers
+ (concat "|-\n|Total:|"
+ (org-minutes-to-clocksum-string org-invoice-total-time)
+ (and with-price (concat "|" (format "%.2f" org-invoice-total-price)))
+ "|\n")))))
+
+(defun org-invoice-collect-invoice-data ()
+ "Collect all the invoice data from the current OrgMode tree and
+return it. Before you call this function, move point to the
+heading that begins the invoice data, usually using the
+`org-invoice-goto-tree' function."
+ (let ((org-invoice-current-invoice
+ (list (cons 'point (point)) (cons 'buffer (current-buffer))))
+ (org-invoice-current-item nil))
+ (save-restriction
+ (org-narrow-to-subtree)
+ (org-clock-sum)
+ (run-hook-with-args 'org-invoice-start-hook)
+ (cons org-invoice-current-invoice
+ (org-invoice-collapse-list
+ (org-map-entries 'org-invoice-heading-info t 'tree 'archive))))))
+
+(defun org-dblock-write:invoice (params)
+ "Function called by OrgMode to write the invoice dblock. To
+create an invoice dblock you can use the `org-invoice-report'
+function.
+
+The following parameters can be given to the invoice block (for
+information about dblock parameters, please see the Org manual):
+
+:scope Allows you to override the `org-invoice-default-level'
+ variable. The only supported values right now are ones
+ that look like :tree1, :tree2, etc.
+
+:prices Set to nil to turn off the price column.
+
+:headers Set to nil to turn off the group headers.
+
+:summary Set to nil to turn off the final summary line."
+ (let ((scope (plist-get params :scope))
+ (org-invoice-table-params params)
+ (zone (point-marker))
+ table)
+ (unless scope (setq scope 'default))
+ (unless (plist-member params :price) (plist-put params :price t))
+ (unless (plist-member params :summary) (plist-put params :summary t))
+ (unless (plist-member params :headers) (plist-put params :headers t))
+ (save-excursion
+ (cond
+ ((eq scope 'tree) (org-invoice-goto-tree "tree1"))
+ ((eq scope 'default) (org-invoice-goto-tree))
+ ((symbolp scope) (org-invoice-goto-tree (symbol-name scope))))
+ (setq table (org-invoice-collect-invoice-data))
+ (goto-char zone)
+ (org-invoice-list-to-table (cdr table))
+ (goto-char zone)
+ (org-table-align)
+ (move-marker zone nil))))
+
+(defun org-invoice-in-report-p ()
+ "Check to see if point is inside an invoice report."
+ (let ((pos (point)) start)
+ (save-excursion
+ (end-of-line 1)
+ (and (re-search-backward "^#\\+BEGIN:[ \t]+invoice" nil t)
+ (setq start (match-beginning 0))
+ (re-search-forward "^#\\+END:.*" nil t)
+ (>= (match-end 0) pos)
+ start))))
+
+(defun org-invoice-report (&optional jump)
+ "Create or update an invoice dblock report. If point is inside
+an existing invoice report, the report is updated. If point
+isn't inside an invoice report, a new report is created.
+
+When called with a prefix argument, move to the first invoice
+report after point and update it.
+
+For information about various settings for the invoice report,
+see the `org-dblock-write:invoice' function documentation.
+
+An invoice report is created by reading a heading tree and
+collecting information from various properties. It is assumed
+that all invoices start at a second level heading, but this can
+be configured using the `org-invoice-default-level' variable.
+
+Here is an example, where all invoices fall under the first-level
+heading Invoices:
+
+* Invoices
+** Client Foo (Jan 01 - Jan 15)
+*** [2008-01-01 Tue] Built New Server for Production
+*** [2008-01-02 Wed] Meeting with Team to Design New System
+** Client Bar (Jan 01 - Jan 15)
+*** [2008-01-01 Tue] Searched for Widgets on Google
+*** [2008-01-02 Wed] Billed You for Taking a Nap
+
+In this layout, invoices begin at level two, and invoice
+items (tasks) are at level three. You'll notice that each level
+three heading starts with an inactive timestamp. The timestamp
+can actually go anywhere you want, either in the heading, or in
+the text under the heading. But you must have a timestamp
+somewhere so that the invoice report can group your items by
+date.
+
+Properties are used to collect various bits of information for
+the invoice. All properties can be set on the invoice item
+headings, or anywhere in the tree. The invoice report will scan
+up the tree looking for each of the properties.
+
+Properties used:
+
+CLOCKSUM: You can use the Org clock-in and clock-out commands to
+ create a CLOCKSUM property. Also see WORK.
+
+WORK: An alternative to the CLOCKSUM property. This property
+ should contain the amount of work that went into this
+ invoice item formatted as HH:MM (e.g. 01:30).
+
+RATE: Used to calculate the total price for an invoice item.
+ Should be the price per hour that you charge (e.g. 45.00).
+ It might make more sense to place this property higher in
+ the hierarchy than on the invoice item headings.
+
+Using this information, a report is generated that details the
+items grouped by days. For each day you will be able to see the
+total number of hours worked, the total price, and the items
+worked on.
+
+You can place the invoice report anywhere in the tree you want.
+I place mine under a third-level heading like so:
+
+* Invoices
+** An Invoice Header
+*** [2008-11-25 Tue] An Invoice Item
+*** Invoice Report
+#+BEGIN: invoice
+#+END:"
+ (interactive "P")
+ (let ((report (org-invoice-in-report-p)))
+ (when (and (not report) jump)
+ (when (re-search-forward "^#\\+BEGIN:[ \t]+invoice" nil t)
+ (org-show-entry)
+ (beginning-of-line)
+ (setq report (point))))
+ (if report (goto-char report)
+ (org-create-dblock (list :name "invoice")))
+ (org-update-dblock)))
+
+(provide 'org-invoice)
diff --git a/contrib/lisp/org-learn.el b/contrib/lisp/org-learn.el
new file mode 100644
index 0000000..db9580f
--- /dev/null
+++ b/contrib/lisp/org-learn.el
@@ -0,0 +1,177 @@
+;;; org-learn.el --- Implements SuperMemo's incremental learning algorithm
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: John Wiegley <johnw at gnu dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 6.32trans
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; The file implements the learning algorithm described at
+;; http://supermemo.com/english/ol/sm5.htm, which is a system for reading
+;; material according to "spaced repetition". See
+;; http://en.wikipedia.org/wiki/Spaced_repetition for more details.
+;;
+;; To use, turn on state logging and schedule some piece of information you
+;; want to read. Then in the agenda buffer type
+
+(require 'org)
+(eval-when-compile
+ (require 'cl))
+
+(defgroup org-learn nil
+ "Options concerning the learning code in Org-mode."
+ :tag "Org Learn"
+ :group 'org-progress)
+
+(defcustom org-learn-always-reschedule nil
+ "If non-nil, always reschedule items, even if retention was \"perfect\"."
+ :type 'boolean
+ :group 'org-learn)
+
+(defcustom org-learn-fraction 0.5
+ "Controls the rate at which EF is increased or decreased.
+Must be a number between 0 and 1 (the greater it is the faster
+the changes of the OF matrix)."
+ :type 'float
+ :group 'org-learn)
+
+(defun initial-optimal-factor (n ef)
+ (if (= 1 n)
+ 4
+ ef))
+
+(defun get-optimal-factor (n ef of-matrix)
+ (let ((factors (assoc n of-matrix)))
+ (or (and factors
+ (let ((ef-of (assoc ef (cdr factors))))
+ (and ef-of (cdr ef-of))))
+ (initial-optimal-factor n ef))))
+
+(defun set-optimal-factor (n ef of-matrix of)
+ (let ((factors (assoc n of-matrix)))
+ (if factors
+ (let ((ef-of (assoc ef (cdr factors))))
+ (if ef-of
+ (setcdr ef-of of)
+ (push (cons ef of) (cdr factors))))
+ (push (cons n (list (cons ef of))) of-matrix)))
+ of-matrix)
+
+(defun inter-repetition-interval (n ef &optional of-matrix)
+ (let ((of (get-optimal-factor n ef of-matrix)))
+ (if (= 1 n)
+ of
+ (* of (inter-repetition-interval (1- n) ef of-matrix)))))
+
+(defun modify-e-factor (ef quality)
+ (if (< ef 1.3)
+ 1.3
+ (+ ef (- 0.1 (* (- 5 quality) (+ 0.08 (* (- 5 quality) 0.02)))))))
+
+(defun modify-of (of q fraction)
+ (let ((temp (* of (+ 0.72 (* q 0.07)))))
+ (+ (* (- 1 fraction) of) (* fraction temp))))
+
+(defun calculate-new-optimal-factor (interval-used quality used-of
+ old-of fraction)
+ "This implements the SM-5 learning algorithm in Lisp.
+INTERVAL-USED is the last interval used for the item in question.
+QUALITY is the quality of the repetition response.
+USED-OF is the optimal factor used in calculation of the last
+interval used for the item in question.
+OLD-OF is the previous value of the OF entry corresponding to the
+relevant repetition number and the E-Factor of the item.
+FRACTION is a number belonging to the range (0,1) determining the
+rate of modifications (the greater it is the faster the changes
+of the OF matrix).
+
+Returns the newly calculated value of the considered entry of the
+OF matrix."
+ (let (;; the value proposed for the modifier in case of q=5
+ (mod5 (/ (1+ interval-used) interval-used))
+ ;; the value proposed for the modifier in case of q=2
+ (mod2 (/ (1- interval-used) interval-used))
+ ;; the number determining how many times the OF value will
+ ;; increase or decrease
+ modifier)
+ (if (< mod5 1.05)
+ (setq mod5 1.05))
+ (if (< mod2 0.75)
+ (setq mod5 0.75))
+ (if (> quality 4)
+ (setq modifier (1+ (* (- mod5 1) (- quality 4))))
+ (setq modifier (- 1 (* (/ (- 1 mod2) 2) (- 4 quality)))))
+ (if (< modifier 0.05)
+ (setq modifier 0.05))
+ (setq new-of (* used-of modifier))
+ (if (> quality 4)
+ (if (< new-of old-of)
+ (setq new-of old-of)))
+ (if (< quality 4)
+ (if (> new-of old-of)
+ (setq new-of old-of)))
+ (setq new-of (+ (* new-of fraction) (* old-of (- 1 fraction))))
+ (if (< new-of 1.2)
+ (setq new-of 1.2)
+ new-of)))
+
+(defvar initial-repetition-state '(-1 1 2.5 nil))
+
+(defun determine-next-interval (n ef quality of-matrix)
+ (assert (> n 0))
+ (assert (and (>= quality 0) (<= quality 5)))
+ (if (< quality 3)
+ (list (inter-repetition-interval n ef) (1+ n) ef nil)
+ (let ((next-ef (modify-e-factor ef quality)))
+ (setq of-matrix
+ (set-optimal-factor n next-ef of-matrix
+ (modify-of (get-optimal-factor n ef of-matrix)
+ quality org-learn-fraction))
+ ef next-ef)
+ ;; For a zero-based quality of 4 or 5, don't repeat
+ (if (and (>= quality 4)
+ (not org-learn-always-reschedule))
+ (list 0 (1+ n) ef of-matrix)
+ (list (inter-repetition-interval n ef of-matrix) (1+ n)
+ ef of-matrix)))))
+
+(defun org-smart-reschedule (quality)
+ (interactive "nHow well did you remember the information (on a scale of 0-5)? ")
+ (let* ((learn-str (org-entry-get (point) "LEARN_DATA"))
+ (learn-data (or (and learn-str
+ (read learn-str))
+ (copy-list initial-repetition-state)))
+ closed-dates)
+ (setq learn-data
+ (determine-next-interval (nth 1 learn-data)
+ (nth 2 learn-data)
+ quality
+ (nth 3 learn-data)))
+ (org-entry-put (point) "LEARN_DATA" (prin1-to-string learn-data))
+ (if (= 0 (nth 0 learn-data))
+ (org-schedule t)
+ (org-schedule nil (time-add (current-time)
+ (days-to-time (nth 0 learn-data)))))))
+
+(provide 'org-learn)
+
+;;; org-learn.el ends here
diff --git a/contrib/lisp/org-license.el b/contrib/lisp/org-license.el
new file mode 100644
index 0000000..2fad68f
--- /dev/null
+++ b/contrib/lisp/org-license.el
@@ -0,0 +1,540 @@
+;;; org-license.el --- Add a license to your org files
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: David Arroyo Menéndez <davidam@es.gnu.org>
+;; Keywords: licenses, creative commons
+;; Homepage: http://orgmode.org
+;;
+;; This file is not part of GNU Emacs, yet.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements functions to add a license fast in org files.
+;; Org-mode doesn't load this module by default - if this is not what
+;; you want, configure the variable `org-modules'. Thanks to #emacs-es
+;; irc channel for your support.
+
+;;; Code:
+
+;;
+;;
+;; You can download the images from http://www.davidam/img/licenses.tar.gz
+;;
+;;; CHANGELOG:
+;; v 0.2 - add public domain functions
+;; v 0.1 - Initial release
+
+
+(defvar org-license-images-directory "")
+
+(defun org-license-cc-by (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eo | eu | fi | fr | gl | it | jp | nl | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by/3.0/br/deed.pt_BR")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Lizenz Creative Commons Namensnennung 3.0 Deutschland]]\n")))
+ ((equal language "eo")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/eo/deed.eo")
+ (insert (concat "* Licenco
+Ĉi tiu verko estas disponebla laŭ la permesilo [[" org-license-cc-url "][Krea Komunaĵo Atribuite 3.0 Neadaptita]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/es/deed.es")
+ (insert (concat "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Atribución 3.0 España]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/es/deed.eu")
+ (insert (concat "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n")))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/fr/deed.fr")
+ (insert (concat "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は [[" org-license-cc-url "][Creative Commons Attribution 2.1 ]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by/4.0/deed")
+ (concat (insert "* License
+This document is under a [[" org-license-cc-url "][Creative Commons Attribution 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by/3.0/80x15.png]]\n"))))
+
+(defun org-license-cc-by-sa (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eu | fi | fr | it | jp | nl | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by-sa/3.0/br/deed.pt_BR")
+ (concat (insert "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Compartil ha Igual 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement-CompartirIgual 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Namensnennung - Weitergabe unter gleichen Bedingungen 3.0 Deutschland]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/es/deed.es")
+ (concat (insert "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Atribución Compartir por Igual 3.0 España]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/es/deed.eu")
+ (concat (insert "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu-PartekatuBerdin 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n")))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä-JaaSamoin 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/fr/deed.fr")
+ (concat (insert "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution - Partage dans les Mêmes Conditions 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione - Condividi allo stesso modo 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は、[[" org-license-cc-url "][Creative Commons Attribution 2.1 ]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding Gelijk Delen 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição-CompartilhaIgual 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-sa/4.0/deed")
+ (insert (concat "* License
+This document is under a [[" org-license-cc-url "][Creative Commons Attribution-ShareAlike 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by-sa/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by-sa/3.0/80x15.png]]\n"))))
+
+(defun org-license-cc-by-nd (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eu | fi | fr | it | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by-nd/3.0/br/deed.pt_BR")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Compartil ha Igual 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement-SenseObraDerivada 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Namensnennung-Keine Bearbeitung 3.0 Deutschland]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/es/deed.es")
+ (insert (concat "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Atribución-SinDerivadas 3.0]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/es/deed.eu")
+ (insert (concat "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu-LanEratorririkGabe 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n")))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä-JaaSamoin 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/fr/deed.fr")
+ (insert (concat "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution - Pas de Modification 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione - Non opere derivate 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は、[[" org-license-cc-url "][Creative Commons No Derivatives 2.1]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding GeenAfgeleideWerken 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Sem Derivados 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nd/4.0/deed")
+ (insert (concat "* License
+This document is under a [[" org-license-cc-url "][Creative Commons No Derivatives 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by-nd/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by-nd/3.0/80x15.png]]\n"))))
+
+
+(defun org-license-cc-by-nc (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eu | fi | fr | it | jp | nl | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by-nc/3.0/br/deed.pt_BR")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Não Comercial 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement-NoComercial 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Namensnennung-Nicht-kommerziell 3.0 Deutschland]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/es/deed.es")
+ (insert (concat "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Reconocimiento-NoComercial 3.0]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/es/deed.eu")
+ (insert "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu-EzKomertziala 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n"))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä-Epäkaupallinen 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/fr/deed.fr")
+ (insert (concat "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution - Pas d'Utilisation Commerciale 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione - Non commerciale 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は、[[" org-license-cc-url "][Creative Commons Attribution-NonCommercial 2.1 ]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding NietCommercieel 3.0 Nederland 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Não Comercial 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/4.0/deed")
+ (insert (concat "* License
+This document is under a [[" org-license-cc-url "][Creative Commons Attribution-NonCommercial 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by-nc/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by-nc/3.0/80x15.png]]\n"))))
+
+(defun org-license-cc-by-nc-sa (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eu | fi | fr | gl | it | jp | nl | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "https://creativecommons.org/licenses/by-nc-sa/3.0/br/deed.pt_BR")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Não Comercial - Compartil ha Igual 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement-NoComercial 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Namensnennung - Weitergabe unter gleichen Bedingungen 3.0 Deutschland]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/es/deed.es")
+ (insert (concat "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Reconocimiento-NoComercial 3.0]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/es/deed.eu")
+ (insert "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu-EzKomertziala-PartekatuBerdin 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n"))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä-Epäkaupallinen-JaaSamoin 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/fr/deed.fr")
+ (insert (concat "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution - Pas d’Utilisation Commerciale - Partage dans les Mêmes Conditions 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione - Non opere derivate 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は、[[" org-license-cc-url "][License Creative Commons Attribution Non Commercial Share Alike 2.1 ]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding NietCommercieel GelijkDelen 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição NãoComercial Compartil ha Igual 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-sa/4.0/deed")
+ (insert (concat "* License
+This document is under a [[" org-license-cc-url "][License Creative Commons Attribution Non Commercial Share Alike 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by-nc-sa/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by-nc-sa/3.0/80x15.png]]\n"))))
+
+(defun org-license-cc-by-nc-nd (language)
+ (interactive "MLanguage ( br | ca | de | en | es | eu | fi | fr | gl | it | pt ): " language)
+ (cond ((equal language "br")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Não Comercial Sem Derivados 3.0 Brasil]]\n")))
+ ((equal language "ca")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/es/deed.ca")
+ (insert (concat "* Licència
+El text està disponible sota la [[" org-license-cc-url "][Reconeixement-NoComercial-SenseObraDerivada 3.0 Espanya]]\n")))
+ ((equal language "de")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/de/deed.de")
+ (insert (concat "* Lizenz
+Dieses Werk bzw. Inhalt steht unter einer [[" org-license-cc-url "][Namensnennung-NichtKommerziell-KeineBearbeitung 3.0 Deutschland]]\n")))
+ ((equal language "es")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/es/deed.es")
+ (insert (concat "* Licencia
+Este documento está bajo una [[" org-license-cc-url "][Licencia Creative Commons Reconocimiento-NoComercial-SinObraDerivada 3.0]]\n")))
+ ((equal language "eu")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/es/deed.eu")
+ (insert (concat "* Licenzua
+Testua [[" org-license-cc-url "][Aitortu-LanEratorririkGabe 3.0 Espainia]] lizentziari jarraituz erabil daiteke\n")))
+ ((equal language "fi")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/1.0/fi/deed.fi")
+ (insert (concat "* Lisenssi
+Teksti on saatavilla [[" org-license-cc-url "][Nimeä-Ei muutoksia-Epäkaupallinen 1.0 Suomi]] lisenssillä\n")))
+ ((equal language "fr")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/fr/deed.fr")
+ (insert (concat "* Licence
+Ce(tte) œuvre est mise à disposition selon les termes de la [[" org-license-cc-url "][Licence Creative Commons Attribution - Pas de Modification 3.0 France]]\n")))
+ ((equal language "gl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/es/deed.gl")
+ (insert (concat "* Licenza
+Todo o texto está dispoñible baixo a [[" org-license-cc-url "][licenza Creative Commons recoñecemento compartir igual 3.0]].\n")))
+ ((equal language "it")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/it/deed.it")
+ (insert (concat "* Licenza
+Quest'opera e distribuita con Licenza [[" org-license-cc-url "][Licenza Creative Commons Attribuzione - Non opere derivate 3.0 Italia]]\n")))
+ ((equal language "jp")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/2.1/jp/deed.en")
+ (insert (concat "* ライセンス
+この文書は [[" org-license-cc-url "][License Creative Commons Attribution Non Commercial - No Derivs 2.1]] ライセンスの下である\n")))
+ ((equal language "nl")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.nl")
+ (insert (concat "* Licentie
+Dit werk is valt onder een [[" org-license-cc-url "][Creative Commons Naamsvermelding NietCommercieel GeenAfgeleideWerken 3.0 Nederland]]\n")))
+ ((equal language "pt")
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/3.0/pt/deed.pt")
+ (insert (concat "* Licença
+Este texto é disponibilizado nos termos da licença [[" org-license-cc-url "][Atribuição Não Comercial Sem Derivados 3.0 Portugal]]\n")))
+ (t
+ (setq org-license-cc-url "http://creativecommons.org/licenses/by-nc-nd/4.0/deed")
+ (insert (concat "* License
+This document is under a [[" org-license-cc-url "][License Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International]]\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-cc-url "][file:http://i.creativecommons.org/l/by-nc-nd/3.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-cc-url "][file:" org-license-images-directory "/by-nc-nd/3.0/80x15.png]]\n"))))
+
+(defun org-license-gfdl (language)
+ (interactive "MLanguage (es | en): " language)
+ (cond ((equal language "es")
+ (insert "* Licencia
+Copyright (C) " (format-time-string "%Y") " " user-full-name
+"\n Se permite copiar, distribuir y/o modificar este documento
+ bajo los términos de la GNU Free Documentation License, Version 1.3
+ o cualquier versión publicada por la Free Software Foundation;
+ sin Secciones Invariantes y sin Textos de Portada o Contraportada.
+ Una copia de la licencia está incluida en [[https://www.gnu.org/copyleft/fdl.html][GNU Free Documentation License]].\n"))
+ (t (insert (concat "* License
+Copyright (C) " (format-time-string "%Y") " " user-full-name
+"\n Permission is granted to copy, distribute and/or modify this document
+ under the terms of the GNU Free Documentation License, Version 1.3
+ or any later version published by the Free Software Foundation;
+ with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
+ A copy of the license is included in [[https://www.gnu.org/copyleft/fdl.html][GNU Free Documentation License]].\n"))))
+ (if (string= "" org-license-images-directory)
+ (insert "\n[[https://www.gnu.org/copyleft/fdl.html][file:https://upload.wikimedia.org/wikipedia/commons/thumb/4/42/GFDL_Logo.svg/200px-GFDL_Logo.svg.png]]\n")
+ (insert (concat "\n[[https://www.gnu.org/copyleft/fdl.html][file:" org-license-images-directory "/gfdl/gfdl.png]]\n"))))
+
+(defun org-license-publicdomain-zero (language)
+ (interactive "MLanguage ( en | es ): " language)
+ (setq org-license-pd-url "http://creativecommons.org/publicdomain/zero/1.0/")
+ (setq org-license-pd-file "zero/1.0/80x15.png")
+ (if (equal language "es")
+ (insert (concat "* Licencia
+Este documento está bajo una licencia [[" org-license-pd-url "][Public Domain Zero]]\n"))
+ (insert (concat "* License
+This documento is under a [[" org-license-pd-url "][Public Domain Zero]] license\n")))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-pd-url "][file:http://i.creativecommons.org/p/zero/1.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-pd-url "][file:" org-license-images-directory org-license-pd-file "]]\n"))))
+
+(defun org-license-publicdomain-mark (language)
+ (interactive "MLanguage ( en | es ): " language)
+ (setq org-license-pd-url "http://creativecommons.org/publicdomain/mark/1.0/")
+ (setq org-license-pd-file "mark/1.0/80x15.png")
+ (if (equal language "es")
+ (insert (concat "* Licencia
+Este documento está bajo una licencia [[" org-license-pd-url "][Etiqueta de Dominio Público 1.0]]\n"))
+ (insert (concat "* License
+This documento is under a [[" org-license-pd-url "][Public Domain Mark]] license\n")))
+ (if (string= "" org-license-images-directory)
+ (insert (concat "\n[[" org-license-pd-url "][file:http://i.creativecommons.org/p/mark/1.0/80x15.png]]\n"))
+ (insert (concat "\n[[" org-license-pd-url "][file:" org-license-images-directory org-license-pd-file "]]\n"))))
+
+(defun org-license-print-all ()
+"Print all combinations of licenses and languages, it's useful to find bugs"
+ (interactive)
+ (org-license-gfdl "es")
+ (org-license-gfdl "en")
+ (org-license-publicdomain-mark "es")
+ (org-license-publicdomain-mark "en")
+ (org-license-publicdomain-zero "es")
+ (org-license-publicdomain-zero "en")
+ (org-license-cc-by "br")
+ (org-license-cc-by "ca")
+ (org-license-cc-by "de")
+ (org-license-cc-by "es")
+ (org-license-cc-by "en")
+ (org-license-cc-by "eo")
+ (org-license-cc-by "eu")
+ (org-license-cc-by "fi")
+ (org-license-cc-by "fr")
+ (org-license-cc-by "gl")
+ (org-license-cc-by "it")
+ (org-license-cc-by "jp")
+ (org-license-cc-by "nl")
+ (org-license-cc-by "pt")
+ (org-license-cc-by-sa "br")
+ (org-license-cc-by-sa "ca")
+ (org-license-cc-by-sa "de")
+ (org-license-cc-by-sa "es")
+ (org-license-cc-by-sa "en")
+;; (org-license-cc-by-sa "eo")
+ (org-license-cc-by-sa "eu")
+ (org-license-cc-by-sa "fi")
+ (org-license-cc-by-sa "fr")
+ (org-license-cc-by-sa "gl")
+ (org-license-cc-by-sa "it")
+ (org-license-cc-by-sa "jp")
+ (org-license-cc-by-sa "nl")
+ (org-license-cc-by-sa "pt")
+ (org-license-cc-by-nd "br")
+ (org-license-cc-by-nd "ca")
+ (org-license-cc-by-nd "de")
+ (org-license-cc-by-nd "es")
+ (org-license-cc-by-nd "en")
+;; (org-license-cc-by-nd "eo")
+ (org-license-cc-by-nd "eu")
+ (org-license-cc-by-nd "fi")
+ (org-license-cc-by-nd "fr")
+ (org-license-cc-by-nd "gl")
+ (org-license-cc-by-nd "it")
+ (org-license-cc-by-nd "jp")
+ (org-license-cc-by-nd "nl")
+ (org-license-cc-by-nd "pt")
+ (org-license-cc-by-nc "br")
+ (org-license-cc-by-nc "ca")
+ (org-license-cc-by-nc "de")
+ (org-license-cc-by-nc "es")
+ (org-license-cc-by-nc "en")
+;; (org-license-cc-by-nc "eo")
+ (org-license-cc-by-nc "eu")
+ (org-license-cc-by-nc "fi")
+ (org-license-cc-by-nc "fr")
+ (org-license-cc-by-nc "gl")
+ (org-license-cc-by-nc "it")
+ (org-license-cc-by-nc "jp")
+ (org-license-cc-by-nc "nl")
+ (org-license-cc-by-nc "pt")
+ (org-license-cc-by-nc-sa "br")
+ (org-license-cc-by-nc-sa "ca")
+ (org-license-cc-by-nc-sa "de")
+ (org-license-cc-by-nc-sa "es")
+ (org-license-cc-by-nc-sa "en")
+;; (org-license-cc-by-nc-sa "eo")
+ (org-license-cc-by-nc-sa "eu")
+ (org-license-cc-by-nc-sa "fi")
+ (org-license-cc-by-nc-sa "fr")
+ (org-license-cc-by-nc-sa "gl")
+ (org-license-cc-by-nc-sa "it")
+ (org-license-cc-by-nc-sa "jp")
+ (org-license-cc-by-nc-sa "nl")
+ (org-license-cc-by-nc-sa "pt")
+ (org-license-cc-by-nc-nd "br")
+ (org-license-cc-by-nc-nd "ca")
+ (org-license-cc-by-nc-nd "de")
+ (org-license-cc-by-nc-nd "es")
+ (org-license-cc-by-nc-nd "en")
+;; (org-license-cc-by-nc-nd "eo")
+ (org-license-cc-by-nc-nd "eu")
+ (org-license-cc-by-nc-nd "fi")
+ (org-license-cc-by-nc-nd "fr")
+ (org-license-cc-by-nc-nd "gl")
+ (org-license-cc-by-nc-nd "it")
+ (org-license-cc-by-nc-nd "jp")
+ (org-license-cc-by-nc-nd "nl")
+ (org-license-cc-by-nc-nd "pt")
+)
+
+
diff --git a/contrib/lisp/org-link-edit.el b/contrib/lisp/org-link-edit.el
new file mode 100644
index 0000000..000dd1c
--- /dev/null
+++ b/contrib/lisp/org-link-edit.el
@@ -0,0 +1,390 @@
+;;; org-link-edit.el --- Slurp and barf with Org links -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2015-2017 Kyle Meyer <kyle@kyleam.com>
+
+;; Author: Kyle Meyer <kyle@kyleam.com>
+;; URL: https://gitlab.com/kyleam/org-link-edit
+;; Keywords: convenience
+;; Version: 1.1.1
+;; Package-Requires: ((cl-lib "0.5") (org "8.2.10"))
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org Link Edit provides Paredit-inspired slurping and barfing
+;; commands for Org link descriptions.
+;;
+;; There are four slurp and barf commands, all which operate when
+;; point is on an Org link.
+;;
+;; - org-link-edit-forward-slurp
+;; - org-link-edit-backward-slurp
+;; - org-link-edit-forward-barf
+;; - org-link-edit-backward-barf
+;;
+;; Org Link Edit doesn't bind these commands to any keys. Finding
+;; good keys for these commands is difficult because, while it's
+;; convenient to be able to quickly repeat these commands, they won't
+;; be used frequently enough to be worthy of a short, repeat-friendly
+;; binding. Using Hydra [1] provides a nice solution to this. After
+;; an initial key sequence, any of the commands will be repeatable
+;; with a single key. (Plus, you get a nice interface that displays
+;; the key for each command.) Below is one example of how you could
+;; configure this.
+;;
+;; (define-key org-mode-map YOUR-KEY
+;; (defhydra hydra-org-link-edit ()
+;; "Org Link Edit"
+;; ("j" org-link-edit-forward-slurp "forward slurp")
+;; ("k" org-link-edit-forward-barf "forward barf")
+;; ("u" org-link-edit-backward-slurp "backward slurp")
+;; ("i" org-link-edit-backward-barf "backward barf")
+;; ("q" nil "cancel")))
+;;
+;; In addition to the slurp and barf commands, the command
+;; `org-link-edit-transport-next-link' searches for the next (or
+;; previous) link and moves it to point, using the word at point or
+;; the selected region as the link's description.
+;;
+;; [1] https://github.com/abo-abo/hydra
+
+;;; Code:
+
+(require 'org)
+(require 'org-element)
+(require 'cl-lib)
+
+(defun org-link-edit--on-link-p (&optional element)
+ (let ((el (or element (org-element-context))))
+ ;; Don't use `org-element-lineage' because it isn't available
+ ;; until Org version 8.3.
+ (while (and el (not (memq (car el) '(link))))
+ (setq el (org-element-property :parent el)))
+ (eq (car el) 'link)))
+
+(defun org-link-edit--link-data ()
+ "Return list with information about the link at point.
+The list includes
+- the position at the start of the link
+- the position at the end of the link
+- the link text
+- the link description (nil when on a plain link)"
+ (let ((el (org-element-context)))
+ (unless (org-link-edit--on-link-p el)
+ (user-error "Point is not on a link"))
+ (save-excursion
+ (goto-char (org-element-property :begin el))
+ (cond
+ ;; Use match-{beginning,end} because match-end is consistently
+ ;; positioned after ]], while the :end property is positioned
+ ;; at the next word on the line, if one is present.
+ ((looking-at org-bracket-link-regexp)
+ (list (match-beginning 0)
+ (match-end 0)
+ (save-match-data
+ (org-link-unescape (match-string-no-properties 1)))
+ (or (and (match-end 3)
+ (match-string-no-properties 3))
+ "")))
+ ((looking-at org-plain-link-re)
+ (list (match-beginning 0)
+ (match-end 0)
+ (org-link-unescape (match-string-no-properties 0))
+ nil))
+ (t
+ (error "What am I looking at?"))))))
+
+(defun org-link-edit--forward-blob (n &optional no-punctuation)
+ "Move forward N blobs (backward if N is negative).
+
+A block of non-whitespace characters is a blob. If
+NO-PUNCTUATION is non-nil, trailing punctuation characters are
+not considered part of the blob when going in the forward
+direction.
+
+If the edge of the buffer is reached before completing the
+movement, return nil. Otherwise, return t."
+ (let* ((forward-p (> n 0))
+ (nblobs (abs n))
+ (skip-func (if forward-p 'skip-syntax-forward 'skip-syntax-backward))
+ skip-func-retval)
+ (while (/= nblobs 0)
+ (funcall skip-func " ")
+ (setq skip-func-retval (funcall skip-func "^ "))
+ (setq nblobs (1- nblobs)))
+ (when (and forward-p no-punctuation)
+ (let ((punc-tail-offset (save-excursion (skip-syntax-backward "."))))
+ ;; Don't consider trailing punctuation as part of the blob
+ ;; unless the whole blob consists of punctuation.
+ (unless (= skip-func-retval (- punc-tail-offset))
+ (goto-char (+ (point) punc-tail-offset)))))
+ (/= skip-func-retval 0)))
+
+;;;###autoload
+(defun org-link-edit-forward-slurp (&optional n)
+ "Slurp N trailing blobs into link's description.
+
+ The \[\[http://orgmode.org/\]\[Org mode\]\] site
+
+ |
+ v
+
+ The \[\[http://orgmode.org/\]\[Org mode site\]\]
+
+A blob is a block of non-whitespace characters. When slurping
+forward, trailing punctuation characters are not considered part
+of a blob.
+
+After slurping, return the slurped text and move point to the
+beginning of the link.
+
+If N is negative, slurp leading blobs instead of trailing blobs."
+ (interactive "p")
+ (setq n (or n 1))
+ (cond
+ ((= n 0))
+ ((< n 0)
+ (org-link-edit-backward-slurp (- n)))
+ (t
+ (cl-multiple-value-bind (beg end link desc) (org-link-edit--link-data)
+ (goto-char (save-excursion
+ (goto-char end)
+ (or (org-link-edit--forward-blob n 'no-punctuation)
+ (user-error "Not enough blobs after the link"))
+ (point)))
+ (let ((slurped (buffer-substring-no-properties end (point))))
+ (setq slurped (replace-regexp-in-string "\n+" " " slurped))
+ (when (and (= (length desc) 0)
+ (string-match "^\\s-+\\(.*\\)" slurped))
+ (setq slurped (match-string 1 slurped)))
+ (setq desc (concat desc slurped)
+ end (+ end (length slurped)))
+ (delete-region beg (point))
+ (insert (org-make-link-string link desc))
+ (goto-char beg)
+ slurped)))))
+
+;;;###autoload
+(defun org-link-edit-backward-slurp (&optional n)
+ "Slurp N leading blobs into link's description.
+
+ The \[\[http://orgmode.org/\]\[Org mode\]\] site
+
+ |
+ v
+
+ \[\[http://orgmode.org/\]\[The Org mode\]\] site
+
+A blob is a block of non-whitespace characters.
+
+After slurping, return the slurped text and move point to the
+beginning of the link.
+
+If N is negative, slurp trailing blobs instead of leading blobs."
+ (interactive "p")
+ (setq n (or n 1))
+ (cond
+ ((= n 0))
+ ((< n 0)
+ (org-link-edit-forward-slurp (- n)))
+ (t
+ (cl-multiple-value-bind (beg end link desc) (org-link-edit--link-data)
+ (goto-char (save-excursion
+ (goto-char beg)
+ (or (org-link-edit--forward-blob (- n))
+ (user-error "Not enough blobs before the link"))
+ (point)))
+ (let ((slurped (buffer-substring-no-properties (point) beg)))
+ (when (and (= (length desc) 0)
+ (string-match "\\(.*\\)\\s-+$" slurped))
+ (setq slurped (match-string 1 slurped)))
+ (setq slurped (replace-regexp-in-string "\n+" " " slurped))
+ (setq desc (concat slurped desc)
+ beg (- beg (length slurped)))
+ (delete-region (point) end)
+ (insert (org-make-link-string link desc))
+ (goto-char beg)
+ slurped)))))
+
+(defun org-link-edit--split-first-blobs (string n)
+ "Split STRING into (N first blobs . other) cons cell.
+'N first blobs' contains all text from the start of STRING up to
+the start of the N+1 blob. 'other' includes the remaining text
+of STRING. If the number of blobs in STRING is fewer than N,
+'other' is nil."
+ (when (< n 0) (user-error "N cannot be negative"))
+ (with-temp-buffer
+ (insert string)
+ (goto-char (point-min))
+ (with-syntax-table org-mode-syntax-table
+ (let ((within-bound (org-link-edit--forward-blob n)))
+ (skip-syntax-forward " ")
+ (cons (buffer-substring 1 (point))
+ (and within-bound
+ (buffer-substring (point) (point-max))))))))
+
+(defun org-link-edit--split-last-blobs (string n)
+ "Split STRING into (other . N last blobs) cons cell.
+'N last blobs' contains all text from the end of STRING back to
+the end of the N+1 last blob. 'other' includes the remaining
+text of STRING. If the number of blobs in STRING is fewer than
+N, 'other' is nil."
+ (when (< n 0) (user-error "N cannot be negative"))
+ (with-temp-buffer
+ (insert string)
+ (goto-char (point-max))
+ (with-syntax-table org-mode-syntax-table
+ (let ((within-bound (org-link-edit--forward-blob (- n))))
+ (skip-syntax-backward " ")
+ (cons (and within-bound
+ (buffer-substring 1 (point)))
+ (buffer-substring (point) (point-max)))))))
+
+;;;###autoload
+(defun org-link-edit-forward-barf (&optional n)
+ "Barf N trailing blobs from link's description.
+
+ The \[\[http://orgmode.org/\]\[Org mode\]\] site
+
+ |
+ v
+
+ The \[\[http://orgmode.org/\]\[Org\]\] mode site
+
+A blob is a block of non-whitespace characters.
+
+After barfing, return the barfed text and move point to the
+beginning of the link.
+
+If N is negative, barf leading blobs instead of trailing blobs."
+ (interactive "p")
+ (setq n (or n 1))
+ (cond
+ ((= n 0))
+ ((< n 0)
+ (org-link-edit-backward-barf (- n)))
+ (t
+ (cl-multiple-value-bind (beg end link desc) (org-link-edit--link-data)
+ (when (= (length desc) 0)
+ (user-error "Link has no description"))
+ (pcase-let ((`(,new-desc . ,barfed) (org-link-edit--split-last-blobs
+ desc n)))
+ (unless new-desc (user-error "Not enough blobs in description"))
+ (goto-char beg)
+ (delete-region beg end)
+ (insert (org-make-link-string link new-desc))
+ (when (string= new-desc "")
+ (setq barfed (concat " " barfed)))
+ (insert barfed)
+ (goto-char beg)
+ barfed)))))
+
+;;;###autoload
+(defun org-link-edit-backward-barf (&optional n)
+ "Barf N leading blobs from link's description.
+
+ The \[\[http://orgmode.org/\]\[Org mode\]\] site
+
+ |
+ v
+
+ The Org \[\[http://orgmode.org/\]\[mode\]\] site
+
+A blob is a block of non-whitespace characters.
+
+After barfing, return the barfed text and move point to the
+beginning of the link.
+
+If N is negative, barf trailing blobs instead of leading blobs."
+ (interactive "p")
+ (setq n (or n 1))
+ (cond
+ ((= n 0))
+ ((< n 0)
+ (org-link-edit-forward-barf (- n)))
+ (t
+ (cl-multiple-value-bind (beg end link desc) (org-link-edit--link-data)
+ (when (= (length desc) 0)
+ (user-error "Link has no description"))
+ (pcase-let ((`(,barfed . ,new-desc) (org-link-edit--split-first-blobs
+ desc n)))
+ (unless new-desc (user-error "Not enough blobs in description"))
+ (goto-char beg)
+ (delete-region beg end)
+ (insert (org-make-link-string link new-desc))
+ (when (string= new-desc "")
+ (setq barfed (concat barfed " ")))
+ (goto-char beg)
+ (insert barfed)
+ barfed)))))
+
+(defun org-link-edit--next-link-data (&optional previous)
+ (save-excursion
+ (if (funcall (if previous #'re-search-backward #'re-search-forward)
+ org-any-link-re nil t)
+ (org-link-edit--link-data)
+ (user-error "No %s link found" (if previous "previous" "next")))))
+
+;;;###autoload
+(defun org-link-edit-transport-next-link (&optional previous beg end)
+ "Move the next link to point.
+
+If the region is active, use the selected text as the link's
+description. Otherwise, use the word at point.
+
+With prefix argument PREVIOUS, move the previous link instead of
+the next link.
+
+Non-interactively, use the text between BEG and END as the
+description, moving the next (or previous) link relative BEG and
+END."
+ (interactive (cons current-prefix-arg
+ (and (use-region-p)
+ (list (region-beginning) (region-end)))))
+ (let ((pt (point))
+ (desc-bounds (cond
+ ((and beg end)
+ (cons (progn (goto-char beg)
+ (point-marker))
+ (progn (goto-char end)
+ (point-marker))))
+ ((not (looking-at-p "\\s-"))
+ (progn (skip-syntax-backward "w")
+ (let ((beg (point-marker)))
+ (skip-syntax-forward "w")
+ (cons beg (point-marker))))))))
+ (when (or (and desc-bounds
+ (or (progn (goto-char (car desc-bounds))
+ (org-link-edit--on-link-p))
+ (progn (goto-char (cdr desc-bounds))
+ (org-link-edit--on-link-p))))
+ (progn (goto-char pt)
+ (org-link-edit--on-link-p)))
+ (user-error "Cannot transport next link with point on a link"))
+ (goto-char (or (car desc-bounds) pt))
+ (cl-multiple-value-bind (link-beg link-end link orig-desc)
+ (org-link-edit--next-link-data previous)
+ (unless (or (not desc-bounds) (= (length orig-desc) 0))
+ (user-error "Link already has a description"))
+ (delete-region link-beg link-end)
+ (insert (org-make-link-string
+ link
+ (if desc-bounds
+ (delete-and-extract-region (car desc-bounds)
+ (cdr desc-bounds))
+ orig-desc))))))
+
+(provide 'org-link-edit)
+;;; org-link-edit.el ends here
diff --git a/contrib/lisp/org-mac-iCal.el b/contrib/lisp/org-mac-iCal.el
new file mode 100644
index 0000000..937b6dd
--- /dev/null
+++ b/contrib/lisp/org-mac-iCal.el
@@ -0,0 +1,250 @@
+;;; org-mac-iCal.el --- Imports events from iCal.app to the Emacs diary
+
+;; Copyright (C) 2009-2014 Christopher Suckling
+
+;; Author: Christopher Suckling <suckling at gmail dot com>
+;; Version: 0.1057.104
+;; Keywords: outlines, calendar
+
+;; This file is not part of GNU Emacs.
+
+;; This program is Free Software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+;; for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This file provides the import of events from Mac OS X 10.5 iCal.app
+;; into the Emacs diary (it is not compatible with OS X < 10.5). The
+;; function org-mac-iCal will import events in all checked iCal.app
+;; calendars for the date range org-mac-iCal-range months, centered
+;; around the current date.
+;;
+;; CAVEAT: This function is destructive; it will overwrite the current
+;; contents of the Emacs diary.
+;;
+;; Installation: add (require 'org-mac-iCal) to your .emacs.
+;;
+;; If you view Emacs diary entries in org-agenda, the following hook
+;; will ensure that all-day events are not orphaned below TODO items
+;; and that any supplementary fields to events (e.g. Location) are
+;; grouped with their parent event
+;;
+;; (add-hook 'org-agenda-cleanup-fancy-diary-hook
+;; (lambda ()
+;; (goto-char (point-min))
+;; (save-excursion
+;; (while (re-search-forward "^[a-z]" nil t)
+;; (goto-char (match-beginning 0))
+;; (insert "0:00-24:00 ")))
+;; (while (re-search-forward "^ [a-z]" nil t)
+;; (goto-char (match-beginning 0))
+;; (save-excursion
+;; (re-search-backward "^[0-9]+:[0-9]+-[0-9]+:[0-9]+ " nil t))
+;; (insert (match-string 0)))))
+
+;;; Code:
+
+(defcustom org-mac-iCal-range 2
+ "The range in months to import iCal.app entries into the Emacs
+diary. The import is centered around today's date; thus a value
+of 2 imports entries for one month before and one month after
+today's date"
+ :group 'org-time
+ :type 'integer)
+
+(defun org-mac-iCal ()
+ "Selects checked calendars in iCal.app and imports them into
+the the Emacs diary"
+ (interactive)
+
+ ;; kill diary buffers then empty diary files to avoid duplicates
+ (setq currentBuffer (buffer-name))
+ (setq openBuffers (mapcar (function buffer-name) (buffer-list)))
+ (omi-kill-diary-buffer openBuffers)
+ (with-temp-buffer
+ (insert-file-contents diary-file)
+ (delete-region (point-min) (point-max))
+ (write-region (point-min) (point-max) diary-file))
+
+ ;; determine available calendars
+ (setq caldav-folders (directory-files "~/Library/Calendars" 1 ".*caldav$"))
+ (setq caldav-calendars nil)
+ (mapc
+ (lambda (x)
+ (setq caldav-calendars (nconc caldav-calendars (directory-files x 1 ".*calendar$"))))
+ caldav-folders)
+
+ (setq local-calendars nil)
+ (setq local-calendars (directory-files "~/Library/Calendars" 1 ".*calendar$"))
+
+ (setq all-calendars (append caldav-calendars local-calendars))
+
+ ;; parse each calendar's Info.plist to see if calendar is checked in iCal
+ (setq all-calendars (delq 'nil (mapcar
+ (lambda (x)
+ (omi-checked x))
+ all-calendars)))
+
+ ;; for each calendar, concatenate individual events into a single ics file
+ (with-temp-buffer
+ (shell-command "sw_vers" (current-buffer))
+ (when (re-search-backward "10\\.[5678]" nil t)
+ (omi-concat-leopard-ics all-calendars)))
+
+ ;; move all caldav ics files to the same place as local ics files
+ (mapc
+ (lambda (x)
+ (mapc
+ (lambda (y)
+ (rename-file (concat x "/" y);
+ (concat "~/Library/Calendars/" y)))
+ (directory-files x nil ".*ics$")))
+ caldav-folders)
+
+ ;; check calendar has contents and import
+ (setq import-calendars (directory-files "~/Library/Calendars" 1 ".*ics$"))
+ (mapc
+ (lambda (x)
+ (when (/= (nth 7 (file-attributes x 'string)) 0)
+ (omi-import-ics x)))
+ import-calendars)
+
+ ;; tidy up intermediate files and buffers
+ (setq usedCalendarsBuffers (mapcar (function buffer-name) (buffer-list)))
+ (omi-kill-ics-buffer usedCalendarsBuffers)
+ (setq usedCalendarsFiles (directory-files "~/Library/Calendars" 1 ".*ics$"))
+ (omi-delete-ics-file usedCalendarsFiles)
+
+ (org-pop-to-buffer-same-window currentBuffer))
+
+(defun omi-concat-leopard-ics (list)
+ "Leopard stores each iCal.app event in a separate ics file.
+Whilst useful for Spotlight indexing, this is less helpful for
+icalendar-import-file. omi-concat-leopard-ics concatenates these
+individual event files into a single ics file"
+ (mapc
+ (lambda (x)
+ (setq omi-leopard-events (directory-files (concat x "/Events") 1 ".*ics$"))
+ (with-temp-buffer
+ (mapc
+ (lambda (y)
+ (insert-file-contents (expand-file-name y)))
+ omi-leopard-events)
+ (write-region (point-min) (point-max) (concat (expand-file-name x) ".ics"))))
+ list))
+
+(defun omi-import-ics (string)
+ "Imports an ics file into the Emacs diary. First tidies up the
+ics file so that it is suitable for import and selects a sensible
+date range so that Emacs calendar view doesn't grind to a halt"
+ (with-temp-buffer
+ (insert-file-contents string)
+ (goto-char (point-min))
+ (while
+ (re-search-forward "^BEGIN:VCALENDAR$" nil t)
+ (setq startEntry (match-beginning 0))
+ (re-search-forward "^END:VCALENDAR$" nil t)
+ (setq endEntry (match-end 0))
+ (save-restriction
+ (narrow-to-region startEntry endEntry)
+ (goto-char (point-min))
+ (re-search-forward "\\(^DTSTART;.*:\\)\\([0-9][0-9][0-9][0-9]\\)\\([0-9][0-9]\\)" nil t)
+ (if (or (eq (match-string 2) nil) (eq (match-string 3) nil))
+ (progn
+ (setq yearEntry 1)
+ (setq monthEntry 1))
+ (setq yearEntry (string-to-number (match-string 2)))
+ (setq monthEntry (string-to-number (match-string 3))))
+ (setq year (string-to-number (format-time-string "%Y")))
+ (setq month (string-to-number (format-time-string "%m")))
+ (setq now (list month 1 year))
+ (setq entryDate (list monthEntry 1 yearEntry))
+ ;; Check to see if this is a repeating event
+ (goto-char (point-min))
+ (setq isRepeating (re-search-forward "^RRULE:" nil t))
+ ;; Delete if outside range and not repeating
+ (when (and
+ (not isRepeating)
+ (> (abs (- (calendar-absolute-from-gregorian now)
+ (calendar-absolute-from-gregorian entryDate)))
+ (* (/ org-mac-iCal-range 2) 30))
+ (delete-region startEntry endEntry)))
+ (goto-char (point-max))))
+ (while
+ (re-search-forward "^END:VEVENT$" nil t)
+ (delete-blank-lines))
+ (goto-line 1)
+ (insert "BEGIN:VCALENDAR\n\n")
+ (goto-line 2)
+ (while
+ (re-search-forward "^BEGIN:VCALENDAR$" nil t)
+ (replace-match "\n"))
+ (goto-line 2)
+ (while
+ (re-search-forward "^END:VCALENDAR$" nil t)
+ (replace-match "\n"))
+ (insert "END:VCALENDAR")
+ (goto-line 1)
+ (delete-blank-lines)
+ (while
+ (re-search-forward "^END:VEVENT$" nil t)
+ (delete-blank-lines))
+ (goto-line 1)
+ (while
+ (re-search-forward "^ORG.*" nil t)
+ (replace-match "\n"))
+ (goto-line 1)
+ (write-region (point-min) (point-max) string))
+
+ (icalendar-import-file string diary-file))
+
+(defun omi-kill-diary-buffer (list)
+ (mapc
+ (lambda (x)
+ (if (string-match "^diary" x)
+ (kill-buffer x)))
+ list))
+
+(defun omi-kill-ics-buffer (list)
+ (mapc
+ (lambda (x)
+ (if (string-match "ics$" x)
+ (kill-buffer x)))
+ list))
+
+(defun omi-delete-ics-file (list)
+ (mapc
+ (lambda (x)
+ (delete-file x))
+ list))
+
+(defun omi-checked (directory)
+ "Parse Info.plist in iCal.app calendar folder and determine
+whether Checked key is 1. If Checked key is not 1, remove
+calendar from list of calendars for import"
+ (let* ((root (xml-parse-file (car (directory-files directory 1 "Info.plist"))))
+ (plist (car root))
+ (dict (car (xml-get-children plist 'dict)))
+ (keys (cdr (xml-node-children dict)))
+ (keys (mapcar
+ (lambda (x)
+ (cond ((listp x)
+ x)))
+ keys))
+ (keys (delq 'nil keys)))
+ (when (equal "1" (car (cddr (lax-plist-get keys '(key nil "Checked")))))
+ directory)))
+
+(provide 'org-mac-iCal)
+
+;;; org-mac-iCal.el ends here
diff --git a/contrib/lisp/org-mac-link.el b/contrib/lisp/org-mac-link.el
new file mode 100644
index 0000000..7f4af30
--- /dev/null
+++ b/contrib/lisp/org-mac-link.el
@@ -0,0 +1,947 @@
+;;; org-mac-link.el --- Insert org-mode links to items selected in various Mac apps
+;;
+;; Copyright (c) 2010-2017 Free Software Foundation, Inc.
+;;
+;; Author: Anthony Lander <anthony.lander@gmail.com>
+;; John Wiegley <johnw@gnu.org>
+;; Christopher Suckling <suckling at gmail dot com>
+;; Daniil Frumin <difrumin@gmail.com>
+;; Alan Schmitt <alan.schmitt@polytechnique.org>
+;; Mike McLean <mike.mclean@pobox.com>
+;;
+;;
+;; Version: 1.1
+;; Keywords: org, mac, hyperlink
+;;
+;; Version: 1.2
+;; Keywords: outlook
+;; Author: Mike McLean <mike.mclean@pobox.com>
+;; Add support for Microsoft Outlook for Mac as Org mode links
+;;
+;; Version: 1.3
+;; Author: Alan Schmitt <alan.schmitt@polytechnique.org>
+;; Consistently use `org-mac-paste-applescript-links'
+;;
+;; Version 1.4
+;; Author: Mike McLean <mike.mclean@pobox.com>
+;; Make the path to Microsoft Outlook a `defcustom'
+;;
+;; Version 1.5
+;; Author: Mike McLean <mike.mclean@pobox.com>
+;; Add Support for Evernote
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+;; This code allows you to grab either the current selected items, or
+;; the frontmost url in various mac appliations, and insert them as
+;; hyperlinks into the current org-mode document at point.
+;;
+;; This code is heavily based on, and indeed incorporates,
+;; org-mac-message.el written by John Wiegley and Christopher
+;; Suckling.
+;;
+;; Detailed comments for each application interface are inlined with
+;; the code. Here is a brief overview of how the code interacts with
+;; each application:
+;;
+;; Finder.app - grab links to the selected files in the frontmost window
+;; Mail.app - grab links to the selected messages in the message list
+;; AddressBook.app - Grab links to the selected addressbook Cards
+;; Firefox.app - Grab the url of the frontmost tab in the frontmost window
+;; Vimperator/Firefox.app - Grab the url of the frontmost tab in the frontmost window
+;; Safari.app - Grab the url of the frontmost tab in the frontmost window
+;; Google Chrome.app - Grab the url of the frontmost tab in the frontmost window
+;; Together.app - Grab links to the selected items in the library list
+;; Skim.app - Grab a link to the selected page in the topmost pdf document
+;; Microsoft Outlook.app - Grab a link to the selected message in the message list
+;; DEVONthink Pro Office.app - Grab a link to the selected DEVONthink item(s); open DEVONthink item by reference
+;; Evernote.app - Grab a link to the selected Evernote item(s); open Evernote item by ID
+;;
+;;
+;; Installation:
+;;
+;; add (require 'org-mac-link) to your .emacs, and optionally bind a
+;; key to activate the link grabber menu, like this:
+;;
+;; (add-hook 'org-mode-hook (lambda ()
+;; (define-key org-mode-map (kbd "C-c g") 'org-mac-grab-link)))
+;;
+;; Usage:
+;;
+;; Type C-c g (or whatever key you defined, as above), or type M-x
+;; org-mac-grab-link RET to activate the link grabber. This will present
+;; you with a menu to choose an application from which to grab a link
+;; to insert at point. You may also type C-g to abort.
+;;
+;; Customizing:
+;;
+;; You may customize which applications appear in the grab menu by
+;; customizing the group `org-mac-link'. Changes take effect
+;; immediately.
+;;
+;;
+;;; Code:
+
+(require 'org)
+
+(defgroup org-mac-link nil
+ "Options for grabbing links from Mac applications."
+ :tag "Org Mac link"
+ :group 'org-link)
+
+(defcustom org-mac-grab-Finder-app-p t
+ "Add menu option [F]inder to grab links from the Finder."
+ :tag "Grab Finder.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Mail-app-p t
+ "Add menu option [m]ail to grab links from Mail.app."
+ :tag "Grab Mail.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Outlook-app-p t
+ "Add menu option [o]utlook to grab links from Microsoft Outlook.app."
+ :tag "Grab Microsoft Outlook.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-outlook-path "/Applications/Microsoft Outlook.app"
+ "The path to the installed copy of Microsoft Outlook.app. Do not escape spaces as the AppleScript call will quote this string."
+ :tag "Path to Microsoft Outlook"
+ :group 'org-mac-link
+ :type 'string)
+
+(defcustom org-mac-grab-devonthink-app-p t
+ "Add menu option [d]EVONthink to grab links from DEVONthink Pro Office.app."
+ :tag "Grab DEVONthink Pro Office.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Addressbook-app-p t
+ "Add menu option [a]ddressbook to grab links from AddressBook.app."
+ :tag "Grab AddressBook.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Safari-app-p t
+ "Add menu option [s]afari to grab links from Safari.app."
+ :tag "Grab Safari.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Firefox-app-p t
+ "Add menu option [f]irefox to grab links from Firefox.app."
+ :tag "Grab Firefox.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Firefox+Vimperator-p nil
+ "Add menu option [v]imperator to grab links from Firefox.app running the Vimperator plugin."
+ :tag "Grab Vimperator/Firefox.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Chrome-app-p t
+ "Add menu option [c]hrome to grab links from Google Chrome.app."
+ :tag "Grab Google Chrome.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Together-app-p nil
+ "Add menu option [t]ogether to grab links from Together.app."
+ :tag "Grab Together.app links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Skim-app-p
+ (< 0 (length (shell-command-to-string
+ "mdfind kMDItemCFBundleIdentifier == 'net.sourceforge.skim-app.skim'")))
+ "Add menu option [S]kim to grab page links from Skim.app."
+ :tag "Grab Skim.app page links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-Skim-highlight-selection-p nil
+ "Highlight the active selection when grabbing a link from Skim.app."
+ :tag "Highlight selection in Skim.app"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-grab-Acrobat-app-p t
+ "Add menu option [A]crobat to grab page links from Acrobat.app."
+ :tag "Grab Acrobat.app page links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defgroup org-mac-flagged-mail nil
+ "Options foring linking to flagged Mail.app messages."
+ :tag "Org Mail.app"
+ :group 'org-link)
+
+(defcustom org-mac-mail-account nil
+ "The Mail.app account in which to search for flagged messages."
+ :group 'org-mac-flagged-mail
+ :type 'string)
+
+(defcustom org-mac-grab-Evernote-app-p
+ (< 0 (length (shell-command-to-string
+ "mdfind kMDItemCFBundleIdentifier == 'com.evernote.Evernote'")))
+ "Add menu option [e]vernote to grab note links from Evernote.app."
+ :tag "Grab Evernote.app note links"
+ :group 'org-mac-link
+ :type 'boolean)
+
+(defcustom org-mac-evernote-path (replace-regexp-in-string (rx (* (any " \t\n")) eos)
+ ""
+ (shell-command-to-string
+ "mdfind kMDItemCFBundleIdentifier == 'com.evernote.Evernote'"))
+ "The path to the installed copy of Evernote.app. Do not escape spaces as the AppleScript call will quote this string."
+ :tag "Path to Evernote"
+ :group 'org-mac-link
+ :type 'string)
+
+
+;; In mac.c, removed in Emacs 23.
+(declare-function do-applescript "org-mac-message" (script))
+(unless (fboundp 'do-applescript)
+ ;; Need to fake this using shell-command-to-string
+ (defun do-applescript (script)
+ (let (start cmd return)
+ (while (string-match "\n" script)
+ (setq script (replace-match "\r" t t script)))
+ (while (string-match "'" script start)
+ (setq start (+ 2 (match-beginning 0))
+ script (replace-match "\\'" t t script)))
+ (setq cmd (concat "osascript -e '" script "'"))
+ (setq return (shell-command-to-string cmd))
+ (concat "\"" (org-trim return) "\""))))
+
+(defun org-mac-grab-link ()
+ "Prompt for an application to grab a link from.
+When done, go grab the link, and insert it at point."
+ (interactive)
+ (let* ((descriptors
+ `(("F" "inder" org-mac-finder-insert-selected ,org-mac-grab-Finder-app-p)
+ ("m" "ail" org-mac-message-insert-selected ,org-mac-grab-Mail-app-p)
+ ("d" "EVONthink Pro Office" org-mac-devonthink-item-insert-selected
+ ,org-mac-grab-devonthink-app-p)
+ ("o" "utlook" org-mac-outlook-message-insert-selected ,org-mac-grab-Outlook-app-p)
+ ("a" "ddressbook" org-mac-addressbook-insert-selected ,org-mac-grab-Addressbook-app-p)
+ ("s" "afari" org-mac-safari-insert-frontmost-url ,org-mac-grab-Safari-app-p)
+ ("f" "irefox" org-mac-firefox-insert-frontmost-url ,org-mac-grab-Firefox-app-p)
+ ("v" "imperator" org-mac-vimperator-insert-frontmost-url ,org-mac-grab-Firefox+Vimperator-p)
+ ("c" "hrome" org-mac-chrome-insert-frontmost-url ,org-mac-grab-Chrome-app-p)
+ ("e" "evernote" org-mac-evernote-note-insert-selected ,org-mac-grab-Evernote-app-p)
+ ("t" "ogether" org-mac-together-insert-selected ,org-mac-grab-Together-app-p)
+ ("S" "kim" org-mac-skim-insert-page ,org-mac-grab-Skim-app-p)
+ ("A" "crobat" org-mac-acrobat-insert-page ,org-mac-grab-Acrobat-app-p)))
+ (menu-string (make-string 0 ?x))
+ input)
+
+ ;; Create the menu string for the keymap
+ (mapc (lambda (descriptor)
+ (when (elt descriptor 3)
+ (setf menu-string (concat menu-string
+ "[" (elt descriptor 0) "]"
+ (elt descriptor 1) " "))))
+ descriptors)
+ (setf (elt menu-string (- (length menu-string) 1)) ?:)
+
+ ;; Prompt the user, and grab the link
+ (message menu-string)
+ (setq input (read-char-exclusive))
+ (mapc (lambda (descriptor)
+ (let ((key (elt (elt descriptor 0) 0))
+ (active (elt descriptor 3))
+ (grab-function (elt descriptor 2)))
+ (when (and active (eq input key))
+ (call-interactively grab-function))))
+ descriptors)))
+
+(defun org-mac-paste-applescript-links (as-link-list)
+ "Paste in a list of links from an applescript handler.
+The links are of the form <link>::split::<name>."
+ (let* ((noquote-as-link-list
+ (if (string-prefix-p "\"" as-link-list)
+ (substring as-link-list 1 -1)
+ as-link-list))
+ (link-list
+ (mapcar (lambda (x) (if (string-match "\\`\"\\(.*\\)\"\\'" x)
+ (setq x (match-string 1 x)))
+ x)
+ (split-string noquote-as-link-list "[\r\n]+")))
+ split-link URL description orglink orglink-insert rtn orglink-list)
+ (while link-list
+ (setq split-link (split-string (pop link-list) "::split::"))
+ (setq URL (car split-link))
+ (setq description (cadr split-link))
+ (when (not (string= URL ""))
+ (setq orglink (org-make-link-string URL description))
+ (push orglink orglink-list)))
+ (setq rtn (mapconcat 'identity orglink-list "\n"))
+ (kill-new rtn)
+ rtn))
+
+
+;; Handle links from Firefox.app
+;;
+;; This code allows you to grab the current active url from the main
+;; Firefox.app window, and insert it as a link into an org-mode
+;; document. Unfortunately, firefox does not expose an applescript
+;; dictionary, so this is necessarily introduces some limitations.
+;;
+;; The applescript to grab the url from Firefox.app uses the System
+;; Events application to give focus to the firefox application, select
+;; the contents of the url bar, and copy it. It then uses the title of
+;; the window as the text of the link. There is no way to grab links
+;; from other open tabs, and further, if there is more than one window
+;; open, it is not clear which one will be used (though emperically it
+;; seems that it is always the last active window).
+
+(defun org-as-mac-firefox-get-frontmost-url ()
+ (let ((result
+ (do-applescript
+ (concat
+ "set oldClipboard to the clipboard\n"
+ "set frontmostApplication to path to frontmost application\n"
+ "tell application \"Firefox\"\n"
+ " activate\n"
+ " delay 0.15\n"
+ " tell application \"System Events\"\n"
+ " keystroke \"l\" using {command down}\n"
+ " keystroke \"a\" using {command down}\n"
+ " keystroke \"c\" using {command down}\n"
+ " end tell\n"
+ " delay 0.15\n"
+ " set theUrl to the clipboard\n"
+ " set the clipboard to oldClipboard\n"
+ " set theResult to (get theUrl) & \"::split::\" & (get name of window 1)\n"
+ "end tell\n"
+ "activate application (frontmostApplication as text)\n"
+ "set links to {}\n"
+ "copy theResult to the end of links\n"
+ "return links as string\n"))))
+ (car (split-string result "[\r\n]+" t))))
+
+(defun org-mac-firefox-get-frontmost-url ()
+ (interactive)
+ (message "Applescript: Getting Firefox url...")
+ (org-mac-paste-applescript-links (org-as-mac-firefox-get-frontmost-url)))
+
+(defun org-mac-firefox-insert-frontmost-url ()
+ (interactive)
+ (insert (org-mac-firefox-get-frontmost-url)))
+
+
+;; Handle links from Google Firefox.app running the Vimperator extension
+;; Grab the frontmost url from Firefox+Vimperator. Same limitations are
+;; Firefox
+
+(defun org-as-mac-vimperator-get-frontmost-url ()
+ (let ((result
+ (do-applescript
+ (concat
+ "set oldClipboard to the clipboard\n"
+ "set frontmostApplication to path to frontmost application\n"
+ "tell application \"Firefox\"\n"
+ " activate\n"
+ " delay 0.15\n"
+ " tell application \"System Events\"\n"
+ " keystroke \"y\"\n"
+ " end tell\n"
+ " delay 0.15\n"
+ " set theUrl to the clipboard\n"
+ " set the clipboard to oldClipboard\n"
+ " set theResult to (get theUrl) & \"::split::\" & (get name of window 1)\n"
+ "end tell\n"
+ "activate application (frontmostApplication as text)\n"
+ "set links to {}\n"
+ "copy theResult to the end of links\n"
+ "return links as string\n"))))
+ (replace-regexp-in-string
+ "\s+-\s+Vimperator" "" (car (split-string result "[\r\n]+" t)))))
+
+(defun org-mac-vimperator-get-frontmost-url ()
+ (interactive)
+ (message "Applescript: Getting Vimperator url...")
+ (org-mac-paste-applescript-links (org-as-mac-vimperator-get-frontmost-url)))
+
+(defun org-mac-vimperator-insert-frontmost-url ()
+ (interactive)
+ (insert (org-mac-vimperator-get-frontmost-url)))
+
+
+;; Handle links from Google Chrome.app
+;; Grab the frontmost url from Google Chrome. Same limitations as
+;; Firefox because Chrome doesn't publish an Applescript dictionary
+
+(defun org-as-mac-chrome-get-frontmost-url ()
+ (let ((result
+ (do-applescript
+ (concat
+ "set frontmostApplication to path to frontmost application\n"
+ "tell application \"Google Chrome\"\n"
+ " set theUrl to get URL of active tab of first window\n"
+ " set theResult to (get theUrl) & \"::split::\" & (get name of window 1)\n"
+ "end tell\n"
+ "activate application (frontmostApplication as text)\n"
+ "set links to {}\n"
+ "copy theResult to the end of links\n"
+ "return links as string\n"))))
+ (replace-regexp-in-string
+ "^\"\\|\"$" "" (car (split-string result "[\r\n]+" t)))))
+
+(defun org-mac-chrome-get-frontmost-url ()
+ (interactive)
+ (message "Applescript: Getting Chrome url...")
+ (org-mac-paste-applescript-links (org-as-mac-chrome-get-frontmost-url)))
+
+(defun org-mac-chrome-insert-frontmost-url ()
+ (interactive)
+ (insert (org-mac-chrome-get-frontmost-url)))
+
+
+;; Handle links from Safari.app
+;; Grab the frontmost url from Safari.
+
+(defun org-as-mac-safari-get-frontmost-url ()
+ (do-applescript
+ (concat
+ "tell application \"Safari\"\n"
+ " set theUrl to URL of document 1\n"
+ " set theName to the name of the document 1\n"
+ " return theUrl & \"::split::\" & theName & \"\n\"\n"
+ "end tell\n")))
+
+(defun org-mac-safari-get-frontmost-url ()
+ (interactive)
+ (message "Applescript: Getting Safari url...")
+ (org-mac-paste-applescript-links
+ (org-as-mac-safari-get-frontmost-url)))
+
+(defun org-mac-safari-insert-frontmost-url ()
+ (interactive)
+ (insert (org-mac-safari-get-frontmost-url)))
+
+
+;; Handle links from together.app
+(org-link-set-parameters "x-together-item" :follow #'org-mac-together-item-open)
+
+(defun org-mac-together-item-open (uid)
+ "Open UID, which is a reference to an item in Together."
+ (shell-command (concat "open -a Together \"x-together-item:" uid "\"")))
+
+(defun as-get-selected-together-items ()
+ (do-applescript
+ (concat
+ "tell application \"Together\"\n"
+ " set theLinkList to {}\n"
+ " set theSelection to selected items\n"
+ " repeat with theItem in theSelection\n"
+ " set theLink to (get item link of theItem) & \"::split::\" & (get name of theItem) & \"\n\"\n"
+ " copy theLink to end of theLinkList\n"
+ " end repeat\n"
+ " return theLinkList as string\n"
+ "end tell")))
+
+(defun org-mac-together-get-selected ()
+ (interactive)
+ (message "Applescript: Getting Togther items...")
+ (org-mac-paste-applescript-links (as-get-selected-together-items)))
+
+(defun org-mac-together-insert-selected ()
+ (interactive)
+ (insert (org-mac-together-get-selected)))
+
+
+;; Handle links from Finder.app
+
+(defun as-get-selected-finder-items ()
+ (do-applescript
+ (concat
+ "tell application \"Finder\"\n"
+ " set theSelection to the selection\n"
+ " set links to {}\n"
+ " repeat with theItem in theSelection\n"
+ " set theLink to \"file://\" & (POSIX path of (theItem as string)) & \"::split::\" & (get the name of theItem) & \"\n\"\n"
+ " copy theLink to the end of links\n"
+ " end repeat\n"
+ " return links as string\n"
+ "end tell\n")))
+
+(defun org-mac-finder-item-get-selected ()
+ (interactive)
+ (message "Applescript: Getting Finder items...")
+ (org-mac-paste-applescript-links (as-get-selected-finder-items)))
+
+(defun org-mac-finder-insert-selected ()
+ (interactive)
+ (insert (org-mac-finder-item-get-selected)))
+
+
+;; Handle links from AddressBook.app
+(org-link-set-parameters "addressbook" :follow #'org-mac-addressbook-item-open)
+
+(defun org-mac-addressbook-item-open (uid)
+ "Open UID, which is a reference to an item in the addressbook."
+ (shell-command (concat "open \"addressbook:" uid "\"")))
+
+(defun as-get-selected-addressbook-items ()
+ (do-applescript
+ (concat
+ "tell application \"Address Book\"\n"
+ " set theSelection to the selection\n"
+ " set links to {}\n"
+ " repeat with theItem in theSelection\n"
+ " set theLink to \"addressbook://\" & (the id of theItem) & \"::split::\" & (the name of theItem) & \"\n\"\n"
+ " copy theLink to the end of links\n"
+ " end repeat\n"
+ " return links as string\n"
+ "end tell\n")))
+
+(defun org-mac-addressbook-item-get-selected ()
+ (interactive)
+ (message "Applescript: Getting Address Book items...")
+ (org-mac-paste-applescript-links (as-get-selected-addressbook-items)))
+
+(defun org-mac-addressbook-insert-selected ()
+ (interactive)
+ (insert (org-mac-addressbook-item-get-selected)))
+
+
+;; Handle links from Skim.app
+;;
+;; Original code & idea by Christopher Suckling (org-mac-protocol)
+
+(org-link-set-parameters "skim" :follow #'org-mac-skim-open)
+
+(defun org-mac-skim-open (uri)
+ "Visit page of pdf in Skim"
+ (let* ((page (when (string-match "::\\(.+\\)\\'" uri)
+ (match-string 1 uri)))
+ (document (substring uri 0 (match-beginning 0))))
+ (do-applescript
+ (concat
+ "tell application \"Skim\"\n"
+ "activate\n"
+ "set theDoc to \"" document "\"\n"
+ "set thePage to " page "\n"
+ "open theDoc\n"
+ "go document 1 to page thePage of document 1\n"
+ "end tell"))))
+
+(defun as-get-skim-page-link ()
+ (do-applescript
+ (concat
+ "tell application \"Skim\"\n"
+ "set theDoc to front document\n"
+ "set theTitle to (name of theDoc)\n"
+ "set thePath to (path of theDoc)\n"
+ "set thePage to (get index for current page of theDoc)\n"
+ "set theSelection to selection of theDoc\n"
+ "set theContent to contents of (get text for theSelection)\n"
+ "if theContent is missing value then\n"
+ " set theContent to theTitle & \", p. \" & thePage\n"
+ (when org-mac-Skim-highlight-selection-p
+ (concat
+ "else\n"
+ " tell theDoc\n"
+ " set theNote to make note with properties {type:highlight note, selection:theSelection}\n"
+ " set text of theNote to (get text for theSelection)\n"
+ " end tell\n"))
+ "end if\n"
+ "set theLink to \"skim://\" & thePath & \"::\" & thePage & "
+ "\"::split::\" & theContent\n"
+ "end tell\n"
+ "return theLink as string\n")))
+
+(defun org-mac-skim-get-page ()
+ (interactive)
+ (message "Applescript: Getting Skim page link...")
+ (org-mac-paste-applescript-links (as-get-skim-page-link)))
+
+(defun org-mac-skim-insert-page ()
+ (interactive)
+ (insert (org-mac-skim-get-page)))
+
+;; Handle links from Adobe Acrobat Pro.app
+;;
+;; Original code & idea by Christopher Suckling (org-mac-protocol)
+;;
+;; The URI format is path_to_pdf_file::page_number
+
+(org-link-set-parameters "acrobat" :follow #'org-mac-acrobat-open)
+
+(defun org-mac-acrobat-open (uri)
+ "Visit page of pdf in Acrobat"
+ (let* ((page (when (string-match "::\\(.+\\)\\'" uri)
+ (match-string 1 uri)))
+ (document (substring uri 0 (match-beginning 0))))
+ (do-applescript
+ (concat
+ "tell application \"Adobe Acrobat Pro\"\n"
+ " activate\n"
+ " set theDoc to \"" document "\"\n"
+ " set thePage to " page "\n"
+ " open theDoc\n"
+ " tell PDF Window 1\n"
+ " goto page thePage\n"
+ " end tell\n"
+ "end tell"))))
+
+;; The applescript returns link in the format
+;; "adobe:path_to_pdf_file::page_number::split::document_title, p.page_label"
+
+(defun org-mac-as-get-acrobat-page-link ()
+ (do-applescript
+ (concat
+ "tell application \"Adobe Acrobat Pro\"\n"
+ " set theDoc to active doc\n"
+ " set theWindow to (PDF Window 1 of theDoc)\n"
+ " set thePath to (file alias of theDoc)\n"
+ " set theTitle to (name of theWindow)\n"
+ " set thePage to (page number of theWindow)\n"
+ " set theLabel to (label text of (page thePage of theWindow))\n"
+ "end tell\n"
+ "set theResult to \"acrobat:\" & thePath & \"::\" & thePage & \"::split::\" & theTitle & \", p.\" & theLabel\n"
+ "return theResult as string\n")))
+
+(defun org-mac-acrobat-get-page ()
+ (interactive)
+ (message "Applescript: Getting Acrobat page link...")
+ (org-mac-paste-applescript-links (org-mac-as-get-acrobat-page-link)))
+
+(defun org-mac-acrobat-insert-page ()
+ (interactive)
+ (insert (org-mac-acrobat-get-page)))
+
+
+;; Handle links from Microsoft Outlook.app
+
+(org-link-set-parameters "mac-outlook" :follow #'org-mac-outlook-message-open)
+
+(defun org-mac-outlook-message-open (msgid)
+ "Open a message in Outlook"
+ (do-applescript
+ (concat
+ "tell application \"" org-mac-outlook-path "\"\n"
+ (format "open message id %s\n" (substring-no-properties msgid))
+ "activate\n"
+ "end tell")))
+
+(defun org-as-get-selected-outlook-mail ()
+ "AppleScript to create links to selected messages in Microsoft Outlook.app."
+ (do-applescript
+ (concat
+ "tell application \"" org-mac-outlook-path "\"\n"
+ "set msgCount to count current messages\n"
+ "if (msgCount < 1) then\n"
+ "return\n"
+ "end if\n"
+ "set theLinkList to {}\n"
+ "set theSelection to (get current messages)\n"
+ "repeat with theMessage in theSelection\n"
+ "set theID to id of theMessage as string\n"
+ "set theURL to \"mac-outlook:\" & theID\n"
+ "set theSubject to subject of theMessage\n"
+ "set theLink to theURL & \"::split::\" & theSubject & \"\n\"\n"
+ "copy theLink to end of theLinkList\n"
+ "end repeat\n"
+ "return theLinkList as string\n"
+ "end tell")))
+
+(defun org-sh-get-flagged-outlook-mail ()
+ "Shell commands to create links to flagged messages in Microsoft Outlook.app."
+ (mapconcat
+ (lambda (x) ""
+ (concat
+ "mac-outlook:"
+ (mapconcat
+ (lambda (y) "" y)
+ (split-string
+ (shell-command-to-string
+ (format "mdls -raw -name com_microsoft_outlook_recordID -name kMDItemDisplayName \"%s\"" x))
+ "\000")
+ "::split::")
+ "\n"))
+ (with-temp-buffer
+ (let ((coding-system-for-read (or file-name-coding-system 'utf-8))
+ (coding-system-for-write 'utf-8))
+ (shell-command
+ "mdfind com_microsoft_outlook_flagged==1"
+ (current-buffer)))
+ (split-string
+ (buffer-string) "\n" t))
+ ""))
+
+(defun org-mac-outlook-message-get-links (&optional select-or-flag)
+ "Create links to the messages currently selected or flagged in Microsoft Outlook.app.
+This will use AppleScript to get the message-id and the subject of the
+messages in Microsoft Outlook.app and make a link out of it.
+When SELECT-OR-FLAG is \"s\", get the selected messages (this is also
+the default). When SELECT-OR-FLAG is \"f\", get the flagged messages.
+The Org-syntax text will be pushed to the kill ring, and also returned."
+ (interactive "sLink to (s)elected or (f)lagged messages: ")
+ (setq select-or-flag (or select-or-flag "s"))
+ (message "Org Mac Outlook: searching mailboxes...")
+ (org-mac-paste-applescript-links
+ (if (string= select-or-flag "s")
+ (org-as-get-selected-outlook-mail)
+ (if (string= select-or-flag "f")
+ (org-sh-get-flagged-outlook-mail)
+ (error "Please select \"s\" or \"f\"")))))
+
+(defun org-mac-outlook-message-insert-selected ()
+ "Insert a link to the messages currently selected in Microsoft Outlook.app.
+This will use AppleScript to get the message-id and the subject
+of the active mail in Microsoft Outlook.app and make a link out
+of it."
+ (interactive)
+ (insert (org-mac-outlook-message-get-links "s")))
+
+(defun org-mac-outlook-message-insert-flagged (org-buffer org-heading)
+ "Asks for an org buffer and a heading within it, and replace message links.
+If heading exists, delete all mac-outlook:// links within
+heading's first level. If heading doesn't exist, create it at
+point-max. Insert list of mac-outlook:// links to flagged mail
+after heading."
+ (interactive "bBuffer in which to insert links: \nsHeading after which to insert links: ")
+ (with-current-buffer org-buffer
+ (goto-char (point-min))
+ (let ((isearch-forward t)
+ (message-re "\\[\\[\\(mac-outlook:\\)\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"))
+ (if (org-goto-local-search-headings org-heading nil t)
+ (if (not (eobp))
+ (progn
+ (save-excursion
+ (while (re-search-forward
+ message-re (save-excursion (outline-next-heading)) t)
+ (delete-region (match-beginning 0) (match-end 0)))
+ (insert "\n" (org-mac-outlook-message-get-links "f")))
+ (flush-lines "^$" (point) (outline-next-heading)))
+ (insert "\n" (org-mac-outlook-message-get-links "f")))
+ (goto-char (point-max))
+ (insert "\n")
+ (org-insert-heading nil t)
+ (insert org-heading "\n" (org-mac-outlook-message-get-links "f"))))))
+
+;; Handle links from Evernote.app
+
+(org-link-set-parameters "mac-evernote" :follow #'org-mac-evernote-note-open)
+
+(defun org-mac-evernote-note-open (noteid)
+ "Open a note in Evernote"
+ (do-applescript
+ (concat
+ "tell application \"" org-mac-evernote-path "\"\n"
+ " set theNotes to get every note of every notebook where its local id is \"" (substring-no-properties noteid) "\"\n"
+ " repeat with _note in theNotes\n"
+ " if length of _note is not 0 then\n"
+ " set _selectedNote to _note\n"
+ " end if\n"
+ " end repeat\n"
+ " open note window with item 1 of _selectedNote\n"
+ " activate\n"
+ "end tell")))
+
+(defun org-as-get-selected-evernote-notes ()
+ "AppleScript to create links to selected notes in Evernote.app."
+ (do-applescript
+ (concat
+ "tell application \"" org-mac-evernote-path "\"\n"
+ " set noteCount to count selection\n"
+ " if (noteCount < 1) then\n"
+ " return\n"
+ " end if\n"
+ " set theLinkList to {}\n"
+ " set theSelection to selection\n"
+ " repeat with theNote in theSelection\n"
+ " set theTitle to title of theNote\n"
+ " set theID to local id of theNote\n"
+ " set theURL to \"mac-evernote:\" & theID\n"
+ " set theLink to theURL & \"::split::\" & theTitle & \"\n\"\n"
+ " copy theLink to end of theLinkList\n"
+ " end repeat\n"
+ " return theLinkList as string\n"
+ "end tell\n")))
+
+(defun org-mac-evernote-note-insert-selected ()
+ "Insert a link to the notes currently selected in Evernote.app.
+This will use AppleScript to get the note id and the title of the
+note(s) in Evernote.app and make a link out of it/them."
+ (interactive)
+ (message "Org Mac Evernote: searching notes...")
+(insert (org-mac-paste-applescript-links
+ (org-as-get-selected-evernote-notes))))
+
+
+;; Handle links from DEVONthink Pro Office.app
+
+(org-link-set-parameters "x-devonthink-item" :follow #'org-devonthink-item-open)
+
+(defun org-devonthink-item-open (uid)
+ "Open UID, which is a reference to an item in DEVONthink Pro Office."
+ (shell-command (concat "open \"x-devonthink-item:" uid "\"")))
+
+(defun org-as-get-selected-devonthink-item ()
+ "AppleScript to create links to selected items in DEVONthink Pro Office.app."
+ (do-applescript
+ (concat
+ "set theLinkList to {}\n"
+ "tell application \"DEVONthink Pro\"\n"
+ "set selectedRecords to selection\n"
+ "set selectionCount to count of selectedRecords\n"
+ "if (selectionCount < 1) then\n"
+ "return\n"
+ "end if\n"
+ "repeat with theRecord in selectedRecords\n"
+ "set theID to uuid of theRecord\n"
+ "set theURL to \"x-devonthink-item:\" & theID\n"
+ "set theSubject to name of theRecord\n"
+ "set theLink to theURL & \"::split::\" & theSubject & \"\n\"\n"
+ "copy theLink to end of theLinkList\n"
+ "end repeat\n"
+ "end tell\n"
+ "return theLinkList as string"
+ )))
+
+(defun org-mac-devonthink-get-links ()
+ "Create links to the item(s) currently selected in DEVONthink Pro Office.
+This will use AppleScript to get the `uuid' and the `name' of the
+selected items in DEVONthink Pro Office.app and make links out of
+it/them. This function will push the Org-syntax text to the kill
+ring, and also return it."
+ (message "Org Mac DEVONthink: looking for selected items...")
+ (org-mac-paste-applescript-links (org-as-get-selected-devonthink-item)))
+
+(defun org-mac-devonthink-item-insert-selected ()
+ "Insert a link to the item(s) currently selected in DEVONthink Pro Office.
+This will use AppleScript to get the `uuid'(s) and the name(s) of the
+selected items in DEVONthink Pro Office and make link(s) out of it/them."
+ (interactive)
+ (insert (org-mac-devonthink-get-links)))
+
+
+;; Handle links from Mail.app
+
+(org-link-set-parameters "message" :follow #'org-mac-message-open)
+
+(defun org-mac-message-open (message-id)
+ "Visit the message with MESSAGE-ID.
+This will use the command `open' with the message URL."
+ (start-process (concat "open message:" message-id) nil
+ "open" (concat "message://<" (substring message-id 2) ">")))
+
+(defun org-as-get-selected-mail ()
+ "AppleScript to create links to selected messages in Mail.app."
+ (do-applescript
+ (concat
+ "tell application \"Mail\"\n"
+ "set theLinkList to {}\n"
+ "set theSelection to selection\n"
+ "repeat with theMessage in theSelection\n"
+ "set theID to message id of theMessage\n"
+ "set theSubject to subject of theMessage\n"
+ "set theLink to \"message://\" & theID & \"::split::\" & theSubject\n"
+ "if (theLinkList is not equal to {}) then\n"
+ "set theLink to \"\n\" & theLink\n"
+ "end if\n"
+ "copy theLink to end of theLinkList\n"
+ "end repeat\n"
+ "return theLinkList as string\n"
+ "end tell")))
+
+(defun org-as-get-flagged-mail ()
+ "AppleScript to create links to flagged messages in Mail.app."
+ (unless org-mac-mail-account
+ (error "You must set org-mac-mail-account"))
+ (do-applescript
+ (concat
+ ;; Get links
+ "tell application \"Mail\"\n"
+ "set theMailboxes to every mailbox of account \"" org-mac-mail-account "\"\n"
+ "set theLinkList to {}\n"
+ "repeat with aMailbox in theMailboxes\n"
+ "set theSelection to (every message in aMailbox whose flagged status = true)\n"
+ "repeat with theMessage in theSelection\n"
+ "set theID to message id of theMessage\n"
+ "set theSubject to subject of theMessage\n"
+ "set theLink to \"message://\" & theID & \"::split::\" & theSubject & \"\n\"\n"
+ "copy theLink to end of theLinkList\n"
+ "end repeat\n"
+ "end repeat\n"
+ "return theLinkList as string\n"
+ "end tell")))
+
+(defun org-mac-message-get-links (&optional select-or-flag)
+ "Create links to the messages currently selected or flagged in Mail.app.
+This will use AppleScript to get the message-id and the subject of the
+messages in Mail.app and make a link out of it.
+When SELECT-OR-FLAG is \"s\", get the selected messages (this is also
+the default). When SELECT-OR-FLAG is \"f\", get the flagged messages.
+The Org-syntax text will be pushed to the kill ring, and also returned."
+ (interactive "sLink to (s)elected or (f)lagged messages: ")
+ (setq select-or-flag (or select-or-flag "s"))
+ (message "AppleScript: searching mailboxes...")
+ (org-mac-paste-applescript-links
+ (cond
+ ((string= select-or-flag "s") (org-as-get-selected-mail))
+ ((string= select-or-flag "f") (org-as-get-flagged-mail))
+ (t (error "Please select \"s\" or \"f\"")))))
+
+(defun org-mac-message-insert-selected ()
+ "Insert a link to the messages currently selected in Mail.app.
+This will use AppleScript to get the message-id and the subject of the
+active mail in Mail.app and make a link out of it."
+ (interactive)
+ (insert (org-mac-message-get-links "s")))
+
+;; The following line is for backward compatibility
+(defalias 'org-mac-message-insert-link 'org-mac-message-insert-selected)
+
+(defun org-mac-message-insert-flagged (org-buffer org-heading)
+ "Asks for an org buffer and a heading within it, and replace message links.
+If heading exists, delete all message:// links within heading's first
+level. If heading doesn't exist, create it at point-max. Insert
+list of message:// links to flagged mail after heading."
+ (interactive "bBuffer in which to insert links: \nsHeading after which to insert links: ")
+ (with-current-buffer org-buffer
+ (goto-char (point-min))
+ (let ((isearch-forward t)
+ (message-re "\\[\\[\\(message:\\)\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"))
+ (if (org-goto-local-search-headings org-heading nil t)
+ (if (not (eobp))
+ (progn
+ (save-excursion
+ (while (re-search-forward
+ message-re (save-excursion (outline-next-heading)) t)
+ (delete-region (match-beginning 0) (match-end 0)))
+ (insert "\n" (org-mac-message-get-links "f")))
+ (flush-lines "^$" (point) (outline-next-heading)))
+ (insert "\n" (org-mac-message-get-links "f")))
+ (goto-char (point-max))
+ (insert "\n")
+ (org-insert-heading nil t)
+ (insert org-heading "\n" (org-mac-message-get-links "f"))))))
+
+
+(provide 'org-mac-link)
+
+;;; org-mac-link.el ends here
diff --git a/contrib/lisp/org-mairix.el b/contrib/lisp/org-mairix.el
new file mode 100644
index 0000000..84c2dfd
--- /dev/null
+++ b/contrib/lisp/org-mairix.el
@@ -0,0 +1,333 @@
+;;; org-mairix.el - Support for hooking mairix search into Org for different MUAs
+;;
+;; Copyright (C) 2007-2014 Georg C. F. Greve
+;; mutt support by Adam Spiers <orgmode at adamspiers dot org>
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; Author: Georg C. F. Greve <greve at fsfeurope dot org>
+;; Keywords: outlines, hypermedia, calendar, wp, email, mairix
+;; Purpose: Integrate mairix email searching into Org mode
+;; See http://orgmode.org and http://www.rpcurnow.force9.co.uk/mairix/
+;; Version: 0.5
+;;
+;; This file is Free Software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; It is distributed in the hope that it will be useful, but WITHOUT
+;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+;; License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; USAGE NOTE
+;;
+;; You will need to configure mairix first, which involves setting up your
+;; .mairixrc in your home directory. Once it is working, you should set up
+;; your way to display results in your favorite way -- usually a MUA.
+;; Currently gnus and mutt are supported.
+;;
+;; After both steps are done, all you should need to hook mairix, org
+;; and your MUA together is to do (require 'org-mairix) in your
+;; startup file. Everything can then be configured normally through
+;; Emacs customisation.
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(require 'org)
+
+;;; The custom variables
+
+(defgroup org-mairix nil
+ "Mairix support/integration in org."
+ :tag "Org Mairix"
+ :group 'org)
+
+(defcustom org-mairix-threaded-links t
+ "Should new links be created as threaded links?
+If t, links will be stored as threaded searches.
+If nil, links will be stored as non-threaded searches."
+ :group 'org-mairix
+ :type 'boolean)
+
+(defcustom org-mairix-augmented-links nil
+ "Should new links be created as augmenting searches?
+If t, links will be stored as augmenting searches.
+If nil, links will be stored as normal searches.
+
+Attention: When activating this option, you will need
+to remove old articles from your mairix results group
+in some other way, mairix will not do it for you."
+ :group 'org-mairix
+ :type 'boolean)
+
+(defcustom org-mairix-display-hook 'org-mairix-gnus-display-results
+ "Hook to call to display the results of a successful mairix search.
+Defaults to Gnus, feel free to add your own MUAs or methods."
+ :group 'org-mairix
+ :type 'hook)
+
+(defcustom org-mairix-open-command "mairix %args% '%search%'"
+ "The mairix command-line to use. If your paths are set up
+correctly, you should not need to change this.
+
+'%search%' will get substituted with the search expression, and
+'%args%' with any additional arguments."
+ :group 'org-mairix
+ :type 'string)
+
+;;; The hooks to integrate mairix into org
+
+(org-link-set-parameters "mairix"
+ :follow #'org-mairix-open
+ :store #'org-mairix-store-gnus-link)
+
+;;; Generic org-mairix functions
+
+(defun org-mairix-construct-link (message-id)
+ "Construct a mairix: hyperlink based on message-id."
+ (concat "mairix:"
+ (if org-mairix-threaded-links "t:")
+ (if org-mairix-augmented-links "a:")
+ "@@"
+ (org-unbracket-string "<" ">" message-id)))
+
+(defun org-store-mairix-link-props (&rest plist)
+ "Take a property list describing a mail, and add mairix link
+and description properties so that org can build a mairix link to
+it."
+ ;; We have to call `org-store-link-props' twice:
+ ;;
+ ;; - It extracts 'fromname'/'fromaddress' from 'from' property,
+ ;; and stores the updated plist to `org-store-link-plist'.
+ ;;
+ ;; - `org-email-link-description' uses these new properties to
+ ;; build a description from the previously stored plist. I
+ ;; wrote a tiny patch to `org-email-link-description' so it
+ ;; could take a non-stored plist as an optional 2nd argument,
+ ;; but the plist provided still needs 'fromname'/'fromaddress'.
+ ;;
+ ;; - Ideally we would decouple the storing bit of
+ ;; `org-store-link-props' from the extraction bit, but lots of
+ ;; stuff in `org-store-link' which calls it would need to be
+ ;; changed. Maybe just factor out the extraction so it can be
+ ;; reused separately?
+ (let ((mid (plist-get plist :message-id)))
+ (apply 'org-store-link-props
+ (append plist
+ (list :type "mairix"
+ :link (org-mairix-construct-link mid))))
+ (apply 'org-store-link-props
+ (append org-store-link-plist
+ (list :description (org-email-link-description))))))
+
+(defun org-mairix-message-send-and-exit-with-link ()
+ "Function that can be assigned as an alternative sending function,
+it sends the message and then stores a mairix link to it before burying
+the buffer just like 'message-send-and-exit' does."
+ (interactive)
+ (message-send)
+ (let* ((message-id (message-fetch-field "Message-Id"))
+ (subject (message-fetch-field "Subject"))
+ (link (org-mairix-construct-link message-id))
+ (desc (concat "Email: '" subject "'")))
+ (setq org-stored-links
+ (cons (list link desc) org-stored-links)))
+ (message-bury (current-buffer)))
+
+(defun org-mairix-open (search)
+ "Function to open mairix link.
+
+We first need to split it into its individual parts, and then
+extract the message-id to be passed on to the display function
+before call mairix, evaluate the number of matches returned, and
+make sure to only call display of mairix succeeded in matching."
+ (let* ((args ""))
+ (if (equal (substring search 0 2) "t:" )
+ (progn (setq search (substring search 2 nil))
+ (setq args (concat args " --threads"))))
+ (if (equal (substring search 0 2) "a:")
+ (progn (setq search (substring search 2 nil))
+ (setq args (concat args " --augment"))))
+ (let ((cmdline (org-mairix-command-substitution
+ org-mairix-open-command search args)))
+ (print cmdline)
+ (setq retval (shell-command-to-string cmdline))
+ (string-match "\[0-9\]+" retval)
+ (setq matches (string-to-number (match-string 0 retval)))
+ (if (eq matches 0) (message "Link failed: no matches, sorry")
+ (message "Link returned %d matches" matches)
+ (run-hook-with-args 'org-mairix-display-hook search args)))))
+
+(defun org-mairix-command-substitution (cmd search args)
+ "Substitute '%search%' and '%args% in mairix search command."
+ (while (string-match "%search%" cmd)
+ (setq cmd (replace-match search 'fixedcase 'literal cmd)))
+ (while (string-match "%args%" cmd)
+ (setq cmd (replace-match args 'fixedcase 'literal cmd)))
+ cmd)
+
+;;; Functions necessary for integration of external MUAs.
+
+;; Of course we cannot call `org-store-link' from within an external
+;; MUA, so we need some other way of storing a link for later
+;; retrieval by org-mode and/or remember-mode. To do this we use a
+;; temporary file as a kind of dedicated clipboard.
+
+(defcustom org-mairix-link-clipboard "~/.org-mairix-link"
+ "Pseudo-clipboard file where mairix URLs get copied to by external
+applications in order to mimic `org-store-link'. Used by
+`org-mairix-insert-link'."
+ :group 'org-mairix
+ :type 'string)
+
+;; When we resolve some of the issues with `org-store-link' detailed
+;; at <http://thread.gmane.org/gmane.emacs.orgmode/4217/focus=4635>,
+;; we might not need org-mairix-insert-link.
+
+(defun org-mairix-insert-link ()
+ "Insert link from file defined by `org-mairix-link-clipboard'."
+ (interactive)
+ (let ((bytes (cadr (insert-file-contents
+ (expand-file-name org-mairix-link-clipboard)))))
+ (forward-char bytes)
+ (save-excursion
+ (forward-char -1)
+ (if (looking-at "\n")
+ (delete-char 1)))))
+
+;;; Functions necessary for mutt integration
+
+(defgroup org-mairix-mutt nil
+ "Use mutt for mairix support in org."
+ :tag "Org Mairix Mutt"
+ :group 'org-mairix)
+
+(defcustom org-mairix-mutt-display-command
+ "xterm -title 'mairix search: %search%' -e 'unset COLUMNS; mutt -f
+~/mail/mairix -e \"push <display-message>\"' &"
+ "Command to execute to display mairix search results via mutt within
+an xterm.
+
+'%search%' will get substituted with the search expression, and
+'%args%' with any additional arguments used in the search."
+ :group 'org-mairix-mutt
+ :type 'string)
+
+(defun org-mairix-mutt-display-results (search args)
+ "Display results of mairix search in mutt, using the command line
+defined in `org-mairix-mutt-display-command'."
+ ;; By default, async `shell-command' invocations display the temp
+ ;; buffer, which is annoying here. We choose a deterministic
+ ;; buffer name so we can hide it again immediately.
+ ;; Note: `call-process' is synchronous so not useful here.
+ (let ((cmd (org-mairix-command-substitution
+ org-mairix-mutt-display-command search args))
+ (tmpbufname (generate-new-buffer-name " *mairix-view*")))
+ (shell-command cmd tmpbufname)
+ (delete-windows-on (get-buffer tmpbufname))))
+
+;;; Functions necessary for gnus integration
+
+(defgroup org-mairix-gnus nil
+ "Use gnus for mairix support in org."
+ :tag "Org Mairix Gnus"
+ :group 'org-mairix)
+
+(defcustom org-mairix-gnus-results-group "nnmaildir:mairix"
+ "The group that is configured to hold the mairix search results,
+which needs to be setup independently of the org-mairix integration,
+along with general mairix configuration."
+ :group 'org-mairix-gnus
+ :type 'string)
+
+(defcustom org-mairix-gnus-select-display-group-function
+'org-mairix-gnus-select-display-group-function-gg
+ "Hook to call to select the group that contains the matching articles.
+We should not need this, it is owed to a problem of gnus that people were
+not yet able to figure out, see
+ http://article.gmane.org/gmane.emacs.gnus.general/65248
+ http://article.gmane.org/gmane.emacs.gnus.general/65265
+ http://article.gmane.org/gmane.emacs.gnus.user/9596
+for reference.
+
+It seems gnus needs a 'forget/ignore everything you think you
+know about that group' function. Volunteers?"
+ :group 'org-mairix-gnus
+ :type 'hook)
+
+(defun org-mairix-store-gnus-link ()
+ "Store a link to the current gnus message as a Mairix search for its
+Message ID."
+
+ ;; gnus integration
+ (when (memq major-mode '(gnus-summary-mode gnus-article-mode))
+ (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
+ (let* ((article (gnus-summary-article-number))
+ (header (gnus-summary-article-header article))
+ (from (mail-header-from header))
+ (message-id (mail-header-id header))
+ (subject (gnus-summary-subject-string)))
+ (org-store-mairix-link-props :from from
+ :subject subject
+ :message-id message-id))))
+
+(defun org-mairix-gnus-display-results (search args)
+ "Display results of mairix search in Gnus.
+
+Note: This does not work as cleanly as I would like it to. The
+problem being that Gnus should simply reread the group cleanly,
+without remembering anything. At the moment it seems to be unable
+to do that -- so you're likely to see zombies floating around.
+
+If you can improve this, please do!"
+ (if (not (equal (substring search 0 2) "m:" ))
+ (error "org-mairix-gnus-display-results: display of search other than
+message-id not implemented yet"))
+ (setq message-id (substring search 2 nil))
+ (require 'gnus)
+ (require 'gnus-sum)
+ ;; FIXME: (bzg/gg) We might need to make sure gnus is running here,
+ ;; and to start it in case it isn't running already. Does
+ ;; anyone know a function to do that? It seems main org mode
+ ;; does not do this, either.
+ (funcall (cdr (assq 'gnus org-link-frame-setup)))
+ (if gnus-other-frame-object (select-frame gnus-other-frame-object))
+
+ ;; FIXME: This is horribly broken. Please see
+ ;; http://article.gmane.org/gmane.emacs.gnus.general/65248
+ ;; http://article.gmane.org/gmane.emacs.gnus.general/65265
+ ;; http://article.gmane.org/gmane.emacs.gnus.user/9596
+ ;; for reference.
+ ;;
+ ;; It seems gnus needs a "forget/ignore everything you think you
+ ;; know about that group" function. Volunteers?
+ ;;
+ ;; For now different methods seem to work differently well for
+ ;; different people. So we're playing hook-selection here to make
+ ;; it easy to play around until we found a proper solution.
+ (run-hook-with-args 'org-mairix-gnus-select-display-group-function)
+ (gnus-summary-select-article
+ nil t t (car (gnus-find-matching-articles "message-id" message-id))))
+
+(defun org-mairix-gnus-select-display-group-function-gg ()
+ "Georg's hack to select a group that gnus (falsely) believes to be
+empty to then call rebuilding of the summary. It leaves zombies of
+old searches around, though."
+ (gnus-group-quick-select-group 0 org-mairix-gnus-results-group)
+ (gnus-group-clear-data)
+ (gnus-summary-reselect-current-group t t))
+
+(defun org-mairix-gnus-select-display-group-function-bzg ()
+ "This is the classic way the org mode is using, and it seems to be
+using better for Bastien, so it may work for you."
+ (gnus-group-clear-data org-mairix-gnus-results-group)
+ (gnus-group-read-group t nil org-mairix-gnus-results-group))
+
+(provide 'org-mairix)
+
+;;; org-mairix.el ends here
diff --git a/contrib/lisp/org-man.el b/contrib/lisp/org-man.el
new file mode 100644
index 0000000..1ccd942
--- /dev/null
+++ b/contrib/lisp/org-man.el
@@ -0,0 +1,75 @@
+;;; org-man.el - Support for links to manpages in Org-mode
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 1.0
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+(require 'org)
+
+(org-link-set-parameters "man"
+ :follow #'org-man-open
+ :export #'org-man-export
+ :store #'org-man-store-link)
+
+(defcustom org-man-command 'man
+ "The Emacs command to be used to display a man page."
+ :group 'org-link
+ :type '(choice (const man) (const woman)))
+
+(defun org-man-open (path)
+ "Visit the manpage on PATH.
+PATH should be a topic that can be thrown at the man command."
+ (funcall org-man-command path))
+
+(defun org-man-store-link ()
+ "Store a link to a README file."
+ (when (memq major-mode '(Man-mode woman-mode))
+ ;; This is a man page, we do make this link
+ (let* ((page (org-man-get-page-name))
+ (link (concat "man:" page))
+ (description (format "Manpage for %s" page)))
+ (org-store-link-props
+ :type "man"
+ :link link
+ :description description))))
+
+(defun org-man-get-page-name ()
+ "Extract the page name from the buffer name."
+ ;; This works for both `Man-mode' and `woman-mode'.
+ (if (string-match " \\(\\S-+\\)\\*" (buffer-name))
+ (match-string 1 (buffer-name))
+ (error "Cannot create link to this man page")))
+
+(defun org-man-export (link description format)
+ "Export a man page link from Org files."
+ (let ((path (format "http://man.he.net/?topic=%s&section=all" link))
+ (desc (or description link)))
+ (cond
+ ((eq format 'html) (format "<a target=\"_blank\" href=\"%s\">%s</a>" path desc))
+ ((eq format 'latex) (format "\\href{%s}{%s}" path desc))
+ ((eq format 'texinfo) (format "@uref{%s,%s}" path desc))
+ ((eq format 'ascii) (format "%s (%s)" desc path))
+ (t path))))
+
+(provide 'org-man)
+
+;;; org-man.el ends here
diff --git a/contrib/lisp/org-mew.el b/contrib/lisp/org-mew.el
new file mode 100644
index 0000000..6dbc67c
--- /dev/null
+++ b/contrib/lisp/org-mew.el
@@ -0,0 +1,354 @@
+;;; org-mew.el --- Support for links to Mew messages from within Org-mode
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Tokuya Kameshima <kames at fa2 dot so-net dot ne dot jp>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to Mew messages from within Org-mode.
+;; Org-mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+;;
+;; Here is an example of workflow:
+
+;; In your ~/.mew.el configuration file:
+;;
+;; (define-key mew-summary-mode-map "'" 'org-mew-search)
+;; (eval-after-load "mew-summary"
+;; '(define-key mew-summary-mode-map "\C-o" 'org-mew-capture))
+
+;; 1. In the Mew's inbox folder, take a glance at new messages to find
+;; a message that requires any action.
+
+;; 2. If the message is a reply from somebody and associated with the
+;; existing orgmode entry, type M-x `org-mew-search' RET (or press
+;; the ' key simply) to find the entry. If you can find the entry
+;; successfully and think you should start the task right now,
+;; start the task by M-x `org-agenda-clock-in' RET.
+
+;; 3. If the message is a new message, type M-x `org-mew-capture' RET,
+;; enter the refile folder, and the buffer to capture the message
+;; is shown up (without selecting the template by hand). Then you
+;; can fill the template and type C-c C-c to complete the capture.
+;; Note that you can configure `org-capture-templates' so that the
+;; captured entry has a link to the message.
+
+;;; Code:
+
+(require 'org)
+
+(defgroup org-mew nil
+ "Options concerning the Mew link."
+ :tag "Org Startup"
+ :group 'org-link)
+
+(defcustom org-mew-link-to-refile-destination t
+ "Create a link to the refile destination if the message is marked as refile."
+ :group 'org-mew
+ :type 'boolean)
+
+(defcustom org-mew-inbox-folder nil
+ "The folder where new messages are incorporated.
+If `org-mew-inbox-folder' is non-nil, `org-mew-open' locates the message
+in this inbox folder as well as the folder specified by the link."
+ :group 'org-mew
+ :type 'string)
+
+(defcustom org-mew-use-id-db t
+ "Use ID database to locate the message if id.db is created."
+ :group 'org-mew
+ :type 'boolean)
+
+(defcustom org-mew-subject-alist
+ (list (cons (concat "^\\(?:\\(?:re\\|fwd?\\): *\\)*"
+ "\\(?:[[(][a-z0-9._-]+[:,]? [0-9]+[])]\\)? *"
+ "\\(?:\\(?:re\\|fwd?\\): *\\)*"
+ "\\(.*\\)[ \t]*")
+ 1))
+ "Alist of subject regular expression and matched group number for search."
+ :group 'org-mew
+ :type '(repeat (cons (regexp) (integer))))
+
+(defcustom org-mew-capture-inbox-folders nil
+ "List of inbox folders whose messages need refile marked before capture.
+`org-mew-capture' will ask you to put the refile mark on the
+message if the message's folder is any of these folders and the
+message is not marked. Nil means `org-mew-capture' never ask you
+destination folders before capture."
+ :group 'org-mew
+ :type '(repeat string))
+
+(defcustom org-mew-capture-guess-alist nil
+ "Alist of the regular expression of the folder name and the capture
+template selection keys.
+
+For example,
+ '((\"^%emacs-orgmode$\" . \"o\")
+ (\"\" . \"t\"))
+the messages in \"%emacs-orgmode\" folder will be captured with
+the capture template associated with \"o\" key, and any other
+messages will be captured with the capture template associated
+with \"t\" key."
+ :group 'org-mew
+ :type '(repeat (cons regexp string)))
+
+;; Declare external functions and variables
+(declare-function mew-cache-hit "ext:mew-cache" (fld msg &optional must-hit))
+(declare-function mew-case-folder "ext:mew-func" (case folder))
+(declare-function mew-folder-path-to-folder
+ "ext:mew-func" (path &optional has-proto))
+(declare-function mew-idstr-to-id-list "ext:mew-header" (idstr &optional rev))
+(declare-function mew-folder-remotep "ext:mew-func" (folder))
+(declare-function mew-folder-virtualp "ext:mew-func" (folder))
+(declare-function mew-header-get-value "ext:mew-header"
+ (field &optional as-list))
+(declare-function mew-init "ext:mew" ())
+(declare-function mew-refile-get "ext:mew-refile" (msg))
+(declare-function mew-sinfo-get-case "ext:mew-summary" ())
+(declare-function mew-summary-diag-global "ext:mew-thread" (id opt who))
+(declare-function mew-summary-display "ext:mew-summary2" (&optional redisplay))
+(declare-function mew-summary-folder-name "ext:mew-syntax" (&optional ext))
+(declare-function mew-summary-get-mark "ext:mew-mark" ())
+(declare-function mew-summary-message-number2 "ext:mew-syntax" ())
+(declare-function mew-summary-pick-with-mewl "ext:mew-pick"
+ (pattern folder src-msgs))
+(declare-function mew-summary-refile "ext:mew-refile" (&optional report))
+(declare-function mew-summary-search-msg "ext:mew-const" (msg))
+(declare-function mew-summary-set-message-buffer "ext:mew-summary3" (fld msg))
+(declare-function mew-summary-visit-folder "ext:mew-summary4"
+ (folder &optional goend no-ls))
+(declare-function mew-window-push "ext:mew" ())
+(declare-function mew-expand-folder "ext:mew-func" (folder))
+(declare-function mew-case:folder-folder "ext:mew-func" (case:folder))
+(declare-function mew "ext:mew" (&optional arg))
+(declare-function mew-message-goto-summary "ext:mew-message" ())
+(declare-function mew-summary-mode "ext:mew-summary" ())
+
+(defvar mew-init-p)
+(defvar mew-mark-afterstep-spec)
+(defvar mew-summary-goto-line-then-display)
+
+;; Install the link type
+(org-link-set-parameters "mew" :follow #'org-mew-open :store #'org-mew-store-link)
+
+;; Implementation
+(defun org-mew-store-link ()
+ "Store a link to a Mew folder or message."
+ (save-window-excursion
+ (if (eq major-mode 'mew-message-mode)
+ (mew-message-goto-summary))
+ (when (memq major-mode '(mew-summary-mode mew-virtual-mode))
+ (let ((msgnum (mew-summary-message-number2))
+ (folder-name (org-mew-folder-name)))
+ (if (fboundp 'mew-summary-set-message-buffer)
+ (mew-summary-set-message-buffer folder-name msgnum)
+ (set-buffer (mew-cache-hit folder-name msgnum t)))
+ (let* ((message-id (mew-header-get-value "Message-Id:"))
+ (from (mew-header-get-value "From:"))
+ (to (mew-header-get-value "To:"))
+ (date (mew-header-get-value "Date:"))
+ (subject (mew-header-get-value "Subject:"))
+ desc link)
+ (org-store-link-props :type "mew" :from from :to to :date date
+ :subject subject :message-id message-id)
+ (setq message-id (org-unbracket-string "<" ">" message-id))
+ (setq desc (org-email-link-description))
+ (setq link (concat "mew:" folder-name "#" message-id))
+ (org-add-link-props :link link :description desc)
+ link)))))
+
+(defun org-mew-folder-name ()
+ "Return the folder name of the current message."
+ (save-window-excursion
+ (if (eq major-mode 'mew-message-mode)
+ (mew-message-goto-summary))
+ (let* ((msgnum (mew-summary-message-number2))
+ (mark-info (mew-summary-get-mark)))
+ (if (and org-mew-link-to-refile-destination
+ (eq mark-info ?o)) ; marked as refile
+ (mew-case-folder (mew-sinfo-get-case)
+ (nth 1 (mew-refile-get msgnum)))
+ (let ((folder-or-path (mew-summary-folder-name)))
+ (mew-folder-path-to-folder folder-or-path t))))))
+
+(defun org-mew-open (path)
+ "Follow the Mew message link specified by PATH."
+ (let (folder message-id)
+ (cond ((string-match "\\`\\(+.*\\)+\\+\\([0-9]+\\)\\'" path) ; for Bastien's
+ (setq folder (match-string 1 path))
+ (setq message-id (match-string 2 path)))
+ ((string-match "\\`\\(\\(%#\\)?[^#]+\\)\\(#\\(.*\\)\\)?" path)
+ (setq folder (match-string 1 path))
+ (setq message-id (match-string 4 path)))
+ ((and org-mew-use-id-db (string-match "\\`#\\(.+\\)" path))
+ (setq folder nil)
+ (setq message-id (match-string 1 path)))
+ (t (error "Error in Mew link")))
+ (require 'mew)
+ (mew-window-push)
+ (unless mew-init-p (mew-init))
+ (if (null folder)
+ (progn
+ (mew t)
+ (org-mew-open-by-message-id message-id))
+ (or (org-mew-follow-link folder message-id)
+ (and org-mew-inbox-folder (not (string= org-mew-inbox-folder folder))
+ (org-mew-follow-link org-mew-inbox-folder message-id))
+ (and org-mew-use-id-db
+ (org-mew-open-by-message-id message-id))
+ (error "Message not found")))))
+
+(defun org-mew-follow-link (folder message-id)
+ (unless (org-mew-folder-exists-p folder)
+ (error "No such folder or wrong folder %s" folder))
+ (mew-summary-visit-folder folder)
+ (when message-id
+ (let ((msgnum (org-mew-get-msgnum folder message-id)))
+ (when (mew-summary-search-msg msgnum)
+ (if mew-summary-goto-line-then-display
+ (mew-summary-display))
+ t))))
+
+(defun org-mew-folder-exists-p (folder)
+ (let ((dir (mew-expand-folder folder)))
+ (cond
+ ((mew-folder-virtualp folder) (get-buffer folder))
+ ((null dir) nil)
+ ((mew-folder-remotep (mew-case:folder-folder folder)) t)
+ (t (file-directory-p dir)))))
+
+(defun org-mew-get-msgnum (folder message-id)
+ (if (string-match "\\`[0-9]+\\'" message-id)
+ message-id
+ (let* ((pattern (concat "message-id=" message-id))
+ (msgs (mew-summary-pick-with-mewl pattern folder nil)))
+ (car msgs))))
+
+(defun org-mew-open-by-message-id (message-id)
+ "Open message using ID database."
+ (let ((result (mew-summary-diag-global (format "<%s>" message-id)
+ "-p" "Message")))
+ (unless (eq result t)
+ (error "Message not found"))))
+
+;; In ~/.mew.el, add the following line:
+;; (define-key mew-summary-mode-map "'" 'org-mew-search)
+(defun org-mew-search (&optional arg)
+ "Show all entries related to the message using `org-search-view'.
+
+It shows entries which contains the message ID, the reference
+IDs, or the subject of the message.
+
+With C-u prefix, search for the entries that contains the message
+ID or any of the reference IDs. With C-u C-u prefix, search for
+the message ID or the last reference ID.
+
+The search phase for the subject is extracted with
+`org-mew-subject-alist', which defines the regular expression of
+the subject and the group number to extract. You can get rid of
+\"Re:\" and some other prefix from the subject text."
+ (interactive "P")
+ (when (memq major-mode '(mew-summary-mode mew-virtual-mode))
+ (let ((last-reference-only (equal arg '(16)))
+ (by-subject (null arg))
+ (msgnum (mew-summary-message-number2))
+ (folder-name (mew-summary-folder-name))
+ subject message-id references id-list)
+ (save-window-excursion
+ (if (fboundp 'mew-summary-set-message-buffer)
+ (mew-summary-set-message-buffer folder-name msgnum)
+ (set-buffer (mew-cache-hit folder-name msgnum t)))
+ (setq subject (mew-header-get-value "Subject:"))
+ (setq message-id (mew-header-get-value "Message-Id:"))
+ (setq references (mew-header-get-value "References:")))
+ (setq id-list (mapcar (lambda (id) (org-unbracket-string "<" ">" id))
+ (mew-idstr-to-id-list references)))
+ (if last-reference-only
+ (setq id-list (last id-list))
+ (if message-id
+ (setq id-list (cons (org-unbracket-string "<" ">" message-id)
+ id-list))))
+ (when (and by-subject (stringp subject))
+ (catch 'matched
+ (mapc (lambda (elem)
+ (let ((regexp (car elem))
+ (num (cdr elem)))
+ (when (string-match regexp subject)
+ (setq subject (match-string num subject))
+ (throw 'matched t))))
+ org-mew-subject-alist))
+ (setq id-list (cons subject id-list)))
+ (cond ((null id-list)
+ (error "No message ID to search"))
+ ((equal (length id-list) 1)
+ (org-search-view nil (car id-list)))
+ (t
+ (org-search-view nil (format "{\\(%s\\)}"
+ (mapconcat 'regexp-quote
+ id-list "\\|"))))))
+ (delete-other-windows)))
+
+(defun org-mew-capture (arg)
+ "Guess the capture template from the folder name and invoke `org-capture'.
+
+This selects a capture template in `org-capture-templates' by
+searching for capture template selection keys defined in
+`org-mew-capture-guess-alist' which are associated with the
+regular expression that matches the message's folder name, and
+then invokes `org-capture'.
+
+If the message's folder is a inbox folder, you are prompted to
+put the refile mark on the message and the capture template is
+guessed from the refile destination folder. You can customize
+the inbox folders by `org-mew-capture-inbox-folders'.
+
+If ARG is non-nil, this does not guess the capture template but
+asks you to select the capture template."
+ (interactive "P")
+ (or (not (member (org-mew-folder-name)
+ org-mew-capture-inbox-folders))
+ (eq (mew-summary-get-mark) ?o)
+ (save-window-excursion
+ (if (eq major-mode 'mew-message-mode)
+ (mew-message-goto-summary))
+ (let ((mew-mark-afterstep-spec '((?o 0 0 0 0 0 0 0))))
+ (mew-summary-refile)))
+ (error "No refile folder selected"))
+ (let* ((org-mew-link-to-refile-destination t)
+ (folder-name (org-mew-folder-name))
+ (keys (if arg
+ nil
+ (org-mew-capture-guess-selection-keys folder-name))))
+ (org-capture nil keys)))
+
+(defun org-mew-capture-guess-selection-keys (folder-name)
+ (catch 'found
+ (let ((alist org-mew-capture-guess-alist))
+ (while alist
+ (let ((elem (car alist)))
+ (if (string-match (car elem) folder-name)
+ (throw 'found (cdr elem))))
+ (setq alist (cdr alist))))))
+
+(provide 'org-mew)
+
+;;; org-mew.el ends here
diff --git a/contrib/lisp/org-mime.el b/contrib/lisp/org-mime.el
new file mode 100644
index 0000000..2ced42e
--- /dev/null
+++ b/contrib/lisp/org-mime.el
@@ -0,0 +1,345 @@
+;;; org-mime.el --- org html export for text/html MIME emails
+
+;; Copyright (C) 2010-2015 Eric Schulte
+
+;; Author: Eric Schulte
+;; Keywords: mime, mail, email, html
+;; Homepage: http://orgmode.org/worg/org-contrib/org-mime.php
+;; Version: 0.01
+
+;; This file is not part of GNU Emacs.
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; WYSWYG, html mime composition using org-mode
+;;
+;; For mail composed using the orgstruct-mode minor mode, this
+;; provides a function for converting all or part of your mail buffer
+;; to embedded html as exported by org-mode. Call `org-mime-htmlize'
+;; in a message buffer to convert either the active region or the
+;; entire buffer to html.
+;;
+;; Similarly the `org-mime-org-buffer-htmlize' function can be called
+;; from within an org-mode buffer to convert the buffer to html, and
+;; package the results into an email handling with appropriate MIME
+;; encoding.
+;;
+;; you might want to bind this to a key with something like the
+;; following message-mode binding
+;;
+;; (add-hook 'message-mode-hook
+;; (lambda ()
+;; (local-set-key "\C-c\M-o" 'org-mime-htmlize)))
+;;
+;; and the following org-mode binding
+;;
+;; (add-hook 'org-mode-hook
+;; (lambda ()
+;; (local-set-key "\C-c\M-o" 'org-mime-org-buffer-htmlize)))
+
+;;; Code:
+(require 'cl)
+
+(declare-function org-export-string-as "ox"
+ (string backend &optional body-only ext-plist))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defcustom org-mime-use-property-inheritance nil
+ "Non-nil means al MAIL_ properties apply also for sublevels."
+ :group 'org-mime
+ :type 'boolean)
+
+(defcustom org-mime-default-header
+ "#+OPTIONS: latex:t\n"
+ "Default header to control html export options, and ensure
+ first line isn't assumed to be a title line."
+ :group 'org-mime
+ :type 'string)
+
+(defcustom org-mime-library 'mml
+ "Library to use for marking up MIME elements."
+ :group 'org-mime
+ :type '(choice 'mml 'semi 'vm))
+
+(defcustom org-mime-preserve-breaks t
+ "Used as temporary value of `org-export-preserve-breaks' during
+ mime encoding."
+ :group 'org-mime
+ :type 'boolean)
+
+(defcustom org-mime-fixedwith-wrap
+ "<pre style=\"font-family: courier, monospace;\">\n%s</pre>\n"
+ "Format string used to wrap a fixedwidth HTML email."
+ :group 'org-mime
+ :type 'string)
+
+(defcustom org-mime-html-hook nil
+ "Hook to run over the html buffer before attachment to email.
+ This could be used for example to post-process html elements."
+ :group 'org-mime
+ :type 'hook)
+
+(mapc (lambda (fmt)
+ (eval `(defcustom
+ ,(intern (concat "org-mime-pre-" fmt "-hook"))
+ nil
+ (concat "Hook to run before " fmt " export.\nFunctions "
+ "should take no arguments and will be run in a "
+ "buffer holding\nthe text to be exported."))))
+ '("ascii" "org" "html"))
+
+(defcustom org-mime-send-subtree-hook nil
+ "Hook to run in the subtree in the Org-mode file before export.")
+
+(defcustom org-mime-send-buffer-hook nil
+ "Hook to run in the Org-mode file before export.")
+
+;; example hook, for setting a dark background in <pre style="background-color: #EEE;"> elements
+(defun org-mime-change-element-style (element style)
+ "Set new default htlm style for <ELEMENT> elements in exported html."
+ (while (re-search-forward (format "<%s\\>" element) nil t)
+ (replace-match (format "<%s style=\"%s\"" element style))))
+
+(defun org-mime-change-class-style (class style)
+ "Set new default htlm style for objects with classs=CLASS in
+exported html."
+ (while (re-search-forward (format "class=\"%s\"" class) nil t)
+ (replace-match (format "class=\"%s\" style=\"%s\"" class style))))
+
+;; ;; example addition to `org-mime-html-hook' adding a dark background
+;; ;; color to <pre> elements
+;; (add-hook 'org-mime-html-hook
+;; (lambda ()
+;; (org-mime-change-element-style
+;; "pre" (format "color: %s; background-color: %s;"
+;; "#E6E1DC" "#232323"))
+;; (org-mime-change-class-style
+;; "verse" "border-left: 2px solid gray; padding-left: 4px;")))
+
+(defun org-mime-file (ext path id)
+ "Markup a file for attachment."
+ (case org-mime-library
+ ('mml (format (concat "<#part type=\"%s\" filename=\"%s\" "
+ "disposition=inline id=\"<%s>\">\n<#/part>\n")
+ ext path id))
+ ('semi (concat
+ (format (concat "--[[%s\nContent-Disposition: "
+ "inline;\nContent-ID: <%s>][base64]]\n")
+ ext id)
+ (base64-encode-string
+ (with-temp-buffer
+ (set-buffer-multibyte nil)
+ (binary-insert-encoded-file path)
+ (buffer-string)))))
+ ('vm "?")))
+
+(defun org-mime-multipart (plain html &optional images)
+ "Markup a multipart/alternative with text/plain and text/html alternatives.
+If the html portion of the message includes images wrap the html
+and images in a multipart/related part."
+ (case org-mime-library
+ ('mml (concat "<#multipart type=alternative><#part type=text/plain>"
+ plain
+ (when images "<#multipart type=related>")
+ "<#part type=text/html>"
+ html
+ images
+ (when images "<#/multipart>\n")
+ "<#/multipart>\n"))
+ ('semi (concat
+ "--" "<<alternative>>-{\n"
+ "--" "[[text/plain]]\n" plain
+ (if (and images (> (length images) 0))
+ (concat "--" "<<related>>-{\n"
+ "--" "[[text/html]]\n" html
+ images
+ "--" "}-<<related>>\n")
+ (concat "--" "[[text/html]]\n" html
+ images))
+ "--" "}-<<alternative>>\n"))
+ ('vm "?")))
+
+(defun org-mime-replace-images (str)
+ "Replace images in html files with cid links."
+ (let (html-images)
+ (cons
+ (replace-regexp-in-string ;; replace images in html
+ "src=\"\\([^\"]+\\)\""
+ (lambda (text)
+ (format
+ "src=\"cid:%s\""
+ (let* ((url (and (string-match "src=\"\\([^\"]+\\)\"" text)
+ (match-string 1 text)))
+ (path (expand-file-name
+ url temporary-file-directory))
+ (ext (file-name-extension path))
+ (id (replace-regexp-in-string "[\/\\\\]" "_" path)))
+ (add-to-list 'html-images
+ (org-mime-file (concat "image/" ext) path id))
+ id)))
+ str)
+ html-images)))
+
+(defun org-mime-htmlize (&optional arg)
+ "Export to HTML an email body composed using `mml-mode'.
+If called with an active region only export that region,
+otherwise export the entire body."
+ (interactive "P")
+ (require 'ox-org)
+ (require 'ox-html)
+ (let* ((region-p (org-region-active-p))
+ (html-start (or (and region-p (region-beginning))
+ (save-excursion
+ (goto-char (point-min))
+ (search-forward mail-header-separator)
+ (+ (point) 1))))
+ (html-end (or (and region-p (region-end))
+ ;; TODO: should catch signature...
+ (point-max)))
+ (raw-body (concat org-mime-default-header
+ (buffer-substring html-start html-end)))
+ (body (org-export-string-as raw-body 'org t))
+ ;; because we probably don't want to export a huge style file
+ (org-export-htmlize-output-type 'inline-css)
+ ;; makes the replies with ">"s look nicer
+ (org-export-preserve-breaks org-mime-preserve-breaks)
+ ;; dvipng for inline latex because MathJax doesn't work in mail
+ (org-html-with-latex 'dvipng)
+ ;; to hold attachments for inline html images
+ (html-and-images
+ (org-mime-replace-images
+ (org-export-string-as raw-body 'html t)))
+ (html-images (unless arg (cdr html-and-images)))
+ (html (org-mime-apply-html-hook
+ (if arg
+ (format org-mime-fixedwith-wrap body)
+ (car html-and-images)))))
+ (delete-region html-start html-end)
+ (save-excursion
+ (goto-char html-start)
+ (insert (org-mime-multipart
+ body html (mapconcat 'identity html-images "\n"))))))
+
+(defun org-mime-apply-html-hook (html)
+ (if org-mime-html-hook
+ (with-temp-buffer
+ (insert html)
+ (goto-char (point-min))
+ (run-hooks 'org-mime-html-hook)
+ (buffer-string))
+ html))
+
+(defmacro org-mime-try (&rest body)
+ `(condition-case nil ,@body (error nil)))
+
+(defun org-mime-send-subtree (&optional fmt)
+ (save-restriction
+ (org-narrow-to-subtree)
+ (run-hooks 'org-mime-send-subtree-hook)
+ (let* ((mp (lambda (p) (org-entry-get nil p org-mime-use-property-inheritance)))
+ (file (buffer-file-name (current-buffer)))
+ (subject (or (funcall mp "MAIL_SUBJECT") (nth 4 (org-heading-components))))
+ (to (funcall mp "MAIL_TO"))
+ (cc (funcall mp "MAIL_CC"))
+ (bcc (funcall mp "MAIL_BCC"))
+ (body (buffer-substring
+ (save-excursion (goto-char (point-min))
+ (forward-line 1)
+ (when (looking-at "[ \t]*:PROPERTIES:")
+ (re-search-forward ":END:" nil)
+ (forward-char))
+ (point))
+ (point-max))))
+ (org-mime-compose body (or fmt 'org) file to subject
+ `((cc . ,cc) (bcc . ,bcc))))))
+
+(defun org-mime-send-buffer (&optional fmt)
+ (run-hooks 'org-mime-send-buffer-hook)
+ (let* ((region-p (org-region-active-p))
+ (file (buffer-file-name (current-buffer)))
+ (subject (if (not file) (buffer-name (buffer-base-buffer))
+ (file-name-sans-extension
+ (file-name-nondirectory file))))
+ (body-start (or (and region-p (region-beginning))
+ (save-excursion (goto-char (point-min)))))
+ (body-end (or (and region-p (region-end)) (point-max)))
+ (temp-body-file (make-temp-file "org-mime-export"))
+ (body (buffer-substring body-start body-end)))
+ (org-mime-compose body (or fmt 'org) file nil subject)))
+
+(defun org-mime-compose (body fmt file &optional to subject headers)
+ (require 'message)
+ (compose-mail to subject headers nil)
+ (message-goto-body)
+ (let ((bhook
+ (lambda (body fmt)
+ (let ((hook (intern (concat "org-mime-pre-"
+ (symbol-name fmt)
+ "-hook"))))
+ (if (> (eval `(length ,hook)) 0)
+ (with-temp-buffer
+ (insert body)
+ (goto-char (point-min))
+ (eval `(run-hooks ',hook))
+ (buffer-string))
+ body))))
+ (fmt (if (symbolp fmt) fmt (intern fmt))))
+ (cond
+ ((eq fmt 'org)
+ (require 'ox-org)
+ (insert (org-export-string-as
+ (org-trim (funcall bhook body 'org)) 'org t)))
+ ((eq fmt 'ascii)
+ (require 'ox-ascii)
+ (insert (org-export-string-as
+ (concat "#+Title:\n" (funcall bhook body 'ascii)) 'ascii t)))
+ ((or (eq fmt 'html) (eq fmt 'html-ascii))
+ (require 'ox-ascii)
+ (require 'ox-org)
+ (let* ((org-link-file-path-type 'absolute)
+ ;; we probably don't want to export a huge style file
+ (org-export-htmlize-output-type 'inline-css)
+ (html-and-images
+ (org-mime-replace-images
+ (org-export-string-as (funcall bhook body 'html) 'html t)))
+ (images (cdr html-and-images))
+ (html (org-mime-apply-html-hook (car html-and-images))))
+ (insert (org-mime-multipart
+ (org-export-string-as
+ (org-trim
+ (funcall bhook body (if (eq fmt 'html) 'org 'ascii)))
+ (if (eq fmt 'html) 'org 'ascii) t)
+ html)
+ (mapconcat 'identity images "\n")))))))
+
+(defun org-mime-org-buffer-htmlize ()
+ "Create an email buffer containing the current org-mode file
+ exported to html and encoded in both html and in org formats as
+ mime alternatives."
+ (interactive)
+ (org-mime-send-buffer 'html))
+
+(defun org-mime-subtree ()
+ "Create an email buffer containing the current org-mode subtree
+ exported to a org format or to the format specified by the
+ MAIL_FMT property of the subtree."
+ (interactive)
+ (org-mime-send-subtree
+ (or (org-entry-get nil "MAIL_FMT" org-mime-use-property-inheritance) 'org)))
+
+(provide 'org-mime)
diff --git a/contrib/lisp/org-notify.el b/contrib/lisp/org-notify.el
new file mode 100644
index 0000000..1a1d557
--- /dev/null
+++ b/contrib/lisp/org-notify.el
@@ -0,0 +1,394 @@
+;;; org-notify.el --- Notifications for Org-mode
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Peter Münster <pmrb@free.fr>
+;; Keywords: notification, todo-list, alarm, reminder, pop-up
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Get notifications, when there is something to do.
+;; Sometimes, you need a reminder a few days before a deadline, e.g. to buy a
+;; present for a birthday, and then another notification one hour before to
+;; have enough time to choose the right clothes.
+;; For other events, e.g. rolling the dustbin to the roadside once per week,
+;; you probably need another kind of notification strategy.
+;; This package tries to satisfy the various needs.
+
+;; In order to activate this package, you must add the following code
+;; into your .emacs:
+;;
+;; (require 'org-notify)
+;; (org-notify-start)
+
+;; Example setup:
+;;
+;; (org-notify-add 'appt
+;; '(:time "-1s" :period "20s" :duration 10
+;; :actions (-message -ding))
+;; '(:time "15m" :period "2m" :duration 100
+;; :actions -notify)
+;; '(:time "2h" :period "5m" :actions -message)
+;; '(:time "3d" :actions -email))
+;;
+;; This means for todo-items with `notify' property set to `appt': 3 days
+;; before deadline, send a reminder-email, 2 hours before deadline, start to
+;; send messages every 5 minutes, then 15 minutes before deadline, start to
+;; pop up notification windows every 2 minutes. The timeout of the window is
+;; set to 100 seconds. Finally, when deadline is overdue, send messages and
+;; make noise."
+
+;; Take also a look at the function `org-notify-add'.
+
+;;; Code:
+
+(eval-when-compile (require 'cl))
+(require 'org-element)
+
+(declare-function appt-delete-window "appt" ())
+(declare-function notifications-notify "notifications" (&rest prms))
+(declare-function article-lapsed-string "gnus-art" (t &optional ms))
+
+(defgroup org-notify nil
+ "Options for Org-mode notifications."
+ :tag "Org Notify"
+ :group 'org)
+
+(defcustom org-notify-audible t
+ "Non-nil means beep to indicate notification."
+ :type 'boolean
+ :group 'org-notify)
+
+(defconst org-notify-actions
+ '("show" "show" "done" "done" "hour" "one hour later" "day" "one day later"
+ "week" "one week later")
+ "Possible actions for call-back functions.")
+
+(defconst org-notify-window-buffer-name "*org-notify-%s*"
+ "Buffer-name for the `org-notify-action-window' function.")
+
+(defvar org-notify-map nil
+ "Mapping between names and parameter lists.")
+
+(defvar org-notify-timer nil
+ "Timer of the notification daemon.")
+
+(defvar org-notify-parse-file nil
+ "Index of current file, that `org-element-parse-buffer' is parsing.")
+
+(defvar org-notify-on-action-map nil
+ "Mapping between on-action identifiers and parameter lists.")
+
+(defun org-notify-string->seconds (str)
+ "Convert time string STR to number of seconds."
+ (when str
+ (let* ((conv `(("s" . 1) ("m" . 60) ("h" . ,(* 60 60))
+ ("d" . ,(* 24 60 60)) ("w" . ,(* 7 24 60 60))
+ ("M" . ,(* 30 24 60 60))))
+ (letters (concat
+ (mapcar (lambda (x) (string-to-char (car x))) conv)))
+ (case-fold-search nil))
+ (string-match (concat "\\(-?\\)\\([0-9]+\\)\\([" letters "]\\)") str)
+ (* (string-to-number (match-string 2 str))
+ (cdr (assoc (match-string 3 str) conv))
+ (if (= (length (match-string 1 str)) 1) -1 1)))))
+
+(defun org-notify-convert-deadline (orig)
+ "Convert original deadline from `org-element-parse-buffer' to
+simple timestamp string."
+ (if orig
+ (replace-regexp-in-string "^<\\|>$" ""
+ (plist-get (plist-get orig 'timestamp)
+ :raw-value))))
+
+(defun org-notify-make-todo (heading &rest ignored)
+ "Create one todo item."
+ (macrolet ((get (k) `(plist-get list ,k))
+ (pr (k v) `(setq result (plist-put result ,k ,v))))
+ (let* ((list (nth 1 heading)) (notify (or (get :NOTIFY) "default"))
+ (deadline (org-notify-convert-deadline (get :deadline)))
+ (heading (get :raw-value))
+ result)
+ (when (and (eq (get :todo-type) 'todo) heading deadline)
+ (pr :heading heading) (pr :notify (intern notify))
+ (pr :begin (get :begin))
+ (pr :file (nth org-notify-parse-file (org-agenda-files 'unrestricted)))
+ (pr :timestamp deadline) (pr :uid (md5 (concat heading deadline)))
+ (pr :deadline (- (org-time-string-to-seconds deadline)
+ (float-time))))
+ result)))
+
+(defun org-notify-todo-list ()
+ "Create the todo-list for one org-agenda file."
+ (let* ((files (org-agenda-files 'unrestricted))
+ (max (1- (length files))))
+ (setq org-notify-parse-file
+ (if (or (not org-notify-parse-file) (>= org-notify-parse-file max))
+ 0
+ (1+ org-notify-parse-file)))
+ (save-excursion
+ (with-current-buffer (find-file-noselect
+ (nth org-notify-parse-file files))
+ (org-element-map (org-element-parse-buffer 'headline)
+ 'headline 'org-notify-make-todo)))))
+
+(defun org-notify-maybe-too-late (diff period heading)
+ "Print warning message, when notified significantly later than defined by
+PERIOD."
+ (if (> (/ diff period) 1.5)
+ (message "Warning: notification for \"%s\" behind schedule!" heading))
+ t)
+
+(defun org-notify-process ()
+ "Process the todo-list, and possibly notify user about upcoming or
+forgotten tasks."
+ (macrolet ((prm (k) `(plist-get prms ,k)) (td (k) `(plist-get todo ,k)))
+ (dolist (todo (org-notify-todo-list))
+ (let* ((deadline (td :deadline)) (heading (td :heading))
+ (uid (td :uid)) (last-run-sym
+ (intern (concat ":last-run-" uid))))
+ (dolist (prms (plist-get org-notify-map (td :notify)))
+ (when (< deadline (org-notify-string->seconds (prm :time)))
+ (let ((period (org-notify-string->seconds (prm :period)))
+ (last-run (prm last-run-sym)) (now (float-time))
+ (actions (prm :actions)) diff plist)
+ (when (or (not last-run)
+ (and period (< period (setq diff (- now last-run)))
+ (org-notify-maybe-too-late diff period heading)))
+ (setq prms (plist-put prms last-run-sym now)
+ plist (append todo prms))
+ (if (if (plist-member prms :audible)
+ (prm :audible)
+ org-notify-audible)
+ (ding))
+ (unless (listp actions)
+ (setq actions (list actions)))
+ (dolist (action actions)
+ (funcall (if (fboundp action) action
+ (intern (concat "org-notify-action"
+ (symbol-name action))))
+ plist))))
+ (return)))))))
+
+(defun org-notify-add (name &rest params)
+ "Add a new notification type.
+The NAME can be used in Org-mode property `notify'. If NAME is
+`default', the notification type applies for todo items without
+the `notify' property. This file predefines such a default
+notification type.
+
+Each element of PARAMS is a list with parameters for a given time
+distance to the deadline. This distance must increase from one
+element to the next.
+
+List of possible parameters:
+
+ :time Time distance to deadline, when this type of notification shall
+ start. It's a string: an integral value (positive or negative)
+ followed by a unit (s, m, h, d, w, M).
+ :actions A function or a list of functions to be called to notify the
+ user. Instead of a function name, you can also supply a suffix
+ of one of the various predefined `org-notify-action-xxx'
+ functions.
+ :period Optional: can be used to repeat the actions periodically.
+ Same format as :time.
+ :duration Some actions use this parameter to specify the duration of the
+ notification. It's an integral number in seconds.
+ :audible Overwrite the value of `org-notify-audible' for this action.
+
+For the actions, you can use your own functions or some of the predefined
+ones, whose names are prefixed with `org-notify-action-'."
+ (setq org-notify-map (plist-put org-notify-map name params)))
+
+(defun org-notify-start (&optional secs)
+ "Start the notification daemon.
+If SECS is positive, it's the period in seconds for processing
+the notifications of one org-agenda file, and if negative,
+notifications will be checked only when emacs is idle for -SECS
+seconds. The default value for SECS is 20."
+ (interactive)
+ (if org-notify-timer
+ (org-notify-stop))
+ (setq secs (or secs 20)
+ org-notify-timer (if (< secs 0)
+ (run-with-idle-timer (* -1 secs) t
+ 'org-notify-process)
+ (run-with-timer secs secs 'org-notify-process))))
+
+(defun org-notify-stop ()
+ "Stop the notification daemon."
+ (when org-notify-timer
+ (cancel-timer org-notify-timer)
+ (setq org-notify-timer nil)))
+
+(defun org-notify-on-action (plist key)
+ "User wants to see action."
+ (let ((file (plist-get plist :file))
+ (begin (plist-get plist :begin)))
+ (if (string-equal key "show")
+ (progn
+ (switch-to-buffer (find-file-noselect file))
+ (org-with-wide-buffer
+ (goto-char begin)
+ (show-entry))
+ (goto-char begin)
+ (search-forward "DEADLINE: <")
+ (if (display-graphic-p)
+ (x-focus-frame nil)))
+ (save-excursion
+ (with-current-buffer (find-file-noselect file)
+ (org-with-wide-buffer
+ (goto-char begin)
+ (search-forward "DEADLINE: <")
+ (cond
+ ((string-equal key "done") (org-todo))
+ ((string-equal key "hour") (org-timestamp-change 60 'minute))
+ ((string-equal key "day") (org-timestamp-up-day))
+ ((string-equal key "week") (org-timestamp-change 7 'day)))))))))
+
+(defun org-notify-on-action-notify (id key)
+ "User wants to see action after mouse-click in notify window."
+ (org-notify-on-action (plist-get org-notify-on-action-map id) key)
+ (org-notify-on-close id nil))
+
+(defun org-notify-on-action-button (button)
+ "User wants to see action after button activation."
+ (macrolet ((get (k) `(button-get button ,k)))
+ (org-notify-on-action (get 'plist) (get 'key))
+ (org-notify-delete-window (get 'buffer))
+ (cancel-timer (get 'timer))))
+
+(defun org-notify-delete-window (buffer)
+ "Delete the notification window."
+ (require 'appt)
+ (let ((appt-buffer-name buffer)
+ (appt-audible nil))
+ (appt-delete-window)))
+
+(defun org-notify-on-close (id reason)
+ "Notification window has been closed."
+ (setq org-notify-on-action-map (plist-put org-notify-on-action-map id nil)))
+
+(defun org-notify-action-message (plist)
+ "Print a message."
+ (message "TODO: \"%s\" at %s!" (plist-get plist :heading)
+ (plist-get plist :timestamp)))
+
+(defun org-notify-action-ding (plist)
+ "Make noise."
+ (let ((timer (run-with-timer 0 1 'ding)))
+ (run-with-timer (or (plist-get plist :duration) 3) nil
+ 'cancel-timer timer)))
+
+(defun org-notify-body-text (plist)
+ "Make human readable string for remaining time to deadline."
+ (require 'gnus-art)
+ (format "%s\n(%s)"
+ (replace-regexp-in-string
+ " in the future" ""
+ (article-lapsed-string
+ (time-add (current-time)
+ (seconds-to-time (plist-get plist :deadline))) 2))
+ (plist-get plist :timestamp)))
+
+(defun org-notify-action-email (plist)
+ "Send email to user."
+ (compose-mail user-mail-address (concat "TODO: " (plist-get plist :heading)))
+ (insert (org-notify-body-text plist))
+ (funcall send-mail-function)
+ (flet ((yes-or-no-p (prompt) t))
+ (kill-buffer)))
+
+(defun org-notify-select-highest-window ()
+ "Select the highest window on the frame, that is not is not an
+org-notify window. Mostly copied from `appt-select-lowest-window'."
+ (let ((highest-window (selected-window))
+ (bottom-edge (nth 3 (window-edges)))
+ next-bottom-edge)
+ (walk-windows (lambda (w)
+ (when (and
+ (not (string-match "^\\*org-notify-.*\\*$"
+ (buffer-name
+ (window-buffer w))))
+ (> bottom-edge (setq next-bottom-edge
+ (nth 3 (window-edges w)))))
+ (setq bottom-edge next-bottom-edge
+ highest-window w))) 'nomini)
+ (select-window highest-window)))
+
+(defun org-notify-action-window (plist)
+ "Pop up a window, mostly copied from `appt-disp-window'."
+ (save-excursion
+ (macrolet ((get (k) `(plist-get plist ,k)))
+ (let ((this-window (selected-window))
+ (buf (get-buffer-create
+ (format org-notify-window-buffer-name (get :uid)))))
+ (when (minibufferp)
+ (other-window 1)
+ (and (minibufferp) (display-multi-frame-p) (other-frame 1)))
+ (if (cdr (assq 'unsplittable (frame-parameters)))
+ (progn (set-buffer buf) (display-buffer buf))
+ (unless (or (special-display-p (buffer-name buf))
+ (same-window-p (buffer-name buf)))
+ (org-notify-select-highest-window)
+ (when (>= (window-height) (* 2 window-min-height))
+ (select-window (split-window nil nil 'above))))
+ (switch-to-buffer buf))
+ (setq buffer-read-only nil buffer-undo-list t)
+ (erase-buffer)
+ (insert (format "TODO: %s, %s.\n" (get :heading)
+ (org-notify-body-text plist)))
+ (let ((timer (run-with-timer (or (get :duration) 10) nil
+ 'org-notify-delete-window buf)))
+ (dotimes (i (/ (length org-notify-actions) 2))
+ (let ((key (nth (* i 2) org-notify-actions))
+ (text (nth (1+ (* i 2)) org-notify-actions)))
+ (insert-button text 'action 'org-notify-on-action-button
+ 'key key 'buffer buf 'plist plist 'timer timer)
+ (insert " "))))
+ (shrink-window-if-larger-than-buffer (get-buffer-window buf t))
+ (set-buffer-modified-p nil) (setq buffer-read-only t)
+ (raise-frame (selected-frame)) (select-window this-window)))))
+
+(defun org-notify-action-notify (plist)
+ "Pop up a notification window."
+ (require 'notifications)
+ (let* ((duration (plist-get plist :duration))
+ (id (notifications-notify
+ :title (plist-get plist :heading)
+ :body (org-notify-body-text plist)
+ :timeout (if duration (* duration 1000))
+ :actions org-notify-actions
+ :on-action 'org-notify-on-action-notify)))
+ (setq org-notify-on-action-map
+ (plist-put org-notify-on-action-map id plist))))
+
+(defun org-notify-action-notify/window (plist)
+ "For a graphics display, pop up a notification window, for a text
+terminal an emacs window."
+ (if (display-graphic-p)
+ (org-notify-action-notify plist)
+ (org-notify-action-window plist)))
+
+;;; Provide a minimal default setup.
+(org-notify-add 'default '(:time "1h" :actions -notify/window
+ :period "2m" :duration 60))
+
+(provide 'org-notify)
+
+;;; org-notify.el ends here
diff --git a/contrib/lisp/org-notmuch.el b/contrib/lisp/org-notmuch.el
new file mode 100644
index 0000000..65d7550
--- /dev/null
+++ b/contrib/lisp/org-notmuch.el
@@ -0,0 +1,135 @@
+;;; org-notmuch.el --- Support for links to notmuch messages from within Org-mode
+
+;; Copyright (C) 2010-2014 Matthieu Lemerre
+
+;; Author: Matthieu Lemerre <racin@free.fr>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+
+;; This file is not part of GNU Emacs.
+
+;; This file is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 2, or (at your option)
+;; any later version.
+
+;; This file is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file implements links to notmuch messages and "searchs". A
+;; search is a query to be performed by notmuch; it is the equivalent
+;; to folders in other mail clients. Similarly, mails are refered to
+;; by a query, so both a link can refer to several mails.
+
+;; Links have one the following form
+;; notmuch:<search terms>
+;; notmuch-search:<search terms>.
+
+;; The first form open the queries in notmuch-show mode, whereas the
+;; second link open it in notmuch-search mode. Note that queries are
+;; performed at the time the link is opened, and the result may be
+;; different from whet the link was stored.
+
+;;; Code:
+
+(require 'org)
+
+;; customisable notmuch open functions
+(defcustom org-notmuch-open-function
+ 'org-notmuch-follow-link
+ "Function used to follow notmuch links.
+
+Should accept a notmuch search string as the sole argument."
+ :group 'org-notmuch
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'function)
+
+(defcustom org-notmuch-search-open-function
+ 'org-notmuch-search-follow-link
+ "Function used to follow notmuch-search links.
+
+Should accept a notmuch search string as the sole argument."
+ :group 'org-notmuch
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'function)
+
+
+
+;; Install the link type
+(org-link-set-parameters "notmuch"
+ :follow #'org-notmuch-open
+ :store #'org-notmuch-store-link)
+
+(defun org-notmuch-store-link ()
+ "Store a link to a notmuch search or message."
+ (when (eq major-mode 'notmuch-show-mode)
+ (let* ((message-id (notmuch-show-get-message-id t))
+ (subject (notmuch-show-get-subject))
+ (to (notmuch-show-get-to))
+ (from (notmuch-show-get-from))
+ (date (org-trim (notmuch-show-get-date)))
+ desc link)
+ (org-store-link-props :type "notmuch" :from from :to to :date date
+ :subject subject :message-id message-id)
+ (setq desc (org-email-link-description))
+ (setq link (concat "notmuch:id:" message-id))
+ (org-add-link-props :link link :description desc)
+ link)))
+
+(defun org-notmuch-open (path)
+ "Follow a notmuch message link specified by PATH."
+ (funcall org-notmuch-open-function path))
+
+(defun org-notmuch-follow-link (search)
+ "Follow a notmuch link to SEARCH.
+
+Can link to more than one message, if so all matching messages are shown."
+ (require 'notmuch)
+ (notmuch-show search))
+
+
+
+(org-link-set-parameters "notmuch-search"
+ :follow #'org-notmuch-search-open
+ :store #'org-notmuch-search-store-link)
+
+(defun org-notmuch-search-store-link ()
+ "Store a link to a notmuch search or message."
+ (when (eq major-mode 'notmuch-search-mode)
+ (let ((link (concat "notmuch-search:"
+ (org-link-escape notmuch-search-query-string)))
+ (desc (concat "Notmuch search: " notmuch-search-query-string)))
+ (org-store-link-props :type "notmuch-search"
+ :link link
+ :description desc)
+ link)))
+
+(defun org-notmuch-search-open (path)
+ "Follow a notmuch message link specified by PATH."
+ (message "%s" path)
+ (funcall org-notmuch-search-open-function path))
+
+(defun org-notmuch-search-follow-link (search)
+ "Follow a notmuch link by displaying SEARCH in notmuch-search mode."
+ (require 'notmuch)
+ (notmuch-search (org-link-unescape search)))
+
+
+
+(defun org-notmuch-tree-follow-link (search)
+ "Follow a notmuch link by displaying SEARCH in notmuch-tree mode."
+ (require 'notmuch)
+ (notmuch-tree (org-link-unescape search)))
+
+(provide 'org-notmuch)
+
+;;; org-notmuch.el ends here
diff --git a/contrib/lisp/org-panel.el b/contrib/lisp/org-panel.el
new file mode 100644
index 0000000..dec7241
--- /dev/null
+++ b/contrib/lisp/org-panel.el
@@ -0,0 +1,638 @@
+;;; org-panel.el --- Simple routines for us with bad memory
+;;
+;; Author: Lennart Borgman (lennart O borgman A gmail O com)
+;; Created: Thu Nov 15 15:35:03 2007
+;; Version: 0.21
+;; Lxast-Updated: Wed Nov 21 03:06:03 2007 (3600 +0100)
+;; URL:
+;; Keywords:
+;; Compatibility:
+;;
+;; Features that might be required by this library:
+;;
+;; `easymenu', `font-lock', `noutline', `org', `outline', `syntax',
+;; `time-date'.
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This defines a kind of control panel for `org-mode'. This control
+;; panel should make it fast to move around and edit structure etc.
+;;
+;; To bring up the control panel type
+;;
+;; M-x orgpan-panel
+;;
+;; Type ? there for help.
+;;
+;; I suggest you add the following to your .emacs for quick access of
+;; the panel:
+;;
+;; (eval-after-load 'org-mode
+;; (define-key org-mode-map [(control ?c) ?p] 'orgpan-panel))
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Change log:
+;;
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or
+;; (at your option) any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Code:
+
+(require 'org)
+(require 'outline)
+
+;; Fix-me: this is for testing. A minor mode version interferes badly
+;; with emulation minor modes. On the other hand, the other version
+;; interferes badly with (interactive ...).
+(defvar orgpan-minor-mode-version t)
+
+(defface orgpan-field
+ '((t (:inherit 'widget-field)))
+ "Face for fields."
+ :group 'winsize)
+(defvar orgpan-field-face 'orgpan-field)
+
+(defface orgpan-active-field
+ '((t (:inherit 'highlight)))
+ "Face for fields."
+ :group 'winsize)
+(defvar orgpan-active-field-face 'orgpan-active-field)
+
+(defface orgpan-spaceline
+ '((t (:height 0.2)))
+ "Face for spacing lines."
+ :group 'winsize)
+
+(defcustom orgpan-panel-buttons nil
+ "Panel style, if non-nil use buttons.
+If there are buttons in the panel they are used to change the way
+the arrow keys work. The panel looks something like this, with
+the first button chosen:
+
+ [Navigate] [Restructure] [TODO/Priority]
+ ----------
+ up/down, left: Go to, right: Visibility
+
+The line below the buttons try to give a short hint about what
+the arrow keys does. \(Personally I prefer the version without
+buttons since I then do not have to remember which button is
+active.)"
+ :type 'boolean
+ :group 'winsize)
+
+;; Fix-me: add org-mode-map
+(defconst orgpan-org-mode-commands nil)
+(defconst orgpan-org-commands
+ '(
+ orgpan-copy-subtree
+ orgpan-cut-subtree
+ orgpan-paste-subtree
+ undo
+ ;;
+ ;orgpan-occur
+ ;;
+ org-cycle
+ org-global-cycle
+ outline-up-heading
+ outline-next-visible-heading
+ outline-previous-visible-heading
+ outline-forward-same-level
+ outline-backward-same-level
+ org-todo
+ org-show-todo-tree
+ org-priority-up
+ org-priority-down
+ org-move-subtree-up
+ org-move-subtree-down
+ org-do-promote
+ org-do-demote
+ org-promote-subtree
+ org-demote-subtree))
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Hook functions etc
+
+(defun orgpan-delete-panel ()
+ "Remove the panel."
+ (interactive)
+ (when (buffer-live-p orgpan-panel-buffer)
+ (delete-windows-on orgpan-panel-buffer)
+ (kill-buffer orgpan-panel-buffer))
+ (setq orgpan-panel-buffer nil)
+ (setq orgpan-panel-window nil)
+ (orgpan-panel-minor-mode 0)
+ (remove-hook 'post-command-hook 'orgpan-minor-post-command)
+ (remove-hook 'post-command-hook 'orgpan-mode-post-command)
+ ;;(remove-hook 'window-configuration-change-hook 'orgpan-window-config-change)
+ )
+
+(defvar orgpan-last-command-was-from-panel nil)
+(defun orgpan-mode-pre-command ()
+ (setq orgpan-last-command-was-from-panel nil)
+ (condition-case err
+ (if (not (and (windowp orgpan-org-window)
+ (window-live-p orgpan-org-window)))
+ (progn
+ (setq this-command 'ignore)
+ (orgpan-delete-panel)
+ (message "The window belonging to the panel had disappeared, removed panel."))
+ (let ((buf (window-buffer orgpan-org-window)))
+ (when (with-current-buffer buf
+ (derived-mode-p 'org-mode))
+ (setq orgpan-last-org-buffer buf))
+ ;; Fix me: add a list of those commands that are not
+ ;; meaningful from the panel (for example org-time-stamp)
+ (when (or (memq this-command orgpan-org-commands)
+ (memq this-command orgpan-org-mode-commands)
+ ;; For some reason not all org commands are found above:
+ (string= "org-" (substring (format "%s" this-command) 0 4)))
+ (if (not (with-current-buffer buf
+ (derived-mode-p 'org-mode)))
+ (progn
+ (if (buffer-live-p orgpan-org-buffer)
+ (set-window-buffer orgpan-org-window orgpan-org-buffer)
+ (message "Please use `l' or `b' to choose an org-mode buffer"))
+ (setq this-command 'ignore))
+ (setq orgpan-org-buffer (window-buffer orgpan-org-window))
+ (setq orgpan-last-command-was-from-panel t)
+ (select-window orgpan-org-window)
+ ;;(when (active-minibuffer-window
+ ;;(set-buffer orgpan-org-buffer)
+ ))))
+ (error (lwarn 't :warning "orgpan-pre: %S" err))))
+
+(defun orgpan-mode-post-command ()
+ (condition-case err
+ (progn
+ (unless (and (windowp orgpan-panel-window)
+ (window-live-p orgpan-panel-window)
+ (bufferp orgpan-panel-buffer)
+ (buffer-live-p orgpan-panel-buffer))
+ ;;(orgpan-delete-panel)
+ )
+ (when (and orgpan-last-command-was-from-panel
+ (windowp orgpan-panel-window)
+ (window-live-p orgpan-panel-window))
+ (select-window orgpan-panel-window)
+ (when (derived-mode-p 'orgpan-mode)
+ (setq deactivate-mark t)
+ (when orgpan-panel-buttons
+ (unless (and orgpan-point
+ (= (point) orgpan-point))
+ ;; Go backward so it is possible to click on a "button":
+ (orgpan-backward-field))))))
+ (error (lwarn 't :warning "orgpan-post: %S" err))))
+
+;; (defun orgpan-window-config-change ()
+;; "Check if any frame is displaying an orgpan panel.
+;; If not remove `orgpan-mode-post-command' and this function from
+;; the hooks."
+;; (condition-case err
+;; (unless (and (
+;; (let ((found-pan nil))
+;; (dolist (f (frame-list))
+;; (dolist (w (window-list f 'nomini))
+;; (with-current-buffer (window-buffer w)
+;; (when (derived-mode-p 'orgpan-mode)
+;; (setq found-pan t)))))
+;; (unless found-pan
+;; (remove-hook 'post-command-hook 'orgpan-mode-post-command)
+;; (remove-hook 'window-configuration-change-hook 'orgpan-window-config-change)))
+;; (error (lwarn 't :warning "Error in orgpan-config-change: %S" err))))
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Commands
+
+(defun orgpan-last-buffer ()
+ "Open last org-mode buffer in panels org window."
+ (interactive)
+ (let ((buf (window-buffer orgpan-org-window))
+ (last-buf orgpan-last-org-buffer))
+ (when (with-current-buffer buf
+ (derived-mode-p 'org-mode))
+ (setq orgpan-last-org-buffer buf))
+ (when (eq last-buf buf)
+ (setq last-buf nil))
+ (if (not last-buf)
+ (orgpan-switch-buffer)
+ (set-window-buffer orgpan-org-window last-buf))))
+
+(defun orgpan-switch-buffer ()
+ "Switch to next org-mode buffer in panels org window."
+ (interactive)
+ (let ((buf (window-buffer orgpan-org-window))
+ (org-buffers nil))
+ (with-current-buffer buf
+ (when (derived-mode-p 'org-mode)
+ (bury-buffer buf)
+ (setq orgpan-last-org-buffer buf)))
+ (setq org-buffers (delq nil (mapcar (lambda (buf)
+ (when (with-current-buffer buf
+ (derived-mode-p 'org-mode))
+ buf))
+ (buffer-list))))
+ (setq org-buffers (delq buf org-buffers))
+ (set-window-buffer orgpan-org-window (car org-buffers))
+ (setq orgpan-org-buffer (car org-buffers))))
+
+(defun orgpan-paste-subtree ()
+ (interactive)
+ (if (y-or-n-p "Paste subtree here? ")
+ (org-paste-subtree)
+ (message "Nothing was pasted")))
+
+(defun orgpan-cut-subtree ()
+ (interactive)
+ (let ((heading (progn
+ (org-back-to-heading)
+ (buffer-substring (point) (line-end-position))
+ )))
+ (if (y-or-n-p (format "Do you want to cut the subtree\n%s\n? " heading))
+ (org-cut-subtree)
+ (message "Nothing was cut"))))
+
+(defun orgpan-copy-subtree ()
+ (interactive)
+ (let ((heading (progn
+ (org-back-to-heading)
+ (buffer-substring (point) (line-end-position))
+ )))
+ (if (y-or-n-p (format "Do you want to copy the subtree\n%s\n? " heading))
+ (org-copy-subtree)
+ (message "Nothing was copied"))))
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Buttons
+
+(defvar orgpan-ovl-help nil)
+
+(defun orgpan-check-panel-mode ()
+ (unless (derived-mode-p 'orgpan-mode)
+ (error "Not orgpan-mode in buffer: %s" major-mode)))
+
+(defun orgpan-display-bindings-help ()
+ (orgpan-check-panel-mode)
+ (setq orgpan-point (point))
+ (let* ((ovls (overlays-at (point)))
+ (ovl (car ovls))
+ (help (when ovl (overlay-get ovl 'orgpan-explain))))
+ (dolist (o (overlays-in (point-min) (point-max)))
+ (overlay-put o 'face orgpan-field-face))
+ (overlay-put ovl 'face orgpan-active-field-face)
+ (overlay-put orgpan-ovl-help 'before-string help)))
+
+(defun orgpan-forward-field ()
+ (interactive)
+ (orgpan-check-panel-mode)
+ (let ((pos (next-overlay-change (point))))
+ (unless (overlays-at pos)
+ (setq pos (next-overlay-change pos)))
+ (when (= pos (point-max))
+ (setq pos (point-min))
+ (unless (overlays-at pos)
+ (setq pos (next-overlay-change pos))))
+ (goto-char pos))
+ (orgpan-display-bindings-help))
+
+(defun orgpan-backward-field ()
+ (interactive)
+ (orgpan-check-panel-mode)
+ (when (= (point) (point-min))
+ (goto-char (point-max)))
+ (let ((pos (previous-overlay-change (point))))
+ (unless (overlays-at pos)
+ (setq pos (previous-overlay-change pos)))
+ (goto-char pos))
+ (orgpan-display-bindings-help))
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Mode
+
+(defconst orgpan-mode-map
+ ;; Fix-me: clean up here!
+ ;; Fix-me: viper support
+ (let ((map (make-sparse-keymap)))
+ (define-key map [?q] 'orgpan-delete-panel)
+ (define-key map [??] 'orgpan-help)
+ ;; Copying etc
+ (define-key map [?c] 'orgpan-copy-subtree)
+ (define-key map [?x] 'orgpan-cut-subtree)
+ (define-key map [?p] 'orgpan-paste-subtree)
+ (define-key map [?z] 'undo)
+ ;; Buffers:
+ (define-key map [?b] 'orgpan-switch-buffer)
+ (define-key map [?l] 'orgpan-last-buffer)
+ ;; Some keys for moving between headings. Emacs keys for next/prev
+ ;; line seems ok:
+ (define-key map [(control ?p)] 'outline-previous-visible-heading)
+ (define-key map [(control ?n)] 'outline-next-visible-heading)
+ (define-key map [(shift control ?p)] 'outline-backward-same-level)
+ (define-key map [(shift control ?n)] 'outline-forward-same-level)
+ ;; A mnemunic for up:
+ (define-key map [(control ?u)] 'outline-up-heading)
+ ;; Search sparse tree:
+ ;;
+ ;; Fix-me: Search does not work, some problem with
+ ;; interactive. Probably have to turn the whole thing around and
+ ;; always be in the org buffer, but with a minor mode running
+ ;; there.
+ ;;
+ ;;(define-key map [?s] 'org-sparse-tree)
+ (define-key map [?s] 'orgpan-occur)
+ ;; Same as in org-mode:
+ ;;(define-key map [(control ?c)(control ?v)] 'org-show-todo-tree)
+ ;; Fix-me: This leads to strange problems:
+ ;;(define-key map [t] 'ignore)
+ map))
+
+(defun orgpan-occur ()
+ "Replacement for `org-occur'.
+Technical reasons."
+ (interactive)
+ (let ((rgx (read-from-minibuffer "my mini Regexp: ")))
+ (setq orgpan-last-command-was-from-panel t)
+ (select-window orgpan-org-window)
+ (org-occur rgx)))
+
+(defvar orgpan-panel-window nil
+ "The window showing `orgpan-panel-buffer'.")
+
+(defvar orgpan-panel-buffer nil
+ "The panel buffer.
+There can be only one such buffer at any time.")
+
+(defvar orgpan-org-window nil)
+;;(make-variable-buffer-local 'orgpan-org-window)
+
+;; Fix-me: used?
+(defvar orgpan-org-buffer nil)
+;;(make-variable-buffer-local 'orgpan-org-buffer)
+
+(defvar orgpan-last-org-buffer nil)
+;;(make-variable-buffer-local 'orgpan-last-org-buffer)
+
+(defvar orgpan-point nil)
+;;(make-variable-buffer-local 'orgpan-point)
+
+(defvar viper-emacs-state-mode-list)
+(defvar viper-new-major-mode-buffer-list)
+
+(defun orgpan-avoid-viper-in-buffer ()
+ ;; Fix-me: This is ugly. However see `this-major-mode-requires-vi-state':
+ (set (make-local-variable 'viper-emacs-state-mode-list) '(orgpan-mode))
+ (set (make-local-variable 'viper-new-major-mode-buffer-list) nil)
+ (local-set-key [?\ ] 'ignore))
+
+(define-derived-mode orgpan-mode nil "Org-Panel"
+ "Mode for org-simple.el control panel."
+ (setq buffer-read-only t)
+ (unless orgpan-minor-mode-version
+ (add-hook 'pre-command-hook 'orgpan-mode-pre-command nil t)
+ (add-hook 'post-command-hook 'orgpan-mode-post-command t))
+ (orgpan-avoid-viper-in-buffer)
+ (setq cursor-type nil))
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Panel layout
+
+(defun orgpan-insert-field (text keymap explain)
+ (insert text)
+ (let* ((end (point))
+ (len (length text))
+ (beg (- end len))
+ (ovl (make-overlay beg end)))
+ (overlay-put ovl 'face orgpan-field-face)
+ (overlay-put ovl 'keymap keymap)
+ (overlay-put ovl 'orgpan-explain explain)))
+
+(defconst orgpan-with-keymap
+ (let ((map (make-sparse-keymap)))
+ (set-keymap-parent map org-mode-map)
+ ;; Users are used to tabbing between fields:
+ (define-key map [(tab)] 'orgpan-forward-field)
+ (define-key map [(shift tab)] 'orgpan-backward-field)
+ ;; Now we must use something else for visibility (first does not work if Viper):
+ (define-key map [(meta tab)] 'org-cycle)
+ (define-key map [(control meta tab)] 'org-global-cycle)
+ map))
+
+(defconst orgpan-without-keymap
+ (let ((map (make-sparse-keymap)))
+ (set-keymap-parent map org-mode-map)
+ ;; Visibility (those are in org-mode-map):
+ ;;(define-key map [tab] 'org-cycle)
+ ;;(define-key map [(shift tab)] 'org-global-cycle)
+ ;; Navigate:
+ (define-key map [left] 'outline-up-heading)
+ (define-key map [right] 'org-cycle)
+ (define-key map [up] 'outline-previous-visible-heading)
+ (define-key map [down] 'outline-next-visible-heading)
+ (define-key map [(shift down)] 'outline-forward-same-level)
+ (define-key map [(shift up)] 'outline-backward-same-level)
+ ;; Restructure:
+ (define-key map [(control up)] 'org-move-subtree-up)
+ (define-key map [(control down)] 'org-move-subtree-down)
+ (define-key map [(control left)] 'org-do-promote)
+ (define-key map [(control right)] 'org-do-demote)
+ (define-key map [(control shift left)] 'org-promote-subtree)
+ (define-key map [(control shift right)] 'org-demote-subtree)
+ ;; Todo etc
+ (define-key map [?+] 'org-priority-up)
+ (define-key map [?-] 'org-priority-down)
+ (define-key map [?t] 'org-todo)
+ map))
+
+(defun orgpan-make-panel-without-buttons (buf)
+ (with-current-buffer buf
+ (insert (propertize "Org Panel" 'face 'orgpan-active-field))
+ (insert " ? for help, q quit\n")
+ (insert (propertize "arrows" 'face 'font-lock-keyword-face)
+ ": Go to, "
+ (propertize "C-arrows" 'face 'font-lock-keyword-face)
+ ": Edit tree\n"
+ (propertize "cxpz" 'face 'font-lock-keyword-face)
+ ": copy cut paste undo, "
+ (propertize "tT+-" 'face 'font-lock-keyword-face)
+ ": todo priority, "
+ (propertize "s" 'face 'font-lock-keyword-face)
+ " search"
+ )
+ (set-keymap-parent orgpan-mode-map orgpan-without-keymap)
+ ))
+
+(defun orgpan-make-panel-with-buttons (buf)
+ (with-current-buffer buf
+ (let* ((base-map (make-sparse-keymap))
+ (space-line (propertize "\n\n" 'face 'orgpan-spaceline))
+ (arrow-face 'font-lock-keyword-face)
+ (L (propertize "left" 'face arrow-face))
+ (R (propertize "right" 'face arrow-face))
+ (U (propertize "up" 'face arrow-face))
+ (D (propertize "down" 'face arrow-face)))
+ ;;(message D)(sit-for 2)
+ (define-key base-map [left] 'ignore)
+ (define-key base-map [right] 'ignore)
+ (define-key base-map [up] 'ignore)
+ (define-key base-map [down] 'ignore)
+ (define-key base-map [?q] 'delete-window)
+ (define-key base-map [??] 'orgpan-help)
+ ;; Navigating
+ (let ((map (copy-keymap base-map)))
+ (define-key map [left] 'outline-up-heading)
+ (define-key map [right] 'org-cycle)
+ (define-key map [up] 'outline-previous-visible-heading)
+ (define-key map [down] 'outline-next-visible-heading)
+ (define-key map [(shift down)] 'outline-forward-same-level)
+ (define-key map [(shift up)] 'outline-backward-same-level)
+ (orgpan-insert-field "Navigate" map (concat U "/" D ", " L ": Go to, " R ": Visibility")))
+ (insert " ")
+ (let ((map (copy-keymap base-map)))
+ (define-key map [up] 'org-move-subtree-up)
+ (define-key map [down] 'org-move-subtree-down)
+ (define-key map [left] 'org-do-promote)
+ (define-key map [right] 'org-do-demote)
+ (define-key map [(shift left)] 'org-promote-subtree)
+ (define-key map [(shift right)] 'org-demote-subtree)
+ (orgpan-insert-field
+ "Restructure" map
+ (concat U "/" D ": "
+ (propertize "Move" 'face 'font-lock-warning-face)
+ ", " L "/" R ": "
+ (propertize "Level (w S: Subtree Level)" 'face 'font-lock-warning-face))))
+ (insert " ")
+ (let ((map (copy-keymap base-map)))
+ (define-key map [up] 'org-priority-up)
+ (define-key map [down] 'org-priority-down)
+ (define-key map [right] 'org-todo)
+ (orgpan-insert-field "TODO/priority" map
+ (concat R ": TODO, " U "/" D ": Priority")))
+ )
+ (insert " ? for help, q quit\n")
+ (orgpan-display-bindings-help)
+ (setq orgpan-ovl-help (make-overlay (point) (point)))
+ ))
+
+(defun orgpan-make-panel-buffer ()
+ "Make the panel buffer."
+ (let* ((buf-name "*Org Panel*"))
+ (when orgpan-panel-buffer (kill-buffer orgpan-panel-buffer))
+ (setq orgpan-panel-buffer (get-buffer-create buf-name))
+ (if orgpan-panel-buttons
+ (orgpan-make-panel-with-buttons orgpan-panel-buffer)
+ (orgpan-make-panel-without-buttons orgpan-panel-buffer))
+ (with-current-buffer orgpan-panel-buffer
+ (orgpan-mode)
+ (goto-char (point-min)))
+ orgpan-panel-buffer))
+
+(defun orgpan-help ()
+ (interactive)
+ (set-keymap-parent orgpan-with-keymap nil)
+ (set-keymap-parent orgpan-without-keymap nil)
+ (describe-function 'orgpan-panel)
+ (set-keymap-parent orgpan-with-keymap org-mode-map)
+ (set-keymap-parent orgpan-without-keymap org-mode-map)
+ (message "Use 'l' to remove help window")
+ )
+
+(defun orgpan-panel ()
+ "Create a control panel for current `org-mode' buffer.
+The control panel may be used to quickly move around and change
+the headings. The idea is that when you want to to a lot of this
+kind of editing you should be able to do that with few
+keystrokes (and without having to remember the complicated
+keystrokes). A typical situation when this perhaps can be useful
+is when you are looking at your notes file \(usually ~/.notes,
+see `remember-data-file') where you have saved quick notes with
+`remember'.
+
+The keys below are defined in the panel. Note that the commands
+are carried out in the `org-mode' buffer that belongs to the
+panel.
+
+\\{orgpan-mode-map}
+
+In addition to the keys above most of the keys in `org-mode' can
+also be used from the panel.
+
+Note: There are two forms of the control panel, one with buttons
+and one without. The default is without, see
+`orgpan-panel-buttons'. If buttons are used choosing a different
+button changes the binding of the arrow keys."
+ (interactive)
+ (unless (derived-mode-p 'org-mode)
+ (error "Buffer is not in org-mode"))
+ (orgpan-delete-panel)
+ (unless orgpan-org-mode-commands
+ (map-keymap (lambda (ev def)
+ (when (and def
+ (symbolp def)
+ (fboundp def))
+ (setq orgpan-org-mode-commands
+ (cons def orgpan-org-mode-commands))))
+ org-mode-map))
+ ;;(org-back-to-heading)
+ ;;(remove-hook 'window-configuration-change-hook 'orgpan-window-config-change)
+ (setq orgpan-org-window (selected-window))
+ (setq orgpan-panel-window (split-window nil -4 'below))
+ (select-window orgpan-panel-window)
+ (set-window-buffer (selected-window) (orgpan-make-panel-buffer))
+ ;;(set-window-dedicated-p (selected-window) t)
+ ;; The minor mode version starts here:
+ (when orgpan-minor-mode-version
+ (select-window orgpan-org-window)
+ (orgpan-panel-minor-mode 1)
+ (add-hook 'post-command-hook 'orgpan-minor-post-command t)))
+
+(defun orgpan-minor-post-command ()
+ (unless (and
+ ;; Check org window and buffer
+ (windowp orgpan-org-window)
+ (window-live-p orgpan-org-window)
+ (eq orgpan-org-window (selected-window))
+ (derived-mode-p 'org-mode)
+ ;; Check panel window and buffer
+ (windowp orgpan-panel-window)
+ (window-live-p orgpan-panel-window)
+ (bufferp orgpan-panel-buffer)
+ (buffer-live-p orgpan-panel-buffer)
+ (eq (window-buffer orgpan-panel-window) orgpan-panel-buffer)
+ ;; Check minor mode
+ orgpan-panel-minor-mode)
+ (orgpan-delete-panel)))
+
+(define-minor-mode orgpan-panel-minor-mode
+ "Minor mode used in `org-mode' buffer when showing panel."
+ :keymap orgpan-mode-map
+ :lighter " PANEL"
+ :group 'orgpan
+ )
+
+
+(provide 'org-panel)
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; org-panel.el ends here
diff --git a/contrib/lisp/org-passwords.el b/contrib/lisp/org-passwords.el
new file mode 100644
index 0000000..4ebd5a6
--- /dev/null
+++ b/contrib/lisp/org-passwords.el
@@ -0,0 +1,384 @@
+;;; org-passwords.el --- org derived mode for managing passwords
+
+;; Author: Jorge A. Alfaro-Murillo <jorge.alfaro-murillo@yale.edu>
+;; Created: December 26, 2012
+;; Keywords: passwords, password
+
+;; This file is NOT part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code for managing your passwords with
+;; Org-mode. It is part of org/contrib (see http://orgmode.org/). If
+;; you want to contribute with development, or have a problem, do it
+;; here: https://bitbucket.org/alfaromurillo/org-passwords.el
+
+;; A basic setup needs to indicate a passwords file, and a dictionary
+;; for the random words:
+
+;; (require 'org-passwords)
+;; (setq org-passwords-file "~/documents/passwords.gpg")
+;; (setq org-passwords-random-words-dictionary "/etc/dictionaries-common/words")
+
+;; Basic usage:
+
+;; `M-x org-passwords' opens the passwords file in
+;; `org-passwords-mode'.
+
+;; `M-x org-passwords-generate-password' generates a random string
+;; of numbers, lowercase letters and uppercase letters.
+
+;; `C-u M-x org-passwords-generate-password' generates a random
+;; string of numbers, lowercase letters, uppercase letters and
+;; symbols.
+
+;; `M-x org-passwords-random-words' concatenates random words from
+;; the dictionary defined by `org-passwords-random-words-dictionary'
+;; into a string, each word separated by the string defined in
+;; `org-passwords-random-words-separator'.
+
+;; `C-u M-x org-passwords-random-words' does the same as above, and
+;; also makes substitutions according to
+;; `org-passwords-random-words-substitutions'.
+
+;; It is also useful to set up keybindings for the functions
+;; `org-passwords-copy-username', `org-passwords-copy-password' and
+;; `org-passwords-open-url' in the `org-passwords-mode', to easily
+;; make the passwords and usernames available to the facility for
+;; pasting text of the window system (clipboard on X and MS-Windows,
+;; pasteboard on Nextstep/Mac OS, etc.), without inserting them in the
+;; kill-ring. You can set for example:
+
+;; (eval-after-load "org-passwords"
+;; '(progn
+;; (define-key org-passwords-mode-map
+;; (kbd "C-c u")
+;; 'org-passwords-copy-username)
+;; (define-key org-passwords-mode-map
+;; (kbd "C-c p")
+;; 'org-passwords-copy-password)
+;; (kbd "C-c o")
+;; 'org-passwords-open-url)))
+
+;; Finally, to enter new passwords, you can use `org-capture' and a
+;; minimal template like:
+
+;; ("p" "password" entry (file "~/documents/passwords.gpg")
+;; "* %^{Title}\n %^{URL}p %^{USERNAME}p %^{PASSWORD}p")
+
+;; When asked for the password you can then call either
+;; `org-passwords-generate-password' or `org-passwords-random-words'.
+;; Be sure to enable recursive minibuffers to call those functions
+;; from the minibuffer:
+
+;; (setq enable-recursive-minibuffers t)
+
+;;; Code:
+
+(require 'org)
+
+;;;###autoload
+(define-derived-mode org-passwords-mode org-mode
+ "org-passwords-mode"
+ "Mode for storing passwords"
+ nil)
+
+(defgroup org-passwords nil
+ "Options for password management."
+ :group 'org)
+
+(defcustom org-passwords-password-property "PASSWORD"
+ "Name of the property for password entry."
+ :type 'string
+ :group 'org-passwords)
+
+(defcustom org-passwords-username-property "USERNAME"
+ "Name of the property for user name entry."
+ :type 'string
+ :group 'org-passwords)
+
+(defcustom org-passwords-url-property "URL"
+ "Name of the property for URL entry."
+ :type 'string
+ :group 'org-passwords)
+
+(defcustom org-passwords-file nil
+ "Default file name for the file that contains the passwords."
+ :type 'file
+ :group 'org-passwords)
+
+(defcustom org-passwords-time-opened "1 min"
+ "Time that the password file will remain open. It has to be a
+string, a number followed by units."
+ :type 'str
+ :group 'org-passwords)
+
+(defcustom org-passwords-default-password-size "20"
+ "Default number of characters to use in
+org-passwords-generate-password. It has to be a string."
+ :type 'str
+ :group 'org-passwords)
+
+(defcustom org-passwords-random-words-dictionary nil
+ "Default file name for the file that contains a dictionary of
+words for `org-passwords-random-words'. Each non-empty line in
+the file is considered a word."
+ :type 'file
+ :group 'org-passwords)
+
+(defcustom org-passwords-default-random-words-number "5"
+ "Default number of words to use in org-passwords-random-words.
+It has to be a string."
+ :type 'str
+ :group 'org-passwords)
+
+(defvar org-passwords-random-words-separator "-"
+ "A string to separate words in `org-passwords-random-words'.")
+
+(defvar org-passwords-random-words-substitutions
+ '(("a" . "@")
+ ("e" . "3")
+ ("o" . "0"))
+"A list of substitutions to be made with
+`org-passwords-random-words' if it is called with
+`universal-argument'. Each element is pair of
+strings (SUBSTITUTE-THIS . BY-THIS).")
+
+(defun org-passwords-copy-password ()
+ "Makes the password available to other programs. Puts the
+password of the entry at the location of the cursor in the
+facility for pasting text of the window system (clipboard on X
+and MS-Windows, pasteboard on Nextstep/Mac OS, etc.), without
+putting it in the kill ring."
+ (interactive)
+ (funcall interprogram-cut-function
+ (org-entry-get (point)
+ org-passwords-password-property)))
+
+(defun org-passwords-copy-username ()
+ "Makes the password available to other programs. Puts the
+username of the entry at the location of the cursor in the
+facility for pasting text of the window system (clipboard on X
+and MS-Windows, pasteboard on Nextstep/Mac OS, etc.), without
+putting it in the kill ring."
+ (interactive)
+ (funcall interprogram-cut-function
+ (org-entry-get (point)
+ org-passwords-username-property
+ t)))
+
+(defun org-passwords-open-url ()
+ "Browse the URL associated with the entry at the location of
+the cursor."
+ (interactive)
+ (browse-url (org-entry-get (point)
+ org-passwords-url-property
+ t)))
+
+;;;###autoload
+(defun org-passwords (&optional arg)
+ "Open the password file. Open the password file defined by the
+variable `org-password-file' in read-only mode and kill that
+buffer later according to the value of the variable
+`org-passwords-time-opened'. It also adds the `org-password-file'
+to the auto-mode-alist so that it is opened with its mode being
+`org-passwords-mode'.
+
+With prefix arg ARG, the command does not set up a timer to kill the buffer.
+
+With a double prefix arg \\[universal-argument] \\[universal-argument], open the file for editing.
+"
+ (interactive "P")
+ (if org-passwords-file
+ (progn
+ (add-to-list 'auto-mode-alist
+ (cons
+ (regexp-quote
+ (expand-file-name org-passwords-file))
+ 'org-passwords-mode))
+ (if (equal arg '(4))
+ (find-file-read-only org-passwords-file)
+ (if (equal arg '(16))
+ (find-file org-passwords-file)
+ (progn
+ (find-file-read-only org-passwords-file)
+ (org-passwords-set-up-kill-password-buffer)))))
+ (minibuffer-message "No default password file defined. Set the variable `org-password-file'.")))
+
+(defun org-passwords-set-up-kill-password-buffer ()
+ (run-at-time org-passwords-time-opened
+ nil
+ '(lambda ()
+ (if (get-file-buffer org-passwords-file)
+ (kill-buffer
+ (get-file-buffer org-passwords-file))))))
+
+;;; Password generator
+
+;; Set random number seed from current time and pid. Otherwise
+;; `random' gives the same results every time emacs restarts.
+(random t)
+
+(defun org-passwords-generate-password (arg)
+ "Ask a number of characters and insert a password of that size.
+Password has a random string of numbers, lowercase letters, and
+uppercase letters. Argument ARG include symbols."
+ (interactive "P")
+ (let ((number-of-chars
+ (read-from-minibuffer
+ (concat "Number of characters (default "
+ org-passwords-default-password-size
+ "): ")
+ nil
+ nil
+ t
+ nil
+ org-passwords-default-password-size)))
+ (if arg
+ (insert (org-passwords-generate-password-with-symbols "" number-of-chars))
+ (insert (org-passwords-generate-password-without-symbols "" number-of-chars)))))
+
+(defun org-passwords-generate-password-with-symbols (previous-string nums-of-chars)
+ "Return a string consisting of PREVIOUS-STRING and
+NUMS-OF-CHARS random characters."
+ (if (eq nums-of-chars 0) previous-string
+ (org-passwords-generate-password-with-symbols
+ (concat previous-string
+ (char-to-string
+ ;; symbols, letters, numbers are from 33 to 126
+ (+ (random (- 127 33)) 33)))
+ (1- nums-of-chars))))
+
+(defun org-passwords-generate-password-without-symbols (previous-string nums-of-chars)
+ "Return string consisting of PREVIOUS-STRING and NUMS-OF-CHARS
+random numbers, lowercase letters, and numbers."
+ (if (eq nums-of-chars 0)
+ previous-string
+ ; There are 10 numbers, 26 lowercase letters and 26 uppercase
+ ; letters. 10 + 26 + 26 = 62. The number characters go from 48
+ ; to 57, the uppercase letters from 65 to 90, and the lowercase
+ ; from 97 to 122. The following makes each equally likely.
+ (let ((temp-value (random 62)))
+ (cond ((< temp-value 10)
+ ; If temp-value<10, then add a number
+ (org-passwords-generate-password-without-symbols
+ (concat previous-string
+ (char-to-string (+ 48 temp-value)))
+ (1- nums-of-chars)))
+ ((and (> temp-value 9) (< temp-value 36))
+ ; If 9<temp-value<36, then add an uppercase letter
+ (org-passwords-generate-password-without-symbols
+ (concat previous-string
+ (char-to-string (+ 65 (- temp-value 10))))
+ (1- nums-of-chars)))
+ ((> temp-value 35)
+ ; If temp-value>35, then add a lowecase letter
+ (org-passwords-generate-password-without-symbols
+ (concat previous-string
+ (char-to-string (+ 97 (- temp-value 36))))
+ (1- nums-of-chars)))))))
+
+;;; Random words
+
+(defun org-passwords-random-words (arg)
+ "Ask for a number of words and inserts a sequence of that many
+random words from the list in the file
+`org-passwords-random-words-dictionary' separated by
+`org-passwords-random-words-separator'. ARG make substitutions in
+the words as defined by
+`org-passwords-random-words-substitutions'."
+ (interactive "P")
+ (if org-passwords-random-words-dictionary
+ (let ((number-of-words
+ (read-from-minibuffer
+ (concat "Number of words (default "
+ org-passwords-default-random-words-number
+ "): ")
+ nil
+ nil
+ t
+ nil
+ org-passwords-default-random-words-number))
+ (list-of-words
+ (with-temp-buffer
+ (insert-file-contents
+ org-passwords-random-words-dictionary)
+ (split-string (buffer-string) "\n" t))))
+ (insert
+ (org-passwords-substitute
+ (org-passwords-random-words-attach-number-of-words
+ (nth (random (length list-of-words))
+ list-of-words)
+ (1- number-of-words)
+ list-of-words
+ org-passwords-random-words-separator)
+ (if arg
+ org-passwords-random-words-substitutions
+ nil))))
+ (minibuffer-message
+ "No default dictionary file defined. Set the variable `org-passwords-random-words-dictionary'.")))
+
+(defun org-passwords-random-words-attach-number-of-words
+ (previous-string number-of-words list-of-words separator)
+ "Returns a string consisting of PREVIOUS-STRING followed by a
+succession of NUMBER-OF-WORDS random words from the list LIST-OF-WORDS
+separated SEPARATOR."
+ (if (eq number-of-words 0)
+ previous-string
+ (org-passwords-random-words-attach-number-of-words
+ (concat previous-string
+ separator
+ (nth (random (length list-of-words)) list-of-words))
+ (1- number-of-words)
+ list-of-words
+ separator)))
+
+(defun org-passwords-substitute (string-to-change list-of-substitutions)
+ "Substitutes each appearence in STRING-TO-CHANGE of the `car' of
+each element of LIST-OF-SUBSTITUTIONS by the `cdr' of that
+element. For example:
+ (org-passwords-substitute \"ab\" \'((\"a\" . \"b\") (\"b\" . \"c\")))
+ => \"bc\"
+Substitutions are made in order of the list, so for example:
+ (org-passwords-substitute \"ab\" \'((\"ab\" . \"c\") (\"b\" . \"d\")))
+ => \"c\""
+ (if list-of-substitutions
+ (concat (org-passwords-concat-this-with-string
+ (cdar list-of-substitutions)
+ (mapcar (lambda (x)
+ (org-passwords-substitute
+ x
+ (cdr list-of-substitutions)))
+ (split-string string-to-change
+ (caar list-of-substitutions)))))
+ string-to-change))
+
+(defun org-passwords-concat-this-with-string (this list-of-strings)
+ "Put the string THIS in between every string in LIST-OF-STRINGS. For example:
+ (org-passwords-concat-this-with-string \"Here\" \'(\"First\" \"Second\" \"Third\"))
+ => \"FirstHereSencondHereThird\""
+ (if (cdr list-of-strings)
+ (concat (car list-of-strings)
+ this
+ (org-passwords-concat-this-with-string
+ this
+ (cdr list-of-strings)))
+ (car list-of-strings)))
+
+(provide 'org-passwords)
+
+;;; org-passwords.el ends here
diff --git a/contrib/lisp/org-registry.el b/contrib/lisp/org-registry.el
new file mode 100644
index 0000000..402ce30
--- /dev/null
+++ b/contrib/lisp/org-registry.el
@@ -0,0 +1,272 @@
+;;; org-registry.el --- a registry for Org links
+;;
+;; Copyright 2007-2014 Bastien Guerry
+;;
+;; Emacs Lisp Archive Entry
+;; Filename: org-registry.el
+;; Version: 0.1a
+;; Author: Bastien Guerry <bzg@gnu.org>
+;; Maintainer: Bastien Guerry <bzg@gnu.org>
+;; Keywords: org, wp, registry
+;; Description: Shows Org files where the current buffer is linked
+;; URL: http://www.cognition.ens.fr/~guerry/u/org-registry.el
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library add a registry to your Org setup.
+;;
+;; Org files are full of links inserted with `org-store-link'. This links
+;; point to e-mail, webpages, files, dirs, info pages, man pages, etc.
+;; Actually, they come from potentially *everywhere* since Org lets you
+;; define your own storing/following functions.
+;;
+;; So, what if you are on a e-mail, webpage or whatever and want to know if
+;; this buffer has already been linked to somewhere in your agenda files?
+;;
+;; This is were org-registry comes in handy.
+;;
+;; M-x org-registry-show will tell you the name of the file
+;; C-u M-x org-registry-show will directly jump to the file
+;;
+;; In case there are several files where the link lives in:
+;;
+;; M-x org-registry-show will display them in a new window
+;; C-u M-x org-registry-show will prompt for a file to visit
+;;
+;; Add this to your Org configuration:
+;;
+;; (require 'org-registry)
+;; (org-registry-initialize)
+;;
+;; If you want to update the registry with newly inserted links in the
+;; current buffer: M-x org-registry-update
+;;
+;; If you want this job to be done each time you save an Org buffer,
+;; hook 'org-registry-update to the local 'after-save-hook in org-mode:
+;;
+;; (org-registry-insinuate)
+
+;;; Code:
+
+(eval-when-compile
+ (require 'cl))
+
+(defgroup org-registry nil
+ "A registry for Org."
+ :group 'org)
+
+(defcustom org-registry-file
+ (concat (getenv "HOME") "/.org-registry.el")
+ "The Org registry file."
+ :group 'org-registry
+ :type 'file)
+
+(defcustom org-registry-find-file 'find-file-other-window
+ "How to find visit files."
+ :type 'function
+ :group 'org-registry)
+
+(defvar org-registry-alist nil
+ "An alist containing the Org registry.")
+
+;;;###autoload
+(defun org-registry-show (&optional visit)
+ "Show Org files where there are links pointing to the current
+buffer."
+ (interactive "P")
+ (org-registry-initialize)
+ (let* ((blink (or (org-remember-annotation) ""))
+ (link (when (string-match org-bracket-link-regexp blink)
+ (match-string-no-properties 1 blink)))
+ (desc (or (and (string-match org-bracket-link-regexp blink)
+ (match-string-no-properties 3 blink)) "No description"))
+ (files (org-registry-assoc-all link))
+ file point selection tmphist)
+ (cond ((and files visit)
+ ;; result(s) to visit
+ (cond ((< 1 (length files))
+ ;; more than one result
+ (setq tmphist (mapcar (lambda(entry)
+ (format "%s (%d) [%s]"
+ (nth 3 entry) ; file
+ (nth 2 entry) ; point
+ (nth 1 entry))) files))
+ (setq selection (completing-read "File: " tmphist
+ nil t nil 'tmphist))
+ (string-match "\\(.+\\) (\\([0-9]+\\))" selection)
+ (setq file (match-string 1 selection))
+ (setq point (string-to-number (match-string 2 selection))))
+ ((eq 1 (length files))
+ ;; just one result
+ (setq file (nth 3 (car files)))
+ (setq point (nth 2 (car files)))))
+ ;; visit the (selected) file
+ (funcall org-registry-find-file file)
+ (goto-char point)
+ (unless (org-before-first-heading-p)
+ (org-show-context)))
+ ((and files (not visit))
+ ;; result(s) to display
+ (cond ((eq 1 (length files))
+ ;; show one file
+ (message "Link in file %s (%d) [%s]"
+ (nth 3 (car files))
+ (nth 2 (car files))
+ (nth 1 (car files))))
+ (t (org-registry-display-files files link))))
+ (t (message "No link to this in org-agenda-files")))))
+
+(defun org-registry-display-files (files link)
+ "Display files in a separate window."
+ (switch-to-buffer-other-window
+ (get-buffer-create " *Org registry info*"))
+ (erase-buffer)
+ (insert (format "Files pointing to %s:\n\n" link))
+ (let (file)
+ (while (setq file (pop files))
+ (insert (format "%s (%d) [%s]\n" (nth 3 file)
+ (nth 2 file) (nth 1 file)))))
+ (shrink-window-if-larger-than-buffer)
+ (other-window 1))
+
+(defun org-registry-assoc-all (link &optional registry)
+ "Return all associated entries of LINK in the registry."
+ (org-registry-find-all
+ (lambda (entry) (string= link (car entry)))
+ registry))
+
+(defun org-registry-find-all (test &optional registry)
+ "Return all entries satisfying `test' in the registry."
+ (delq nil
+ (mapcar
+ (lambda (x) (and (funcall test x) x))
+ (or registry org-registry-alist))))
+
+;;;###autoload
+(defun org-registry-visit ()
+ "If an Org file contains a link to the current location, visit
+this file."
+ (interactive)
+ (org-registry-show t))
+
+;;;###autoload
+(defun org-registry-initialize (&optional from-scratch)
+ "Initialize `org-registry-alist'.
+If FROM-SCRATCH is non-nil or the registry does not exist yet,
+create a new registry from scratch and eval it. If the registry
+exists, eval `org-registry-file' and make it the new value for
+`org-registry-alist'."
+ (interactive "P")
+ (if (or from-scratch (not (file-exists-p org-registry-file)))
+ ;; create a new registry
+ (let ((files org-agenda-files) file)
+ (while (setq file (pop files))
+ (setq file (expand-file-name file))
+ (mapc (lambda (entry)
+ (add-to-list 'org-registry-alist entry))
+ (org-registry-get-entries file)))
+ (when from-scratch
+ (org-registry-create org-registry-alist)))
+ ;; eval the registry file
+ (with-temp-buffer
+ (insert-file-contents org-registry-file)
+ (eval-buffer))))
+
+;;;###autoload
+(defun org-registry-insinuate ()
+ "Call `org-registry-update' after saving in Org-mode.
+Use with caution. This could slow down things a bit."
+ (interactive)
+ (add-hook 'org-mode-hook
+ (lambda() (add-hook 'after-save-hook
+ 'org-registry-update t t))))
+
+(defun org-registry-get-entries (file)
+ "List Org links in FILE that will be put in the registry."
+ (let (bufstr result)
+ (with-temp-buffer
+ (insert-file-contents file)
+ (goto-char (point-min))
+ (while (re-search-forward org-angle-link-re nil t)
+ (let* ((point (match-beginning 0))
+ (link (match-string-no-properties 0))
+ (desc (match-string-no-properties 0)))
+ (add-to-list 'result (list link desc point file))))
+ (goto-char (point-min))
+ (while (re-search-forward org-bracket-link-regexp nil t)
+ (let* ((point (match-beginning 0))
+ (link (match-string-no-properties 1))
+ (desc (or (match-string-no-properties 3) "No description")))
+ (add-to-list 'result (list link desc point file)))))
+ ;; return the list of new entries
+ result))
+
+;;;###autoload
+(defun org-registry-update ()
+ "Update the registry for the current Org file."
+ (interactive)
+ (unless (eq major-mode 'org-mode) (error "Not in org-mode"))
+ (let* ((from-file (expand-file-name (buffer-file-name)))
+ (new-entries (org-registry-get-entries from-file)))
+ (with-temp-buffer
+ (unless (file-exists-p org-registry-file)
+ (org-registry-initialize t))
+ (find-file org-registry-file)
+ (goto-char (point-min))
+ (while (re-search-forward (concat from-file "\")$") nil t)
+ (let ((end (1+ (match-end 0)))
+ (beg (progn (re-search-backward "^(\"" nil t)
+ (match-beginning 0))))
+ (delete-region beg end)))
+ (goto-char (point-min))
+ (re-search-forward "^(\"" nil t)
+ (goto-char (match-beginning 0))
+ (mapc (lambda (elem)
+ (insert (with-output-to-string (prin1 elem)) "\n"))
+ new-entries)
+ (save-buffer)
+ (kill-buffer (current-buffer)))
+ (message (format "Org registry updated for %s"
+ (file-name-nondirectory from-file)))))
+
+(defun org-registry-create (entries)
+ "Create `org-registry-file' with ENTRIES."
+ (let (entry)
+ (with-temp-buffer
+ (find-file org-registry-file)
+ (erase-buffer)
+ (insert
+ (with-output-to-string
+ (princ ";; -*- emacs-lisp -*-\n")
+ (princ ";; Org registry\n")
+ (princ ";; You shouldn't try to modify this buffer manually\n\n")
+ (princ "(setq org-registry-alist\n'(\n")
+ (while entries
+ (when (setq entry (pop entries))
+ (prin1 entry)
+ (princ "\n")))
+ (princ "))\n")))
+ (save-buffer)
+ (kill-buffer (current-buffer))))
+ (message "Org registry created"))
+
+(provide 'org-registry)
+
+;;; User Options, Variables
+
+;;; org-registry.el ends here
diff --git a/contrib/lisp/org-screen.el b/contrib/lisp/org-screen.el
new file mode 100644
index 0000000..6b870f2
--- /dev/null
+++ b/contrib/lisp/org-screen.el
@@ -0,0 +1,106 @@
+;;; org-screen.el --- Integreate Org-mode with screen.
+
+;; Copyright (c) 2008-2014 Andrew Hyatt
+;;
+;; Author: Andrew Hyatt <ahyatt at gmail dot com>
+;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This file contains functionality to integrate screen and org-mode.
+;; When using org-mode, it is often useful to take tasks that have
+;; some command-line work associated with them, and associate them
+;; with a screen session. Screen is used rather than a direct
+;; terminal to facilitate portability of the resulting session.
+;;
+;; To use screen in org, in your .emacs file, simply put this file in
+;; a directory in your load-path and write:
+;;
+;; (require 'org-screen)
+;;
+;; When have a task and want to start some command-line activity
+;; associated with that task, go to the end of your item and type:
+;;
+;; M-x org-screen
+;;
+;; This will prompt you for a name of a screen session. Type in a
+;; name and it will insert a link into your org file at your current
+;; location.
+;;
+;; When you want to visit the link, go to the link and type C-c C-o to
+;; open the link.
+;;
+;; You may want to get rid of the constant queries about whether you
+;; really want to execute lisp code. Do so by adding to your .emacs:
+;;
+;; (setq org-confirm-elisp-link-function nil)
+
+(require 'term)
+(require 'org)
+
+(defcustom org-screen-program-name "/usr/bin/screen"
+ "Full location of the screen executable."
+ :group 'org-screen
+ :type 'string)
+
+(defun org-screen (name)
+ "Start a screen session with name"
+ (interactive "MScreen name: ")
+ (save-excursion
+ (org-screen-helper name "-S"))
+ (insert-string (concat "[[screen:" name "]]")))
+
+(defun org-screen-buffer-name (name)
+ "Returns the buffer name corresponding to the screen name given."
+ (concat "*screen " name "*"))
+
+(defun org-screen-helper (name arg)
+ "This method will create a screen session with a specified name
+and taking the specified screen arguments. Much of this function
+is copied from ansi-term method."
+
+ ;; Pick the name of the new buffer.
+ (let ((term-ansi-buffer-name
+ (generate-new-buffer-name
+ (org-screen-buffer-name name))))
+ (setq term-ansi-buffer-name
+ (term-ansi-make-term
+ term-ansi-buffer-name org-screen-program-name nil arg name))
+ (set-buffer term-ansi-buffer-name)
+ (term-mode)
+ (term-char-mode)
+ (term-set-escape-char ?\C-x)
+ term-ansi-buffer-name))
+
+(defun org-screen-goto (name)
+ "Open the screen with the specified name in the window"
+ (interactive "MScreen name: ")
+ (let ((screen-buffer-name (org-screen-buffer-name name)))
+ (if (member screen-buffer-name
+ (mapcar 'buffer-name (buffer-list)))
+ (org-pop-to-buffer-same-window screen-buffer-name)
+ (org-pop-to-buffer-same-window (org-screen-helper name "-dr")))))
+
+(if org-link-abbrev-alist
+ (add-to-list 'org-link-abbrev-alist
+ '("screen" . "elisp:(org-screen-goto \"%s\")"))
+ (setq org-link-abbrev-alist
+ '(("screen" . "elisp:(org-screen-goto \"%s\")"))))
+
+(provide 'org-screen)
diff --git a/contrib/lisp/org-screenshot.el b/contrib/lisp/org-screenshot.el
new file mode 100644
index 0000000..1cf6911
--- /dev/null
+++ b/contrib/lisp/org-screenshot.el
@@ -0,0 +1,529 @@
+;;; org-screenshot.el --- Take and manage screenshots in Org-mode files
+;;
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Max Mikhanosha <max@openchat.com>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 8.0
+;;
+;; Released under the GNU General Public License version 3
+;; see: http://www.gnu.org/licenses/gpl-3.0.html
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; NOTE: This library requires external screenshot taking executable "scrot",
+;; which is available as a package from all major Linux distribution. If your
+;; distribution does not have it, source can be found at:
+;;
+;; http://freecode.com/projects/scrot
+;;
+;; org-screenshot.el have been tested with scrot version 0.8.
+;;
+;; Usage:
+;;
+;; (require 'org-screenshot)
+;;
+;; Available commands with default bindings
+;;
+;; `org-screenshot-take' C-c M-s M-t and C-c M-s M-s
+;;
+;; Take the screenshot, C-u argument delays 1 second, double C-u 2 seconds
+;; triple C-u 3 seconds, and subsequent C-u add 2 seconds to the delay.
+;;
+;; Screenshot area is selected with the mouse, or left-click on the window
+;; for an entire window.
+;;
+;; `org-screenshot-rotate-prev' C-c M-s M-p and C-c M-s C-p
+;;
+;; Rotate screenshot before the point to one before it (sorted by date)
+;;
+;; `org-screenshot-rotate-next' C-c M-s M-n and C-c M-s C-n
+;;
+;; Rotate screenshot before the point to one after it
+;;
+;; `org-screenshot-show-unused' C-c M-s M-u and C-c M-s u
+;;
+;; Open dired buffer with screenshots that are not used in current
+;; Org buffer marked
+;;
+;; The screenshot take and rotate commands will update the inline images
+;; if they are already shown, if you are inserting first screenshot in the Org
+;; Buffer (and there are no other images shown), you need to manually display
+;; inline images with C-c C-x C-v
+;;
+;; Screenshot take and rotate commands offer user to continue by by using single
+;; keys, in a manner similar to to "repeat-char" of keyboard macros, user can
+;; continue rotating screenshots by pressing just the last key of the binding
+;;
+;; For example: C-c M-s M-t creates the screenshot and then user can
+;; repeatedly press M-p or M-n to rotate it back and forth with
+;; previously taken ones.
+;;
+
+(require 'org)
+(require 'dired)
+
+(defgroup org-screenshot nil
+ "Options for taking and managing screen-shots"
+ :group 'org-link)
+
+(defcustom org-screenshot-image-directory "./images/"
+ "Directory in which screenshot image files will be stored, it
+be automatically created if it does't already exist."
+ :type 'string
+ :group 'org-screenshot)
+
+(defcustom org-screenshot-file-name-format "screenshot-%2.2d.png"
+ "The string used to generate screenshot file name.
+
+Any %d format string recipe will be expanded with `format'
+function with the argument of a screenshot sequence number.
+
+A sequence like %XXXX will be replaced with string of the same
+length as there are X's, consisting of random characters in the
+range of [A-Za-z]."
+ :type 'string
+ :group 'org-screenshot)
+
+(defcustom org-screenshot-max-tries 200
+ "Number of times we will try to generate generate filename that
+does not exist. With default `org-screenshot-name-format' its the
+limit for number of screenshots, before `org-screenshot-take' is
+unable to come up with a unique name."
+ :type 'integer
+ :group 'org-screenshot)
+
+(defvar org-screenshot-map (make-sparse-keymap)
+ "Map for OrgMode screenshot related commands")
+
+;; prefix
+(org-defkey org-mode-map (kbd "C-c M-s") org-screenshot-map)
+
+;; Mnemonic is Control-C Meta "Screenshot" "Take"
+(org-defkey org-screenshot-map (kbd "M-t") 'org-screenshot-take)
+(org-defkey org-screenshot-map (kbd "M-s") 'org-screenshot-take)
+
+;; No reason to require meta key, since its our own keymap
+(org-defkey org-screenshot-map "s" 'org-screenshot-take)
+(org-defkey org-screenshot-map "t" 'org-screenshot-take)
+
+;; Rotations, the fast rotation user hint, would prefer the modifier
+;; used by the original command that started the rotation
+(org-defkey org-screenshot-map (kbd "M-n") 'org-screenshot-rotate-next)
+(org-defkey org-screenshot-map (kbd "M-p") 'org-screenshot-rotate-prev)
+(org-defkey org-screenshot-map (kbd "C-n") 'org-screenshot-rotate-next)
+(org-defkey org-screenshot-map (kbd "C-p") 'org-screenshot-rotate-prev)
+
+;; Show unused image files in Dired
+(org-defkey org-screenshot-map (kbd "M-u") 'org-screenshot-show-unused)
+(org-defkey org-screenshot-map (kbd "u") 'org-screenshot-show-unused)
+
+
+(random t)
+
+(defun org-screenshot-random-string (length)
+ "Generate a random string of LENGTH consisting of random upper
+case and lower case letters."
+ (let ((name (make-string length ?x)))
+ (dotimes (i length)
+ (let ((n (random 52)))
+ (aset name i (if (< n 26)
+ (+ ?a n)
+ (+ ?A n -26)))))
+ name))
+
+(defvar org-screenshot-process nil
+ "Currently running screenshot process")
+
+(defvar org-screenshot-directory-seq-numbers (make-hash-table :test 'equal))
+
+(defun org-screenshot-update-seq-number (directory &optional reset)
+ "Set `org-screenshot-file-name-format' sequence number for the directory.
+When RESET is NIL, increments the number stored, otherwise sets
+RESET as a new number. Intended to be called if screenshot was
+successful. Updating of sequence number is done in two steps, so
+aborted/canceled screenshot attempts don't increase the number"
+
+ (setq directory (file-name-as-directory directory))
+ (puthash directory (if reset
+ (if (numberp reset) reset 1)
+ (1+ (gethash directory
+ org-screenshot-directory-seq-numbers
+ 0)))
+ org-screenshot-directory-seq-numbers))
+
+(defun org-screenshot-generate-file-name (directory)
+ "Use `org-screenshot-name-format' to generate new screenshot
+file name for a specific directory. Keeps re-generating name if
+it already exists, up to `org-screenshot-max-tries'
+times. Returns just the file, without directory part"
+ (setq directory (file-name-as-directory directory))
+ (when (file-exists-p directory)
+ (let ((tries 0)
+ name
+ had-seq
+ (case-fold-search nil))
+ (while (and (< tries org-screenshot-max-tries)
+ (not name))
+ (incf tries)
+ (let ((tmp org-screenshot-file-name-format)
+ (seq-re "%[-0-9.]*d")
+ (rand-re "%X+"))
+ (when (string-match seq-re tmp)
+ (let ((seq (gethash
+ directory
+ org-screenshot-directory-seq-numbers 1)))
+ (setq tmp
+ (replace-regexp-in-string
+ seq-re (format (match-string 0 tmp) seq)
+ tmp)
+ had-seq t)))
+ (when (string-match rand-re tmp)
+ (setq tmp
+ (replace-regexp-in-string
+ rand-re (org-screenshot-random-string
+ (1- (length (match-string 0 tmp))))
+ tmp t)))
+ (let ((fullname (concat directory tmp)))
+ (if (file-exists-p fullname)
+ (when had-seq (org-screenshot-update-seq-number directory))
+ (setq name tmp)))))
+ name)))
+
+(defun org-screenshot-image-directory ()
+ "Return the `org-screenshot-image-directory', ensuring there is
+trailing slash, and that it exists"
+ (let ((dir (file-name-as-directory org-screenshot-image-directory)))
+ (if (file-exists-p dir)
+ dir
+ (make-directory dir t)
+ dir)))
+
+(defvar org-screenshot-last-file nil
+ "File name of the last taken or rotated screenshot file,
+without directory")
+
+(defun org-screenshot-process-done (process event file
+ orig-buffer
+ orig-delay
+ orig-event)
+ "Called when \"scrot\" process exits. PROCESS and EVENT are
+same arguments as in `set-process-sentinel'. ORIG-BUFFER,
+ORIG-DELAY and ORIG-EVENT are Org Buffer, the screenshot delay
+used, and LAST-INPUT-EVENT values from when screenshot was
+initiated.
+"
+ (setq org-screenshot-process nil)
+ (with-current-buffer (process-buffer process)
+ (if (not (equal event "finished\n"))
+ (progn
+ (insert event)
+ (cond ((save-excursion
+ (goto-char (point-min))
+ (re-search-forward "Key was pressed" nil t))
+ (ding)
+ (message "Key was pressed, screenshot aborted"))
+ (t
+ (display-buffer (process-buffer process))
+ (message "Error running \"scrot\" program")
+ (ding))))
+ (with-current-buffer orig-buffer
+ (let ((link (format "[[file:%s]]" file)))
+ (setq org-screenshot-last-file (file-name-nondirectory file))
+ (let ((beg (point)))
+ (insert link)
+ (when org-inline-image-overlays
+ (org-display-inline-images nil t beg (point))))
+ (unless (< orig-delay 3)
+ (ding))
+ (org-screenshot-rotate-continue t orig-event))))))
+
+
+;;;###autoload
+(defun org-screenshot-take (&optional delay)
+ "Take a screenshot and insert link to it at point, if image
+display is already on (see \\[org-toggle-inline-images])
+screenshot will be displayed as an image
+
+Screen area for the screenshot is selected with the mouse, left
+click on a window screenshots that window, while left click and
+drag selects a region. Pressing any key cancels the screen shot
+
+With `C-u' universal argument waits one second after target is
+selected before taking the screenshot. With double `C-u' wait two
+seconds.
+
+With triple `C-u' wait 3 seconds, and also rings the bell when
+screenshot is done, any more `C-u' after that increases delay by
+2 seconds
+"
+ (interactive "P")
+
+ ;; probably easier way to count number of C-u C-u out there
+ (setq delay
+ (cond ((null delay) 0)
+ ((integerp delay) delay)
+ ((and (consp delay)
+ (integerp (car delay))
+ (plusp (car delay)))
+ (let ((num 1)
+ (limit (car delay))
+ (cnt 0))
+ (while (< num limit)
+ (setq num (* num 4)
+ cnt (+ cnt (if (< cnt 3) 1 2))))
+ cnt))
+ (t (error "Invald delay"))))
+ (when (and org-screenshot-process
+ (member (process-status org-screenshot-process)
+ '(run stop)))
+ (error "scrot process is still running"))
+ (let* ((name (org-screenshot-generate-file-name (org-screenshot-image-directory)))
+ (file (format "%s%s" (org-screenshot-image-directory)
+ name))
+ (path (expand-file-name file)))
+ (when (get-buffer "*scrot*")
+ (with-current-buffer (get-buffer "*scrot*")
+ (erase-buffer)))
+ (setq org-screenshot-process
+ (or
+ (apply 'start-process
+ (append
+ (list "scrot" "*scrot*" "scrot" "-s" path)
+ (when (plusp delay)
+ (list "-d" (format "%d" delay)))))
+ (error "Unable to start scrot process")))
+ (when org-screenshot-process
+ (if (plusp delay)
+ (message "Click on a window, or select a rectangle (delay is %d sec)..."
+ delay)
+ (message "Click on a window, or select a rectangle..."))
+ (set-process-sentinel
+ org-screenshot-process
+ `(lambda (process event)
+ (org-screenshot-process-done
+ process event ,file ,(current-buffer) ,delay ',last-input-event))))))
+
+(defvar org-screenshot-file-list nil
+ "List of files in `org-screenshot-image-directory' used by
+`org-screenshot-rotate-prev' and `org-screenshot-rotate-next'")
+
+(defvar org-screenshot-rotation-index -1)
+
+(make-variable-buffer-local 'org-screenshot-file-list)
+(make-variable-buffer-local 'org-screenshot-rotation-index)
+
+(defun org-screenshot-rotation-init (lastfile)
+ "Initialize variable `org-screenshot-file-list' variabel with
+the list of PNG files in `org-screenshot-image-directory' sorted
+by most recent first"
+ (setq
+ org-screenshot-rotation-index -1
+ org-screenshot-file-list
+ (let ((files (directory-files org-screenshot-image-directory
+ t (image-file-name-regexp) t)))
+ (mapcar 'file-name-nondirectory
+ (sort files
+ (lambda (file1 file2)
+ (let ((mtime1 (nth 5 (file-attributes file1)))
+ (mtime2 (nth 5 (file-attributes file2))))
+ (setq mtime1 (+ (ash (first mtime1) 16)
+ (second mtime1)))
+ (setq mtime2 (+ (ash (first mtime2) 16)
+ (second mtime2)))
+ (> mtime1 mtime2)))))))
+ (let ((n -1) (list org-screenshot-file-list))
+ (while (and list (not (equal (pop list) lastfile)))
+ (incf n))
+ (setq org-screenshot-rotation-index n)))
+
+(defun org-screenshot-do-rotate (dir from-continue-rotating)
+ "Rotate last screenshot with one of the previously taken
+screenshots from the same directory. If DIR is negative, in the
+other direction"
+ (setq org-screenshot-last-file nil)
+ (let* ((ourdir (file-name-as-directory (org-screenshot-image-directory)))
+ done
+ (link-re
+ ;; taken from `org-display-inline-images'
+ (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
+ (substring (image-file-name-regexp) 0 -2)
+ "\\)\\]"))
+ newfile oldfile)
+ (save-excursion
+ ;; Search for link to image file in the same directory before the point
+ (while (not done)
+ (if (not (re-search-backward link-re (point-min) t))
+ (error "Unable to find link to image from %S directory before point" ourdir)
+ (let ((file (concat (or (match-string 3) "") (match-string 4))))
+ (when (equal (file-name-directory file)
+ ourdir)
+ (setq done t
+ oldfile (file-name-nondirectory file))))))
+ (when (or (null org-screenshot-file-list)
+ (and (not from-continue-rotating)
+ (not (member last-command
+ '(org-screenshot-rotate-prev
+ org-screenshot-rotate-next)))))
+ (org-screenshot-rotation-init oldfile))
+ (unless (> (length org-screenshot-file-list) 1)
+ (error "Can't rotate a single image file"))
+ (replace-match "" nil nil nil 1)
+
+ (setq org-screenshot-rotation-index
+ (mod (+ org-screenshot-rotation-index dir)
+ (length org-screenshot-file-list))
+ newfile (nth org-screenshot-rotation-index
+ org-screenshot-file-list))
+ ;; in case we started rotating from the file we just inserted,
+ ;; advance one more time
+ (when (equal oldfile newfile)
+ (setq org-screenshot-rotation-index
+ (mod (+ org-screenshot-rotation-index (if (plusp dir) 1 -1))
+ (length org-screenshot-file-list))
+ newfile (nth org-screenshot-rotation-index
+ org-screenshot-file-list)))
+ (replace-match (concat "file:" ourdir
+ newfile)
+ t t nil 4))
+ ;; out of save-excursion
+ (setq org-screenshot-last-file newfile)
+ (when org-inline-image-overlays
+ (org-display-inline-images nil t (match-beginning 0) (point)))))
+
+;;;###autoload
+(defun org-screenshot-rotate-prev (dir)
+ "Rotate last screenshot with one of the previously taken
+screenshots from the same directory. If DIR is negative, rotate
+in the other direction"
+ (interactive "p")
+ (org-screenshot-do-rotate dir nil)
+ (when org-screenshot-last-file
+ (org-screenshot-rotate-continue nil nil)))
+
+;;;###autoload
+(defun org-screenshot-rotate-next (dir)
+ "Rotate last screenshot with one of the previously taken
+screenshots from the same directory. If DIR is negative, rotate
+in the other direction"
+ (interactive "p")
+ (org-screenshot-do-rotate (- dir) nil)
+ (when org-screenshot-last-file
+ (org-screenshot-rotate-continue nil nil)))
+
+(defun org-screenshot-prefer-same-modifiers (list event)
+ (if (not (eventp nil)) (car list)
+ (let (ret (keys list))
+ (while (and (null ret) keys)
+ (let ((key (car keys)))
+ (if (and (= 1 (length key))
+ (equal (event-modifiers event)
+ (event-modifiers (elt key 0))))
+ (setq ret (car keys))
+ (setq keys (cdr keys)))))
+ (or ret (car list)))))
+
+(defun org-screenshot-rotate-continue (from-take-screenshot orig-event)
+ "Display the message with the name of the last changed
+image-file and inform user that they can rotate by pressing keys
+bound to `org-screenshot-rotate-next' and
+`org-screenshot-rotate-prev' in `org-screenshot-map'
+
+This works similarly to `kmacro-end-or-call-macro' so that user
+can press a long key sequence to invoke the first command, and
+then uses single keys to rotate, until unregognized key is
+entered, at which point event will be unread"
+
+ (let* ((event (if from-take-screenshot orig-event
+ last-input-event))
+ done
+ (prev-key
+ (org-screenshot-prefer-same-modifiers
+ (where-is-internal 'org-screenshot-rotate-prev
+ org-screenshot-map nil)
+ event))
+ (next-key
+ (org-screenshot-prefer-same-modifiers
+ (where-is-internal 'org-screenshot-rotate-next
+ org-screenshot-map nil)
+ event))
+ prev-key-str next-key-str)
+ (when (and (= (length prev-key) 1)
+ (= (length next-key) 1))
+ (setq
+ prev-key-str (format-kbd-macro prev-key nil)
+ next-key-str (format-kbd-macro next-key nil)
+ prev-key (elt prev-key 0)
+ next-key (elt next-key 0))
+ (while (not done)
+ (message "%S - '%s' and '%s' to rotate"
+ org-screenshot-last-file prev-key-str next-key-str)
+ (setq event (read-event))
+ (cond ((equal event prev-key)
+ (clear-this-command-keys t)
+ (org-screenshot-do-rotate 1 t)
+ (setq last-input-event nil))
+ ((equal event next-key)
+ (clear-this-command-keys t)
+ (org-screenshot-do-rotate -1 t)
+ (setq last-input-event nil))
+ (t (setq done t))))
+ (when last-input-event
+ (clear-this-command-keys t)
+ (setq unread-command-events (list last-input-event))))))
+
+;;;###autoload
+(defun org-screenshot-show-unused ()
+ "Open A Dired buffer with unused screenshots marked"
+ (interactive)
+ (let ((files-in-buffer)
+ dired-buffer
+ had-any
+ (image-re (image-file-name-regexp))
+ beg end)
+ (save-excursion
+ (save-restriction
+ (widen)
+ (setq beg (or beg (point-min)) end (or end (point-max)))
+ (goto-char beg)
+ (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
+ (substring (image-file-name-regexp) 0 -2)
+ "\\)\\]"))
+ (case-fold-search t)
+ old file ov img type attrwidth width)
+ (while (re-search-forward re end t)
+ (setq file (concat (or (match-string 3) "") (match-string 4)))
+ (when (and (file-exists-p file)
+ (equal (file-name-directory file)
+ (org-screenshot-image-directory)))
+ (push (file-name-nondirectory file)
+ files-in-buffer))))))
+ (setq dired-buffer (dired-noselect (org-screenshot-image-directory)))
+ (with-current-buffer dired-buffer
+ (dired-unmark-all-files ?\r)
+ (dired-mark-if
+ (let ((file (dired-get-filename 'no-dir t)))
+ (and file (string-match image-re file)
+ (not (member file files-in-buffer))
+ (setq had-any t)))
+ "Unused screenshot"))
+ (when had-any (pop-to-buffer dired-buffer))))
+
+(provide 'org-screenshot)
diff --git a/contrib/lisp/org-secretary.el b/contrib/lisp/org-secretary.el
new file mode 100644
index 0000000..babfb75
--- /dev/null
+++ b/contrib/lisp/org-secretary.el
@@ -0,0 +1,230 @@
+;;; org-secretary.el --- Team management with org-mode
+;; Copyright (C) 2010-2014 Juan Reyero
+;;
+;; Author: Juan Reyero <juan _at_ juanreyero _dot_ com>
+;; Keywords: outlines, tasks, team, management
+;; Homepage: http://juanreyero.com/article/emacs/org-teams.html
+;; Version: 0.02
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This file is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; THis file is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This module implements helper functions for team management. It
+;; makes it easy to keep track of the work of several people. It
+;; keeps context (with whom and where you are) and allows you to use
+;; it to metadata to your notes, and to query the tasks associated
+;; with the people you are with and the place.
+;;
+;; See http://juanreyero.com/article/emacs/org-teams.html for a full
+;; explanation and configuration instructions.
+;;
+;;; Configuration
+;;;;;;;;;;;;;;;;;
+;;
+;; In short; your todos use the TODO keyword, your team's use TASK.
+;; Your org-todo-keywords should look something like this:
+;;
+;; (setq org-todo-keywords
+;; '((sequence "TODO(t)" "|" "DONE(d)" "CANCELLED(c)")
+;; (sequence "TASK(f)" "|" "DONE(d)")
+;; (sequence "MAYBE(m)" "|" "CANCELLED(c)")))
+;;
+;; It helps to distinguish them by color, like this:
+;;
+;; (setq org-todo-keyword-faces
+;; '(("TODO" . (:foreground "DarkOrange1" :weight bold))
+;; ("MAYBE" . (:foreground "sea green"))
+;; ("DONE" . (:foreground "light sea green"))
+;; ("CANCELLED" . (:foreground "forest green"))
+;; ("TASK" . (:foreground "blue"))))
+;;
+;; If you want to keep track of stuck projects you should tag your
+;; projects with :prj:, and define:
+;;
+;; (setq org-tags-exclude-from-inheritance '("prj")
+;; org-stuck-projects '("+prj/-MAYBE-DONE"
+;; ("TODO" "TASK") ()))
+;;
+;; Define a tag that marks TASK entries as yours:
+;;
+;; (setq org-sec-me "juanre")
+;;
+;; Finally, you add the special views to your org-agenda-custom-commands:
+;;
+;; (setq org-agenda-custom-commands
+;; '(("h" "Work todos" tags-todo
+;; "-personal-doat={.+}-dowith={.+}/!-TASK"
+;; ((org-agenda-todo-ignore-scheduled t)))
+;; ("H" "All work todos" tags-todo "-personal/!-TASK-MAYBE"
+;; ((org-agenda-todo-ignore-scheduled nil)))
+;; ("A" "Work todos with doat or dowith" tags-todo
+;; "-personal+doat={.+}|dowith={.+}/!-TASK"
+;; ((org-agenda-todo-ignore-scheduled nil)))
+;; ("j" "TODO dowith and TASK with"
+;; ((org-sec-with-view "TODO dowith")
+;; (org-sec-where-view "TODO doat")
+;; (org-sec-assigned-with-view "TASK with")
+;; (org-sec-stuck-with-view "STUCK with")))
+;; ("J" "Interactive TODO dowith and TASK with"
+;; ((org-sec-who-view "TODO dowith")))))
+;;
+;;; Usage
+;;;;;;;;;
+;;
+;; Do C-c w to say with whom you are meeting (a space-separated list
+;; of names). Maybe do also C-c W to say where you are. Then do C-c a
+;; j to see:
+;; - Todo items defined with TODO (ie, mine) in which the
+;; =dowith= property matches any of the people with me.
+;; - Todo items defined with TODO in which the =doat= property
+;; matches my current location.
+;; - Todo items defined with TASK that are tagged with the name
+;; of any of the people with me (this is, assigned to them).
+;; - Stuck projects tagged with the name of the people with me.
+;;
+;; Use C-c j to add meta-data with the people with me, the
+;; location and the time to entries.
+
+(require 'org)
+
+(defvar org-sec-me nil
+ "Tag that defines TASK todo entries associated to me")
+
+(defvar org-sec-with nil
+ "Value of the :with: property when doing an
+ org-sec-tag-entry. Change it with org-sec-set-with,
+ set to C-c w. Defaults to org-sec-me")
+
+(defvar org-sec-where ""
+ "Value of the :at: property when doing an
+ org-sec-tag-entry. Change it with org-sec-set-with,
+ set to C-c W")
+
+(defvar org-sec-with-history '()
+ "History list of :with: properties")
+
+(defvar org-sec-where-history '()
+ "History list of :where: properties")
+
+(defun org-sec-set-with ()
+ "Changes the value of the org-sec-with variable for use in the
+ next call of org-sec-tag-entry. Leave it empty to default to
+ org-sec-me (you)."
+ (interactive)
+ (setq org-sec-with (let ((w (read-string "With: " nil
+ 'org-sec-with-history "")))
+ (if (string= w "")
+ nil
+ w))))
+(global-set-key "\C-cw" 'org-sec-set-with)
+
+(defun org-sec-set-where ()
+ "Changes the value of the org-sec-where variable for use
+ in the next call of org-sec-tag-entry."
+ (interactive)
+ (setq org-sec-where
+ (read-string "Where: " nil
+ 'org-sec-where-history "")))
+(global-set-key "\C-cW" 'org-sec-set-where)
+
+(defun org-sec-set-dowith ()
+ "Sets the value of the dowith property."
+ (interactive)
+ (let ((do-with
+ (read-string "Do with: "
+ nil 'org-sec-dowith-history "")))
+ (unless (string= do-with "")
+ (org-entry-put nil "dowith" do-with))))
+(global-set-key "\C-cd" 'org-sec-set-dowith)
+
+(defun org-sec-set-doat ()
+ "Sets the value of the doat property."
+ (interactive)
+ (let ((do-at (read-string "Do at: "
+ nil 'org-sec-doat-history "")))
+ (unless (string= do-at "")
+ (org-entry-put nil "doat" do-at))))
+(global-set-key "\C-cD" 'org-sec-set-doat)
+
+(defun org-sec-tag-entry ()
+ "Adds a :with: property with the value of org-sec-with if
+ defined, an :at: property with the value of org-sec-where
+ if defined, and an :on: property with the current time."
+ (interactive)
+ (save-excursion
+ (org-entry-put nil "on" (format-time-string
+ (org-time-stamp-format 'long)
+ (current-time)))
+ (unless (string= org-sec-where "")
+ (org-entry-put nil "at" org-sec-where))
+ (if org-sec-with
+ (org-entry-put nil "with" org-sec-with))))
+(global-set-key "\C-cj" 'org-sec-tag-entry)
+
+(defun join (lst sep &optional pre post)
+ (mapconcat (function (lambda (x) (concat pre x post))) lst sep))
+
+(defun org-sec-get-with ()
+ (if org-sec-with
+ org-sec-with
+ org-sec-me))
+
+(defun org-sec-with-view (par &optional who)
+ "Select tasks marked as dowith=who, where who
+ defaults to the value of org-sec-with."
+ (org-tags-view '(4) (join (split-string (if who
+ who
+ (org-sec-get-with)))
+ "|" "dowith=\"" "\"")))
+
+(defun org-sec-where-view (par)
+ "Select tasks marked as doat=org-sec-where."
+ (org-tags-view '(4) (concat "doat={" org-sec-where "}")))
+
+(defun org-sec-assigned-with-view (par &optional who)
+ "Select tasks assigned to who, by default org-sec-with."
+ (org-tags-view '(4)
+ (concat (join (split-string (if who
+ who
+ (org-sec-get-with)))
+ "|")
+ "/TASK")))
+
+(defun org-sec-stuck-with-view (par &optional who)
+ "Select stuck projects assigned to who, by default
+ org-sec-with."
+ (let ((org-stuck-projects
+ `(,(concat "+prj+"
+ (join (split-string (if who
+ who
+ (org-sec-get-with))) "|")
+ "/-MAYBE-DONE")
+ ("TODO" "TASK") ())))
+ (org-agenda-list-stuck-projects)))
+
+(defun org-sec-who-view (par)
+ "Builds agenda for a given user. Queried. "
+ (let ((who (read-string "Build todo for user/tag: "
+ "" "" "")))
+ (org-sec-with-view "TODO dowith" who)
+ (org-sec-assigned-with-view "TASK with" who)
+ (org-sec-stuck-with-view "STUCK with" who)))
+
+(provide 'org-secretary)
+
+;;; org-secretary.el ends here
diff --git a/contrib/lisp/org-static-mathjax.el b/contrib/lisp/org-static-mathjax.el
new file mode 100644
index 0000000..ac13ee2
--- /dev/null
+++ b/contrib/lisp/org-static-mathjax.el
@@ -0,0 +1,187 @@
+;;; org-static-mathjax.el --- Muse-like tags in Org-mode
+;;
+;; Author: Jan Böker <jan dot boecker at jboecker dot de>
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;; This elisp code integrates Static MathJax into the
+;; HTML export process of Org-mode.
+;;
+;; The supporting files for this package are in contrib/scripts/staticmathjax
+;; Please read the README.org file in that directory for more information.
+
+;; To use it, evaluate it on startup, add the following to your .emacs:
+
+;; (require 'org-static-mathjax)
+;;
+;; You will then have to customize the following two variables:
+;; - org-static-mathjax-app-ini-path
+;; - org-static-mathjax-local-mathjax-path
+;;
+;; If xulrunner is not in your $PATH, you will also need to customize
+;; org-static-mathjax-xulrunner-path.
+;;
+;; If everything is setup correctly, you can trigger Static MathJax on
+;; export to HTML by adding the following line to your Org file:
+;; #+StaticMathJax: embed-fonts:nil output-file-name:"embedded-math.html"
+;;
+;; You can omit either argument.
+;; embed-fonts defaults to nil. If you do not specify output-file-name,
+;; the exported file is overwritten with the static version.
+;;
+;; If embed-fonts is non-nil, the fonts are embedded directly into the
+;; output file using data: URIs.
+;;
+;; output-file-name specifies the file name of the static version. You
+;; can use any arbitrary lisp form here, for example:
+;; output-file-name:(concat (file-name-sans-extension buffer-file-name) "-static.html")
+;;
+;; The StaticMathJax XULRunner application expects a UTF-8 encoded
+;; input file. If the static version displays random characters instead
+;; of your math, add the following line at the top of your Org file:
+;; -*- coding: utf-8; -*-
+;;
+;;; Code:
+
+(defcustom org-static-mathjax-app-ini-path
+ (or (expand-file-name
+ "../scripts/staticmatchjax/application.ini"
+ (file-name-directory (or load-file-name buffer-file-name)))
+ "")
+ "Path to \"application.ini\" of the Static MathJax XULRunner application.
+If you have extracted StaticMathJax to e.g. ~/.local/staticmathjax, set
+this to ~/.local/staticmathjax/application.ini"
+ :type 'string)
+
+(defcustom org-static-mathjax-xulrunner-path
+ "xulrunner"
+ "Path to your xulrunner binary"
+ :type 'string)
+
+(defcustom org-static-mathjax-local-mathjax-path
+ ""
+ "Extract the MathJax zip file somewhere on your local
+hard drive and specify the path here.
+
+The directory has to be writeable, as org-static-mathjax
+creates a temporary file there during export."
+ :type 'string)
+
+(defvar org-static-mathjax-debug
+ nil
+ "If non-nil, org-static-mathjax will print some debug messages")
+
+(defun org-static-mathjax-hook-installer ()
+ "Installs org-static-mathjax-process in after-save-hook.
+
+Sets the following buffer-local variables for org-static-mathjax-process to pick up:
+org-static-mathjax-mathjax-path: The path to MathJax.js as used by Org HTML export
+org-static-mathjax-options: The string given with #+STATICMATHJAX: in the file"
+ (let ((static-mathjax-option-string (plist-get opt-plist :static-mathjax)))
+ (if static-mathjax-option-string
+ (progn (set (make-local-variable 'org-static-mathjax-options) static-mathjax-option-string)
+ (set (make-local-variable 'org-static-mathjax-mathjax-path)
+ (nth 1 (assq 'path org-export-html-mathjax-options)))
+ (let ((mathjax-options (plist-get opt-plist :mathjax)))
+ (if mathjax-options
+ (if (string-match "\\<path:" mathjax-options)
+ (set 'org-static-mathjax-mathjax-path
+ (car (read-from-string
+ (substring mathjax-options (match-end 0))))))))
+ (add-hook 'after-save-hook
+ 'org-static-mathjax-process
+ nil t)))))
+
+
+(defun org-static-mathjax-process ()
+ (save-excursion
+ ; some sanity checking
+ (if (or (string= org-static-mathjax-app-ini-path "")
+ (not (file-exists-p org-static-mathjax-app-ini-path)))
+ (error "Static MathJax: You must customize org-static-mathjax-app-ini-path!"))
+ (if (or (string= org-static-mathjax-local-mathjax-path "")
+ (not (file-exists-p org-static-mathjax-local-mathjax-path)))
+ (error "Static MathJax: You must customize org-static-mathjax-local-mathjax-path!"))
+
+ ; define variables
+ (let* ((options org-static-mathjax-options)
+ (output-file-name buffer-file-name)
+ (input-file-name (let ((temporary-file-directory (file-name-directory org-static-mathjax-local-mathjax-path)))
+ (make-temp-file "org-static-mathjax-" nil ".html")))
+ (html-code (buffer-string))
+ (mathjax-oldpath (concat "src=\"" org-static-mathjax-mathjax-path))
+ (mathjax-newpath (concat "src=\"" org-static-mathjax-local-mathjax-path))
+ embed-fonts)
+ ; read file-local options
+ (mapc
+ (lambda (symbol)
+ (if (string-match (concat "\\<" (symbol-name symbol) ":") options)
+ (set symbol (eval (car (read-from-string
+ (substring options (match-end 0))))))))
+ '(embed-fonts output-file-name))
+
+ ; debug
+ (when org-static-mathjax-debug
+ (message "output file name, embed-fonts")
+ (print output-file-name)
+ (print embed-fonts))
+
+ ; open (temporary) input file, copy contents there, replace MathJax path with local installation
+ (with-temp-buffer
+ (insert html-code)
+ (goto-char 1)
+ (replace-regexp mathjax-oldpath mathjax-newpath)
+ (write-file input-file-name))
+
+ ; prepare argument list for call-process
+ (let ((call-process-args (list org-static-mathjax-xulrunner-path
+ nil nil nil
+ org-static-mathjax-app-ini-path
+ input-file-name
+ output-file-name)))
+ ; if fonts are embedded, just append the --embed-fonts flag
+ (if embed-fonts
+ (add-to-list 'call-process-args "--embed-fonts" t))
+ ; if fonts are not embedded, the XULRunner app must replace all references
+ ; to the font files with the real location (Firefox inserts file:// URLs there,
+ ; because we are using a local MathJax installation here)
+ (if (not embed-fonts)
+ (progn
+ (add-to-list 'call-process-args "--final-mathjax-url" t)
+ (add-to-list 'call-process-args
+ (file-name-directory org-static-mathjax-mathjax-path)
+ t)))
+
+ ; debug
+ (when org-static-mathjax-debug
+ (print call-process-args))
+ ; call it
+ (apply 'call-process call-process-args)
+ ; delete our temporary input file
+ (kill-buffer)
+ (delete-file input-file-name)
+ (let ((backup-file (concat input-file-name "~")))
+ (if (file-exists-p backup-file)
+ (delete-file backup-file)))))))
+
+(add-to-list 'org-export-inbuffer-options-extra
+'("STATICMATHJAX" :static-mathjax))
+
+(add-hook 'org-export-html-final-hook 'org-static-mathjax-hook-installer)
+
+
+(provide 'org-static-mathjax)
diff --git a/contrib/lisp/org-sudoku.el b/contrib/lisp/org-sudoku.el
new file mode 100644
index 0000000..baa9fcd
--- /dev/null
+++ b/contrib/lisp/org-sudoku.el
@@ -0,0 +1,288 @@
+;;; org-sudoku.el --- Greate and solve SUDOKU games in Org tables
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp, games
+;; Homepage: http://orgmode.org
+;; Version: 0.01
+;;
+;; This file is not yet part of GNU Emacs.
+;;
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This is a quick hack to create and solve SUDOKU games in org tables.
+;;
+;; Commands:
+;;
+;; org-sudoku-create Create a new SUDOKU game
+;; org-sudoku-solve-field Solve the field at point in a SUDOKU game
+;; (this is for cheeting when you are stuck)
+;; org-sudoku-solve Solve the entire game
+;;
+
+;;; Code
+
+(require 'org)
+(require 'org-table)
+
+;;; Customization
+
+(defvar org-sudoku-size 9
+ "The size of the sudoku game, 9 for a 9x9 game and 4 for a 4x4 game.
+Larger games do not seem to work because of limited resources - even though
+the algorithm is general.")
+
+(defvar org-sudoku-timeout 2.0
+ "Timeout for finding a solution when creating a new game.
+After this timeout, the program starts over from scratch to create
+a game.")
+
+;;; Interactive commands
+
+(defun org-sudoku-create (nfilled)
+ "Create a sudoku game."
+ (interactive "nNumber of pre-filled fields: ")
+ (let ((sizesq org-sudoku-size)
+ game)
+ (loop for i from 1 to org-sudoku-size do
+ (loop for j from 1 to org-sudoku-size do
+ (push (list (cons i j) 0) game)))
+ (setq game (nreverse game))
+ (random t)
+ (setq game (org-sudoku-build-allowed game))
+ (setq game (org-sudoku-set-field game (cons 1 1)
+ (1+ (random org-sudoku-size))))
+ (catch 'solved
+ (let ((cnt 0))
+ (while t
+ (catch 'abort
+ (message "Attempt %d to create a game" (setq cnt (1+ cnt)))
+ (setq game1 (org-sudoku-deep-copy game))
+ (setq game1 (org-sudoku-solve-game
+ game1 'random (+ (float-time) org-sudoku-timeout)))
+ (when game1
+ (setq game game1)
+ (throw 'solved t))))))
+ (let ((sqrtsize (floor (sqrt org-sudoku-size))))
+ (loop for i from 1 to org-sudoku-size do
+ (insert "| |\n")
+ (if (and (= (mod i sqrtsize) 0) (< i org-sudoku-size))
+ (insert "|-\n")))
+ (backward-char 5)
+ (org-table-align))
+ (while (> (length game) nfilled)
+ (setq game (delete (nth (1+ (random (length game))) game) game)))
+ (mapc (lambda (e)
+ (org-table-put (caar e) (cdar e) (int-to-string (nth 1 e))))
+ game)
+ (org-table-align)
+ (org-table-goto-line 1)
+ (org-table-goto-column 1)
+ (message "Enjoy!")))
+
+(defun org-sudoku-solve ()
+ "Solve the sudoku game in the table at point."
+ (interactive)
+ (unless (org-at-table-p)
+ (error "not at a table"))
+ (let (game)
+ (setq game (org-sudoku-get-game))
+ (setq game (org-sudoku-build-allowed game))
+ (setq game (org-sudoku-solve-game game))
+ ;; Insert the values
+ (mapc (lambda (e)
+ (org-table-put (caar e) (cdar e) (int-to-string (nth 1 e))))
+ game)
+ (org-table-align)))
+
+(defun org-sudoku-solve-field ()
+ "Just solve the field at point.
+This works by solving the whole game, then inserting only the single field."
+ (interactive)
+ (unless (org-at-table-p)
+ (error "Not at a table"))
+ (org-table-check-inside-data-field)
+ (let ((i (org-table-current-dline))
+ (j (org-table-current-column))
+ game)
+ (setq game (org-sudoku-get-game))
+ (setq game (org-sudoku-build-allowed game))
+ (setq game (org-sudoku-solve-game game))
+ (if game
+ (progn
+ (org-table-put i j (number-to-string
+ (nth 1 (assoc (cons i j) game)))
+ 'align)
+ (org-table-goto-line i)
+ (org-table-goto-column j))
+ (error "No solution"))))
+
+;;; Internal functions
+
+(defun org-sudoku-get-game ()
+ "Interpret table at point as sudoku game and read it.
+A game structure is returned."
+ (let (b e g i j game)
+
+ (org-table-goto-line 1)
+ (org-table-goto-column 1)
+ (setq b (point))
+ (org-table-goto-line org-sudoku-size)
+ (org-table-goto-column org-sudoku-size)
+ (setq e (point))
+ (setq g (org-table-copy-region b e))
+ (setq i 0 j 0)
+ (mapc (lambda (c)
+ (setq i (1+ i) j 0)
+ (mapc
+ (lambda (v)
+ (setq j (1+ j))
+ (push (list (cons i j)
+ (string-to-number v))
+ game))
+ c))
+ g)
+ (nreverse game)))
+
+(defun org-sudoku-build-allowed (game)
+ (let (i j v numbers)
+ (loop for i from 1 to org-sudoku-size do
+ (push i numbers))
+ (setq numbers (nreverse numbers))
+ ;; add the lists of allowed values for each entry
+ (setq game (mapcar
+ (lambda (e)
+ (list (car e) (nth 1 e)
+ (if (= (nth 1 e) 0)
+ (copy-sequence numbers)
+ nil)))
+ game))
+ ;; remove the known values from the list of allowed values
+ (mapc
+ (lambda (e)
+ (setq i (caar e) j (cdar e) v (cadr e))
+ (when (> v 0)
+ ;; We do have a value here
+ (mapc
+ (lambda (f)
+ (setq a (assoc f game))
+ (setf (nth 2 a) (delete v (nth 2 a))))
+ (cons (cons i j) (org-sudoku-rel-fields i j)))))
+ game)
+ game))
+
+(defun org-sudoku-find-next-constrained-field (game)
+ (setq game (mapcar (lambda (e) (if (nth 2 e) e nil)) game))
+ (setq game (delq nil game))
+ (let (va vb la lb)
+ (setq game
+ (sort game (lambda (a b)
+ (setq va (nth 1 a) vb (nth 1 b)
+ la (length (nth 2 a)) lb (length (nth 2 b)))
+ (cond
+ ((and (= va 0) (> vb 0)) t)
+ ((and (> va 0) (= vb 0)) nil)
+ ((not (= (* va vb) 0)) nil)
+ (t (< la lb))))))
+ (if (or (not game) (> 0 (nth 1 (car game))))
+ nil
+ (caar game))))
+
+(defun org-sudoku-solve-game (game &optional random stop-at)
+ "Solve GAME.
+If RANDOM is non-nit, select candidates randomly from a fields option.
+If RANDOM is nil, always start with the first allowed value and try
+solving from there.
+STOP-AT can be a float time, the solver will abort at that time because
+it is probably stuck."
+ (let (e v v1 allowed next g)
+ (when (and stop-at
+ (> (float-time) stop-at))
+ (setq game nil)
+ (throw 'abort nil))
+ (while (setq next (org-sudoku-find-next-constrained-field game))
+ (setq e (assoc next game)
+ v (nth 1 e)
+ allowed (nth 2 e))
+ (catch 'solved
+ (if (= (length allowed) 1)
+ (setq game (org-sudoku-set-field game next (car allowed)))
+ (while allowed
+ (setq g (org-sudoku-deep-copy game))
+ (if (not random)
+ (setq v1 (car allowed))
+ (setq v1 (nth (random (length allowed)) allowed)))
+ (setq g (org-sudoku-set-field g next v1))
+ (setq g (org-sudoku-solve-game g random stop-at))
+ (when g
+ (setq game g)
+ (throw 'solved g)))
+ (setq game nil))))
+ (if (or (not game)
+ (org-sudoku-unknown-field-p game))
+ nil
+ game)))
+
+(defun org-sudoku-unknown-field-p (game)
+ "Are there still unknown fields in the game?"
+ (delq nil (mapcar (lambda (e) (if (> (nth 1 e) 0) nil t)) game)))
+
+(defun org-sudoku-deep-copy (game)
+ "Make a copy of the game so that manipulating the copy does not change the parent."
+ (mapcar (lambda(e)
+ (list (car e) (nth 1 e) (copy-sequence (nth 2 e))))
+ game))
+
+(defun org-sudoku-set-field (game field value)
+ "Put VALUE into FIELD, and tell related fields that they cannot be VALUE."
+ (let (i j)
+ (setq i (car field) j (cdr field))
+ (setq a (assoc field game))
+ (setf (nth 1 a) value)
+ (setf (nth 2 a) nil)
+
+ ;; Remove value from all related fields
+ (mapc
+ (lambda (f)
+ (setq a (assoc f game))
+ (setf (nth 2 a) (delete value (nth 2 a))))
+ (org-sudoku-rel-fields i j))
+ game))
+
+(defun org-sudoku-rel-fields (i j)
+ "Compute the list of related fields for field (i j)."
+ (let ((sqrtsize (floor (sqrt org-sudoku-size)))
+ ll imin imax jmin jmax f)
+ (setq f (cons i j))
+ (loop for ii from 1 to org-sudoku-size do
+ (or (= ii i) (push (cons ii j) ll)))
+ (loop for jj from 1 to org-sudoku-size do
+ (or (= jj j) (push (cons i jj) ll)))
+ (setq imin (1+ (* sqrtsize (/ (1- i) sqrtsize)))
+ imax (+ imin sqrtsize -1))
+ (setq jmin (1+ (* sqrtsize (/ (1- j) sqrtsize)))
+ jmax (+ jmin sqrtsize -1))
+ (loop for ii from imin to imax do
+ (loop for jj from jmin to jmax do
+ (setq ff (cons ii jj))
+ (or (equal ff f)
+ (member ff ll)
+ (push ff ll))))
+ ll))
+
+;;; org-sudoku ends here
diff --git a/contrib/lisp/org-toc.el b/contrib/lisp/org-toc.el
new file mode 100644
index 0000000..1c14a4f
--- /dev/null
+++ b/contrib/lisp/org-toc.el
@@ -0,0 +1,508 @@
+;;; org-toc.el --- Table of contents for Org-mode buffer
+
+;; Copyright 2007-2017 Free Software Foundation, Inc.
+;;
+;; Author: Bastien Guerry <bzg@gnu.org>
+;; Keywords: Org table of contents
+;; Homepage: http://www.cognition.ens.fr/~guerry/u/org-toc.el
+;; Version: 0.8
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a browsable table of contents for Org files.
+
+;; Put this file into your load-path and the following into your ~/.emacs:
+;; (require 'org-toc)
+
+;;; Code:
+
+(provide 'org-toc)
+(eval-when-compile
+ (require 'cl))
+
+;;; Custom variables:
+(defvar org-toc-base-buffer nil)
+(defvar org-toc-columns-shown nil)
+(defvar org-toc-odd-levels-only nil)
+(defvar org-toc-config-alist nil)
+(defvar org-toc-cycle-global-status nil)
+(defalias 'org-show-table-of-contents 'org-toc-show)
+
+(defgroup org-toc nil
+ "Options concerning the browsable table of contents of Org-mode."
+ :tag "Org TOC"
+ :group 'org)
+
+(defcustom org-toc-default-depth 1
+ "Default depth when invoking `org-toc-show' without argument."
+ :group 'org-toc
+ :type '(choice
+ (const :tag "same as base buffer" nil)
+ (integer :tag "level")))
+
+(defcustom org-toc-follow-mode nil
+ "Non-nil means navigating through the table of contents will
+move the point in the Org buffer accordingly."
+ :group 'org-toc
+ :type 'boolean)
+
+(defcustom org-toc-info-mode nil
+ "Non-nil means navigating through the table of contents will
+show the properties for the current headline in the echo-area."
+ :group 'org-toc
+ :type 'boolean)
+
+(defcustom org-toc-show-subtree-mode nil
+ "Non-nil means show subtree when going to headline or following
+it while browsing the table of contents."
+ :group 'org-toc
+ :type '(choice
+ (const :tag "show subtree" t)
+ (const :tag "show entry" nil)))
+
+(defcustom org-toc-recenter-mode t
+ "Non-nil means recenter the Org buffer when following the
+headlines in the TOC buffer."
+ :group 'org-toc
+ :type 'boolean)
+
+(defcustom org-toc-recenter 0
+ "Where to recenter the Org buffer when unfolding a subtree.
+This variable is only used when `org-toc-recenter-mode' is set to
+'custom. A value >=1000 will call recenter with no arg."
+ :group 'org-toc
+ :type 'integer)
+
+(defcustom org-toc-info-exclude '("ALLTAGS")
+ "A list of excluded properties when displaying info in the
+echo-area. The COLUMNS property is always exluded."
+ :group 'org-toc
+ :type 'lits)
+
+;;; Org TOC mode:
+(defvar org-toc-mode-map (make-sparse-keymap)
+ "Keymap for `org-toc-mode'.")
+
+(defun org-toc-mode ()
+ "A major mode for browsing the table of contents of an Org buffer.
+
+\\{org-toc-mode-map}"
+ (interactive)
+ (kill-all-local-variables)
+ (use-local-map org-toc-mode-map)
+ (setq mode-name "Org TOC")
+ (setq major-mode 'org-toc-mode))
+
+;; toggle modes
+(define-key org-toc-mode-map "F" 'org-toc-follow-mode)
+(define-key org-toc-mode-map "S" 'org-toc-show-subtree-mode)
+(define-key org-toc-mode-map "s" 'org-toc-store-config)
+(define-key org-toc-mode-map "g" 'org-toc-restore-config)
+(define-key org-toc-mode-map "i" 'org-toc-info-mode)
+(define-key org-toc-mode-map "r" 'org-toc-recenter-mode)
+
+;; navigation keys
+(define-key org-toc-mode-map "p" 'org-toc-previous)
+(define-key org-toc-mode-map "n" 'org-toc-next)
+(define-key org-toc-mode-map "f" 'org-toc-forward)
+(define-key org-toc-mode-map "b" 'org-toc-back)
+(define-key org-toc-mode-map [(left)] 'org-toc-back)
+(define-key org-toc-mode-map [(right)] 'org-toc-forward)
+(define-key org-toc-mode-map [(up)] 'org-toc-previous)
+(define-key org-toc-mode-map [(down)] 'org-toc-next)
+(define-key org-toc-mode-map "1" (lambda() (interactive) (org-toc-show 1 (point))))
+(define-key org-toc-mode-map "2" (lambda() (interactive) (org-toc-show 2 (point))))
+(define-key org-toc-mode-map "3" (lambda() (interactive) (org-toc-show 3 (point))))
+(define-key org-toc-mode-map "4" (lambda() (interactive) (org-toc-show 4 (point))))
+(define-key org-toc-mode-map " " 'org-toc-goto)
+(define-key org-toc-mode-map "q" 'org-toc-quit)
+(define-key org-toc-mode-map "x" 'org-toc-quit)
+;; go to the location and stay in the base buffer
+(define-key org-toc-mode-map [(tab)] 'org-toc-jump)
+(define-key org-toc-mode-map "v" 'org-toc-jump)
+;; go to the location and delete other windows
+(define-key org-toc-mode-map [(return)]
+ (lambda() (interactive) (org-toc-jump t)))
+
+;; special keys
+(define-key org-toc-mode-map "c" 'org-toc-columns)
+(define-key org-toc-mode-map "?" 'org-toc-help)
+(define-key org-toc-mode-map ":" 'org-toc-cycle-subtree)
+(define-key org-toc-mode-map "\C-c\C-o" 'org-open-at-point)
+;; global cycling in the base buffer
+(define-key org-toc-mode-map (kbd "C-S-<iso-lefttab>")
+ 'org-toc-cycle-base-buffer)
+;; subtree cycling in the base buffer
+(define-key org-toc-mode-map [(control tab)]
+ (lambda() (interactive) (org-toc-goto nil t)))
+
+;;; Toggle functions:
+(defun org-toc-follow-mode ()
+ "Toggle follow mode in a `org-toc-mode' buffer."
+ (interactive)
+ (setq org-toc-follow-mode (not org-toc-follow-mode))
+ (message "Follow mode is %s"
+ (if org-toc-follow-mode "on" "off")))
+
+(defun org-toc-info-mode ()
+ "Toggle info mode in a `org-toc-mode' buffer."
+ (interactive)
+ (setq org-toc-info-mode (not org-toc-info-mode))
+ (message "Info mode is %s"
+ (if org-toc-info-mode "on" "off")))
+
+(defun org-toc-show-subtree-mode ()
+ "Toggle show subtree mode in a `org-toc-mode' buffer."
+ (interactive)
+ (setq org-toc-show-subtree-mode (not org-toc-show-subtree-mode))
+ (message "Show subtree mode is %s"
+ (if org-toc-show-subtree-mode "on" "off")))
+
+(defun org-toc-recenter-mode (&optional line)
+ "Toggle recenter mode in a `org-toc-mode' buffer. If LINE is
+specified, then make `org-toc-recenter' use this value."
+ (interactive "P")
+ (setq org-toc-recenter-mode (not org-toc-recenter-mode))
+ (when (numberp line)
+ (setq org-toc-recenter-mode t)
+ (setq org-toc-recenter line))
+ (message "Recenter mode is %s"
+ (if org-toc-recenter-mode
+ (format "on, line %d" org-toc-recenter) "off")))
+
+(defun org-toc-cycle-subtree ()
+ "Locally cycle a headline through two states: 'children and
+'folded"
+ (interactive)
+ (let ((beg (point))
+ (end (save-excursion (end-of-line) (point)))
+ (ov (car (overlays-at (point))))
+ status)
+ (if ov (setq status (overlay-get ov 'status))
+ (setq ov (make-overlay beg end)))
+ ;; change the folding status of this headline
+ (cond ((or (null status) (eq status 'folded))
+ (org-show-children)
+ (message "CHILDREN")
+ (overlay-put ov 'status 'children))
+ ((eq status 'children)
+ (show-branches)
+ (message "BRANCHES")
+ (overlay-put ov 'status 'branches))
+ (t (hide-subtree)
+ (message "FOLDED")
+ (overlay-put ov 'status 'folded)))))
+
+;;; Main show function:
+;; FIXME name this org-before-first-heading-p?
+(defun org-toc-before-first-heading-p ()
+ "Before first heading?"
+ (save-excursion
+ (null (re-search-backward org-outline-regexp-bol nil t))))
+
+;;;###autoload
+(defun org-toc-show (&optional depth position)
+ "Show the table of contents of the current Org-mode buffer."
+ (interactive "P")
+ (if (eq major-mode 'org-mode)
+ (progn (setq org-toc-base-buffer (current-buffer))
+ (setq org-toc-odd-levels-only org-odd-levels-only))
+ (if (eq major-mode 'org-toc-mode)
+ (org-pop-to-buffer-same-window org-toc-base-buffer)
+ (error "Not in an Org buffer")))
+ ;; create the new window display
+ (let ((pos (or position
+ (save-excursion
+ (if (org-toc-before-first-heading-p)
+ (progn (re-search-forward org-outline-regexp-bol nil t)
+ (match-beginning 0))
+ (point))))))
+ (setq org-toc-cycle-global-status org-cycle-global-status)
+ (delete-other-windows)
+ (and (get-buffer "*org-toc*") (kill-buffer "*org-toc*"))
+ (switch-to-buffer-other-window
+ (make-indirect-buffer org-toc-base-buffer "*org-toc*"))
+ ;; make content before 1st headline invisible
+ (goto-char (point-min))
+ (let* ((beg (point-min))
+ (end (and (re-search-forward "^\\*" nil t)
+ (1- (match-beginning 0))))
+ (ov (make-overlay beg end))
+ (help (format "Table of contents for %s (press ? for a quick help):\n"
+ (buffer-name org-toc-base-buffer))))
+ (overlay-put ov 'invisible t)
+ (overlay-put ov 'before-string help))
+ ;; build the browsable TOC
+ (cond (depth
+ (let* ((dpth (if org-toc-odd-levels-only
+ (1- (* depth 2)) depth)))
+ (org-content dpth)
+ (setq org-toc-cycle-global-status
+ `(org-content ,dpth))))
+ ((null org-toc-default-depth)
+ (if (eq org-toc-cycle-global-status 'overview)
+ (progn (org-overview)
+ (setq org-cycle-global-status 'overview)
+ (run-hook-with-args 'org-cycle-hook 'overview))
+ (progn (org-overview)
+ ;; FIXME org-content to show only headlines?
+ (org-content)
+ (setq org-cycle-global-status 'contents)
+ (run-hook-with-args 'org-cycle-hook 'contents))))
+ (t (let* ((dpth0 org-toc-default-depth)
+ (dpth (if org-toc-odd-levels-only
+ (1- (* dpth0 2)) dpth0)))
+ (org-content dpth)
+ (setq org-toc-cycle-global-status
+ `(org-content ,dpth)))))
+ (goto-char pos))
+ (move-beginning-of-line nil)
+ (org-toc-mode)
+ (shrink-window-if-larger-than-buffer)
+ (setq buffer-read-only t))
+
+;;; Navigation functions:
+(defun org-toc-goto (&optional jump cycle)
+ "From Org TOC buffer, follow the targeted subtree in the Org window.
+If JUMP is non-nil, go to the base buffer.
+If JUMP is 'delete, go to the base buffer and delete other windows.
+If CYCLE is non-nil, cycle the targeted subtree in the Org window."
+ (interactive)
+ (let ((pos (point))
+ (toc-buf (current-buffer)))
+ (switch-to-buffer-other-window org-toc-base-buffer)
+ (goto-char pos)
+ (if cycle (org-cycle)
+ (progn (org-overview)
+ (if org-toc-show-subtree-mode
+ (org-show-subtree)
+ (org-show-entry))
+ (org-show-context)))
+ (if org-toc-recenter-mode
+ (if (>= org-toc-recenter 1000) (recenter)
+ (recenter org-toc-recenter)))
+ (cond ((null jump)
+ (switch-to-buffer-other-window toc-buf))
+ ((eq jump 'delete)
+ (delete-other-windows)))))
+
+(defun org-toc-cycle-base-buffer ()
+ "Call `org-cycle' with a prefix argument in the base buffer."
+ (interactive)
+ (switch-to-buffer-other-window org-toc-base-buffer)
+ (org-cycle t)
+ (other-window 1))
+
+(defun org-toc-jump (&optional delete)
+ "From Org TOC buffer, jump to the targeted subtree in the Org window.
+If DELETE is non-nil, delete other windows when in the Org buffer."
+ (interactive "P")
+ (if delete (org-toc-goto 'delete)
+ (org-toc-goto t)))
+
+(defun org-toc-previous ()
+ "Go to the previous headline of the TOC."
+ (interactive)
+ (if (save-excursion
+ (beginning-of-line)
+ (re-search-backward "^\\*" nil t))
+ (outline-previous-visible-heading 1)
+ (message "No previous heading"))
+ (if org-toc-info-mode (org-toc-info))
+ (if org-toc-follow-mode (org-toc-goto)))
+
+(defun org-toc-next ()
+ "Go to the next headline of the TOC."
+ (interactive)
+ (outline-next-visible-heading 1)
+ (if org-toc-info-mode (org-toc-info))
+ (if org-toc-follow-mode (org-toc-goto)))
+
+(defun org-toc-forward ()
+ "Go to the next headline at the same level in the TOC."
+ (interactive)
+ (condition-case nil
+ (outline-forward-same-level 1)
+ (error (message "No next headline at this level")))
+ (if org-toc-info-mode (org-toc-info))
+ (if org-toc-follow-mode (org-toc-goto)))
+
+(defun org-toc-back ()
+ "Go to the previous headline at the same level in the TOC."
+ (interactive)
+ (condition-case nil
+ (outline-backward-same-level 1)
+ (error (message "No previous headline at this level")))
+ (if org-toc-info-mode (org-toc-info))
+ (if org-toc-follow-mode (org-toc-goto)))
+
+(defun org-toc-quit ()
+ "Quit the current Org TOC buffer."
+ (interactive)
+ (kill-buffer)
+ (other-window 1)
+ (delete-other-windows))
+
+;;; Special functions:
+(defun org-toc-columns ()
+ "Toggle columns view in the Org buffer from Org TOC."
+ (interactive)
+ (let ((indirect-buffer (current-buffer)))
+ (org-pop-to-buffer-same-window org-toc-base-buffer)
+ (if (not org-toc-columns-shown)
+ (progn (org-columns)
+ (setq org-toc-columns-shown t))
+ (progn (org-columns-remove-overlays)
+ (setq org-toc-columns-shown nil)))
+ (org-pop-to-buffer-same-window indirect-buffer)))
+
+(defun org-toc-info ()
+ "Show properties of current subtree in the echo-area."
+ (interactive)
+ (let ((pos (point))
+ (indirect-buffer (current-buffer))
+ props prop msg)
+ (org-pop-to-buffer-same-window org-toc-base-buffer)
+ (goto-char pos)
+ (setq props (org-entry-properties))
+ (while (setq prop (pop props))
+ (unless (or (equal (car prop) "COLUMNS")
+ (member (car prop) org-toc-info-exclude))
+ (let ((p (car prop))
+ (v (cdr prop)))
+ (if (equal p "TAGS")
+ (setq v (mapconcat 'identity (split-string v ":" t) " ")))
+ (setq p (concat p ":"))
+ (add-text-properties 0 (length p) '(face org-special-keyword) p)
+ (setq msg (concat msg p " " v " ")))))
+ (org-pop-to-buffer-same-window indirect-buffer)
+ (message msg)))
+
+;;; Store and restore TOC configuration:
+(defun org-toc-store-config ()
+ "Store the current status of the tables of contents in
+`org-toc-config-alist'."
+ (interactive)
+ (let ((file (buffer-file-name org-toc-base-buffer))
+ (pos (point))
+ (hlcfg (org-toc-get-headlines-status)))
+ (setq org-toc-config-alist
+ (delete (assoc file org-toc-config-alist)
+ org-toc-config-alist))
+ (add-to-list 'org-toc-config-alist
+ `(,file ,pos ,org-toc-cycle-global-status ,hlcfg))
+ (message "TOC configuration saved: (%s)"
+ (if (listp org-toc-cycle-global-status)
+ (concat "org-content "
+ (number-to-string
+ (cadr org-toc-cycle-global-status)))
+ (symbol-name org-toc-cycle-global-status)))))
+
+(defun org-toc-restore-config ()
+ "Get the stored status in `org-toc-config-alist' and set the
+current table of contents to it."
+ (interactive)
+ (let* ((file (buffer-file-name org-toc-base-buffer))
+ (conf (cdr (assoc file org-toc-config-alist)))
+ (pos (car conf))
+ (status (cadr conf))
+ (hlcfg (caddr conf)) hlcfg0 ov)
+ (cond ((listp status)
+ (org-toc-show (cadr status) (point)))
+ ((eq status 'overview)
+ (org-overview)
+ (setq org-cycle-global-status 'overview)
+ (run-hook-with-args 'org-cycle-hook 'overview))
+ (t
+ (org-overview)
+ (org-content)
+ (setq org-cycle-global-status 'contents)
+ (run-hook-with-args 'org-cycle-hook 'contents)))
+ (while (setq hlcfg0 (pop hlcfg))
+ (save-excursion
+ (goto-char (point-min))
+ (when (search-forward (car hlcfg0) nil t)
+ (unless (overlays-at (match-beginning 0))
+ (setq ov (make-overlay (match-beginning 0)
+ (match-end 0))))
+ (cond ((eq (cdr hlcfg0) 'children)
+ (org-show-children)
+ (message "CHILDREN")
+ (overlay-put ov 'status 'children))
+ ((eq (cdr hlcfg0) 'branches)
+ (show-branches)
+ (message "BRANCHES")
+ (overlay-put ov 'status 'branches))))))
+ (goto-char pos)
+ (if org-toc-follow-mode (org-toc-goto))
+ (message "Last TOC configuration restored")
+ (sit-for 1)
+ (if org-toc-info-mode (org-toc-info))))
+
+(defun org-toc-get-headlines-status ()
+ "Return an alist of headlines and their associated folding
+status."
+ (let (output ovs)
+ (save-excursion
+ (goto-char (point-min))
+ (while (and (not (eobp))
+ (goto-char (next-overlay-change (point))))
+ (when (looking-at org-outline-regexp-bol)
+ (add-to-list
+ 'output
+ (cons (buffer-substring-no-properties
+ (match-beginning 0)
+ (save-excursion
+ (end-of-line) (point)))
+ (overlay-get
+ (car (overlays-at (point))) 'status))))))
+ ;; return an alist like (("* Headline" . 'status))
+ output))
+
+;; In Org TOC buffer, hide headlines below the first level.
+(defun org-toc-help ()
+ "Display a quick help message in the echo-area for `org-toc-mode'."
+ (interactive)
+ (let ((st-start 0)
+ (help-message
+ "\[space\] show heading \[1-4\] hide headlines below this level
+\[TAB\] jump to heading \[F\] toggle follow mode (currently %s)
+\[return\] jump and delete others windows \[i\] toggle info mode (currently %s)
+\[S-TAB\] cycle subtree (in Org) \[S\] toggle show subtree mode (currently %s)
+\[C-S-TAB\] global cycle (in Org) \[r\] toggle recenter mode (currently %s)
+\[:\] cycle subtree (in TOC) \[c\] toggle column view (currently %s)
+\[n/p\] next/previous heading \[s\] save TOC configuration
+\[f/b\] next/previous heading of same level
+\[q\] quit the TOC \[g\] restore last TOC configuration"))
+ (while (string-match "\\[[^]]+\\]" help-message st-start)
+ (add-text-properties (match-beginning 0)
+ (match-end 0) '(face bold) help-message)
+ (setq st-start (match-end 0)))
+ (message help-message
+ (if org-toc-follow-mode "on" "off")
+ (if org-toc-info-mode "on" "off")
+ (if org-toc-show-subtree-mode "on" "off")
+ (if org-toc-recenter-mode (format "on, line %s" org-toc-recenter) "off")
+ (if org-toc-columns-shown "on" "off"))))
+
+
+;;;;##########################################################################
+;;;; User Options, Variables
+;;;;##########################################################################
+
+;;; org-toc.el ends here
diff --git a/contrib/lisp/org-track.el b/contrib/lisp/org-track.el
new file mode 100644
index 0000000..36724de
--- /dev/null
+++ b/contrib/lisp/org-track.el
@@ -0,0 +1,211 @@
+;;; org-track.el --- Track the most recent Org-mode version available.
+;;
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Bastien Guerry <bzg@gnu.org>
+;; Eric S Fraga <e.fraga at ucl.ac dot uk>
+;; Sebastian Rose <sebastian_rose at gmx dot de>
+;; The Worg people http://orgmode.org/worg/
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 6.29a
+;;
+;; Released under the GNU General Public License version 3
+;; see: http://www.gnu.org/licenses/gpl-3.0.html
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; WARNING: This library is obsolete, you should use the make targets
+;; to keep track of Org latest developments.
+;;
+;; Download the latest development tarball, unpack and optionally compile it
+;;
+;; Usage:
+;;
+;; (require 'org-track)
+;;
+;; ;; ... somewhere in your setup (use customize):
+;;
+;; (setq org-track-directory "~/test/")
+;; (setq org-track-compile-sources nil)
+;; (setq org-track-remove-package t)
+;;
+;; M-x org-track-update RET
+
+(require 'url-parse)
+(require 'url-handlers)
+(autoload 'url-file-local-copy "url-handlers")
+(autoload 'url-generic-parse-url "url-parse")
+
+
+
+;;; Variables:
+
+(defgroup org-track nil
+ "Track the most recent Org-mode version available.
+
+To use org-track, adjust `org-track-directory'.
+Org will download the archived latest git version for you,
+unpack it into that directory (i.e. a subdirectory
+`org-mode/' is added), create the autoloads file
+`org-loaddefs.el' for you and, optionally, compile the
+sources.
+All you'll have to do is call `M-x org-track-update' from
+time to time."
+ :group 'org)
+
+(defcustom org-track-directory (concat user-emacs-directory "org/lisp")
+ "Directory where your org-mode/ directory lives.
+If that directory does not exist, it will be created."
+ :type 'directory)
+
+(defcustom org-track-compile-sources t
+ "If `nil', never compile org-sources.
+Org will only create the autoloads file `org-loaddefs.el' for
+you then. If `t', compile the sources, too.
+Note, that emacs preferes compiled elisp files over
+non-compiled ones."
+ :type 'boolean)
+
+(defcustom org-track-org-url "http://orgmode.org/"
+ "The URL where the package to download can be found.
+Please append a slash."
+ :type 'string)
+
+(defcustom org-track-org-package "org-latest.tar.gz"
+ "The basename of the package you use.
+Defaults to the development version of Org-mode.
+This should be a *.tar.gz package, since emacs provides all
+you need to unpack it."
+ :type 'string)
+
+(defcustom org-track-remove-package nil
+ "Remove org-latest.tar.gz after updates?"
+ :type 'boolean)
+
+
+
+;;; Frontend
+
+(defun org-track-update ()
+ "Update to current Org-mode version.
+Also, generate autoloads and evtl. compile the sources."
+ (interactive)
+ (let* ((base (file-truename org-track-directory))
+ (org-exists (file-exists-p
+ (file-truename
+ (concat base "/org-mode/lisp/org.el"))))
+ (nobase (not (file-directory-p
+ (file-truename org-track-directory)))))
+ (if nobase
+ (when (y-or-n-p
+ (format "Directory %s does not exist. Create it?" base))
+ (make-directory base t)
+ (setq nobase nil)))
+ (if nobase
+ (message "Not creating %s - giving up." org-track-directory)
+ (condition-case err
+ (progn
+ (org-track-fetch-package)
+ (org-track-compile-org))
+ (error (message "%s" (error-message-string err)))))))
+
+
+
+;;; tar related functions
+
+;; `url-retrieve-synchronously' fetches files synchronously. How can we ensure
+;; that? If the maintainers of that package decide, that an assynchronous
+;; download might be better??? (used by `url-file-local-copy')
+
+;;;###autoload
+(defun org-track-fetch-package (&optional directory)
+ "Fetch Org package depending on `org-track-fetch-package-extension'.
+If DIRECTORY is defined, unpack the package there, i.e. add the
+subdirectory org-mode/ to DIRECTORY."
+ (interactive "Dorg-track directory: ")
+ (let* ((pack (concat
+ (if (string-match "/$" org-track-org-url)
+ org-track-org-url
+ (concat org-track-org-url "/"))
+ org-track-org-package))
+ (base (file-truename
+ (or directory org-track-directory)))
+ (target (file-truename
+ (concat base "/" org-track-org-package)))
+ url download tarbuff)
+ (message "Fetching to %s - this might take some time..." base)
+ (setq url (url-generic-parse-url pack))
+ (setq download (url-file-local-copy url)) ;; errors if fail
+ (copy-file download target t)
+ (delete-file download)
+ ;; (tar-mode) leads to dubious errors. We use the auto-mode-alist to
+ ;; ensure tar-mode is used:
+ (add-to-list 'auto-mode-alist '("org-latest\\.tar\\.gz\\'" . tar-mode))
+ (setq tarbuff (find-file target))
+ (with-current-buffer tarbuff ;; with-temp-buffer does not work with tar-mode??
+ (tar-untar-buffer))
+ (kill-buffer tarbuff)
+ (if org-track-remove-package
+ (delete-file target))))
+
+
+
+;;; Compile Org-mode sources
+
+
+;;;###autoload
+(defun org-track-compile-org (&optional directory)
+ "Compile all *.el files that come with org-mode.
+Generate the autoloads file `org-loaddefs.el'.
+
+DIRECTORY is where the directory org-mode/ lives (i.e. the
+ parent directory of your local repo."
+ (interactive)
+ ;; file-truename expands the filename and removes double slash, if exists:
+ (setq directory (file-truename
+ (concat
+ (or directory
+ (file-truename (concat org-track-directory "/org-mode/lisp")))
+ "/")))
+ (add-to-list 'load-path directory)
+ (let ((list-of-org-files (file-expand-wildcards (concat directory "*.el"))))
+ ;; create the org-loaddefs file
+ (require 'autoload)
+ (setq esf/org-install-file (concat directory "org-loaddefs.el"))
+ (find-file esf/org-install-file)
+ (erase-buffer)
+ (mapc (lambda (x)
+ (generate-file-autoloads x))
+ list-of-org-files)
+ (insert "\n(provide (quote org-loaddefs))\n")
+ (save-buffer)
+ (kill-buffer)
+ (byte-compile-file esf/org-install-file t)
+
+ (mapc (lambda (f)
+ (if (file-exists-p (concat f "c"))
+ (delete-file (concat f "c"))))
+ list-of-org-files)
+ (if org-track-compile-sources
+ (mapc (lambda (f) (byte-compile-file f)) list-of-org-files))))
+
+(provide 'org-track)
+
+;;; org-track.el ends here
diff --git a/contrib/lisp/org-velocity.el b/contrib/lisp/org-velocity.el
new file mode 100644
index 0000000..bfc4d6c
--- /dev/null
+++ b/contrib/lisp/org-velocity.el
@@ -0,0 +1,819 @@
+;;; org-velocity.el --- something like Notational Velocity for Org. -*- lexical-binding: t -*-
+
+;; Copyright (C) 2010-2014 Paul M. Rodriguez
+
+;; Author: Paul M. Rodriguez <paulmrodriguez@gmail.com>
+;; Created: 2010-05-05
+;; Version: 4.1
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation version 2.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;; Org-Velocity.el is an interface for Org inspired by the minimalist
+;; notetaking program Notational Velocity. The idea is to let you
+;; amass and access brief notes on many subjects with minimal fuss.
+;; Each note is an entry in an ordinary Org file.
+
+;; Org-Velocity can be used in two ways: when called outside Org, to
+;; store and access notes in a designated bucket file; or, when called
+;; inside Org, as a method for navigating any Org file. (Setting the
+;; option `org-velocity-always-use-bucket' disables navigation inside
+;; Org files by default, although you can still force this behavior by
+;; calling `org-velocity-read' with an argument.)
+
+;; Org-Velocity prompts for search terms in the minibuffer. A list of
+;; headings of entries whose text matches your search is updated as
+;; you type; you can end the search and visit an entry at any time by
+;; clicking on its heading.
+
+;; RET displays the results. If there are no matches, Org-Velocity
+;; offers to create a new entry with your search string as its
+;; heading. If there are matches, it displays a list of results where
+;; the heading of each matching entry is hinted with a number or
+;; letter; clicking a result, or typing the matching hint, opens the
+;; entry for editing in an indirect buffer. 0 forces a new entry; RET
+;; reopens the search for editing.
+
+;; You can customize every step in this process, including the search
+;; method, completion for search terms, and templates for creating new
+;; entries; M-x customize-group RET org-velocity RET to see all the
+;; options.
+
+;; Thanks to Richard Riley, Carsten Dominik, Bastien Guerry, and Jeff
+;; Horn for their suggestions.
+
+;;; Usage:
+;; (require 'org-velocity)
+;; (setq org-velocity-bucket (expand-file-name "bucket.org" org-directory))
+;; (global-set-key (kbd "C-c v") 'org-velocity)
+
+;;; Code:
+(require 'org)
+(require 'button)
+(require 'electric)
+(require 'dabbrev)
+(require 'cl-lib)
+
+(defgroup org-velocity nil
+ "Notational Velocity-style interface for Org."
+ :tag "Org-Velocity"
+ :group 'outlines
+ :group 'hypermedia
+ :group 'org)
+
+(defcustom org-velocity-bucket ""
+ "Where is the bucket file?"
+ :group 'org-velocity
+ :type 'file)
+
+(defcustom org-velocity-show-previews t
+ "Show previews of the text of each heading?"
+ :group 'velocity
+ :type 'boolean
+ :safe 'booleanp)
+
+(defcustom org-velocity-exit-on-match nil
+ "When searching incrementally, exit on a single match?"
+ :group 'org-velocity
+ :type 'boolean
+ :safe 'booleanp)
+
+(defcustom org-velocity-force-new nil
+ "Should exiting the minibuffer with C-j force a new entry?"
+ :group 'org-velocity
+ :type 'boolean
+ :safe 'booleanp)
+
+(defcustom org-velocity-use-search-ring t
+ "Push search to `search-ring' when visiting an entry?
+
+This means that C-s C-s will take you directly to the first
+instance of the search string."
+ :group 'org-velocity
+ :type 'boolean
+ :safe 'booleanp)
+
+(defcustom org-velocity-always-use-bucket nil
+ "Use bucket file even when called from an Org buffer?"
+ :group 'org-velocity
+ :type 'boolean
+ :safe 'booleanp)
+
+(defcustom org-velocity-use-completion nil
+ "Use completion?
+
+Notwithstanding the value of this option, calling
+`dabbrev-expand' always completes against the text of the bucket
+file."
+ :group 'org-velocity
+ :type '(choice
+ (const :tag "Do not use completion" nil)
+ (const :tag "Use completion" t))
+ :safe 'booleanp)
+
+(defcustom org-velocity-search-method 'phrase
+ "Match on whole phrase, any word, or all words?"
+ :group 'org-velocity
+ :type '(choice
+ (const :tag "Match whole phrase" phrase)
+ (const :tag "Match any word" any)
+ (const :tag "Match all words" all)
+ (const :tag "Match a regular expression" regexp))
+ :safe (lambda (v) (memq v '(phrase any all regexp))))
+
+(defcustom org-velocity-capture-templates
+ '(("v"
+ "Velocity entry"
+ entry
+ (file "")
+ "* %:search\n\n%i%?"))
+ "Use these template with `org-capture'.
+Meanwhile `org-default-notes-file' is bound to `org-velocity-bucket-file'.
+The keyword :search inserts the current search.
+See the documentation for `org-capture-templates'."
+ :group 'org-velocity
+ :type (or (get 'org-capture-templates 'custom-type) 'list))
+
+(defcustom org-velocity-heading-level 1
+ "Only match headings at this level or higher.
+0 means to match headings at any level."
+ :group 'org-velocity
+ :type 'integer
+ :safe (lambda (x)
+ (and (integerp x)
+ (>= x 0))))
+
+(defvar crm-separator) ;Ensure dynamic binding.
+
+(defsubst org-velocity-grab-preview ()
+ "Grab preview of a subtree.
+The length of the preview is determined by `window-width'.
+
+Replace all contiguous whitespace with single spaces."
+ (let* ((start (progn
+ (forward-line 1)
+ (if (looking-at org-property-start-re)
+ (re-search-forward org-property-end-re)
+ (1- (point)))))
+ (string+props (buffer-substring
+ start
+ (min
+ (+ start (window-width))
+ (point-max)))))
+ ;; We want to preserve the text properties so that, for example,
+ ;; we don't end up with the raw text of links in the preview.
+ (with-temp-buffer
+ (insert string+props)
+ (goto-char (point-min))
+ (save-match-data
+ (while (re-search-forward split-string-default-separators
+ (point-max)
+ t)
+ (replace-match " ")))
+ (buffer-string))))
+
+(cl-defstruct org-velocity-heading buffer position name level preview)
+
+(defsubst org-velocity-nearest-heading (position)
+ "Return last heading at POSITION.
+If there is no last heading, return nil."
+ (save-excursion
+ (goto-char position)
+ (re-search-backward (org-velocity-heading-regexp))
+ (let ((components (org-heading-components)))
+ (make-org-velocity-heading
+ :buffer (current-buffer)
+ :position (point)
+ :name (nth 4 components)
+ :level (nth 0 components)
+ :preview (if org-velocity-show-previews
+ (org-velocity-grab-preview))))))
+
+(defconst org-velocity-index
+ (eval-when-compile
+ (nconc (number-sequence 49 57) ;numbers
+ (number-sequence 97 122) ;lowercase letters
+ (number-sequence 65 90))) ;uppercase letters
+ "List of chars for indexing results.")
+
+(defconst org-velocity-match-buffer-name "*Velocity matches*")
+
+(cl-defun org-velocity-heading-regexp (&optional (level org-velocity-heading-level))
+ "Regexp to match headings at LEVEL or deeper."
+ (if (zerop level)
+ "^\\*+ "
+ (format "^\\*\\{1,%d\\} " level)))
+
+(defvar org-velocity-search nil
+ "Variable to bind to current search.")
+
+(defun org-velocity-buffer-file-name (&optional buffer)
+ "Return the name of the file BUFFER saves to.
+Same as function `buffer-file-name' unless BUFFER is an indirect
+buffer or a minibuffer. In the former case, return the file name
+of the base buffer; in the latter, return the file name of
+`minibuffer-selected-window' (or its base buffer)."
+ (let ((buffer (if (minibufferp buffer)
+ (window-buffer (minibuffer-selected-window))
+ buffer)))
+ (buffer-file-name
+ (or (buffer-base-buffer buffer)
+ buffer))))
+
+(defun org-velocity-minibuffer-contents ()
+ "Return the contents of the minibuffer when it is active."
+ (when (active-minibuffer-window)
+ (with-current-buffer (window-buffer (active-minibuffer-window))
+ (minibuffer-contents))))
+
+(defun org-velocity-nix-minibuffer ()
+ "Return the contents of the minibuffer and clear it."
+ (when (active-minibuffer-window)
+ (with-current-buffer (window-buffer (active-minibuffer-window))
+ (prog1 (minibuffer-contents)
+ (delete-minibuffer-contents)))))
+
+(defun org-velocity-bucket-file ()
+ "Return the proper file for Org-Velocity to search.
+If `org-velocity-always-use-bucket' is t, use bucket file;
+complain if missing. Otherwise, if an Org file is current, then
+use it."
+ (let ((org-velocity-bucket
+ (when org-velocity-bucket (expand-file-name org-velocity-bucket)))
+ (buffer
+ (let ((buffer-file (org-velocity-buffer-file-name)))
+ (when buffer-file
+ ;; Use the target in capture buffers.
+ (org-find-base-buffer-visiting buffer-file)))))
+ (if org-velocity-always-use-bucket
+ (or org-velocity-bucket (error "Bucket required but not defined"))
+ (if (and (eq (buffer-local-value 'major-mode (or buffer (current-buffer)))
+ 'org-mode)
+ (org-velocity-buffer-file-name))
+ (org-velocity-buffer-file-name)
+ (or org-velocity-bucket
+ (error "No bucket and not an Org file"))))))
+
+(defvar org-velocity-bucket-buffer nil)
+(defvar org-velocity-navigating nil)
+
+(defsubst org-velocity-bucket-buffer ()
+ (or org-velocity-bucket-buffer
+ (find-file-noselect (org-velocity-bucket-file))))
+
+(defsubst org-velocity-match-buffer ()
+ "Return the proper buffer for Org-Velocity to display in."
+ (get-buffer-create org-velocity-match-buffer-name))
+
+(defsubst org-velocity-match-window ()
+ (get-buffer-window (org-velocity-match-buffer)))
+
+(defun org-velocity-beginning-of-headings ()
+ "Goto the start of the first heading."
+ (goto-char (point-min))
+ ;; If we are before the first heading we could still be at the
+ ;; first heading.
+ (or (looking-at (org-velocity-heading-regexp))
+ (re-search-forward (org-velocity-heading-regexp))))
+
+(defun org-velocity-make-indirect-buffer (heading)
+ "Make or switch to an indirect buffer visiting HEADING."
+ (let* ((bucket (org-velocity-heading-buffer heading))
+ (name (org-velocity-heading-name heading))
+ (existing (get-buffer name)))
+ (if (and existing (buffer-base-buffer existing)
+ (equal (buffer-base-buffer existing) bucket))
+ existing
+ (make-indirect-buffer
+ bucket
+ (generate-new-buffer-name (org-velocity-heading-name heading))
+ t))))
+
+(defun org-velocity-capture ()
+ "Record a note with `org-capture'."
+ (let ((org-capture-templates
+ org-velocity-capture-templates))
+ (org-capture nil
+ ;; This is no longer automatically selected.
+ (when (null (cdr org-capture-templates))
+ (caar org-capture-templates)))
+ (when org-capture-mode
+ (rename-buffer org-velocity-search t))))
+
+(defvar org-velocity-saved-winconf nil)
+(make-variable-buffer-local 'org-velocity-saved-winconf)
+
+(defun org-velocity-edit-entry (heading)
+ (if org-velocity-navigating
+ (org-velocity-edit-entry/inline heading)
+ (org-velocity-edit-entry/indirect heading)))
+
+(cl-defun org-velocity-goto-entry (heading &key narrow)
+ (goto-char (org-velocity-heading-position heading))
+ (save-excursion
+ (when narrow
+ (org-narrow-to-subtree))
+ (outline-show-all)))
+
+(defun org-velocity-edit-entry/inline (heading)
+ "Edit entry at HEADING in the original buffer."
+ (let ((buffer (org-velocity-heading-buffer heading)))
+ (pop-to-buffer buffer)
+ (with-current-buffer buffer
+ (org-velocity-goto-entry heading))))
+
+(defun org-velocity-format-header-line (control-string &rest args)
+ (set (make-local-variable 'header-line-format)
+ (apply #'format control-string args)))
+
+(defun org-velocity-edit-entry/indirect (heading)
+ "Edit entry at HEADING in an indirect buffer."
+ (let ((winconf (current-window-configuration))
+ (dd default-directory)
+ (buffer (org-velocity-make-indirect-buffer heading))
+ (inhibit-point-motion-hooks t)
+ (inhibit-field-text-motion t))
+ (with-current-buffer buffer
+ (setq default-directory dd) ;Inherit default directory.
+ (setq org-velocity-saved-winconf winconf)
+ (org-velocity-goto-entry heading :narrow t)
+ (goto-char (point-max))
+ (add-hook 'org-ctrl-c-ctrl-c-hook 'org-velocity-dismiss nil t))
+ (pop-to-buffer buffer)
+ (org-velocity-format-header-line
+ "%s Use C-c C-c to finish."
+ (abbreviate-file-name
+ (buffer-file-name
+ (org-velocity-heading-buffer heading))))))
+
+(defun org-velocity-dismiss ()
+ "Save current entry and close indirect buffer."
+ (let ((winconf org-velocity-saved-winconf))
+ (prog1 t ;Tell hook we're done.
+ (save-buffer)
+ (kill-buffer)
+ (when (window-configuration-p winconf)
+ (set-window-configuration winconf)))))
+
+(defun org-velocity-visit-button (button)
+ (run-hooks 'mouse-leave-buffer-hook)
+ (when org-velocity-use-search-ring
+ (add-to-history 'search-ring
+ (button-get button 'search)
+ search-ring-max))
+ (let ((match (button-get button 'match)))
+ (throw 'org-velocity-done match)))
+
+(define-button-type 'org-velocity-button
+ 'action #'org-velocity-visit-button
+ 'follow-link 'mouse-face)
+
+(defsubst org-velocity-buttonize (heading)
+ "Insert HEADING as a text button with no hints."
+ (insert-text-button
+ (propertize (org-velocity-heading-name heading) 'face 'link)
+ :type 'org-velocity-button
+ 'match heading
+ 'search org-velocity-search))
+
+(defsubst org-velocity-insert-preview (heading)
+ (when org-velocity-show-previews
+ (insert-char ?\ 1)
+ (insert
+ (propertize
+ (org-velocity-heading-preview heading)
+ 'face 'shadow))))
+
+(defvar org-velocity-recursive-headings nil)
+(defvar org-velocity-recursive-search nil)
+
+(cl-defun org-velocity-search-with (fun style search
+ &key (headings org-velocity-recursive-headings))
+ (if headings
+ (save-restriction
+ (dolist (heading headings)
+ (widen)
+ (let ((start (org-velocity-heading-position heading)))
+ (goto-char start)
+ (let ((end (save-excursion
+ (org-end-of-subtree)
+ (point))))
+ (narrow-to-region start end)
+ (org-velocity-search-with fun style search
+ :headings nil)))))
+ (cl-ecase style
+ ((phrase any regexp)
+ (cl-block nil
+ (while (re-search-forward search nil t)
+ (let ((match (org-velocity-nearest-heading (point))))
+ (funcall fun match))
+ ;; Skip to the next heading.
+ (unless (re-search-forward (org-velocity-heading-regexp) nil t)
+ (cl-return)))))
+ ((all)
+ (let ((keywords
+ (cl-loop for word in (split-string search)
+ collect (concat "\\<" (regexp-quote word) "\\>"))))
+ (org-map-entries
+ (lambda ()
+ ;; Only search the subtree once.
+ (setq org-map-continue-from
+ (save-excursion
+ (org-end-of-subtree)
+ (point)))
+ (when (cl-loop for word in keywords
+ always (save-excursion
+ (re-search-forward word org-map-continue-from t)))
+ (let ((match (org-velocity-nearest-heading (match-end 0))))
+ (funcall fun match))))))))))
+
+(defun org-velocity-all-results (style search)
+ (with-current-buffer (org-velocity-bucket-buffer)
+ (save-excursion
+ (goto-char (point-min))
+ (let (matches)
+ (org-velocity-search-with (lambda (match)
+ (push match matches))
+ style
+ search)
+ (nreverse matches)))))
+
+(defsubst org-velocity-present-match (hint match)
+ (with-current-buffer (org-velocity-match-buffer)
+ (when hint (insert "#" hint " "))
+ (org-velocity-buttonize match)
+ (org-velocity-insert-preview match)
+ (newline)))
+
+(defun org-velocity-present-search (style search hide-hints)
+ (let ((hints org-velocity-index) matches)
+ (cl-block nil
+ (org-velocity-search-with (lambda (match)
+ (unless hints
+ (cl-return))
+ (let ((hint (if hide-hints
+ nil
+ (car hints))))
+ (org-velocity-present-match hint match))
+ (pop hints)
+ (push match matches))
+ style
+ search))
+ (nreverse matches)))
+
+(defun org-velocity-restrict-search ()
+ (interactive)
+ (let ((search (org-velocity-nix-minibuffer)))
+ (when (equal search "")
+ (error "No search to restrict to"))
+ (push search org-velocity-recursive-search)
+ (setq org-velocity-recursive-headings
+ (org-velocity-all-results
+ org-velocity-search-method
+ search))
+ ;; TODO We could extend the current search instead of starting
+ ;; over.
+ (org-velocity-update-match-header)
+ (minibuffer-message "Restricting search to %s" search)))
+
+(cl-defun org-velocity-update-match-header (&key (match-buffer (org-velocity-match-buffer))
+ (bucket-buffer (org-velocity-bucket-buffer))
+ (search-method org-velocity-search-method))
+ (let ((navigating? org-velocity-navigating)
+ (recursive? org-velocity-recursive-search))
+ (with-current-buffer match-buffer
+ (org-velocity-format-header-line
+ "%s search in %s%s (%s mode)"
+ (capitalize (symbol-name search-method))
+ (abbreviate-file-name (buffer-file-name bucket-buffer))
+ (if (not recursive?)
+ ""
+ (let ((sep " > "))
+ (concat sep (string-join (reverse recursive?) sep))))
+ (if navigating? "nav" "notes")))))
+
+(cl-defun org-velocity-present (search &key hide-hints)
+ "Buttonize matches for SEARCH in `org-velocity-match-buffer'.
+If HIDE-HINTS is non-nil, display entries without indices. SEARCH
+binds `org-velocity-search'.
+
+Return matches."
+ (let ((match-buffer (org-velocity-match-buffer))
+ (bucket-buffer (org-velocity-bucket-buffer))
+ (search-method org-velocity-search-method))
+ (if (and (stringp search) (not (string= "" search)))
+ ;; Fold case when the search string is all lowercase.
+ (let ((case-fold-search (equal search (downcase search)))
+ (truncate-partial-width-windows t))
+ (with-current-buffer match-buffer
+ (erase-buffer)
+ ;; Permanent locals.
+ (setq cursor-type nil
+ truncate-lines t)
+ (org-velocity-update-match-header
+ :match-buffer match-buffer
+ :bucket-buffer bucket-buffer
+ :search-method search-method))
+ (prog1
+ (with-current-buffer bucket-buffer
+ (widen)
+ (let* ((inhibit-point-motion-hooks t)
+ (inhibit-field-text-motion t)
+ (anchored? (string-match-p "^\\s-" search))
+ (search
+ (cl-ecase search-method
+ (all search)
+ (phrase
+ (if anchored?
+ (regexp-quote search)
+ ;; Anchor the search to the start of a word.
+ (concat "\\<" (regexp-quote search))))
+ (any
+ (concat "\\<" (regexp-opt (split-string search))))
+ (regexp search))))
+ (save-excursion
+ (org-velocity-beginning-of-headings)
+ (condition-case lossage
+ (org-velocity-present-search search-method search hide-hints)
+ (invalid-regexp
+ (minibuffer-message "%s" lossage))))))
+ (with-current-buffer match-buffer
+ (goto-char (point-min)))))
+ (with-current-buffer match-buffer
+ (erase-buffer)))))
+
+(defun org-velocity-store-link ()
+ "Function for `org-store-link-functions'."
+ (if org-velocity-search
+ (org-store-link-props
+ :search org-velocity-search)))
+
+(add-hook 'org-store-link-functions 'org-velocity-store-link)
+
+(cl-defun org-velocity-create (search &key ask)
+ "Create new heading named SEARCH.
+If ASK is non-nil, ask first."
+ (when (or (null ask) (y-or-n-p "No match found, create? "))
+ (let ((org-velocity-search search)
+ (org-default-notes-file (org-velocity-bucket-file))
+ ;; save a stored link
+ org-store-link-plist)
+ (org-velocity-capture))
+ search))
+
+(defun org-velocity-engine (search)
+ "Display a list of headings where SEARCH occurs."
+ (let ((org-velocity-search search))
+ (unless (or
+ (not (stringp search))
+ (string= "" search)) ;exit on empty string
+ (cl-case
+ (if (and org-velocity-force-new (eq last-command-event ?\C-j))
+ :force
+ (let* ((org-velocity-index (org-velocity-adjust-index))
+ (matches (org-velocity-present search)))
+ (cond ((null matches) :new)
+ ((null (cdr matches)) :follow)
+ (t :prompt))))
+ (:prompt (progn
+ (pop-to-buffer (org-velocity-match-buffer))
+ (let ((hint (org-velocity-electric-read-hint)))
+ (when hint (cl-case hint
+ (:edit (org-velocity-read nil search))
+ (:force (org-velocity-create search))
+ (otherwise (org-velocity-activate-button hint)))))))
+ (:new (unless (org-velocity-create search :ask t)
+ (org-velocity-read nil search)))
+ (:force (org-velocity-create search))
+ (:follow (if (y-or-n-p "One match, follow? ")
+ (progn
+ (set-buffer (org-velocity-match-buffer))
+ (goto-char (point-min))
+ (button-activate (next-button (point))))
+ (org-velocity-read nil search)))))))
+
+(defun org-velocity-activate-button (char)
+ "Go to button on line number associated with CHAR in `org-velocity-index'."
+ (goto-char (point-min))
+ (forward-line (cl-position char org-velocity-index))
+ (goto-char
+ (button-start
+ (next-button (point))))
+ (message "%s" (button-label (button-at (point))))
+ (button-activate (button-at (point))))
+
+(defun org-velocity-electric-undefined ()
+ "Complain about an undefined key."
+ (interactive)
+ (message "%s"
+ (substitute-command-keys
+ "\\[org-velocity-electric-new] for new entry,
+\\[org-velocity-electric-edit] to edit search,
+\\[scroll-up] to scroll up,
+\\[scroll-down] to scroll down,
+\\[keyboard-quit] to quit."))
+ (sit-for 4))
+
+(defun org-velocity-electric-follow (ev)
+ "Follow a hint indexed by keyboard event EV."
+ (interactive (list last-command-event))
+ (if (not (> (cl-position ev org-velocity-index)
+ (1- (count-lines (point-min) (point-max)))))
+ (throw 'org-velocity-select ev)
+ (call-interactively 'org-velocity-electric-undefined)))
+
+(defun org-velocity-electric-edit ()
+ "Edit the search string."
+ (interactive)
+ (throw 'org-velocity-select :edit))
+
+(defun org-velocity-electric-new ()
+ "Force a new entry."
+ (interactive)
+ (throw 'org-velocity-select :force))
+
+(defvar org-velocity-electric-map
+ (let ((map (make-sparse-keymap)))
+ (define-key map [t] 'org-velocity-electric-undefined)
+ (dolist (c org-velocity-index)
+ (define-key map (char-to-string c)
+ 'org-velocity-electric-follow))
+ (define-key map "0" 'org-velocity-electric-new)
+ (define-key map "\C-v" 'scroll-up)
+ (define-key map "\M-v" 'scroll-down)
+ (define-key map (kbd "RET") 'org-velocity-electric-edit)
+ (define-key map [mouse-1] nil)
+ (define-key map [mouse-2] nil)
+ (define-key map [escape] 'keyboard-quit)
+ (define-key map "\C-h" 'help-command)
+ map))
+
+(defun org-velocity-electric-read-hint ()
+ "Read index of button electrically."
+ (with-current-buffer (org-velocity-match-buffer)
+ (when (featurep 'evil)
+ ;; NB Idempotent.
+ (evil-make-overriding-map org-velocity-electric-map))
+ (use-local-map org-velocity-electric-map)
+ (catch 'org-velocity-select
+ (Electric-command-loop 'org-velocity-select "Follow: "))))
+
+(defvar org-velocity-incremental-keymap
+ (let ((map (make-sparse-keymap)))
+ (define-key map "\C-v" 'scroll-up)
+ (define-key map "\M-v" 'scroll-down)
+ map))
+
+(defun org-velocity-displaying-completions-p ()
+ "Is there a *Completions* buffer showing?"
+ (get-window-with-predicate
+ (lambda (w)
+ (eq (buffer-local-value 'major-mode (window-buffer w))
+ 'completion-list-mode))))
+
+(defun org-velocity-update ()
+ "Display results of search without hinting."
+ (unless (org-velocity-displaying-completions-p)
+ (let* ((search (org-velocity-minibuffer-contents))
+ (matches (org-velocity-present search :hide-hints t)))
+ (cond ((null matches)
+ (select-window (active-minibuffer-window))
+ (unless (or (null search) (= (length search) 0))
+ (minibuffer-message "No match; RET to create")))
+ ((and (null (cdr matches))
+ org-velocity-exit-on-match)
+ (throw 'click search))
+ (t
+ (with-current-buffer (org-velocity-match-buffer)
+ (use-local-map org-velocity-incremental-keymap)))))))
+
+(defvar dabbrev--last-abbreviation)
+
+(defun org-velocity-dabbrev-completion-list (abbrev)
+ "Return all dabbrev completions for ABBREV."
+ ;; This is based on `dabbrev-completion'.
+ (dabbrev--reset-global-variables)
+ (setq dabbrev--last-abbreviation abbrev)
+ (dabbrev--find-all-expansions abbrev case-fold-search))
+
+(defvar org-velocity-local-completion-map
+ (let ((map (make-sparse-keymap)))
+ (set-keymap-parent map minibuffer-local-completion-map)
+ (define-key map " " 'self-insert-command)
+ (define-key map "?" 'self-insert-command)
+ (define-key map [remap minibuffer-complete] 'minibuffer-complete-word)
+ (define-key map [(control ?@)] 'org-velocity-restrict-search)
+ (define-key map [(control ?\s)] 'org-velocity-restrict-search)
+ map)
+ "Keymap for completion with `completing-read'.")
+
+(defun org-velocity-read-with-completion (prompt)
+ "Completing read with PROMPT."
+ (let ((minibuffer-local-completion-map
+ org-velocity-local-completion-map)
+ (completion-no-auto-exit t)
+ (crm-separator " "))
+ (completing-read prompt
+ (completion-table-dynamic
+ 'org-velocity-dabbrev-completion-list))))
+
+(cl-defun org-velocity-adjust-index
+ (&optional (match-window (org-velocity-match-window)))
+ "Truncate or extend `org-velocity-index' to the lines in
+MATCH-WINDOW."
+ (with-selected-window match-window
+ (let ((lines (window-height))
+ (hints (length org-velocity-index)))
+ (cond ((= lines hints)
+ org-velocity-index)
+ ;; Truncate the index to the size of
+ ;; the buffer to be displayed.
+ ((< lines hints)
+ (cl-subseq org-velocity-index 0 lines))
+ ;; If the window is so tall we run out of indices, at
+ ;; least make the additional results clickable.
+ ((> lines hints)
+ (append org-velocity-index
+ (make-list (- lines hints) nil)))))))
+
+(defun org-velocity-incremental-read (prompt)
+ "Read string with PROMPT and display results incrementally.
+Stop searching once there are more matches than can be
+displayed."
+ (let ((res
+ (unwind-protect
+ (let* ((match-window (display-buffer (org-velocity-match-buffer)))
+ (org-velocity-index (org-velocity-adjust-index match-window)))
+ (catch 'click
+ (add-hook 'post-command-hook 'org-velocity-update)
+ (cond ((eq org-velocity-search-method 'regexp)
+ (read-regexp prompt))
+ (org-velocity-use-completion
+ (org-velocity-read-with-completion prompt))
+ (t (read-string prompt)))))
+ (remove-hook 'post-command-hook 'org-velocity-update))))
+ (if (bufferp res) (org-pop-to-buffer-same-window res) res)))
+
+(defun org-velocity (arg &optional search)
+ "Read a search string SEARCH for Org-Velocity interface.
+This means that a buffer will display all headings where SEARCH
+occurs, where one can be selected by a mouse click or by typing
+its index. If SEARCH does not occur, then a new heading may be
+created named SEARCH.
+
+If `org-velocity-bucket' is defined and
+`org-velocity-always-use-bucket' is non-nil, then the bucket file
+will be used; otherwise, this will work when called in any Org
+file.
+
+Calling with ARG reverses which file – the current file or the
+bucket file – to use. If the bucket file would have been used,
+then the current file is used instead, and vice versa."
+ (interactive "P")
+ (let ((org-velocity-always-use-bucket
+ (if org-velocity-always-use-bucket
+ (not arg)
+ arg)))
+ ;; complain if inappropriate
+ (cl-assert (org-velocity-bucket-file))
+ (let* ((starting-buffer (current-buffer))
+ (org-velocity-bucket-buffer
+ (find-file-noselect (org-velocity-bucket-file)))
+ (org-velocity-navigating
+ (eq starting-buffer org-velocity-bucket-buffer))
+ (org-velocity-recursive-headings '())
+ (org-velocity-recursive-search '())
+ (org-velocity-heading-level
+ (if org-velocity-navigating
+ 0
+ org-velocity-heading-level))
+ (dabbrev-search-these-buffers-only
+ (list org-velocity-bucket-buffer)))
+ (unwind-protect
+ (let ((match
+ (catch 'org-velocity-done
+ (org-velocity-engine
+ (or search
+ (org-velocity-incremental-read "Velocity search: ")))
+ nil)))
+ (when (org-velocity-heading-p match)
+ (org-velocity-edit-entry match)))
+ (kill-buffer (org-velocity-match-buffer))))))
+
+(defalias 'org-velocity-read 'org-velocity)
+
+(provide 'org-velocity)
+
+;;; org-velocity.el ends here
diff --git a/contrib/lisp/org-vm.el b/contrib/lisp/org-vm.el
new file mode 100644
index 0000000..4deca8f
--- /dev/null
+++ b/contrib/lisp/org-vm.el
@@ -0,0 +1,168 @@
+;;; org-vm.el --- Support for links to VM messages from within Org-mode
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; Support for IMAP folders added
+;; by Konrad Hinsen <konrad dot hinsen at fastmail dot net>
+;; Requires VM 8.2.0a or later.
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;; This file implements links to VM messages and folders from within Org-mode.
+;; Org-mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+
+;; Declare external functions and variables
+(declare-function vm-preview-current-message "ext:vm-page" ())
+(declare-function vm-follow-summary-cursor "ext:vm-motion" ())
+(declare-function vm-get-header-contents "ext:vm-summary"
+ (message header-name-regexp &optional clump-sep))
+(declare-function vm-isearch-narrow "ext:vm-search" ())
+(declare-function vm-isearch-update "ext:vm-search" ())
+(declare-function vm-select-folder-buffer "ext:vm-macro" ())
+(declare-function vm-su-message-id "ext:vm-summary" (m))
+(declare-function vm-su-subject "ext:vm-summary" (m))
+(declare-function vm-summarize "ext:vm-summary" (&optional display raise))
+(declare-function vm-imap-folder-p "ext:vm-save" ())
+(declare-function vm-imap-find-spec-for-buffer "ext:vm-imap" (buffer))
+(declare-function vm-imap-folder-for-spec "ext:vm-imap" (spec))
+(declare-function vm-imap-parse-spec-to-list "ext:vm-imap" (spec))
+(declare-function vm-imap-spec-for-account "ext:vm-imap" (account))
+(defvar vm-message-pointer)
+(defvar vm-folder-directory)
+
+;; Install the link type
+(org-link-set-parameters "vm" :follow #'org-vm-open :store #'org-vm-store-link)
+(org-link-set-parameters "vm-imap" :follow #'org-vm-imap-open)
+
+;; Implementation
+(defun org-vm-store-link ()
+ "Store a link to a VM folder or message."
+ (when (and (or (eq major-mode 'vm-summary-mode)
+ (eq major-mode 'vm-presentation-mode))
+ (save-window-excursion
+ (vm-select-folder-buffer) buffer-file-name))
+ (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
+ (vm-follow-summary-cursor)
+ (save-excursion
+ (vm-select-folder-buffer)
+ (let* ((message (car vm-message-pointer))
+ (subject (vm-su-subject message))
+ (to (vm-get-header-contents message "To"))
+ (from (vm-get-header-contents message "From"))
+ (message-id (vm-su-message-id message))
+ (link-type (if (vm-imap-folder-p) "vm-imap" "vm"))
+ (date (vm-get-header-contents message "Date"))
+ folder desc link)
+ (if (vm-imap-folder-p)
+ (let ((spec (vm-imap-find-spec-for-buffer (current-buffer))))
+ (setq folder (vm-imap-folder-for-spec spec)))
+ (progn
+ (setq folder (abbreviate-file-name buffer-file-name))
+ (if (and vm-folder-directory
+ (string-match (concat "^" (regexp-quote vm-folder-directory))
+ folder))
+ (setq folder (replace-match "" t t folder)))))
+ (setq message-id (org-unbracket-string "<" ">" message-id))
+ (org-store-link-props :type link-type :from from :to to :subject subject
+ :message-id message-id :date date)
+ (setq desc (org-email-link-description))
+ (setq link (concat (concat link-type ":") folder "#" message-id))
+ (org-add-link-props :link link :description desc)
+ link))))
+
+(defun org-vm-open (path)
+ "Follow a VM message link specified by PATH."
+ (let (folder article)
+ (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
+ (error "Error in VM link"))
+ (setq folder (match-string 1 path)
+ article (match-string 3 path))
+ ;; The prefix argument will be interpreted as read-only
+ (org-vm-follow-link folder article current-prefix-arg)))
+
+(defun org-vm-follow-link (&optional folder article readonly)
+ "Follow a VM link to FOLDER and ARTICLE."
+ (require 'vm)
+ (setq article (org-add-angle-brackets article))
+ (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
+ ;; ange-ftp or efs or tramp access
+ (let ((user (or (match-string 1 folder) (user-login-name)))
+ (host (match-string 2 folder))
+ (file (match-string 3 folder)))
+ (cond
+ ((featurep 'tramp)
+ ;; use tramp to access the file
+ (setq folder (format "/%s@%s:%s" user host file)))
+ (t
+ ;; use ange-ftp or efs
+ (require 'ange-ftp)
+ (setq folder (format "/%s@%s:%s" user host file))))))
+ (when folder
+ (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
+ (when article
+ (org-vm-select-message (org-add-angle-brackets article)))))
+
+(defun org-vm-imap-open (path)
+ "Follow a VM link to an IMAP folder."
+ (require 'vm-imap)
+ (when (string-match "\\([^:]+\\):\\([^#]+\\)#?\\(.+\\)?" path)
+ (let* ((account-name (match-string 1 path))
+ (mailbox-name (match-string 2 path))
+ (message-id (match-string 3 path))
+ (account-spec (vm-imap-parse-spec-to-list
+ (vm-imap-spec-for-account account-name)))
+ (mailbox-spec (mapconcat 'identity
+ (append (butlast account-spec 4)
+ (cons mailbox-name
+ (last account-spec 3)))
+ ":")))
+ (funcall (cdr (assq 'vm-imap org-link-frame-setup))
+ mailbox-spec)
+ (when message-id
+ (org-vm-select-message (org-add-angle-brackets message-id))))))
+
+(defun org-vm-select-message (message-id)
+ "Go to the message with message-id in the current folder."
+ (require 'vm-search)
+ (sit-for 0.1)
+ (vm-select-folder-buffer)
+ (widen)
+ (let ((case-fold-search t))
+ (goto-char (point-min))
+ (if (not (re-search-forward
+ (concat "^" "message-id: *" (regexp-quote message-id))))
+ (error "Could not find the specified message in this folder"))
+ (vm-isearch-update)
+ (vm-isearch-narrow)
+ (vm-preview-current-message)
+ (vm-summarize)))
+
+(provide 'org-vm)
+
+
+
+;;; org-vm.el ends here
diff --git a/contrib/lisp/org-wikinodes.el b/contrib/lisp/org-wikinodes.el
new file mode 100644
index 0000000..35242db
--- /dev/null
+++ b/contrib/lisp/org-wikinodes.el
@@ -0,0 +1,327 @@
+;;; org-wikinodes.el --- Wiki-like CamelCase links to outline nodes
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;; Version: 7.01trans
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(require 'org)
+(eval-when-compile
+ (require 'cl))
+
+(defgroup org-wikinodes nil
+ "Wiki-like CamelCase links words to outline nodes in Org mode."
+ :tag "Org WikiNodes"
+ :group 'org)
+
+(defconst org-wikinodes-camel-regexp "\\<[A-Z]+[a-z]+[A-Z]+[a-z]+[a-zA-Z]*\\>"
+ "Regular expression matching CamelCase words.")
+
+(defcustom org-wikinodes-active t
+ "Should CamelCase links be active in the current file?"
+ :group 'org-wikinodes
+ :type 'boolean)
+(put 'org-wikinodes-active 'safe-local-variable 'booleanp)
+
+(defcustom org-wikinodes-scope 'file
+ "The scope of searches for wiki targets.
+Allowed values are:
+
+file Search for targets in the current file only
+directory Search for targets in all org files in the current directory"
+ :group 'org-wikinodes
+ :type '(choice
+ (const :tag "Find targets in current file" file)
+ (const :tag "Find targets in current directory" directory)))
+
+(defcustom org-wikinodes-create-targets 'query
+ "Non-nil means create Wiki target when following a wiki link fails.
+Allowed values are:
+
+nil never create node, just throw an error if the target does not exist
+query ask the user what to do
+t create the node in the current buffer
+\"file.org\" create the node in the file \"file.org\", in the same directory
+
+If you are using wiki links across files, you need to set `org-wikinodes-scope'
+to `directory'."
+ :group 'org-wikinodes
+ :type '(choice
+ (const :tag "Never automatically create node" nil)
+ (const :tag "In current file" t)
+ (file :tag "In one special file\n")
+ (const :tag "Query the user" query)))
+
+;;; Link activation
+
+(defun org-wikinodes-activate-links (limit)
+ "Activate CamelCase words as links to Wiki targets."
+ (when org-wikinodes-active
+ (let (case-fold-search)
+ (if (re-search-forward org-wikinodes-camel-regexp limit t)
+ (if (equal (char-after (point-at-bol)) ?*)
+ (progn
+ ;; in heading - deactivate flyspell
+ (org-remove-flyspell-overlays-in (match-beginning 0)
+ (match-end 0))
+ t)
+ ;; this is a wiki link
+ (org-remove-flyspell-overlays-in (match-beginning 0)
+ (match-end 0))
+ (add-text-properties (match-beginning 0) (match-end 0)
+ (list 'mouse-face 'highlight
+ 'face 'org-link
+ 'keymap org-mouse-map
+ 'help-echo "Wiki Link"))
+ t)))))
+
+;;; Following links and creating non-existing target nodes
+
+(defun org-wikinodes-open-at-point ()
+ "Check if the cursor is on a Wiki link and follow the link.
+
+This function goes into `org-open-at-point-functions'."
+ (and org-wikinodes-active
+ (not (org-at-heading-p))
+ (let (case-fold-search) (org-in-regexp org-wikinodes-camel-regexp))
+ (progn (org-wikinodes-follow-link (match-string 0)) t)))
+
+(defun org-wikinodes-follow-link (target)
+ "Follow a wiki link to TARGET.
+
+This need to be found as an exact headline match, either in the current
+buffer, or in any .org file in the current directory, depending on the
+variable `org-wikinodes-scope'.
+
+If a target headline is not found, it may be created according to the
+setting of `org-wikinodes-create-targets'."
+ (if current-prefix-arg (org-wikinodes-clear-directory-targets-cache))
+ (let ((create org-wikinodes-create-targets)
+ visiting buffer m pos file rpl)
+ (setq pos
+ (or (org-find-exact-headline-in-buffer target (current-buffer))
+ (and (eq org-wikinodes-scope 'directory)
+ (setq file (org-wikinodes-which-file
+ target (file-name-directory (buffer-file-name))))
+ (org-find-exact-headline-in-buffer
+ target (or (get-file-buffer file)
+ (find-file-noselect file))))))
+ (if pos
+ (progn
+ (org-mark-ring-push (point))
+ (org-goto-marker-or-bmk pos)
+ (move-marker pos nil))
+ (when (eq create 'query)
+ (if (eq org-wikinodes-scope 'directory)
+ (progn
+ (message "Node \"%s\" does not exist. Should it be created?
+\[RET] in this buffer [TAB] in another file [q]uit" target)
+ (setq rpl (read-char-exclusive))
+ (cond
+ ((member rpl '(?\C-g ?q)) (error "Abort"))
+ ((equal rpl ?\C-m) (setq create t))
+ ((equal rpl ?\C-i)
+ (setq create (file-name-nondirectory
+ (read-file-name "Create in file: "))))
+ (t (error "Invalid selection"))))
+ (if (y-or-n-p (format "Create new node \"%s\" in current buffer? "
+ target))
+ (setq create t)
+ (error "Abort"))))
+
+ (cond
+ ((not create)
+ ;; We are not allowed to create the new node
+ (error "No match for link to \"%s\"" target))
+ ((stringp create)
+ ;; Make new node in another file
+ (org-mark-ring-push (point))
+ (org-pop-to-buffer-same-window (find-file-noselect create))
+ (goto-char (point-max))
+ (or (bolp) (newline))
+ (insert "\n* " target "\n")
+ (backward-char 1)
+ (org-wikinodes-add-target-to-cache target)
+ (message "New Wiki target `%s' created in file \"%s\""
+ target create))
+ (t
+ ;; Make new node in current buffer
+ (org-mark-ring-push (point))
+ (goto-char (point-max))
+ (or (bolp) (newline))
+ (insert "* " target "\n")
+ (backward-char 1)
+ (org-wikinodes-add-target-to-cache target)
+ (message "New Wiki target `%s' created in current buffer"
+ target))))))
+
+;;; The target cache
+
+(defvar org-wikinodes-directory-targets-cache nil)
+
+(defun org-wikinodes-clear-cache-when-on-target ()
+ "When on a headline that is a Wiki target, clear the cache."
+ (when (and (org-at-heading-p)
+ (org-in-regexp (format org-complex-heading-regexp-format
+ org-wikinodes-camel-regexp))
+ (org-in-regexp org-wikinodes-camel-regexp))
+ (org-wikinodes-clear-directory-targets-cache)
+ t))
+
+(defun org-wikinodes-clear-directory-targets-cache ()
+ "Clear the cache where to find wiki targets."
+ (interactive)
+ (setq org-wikinodes-directory-targets-cache nil)
+ (message "Wiki target cache cleared, so that it will update when used again"))
+
+(defun org-wikinodes-get-targets ()
+ "Return a list of all wiki targets in the current buffer."
+ (let ((re (format org-complex-heading-regexp-format
+ org-wikinodes-camel-regexp))
+ (case-fold-search nil)
+ targets)
+ (save-excursion
+ (save-restriction
+ (widen)
+ (goto-char (point-min))
+ (while (re-search-forward re nil t)
+ (push (match-string-no-properties 4) targets))))
+ (nreverse targets)))
+
+(defun org-wikinodes-get-links-for-directory (dir)
+ "Return an alist that connects wiki links to files in directory DIR."
+ (let ((files (directory-files dir nil "\\`[^.#].*\\.org\\'"))
+ (org-inhibit-startup t)
+ target-file-alist file visiting m buffer)
+ (while (setq file (pop files))
+ (setq visiting (org-find-base-buffer-visiting file))
+ (setq buffer (or visiting (find-file-noselect file)))
+ (with-current-buffer buffer
+ (mapc
+ (lambda (target)
+ (setq target-file-alist (cons (cons target file) target-file-alist)))
+ (org-wikinodes-get-targets)))
+ (or visiting (kill-buffer buffer)))
+ target-file-alist))
+
+(defun org-wikinodes-add-target-to-cache (target &optional file)
+ (setq file (or file buffer-file-name (error "No file for new wiki target")))
+ (set-text-properties 0 (length target) nil target)
+ (let ((dir (file-name-directory (expand-file-name file)))
+ a)
+ (setq a (assoc dir org-wikinodes-directory-targets-cache))
+ (if a
+ ;; Push the new target onto the existing list
+ (push (cons target (expand-file-name file)) (cdr a))
+ ;; Call org-wikinodes-which-file so that the cache will be filled
+ (org-wikinodes-which-file target dir))))
+
+(defun org-wikinodes-which-file (target &optional directory)
+ "Return the file for wiki headline TARGET DIRECTORY.
+If there is no such wiki target, return nil."
+ (let* ((directory (expand-file-name (or directory default-directory)))
+ (founddir (assoc directory org-wikinodes-directory-targets-cache))
+ (foundfile (cdr (assoc target (cdr founddir)))))
+ (or foundfile
+ (and (push (cons directory (org-wikinodes-get-links-for-directory directory))
+ org-wikinodes-directory-targets-cache)
+ (cdr (assoc target (cdr (assoc directory
+ org-wikinodes-directory-targets-cache))))))))
+
+;;; Exporting Wiki links
+
+(defvar target)
+(defvar target-alist)
+(defvar last-section-target)
+(defvar org-export-target-aliases)
+(defun org-wikinodes-set-wiki-targets-during-export (_)
+ (let ((line (buffer-substring (point-at-bol) (point-at-eol)))
+ (case-fold-search nil)
+ wtarget a)
+ (when (string-match (format org-complex-heading-regexp-format
+ org-wikinodes-camel-regexp)
+ line)
+ (setq wtarget (match-string 4 line))
+ (push (cons wtarget target) target-alist)
+ (setq a (or (assoc last-section-target org-export-target-aliases)
+ (progn
+ (push (list last-section-target)
+ org-export-target-aliases)
+ (car org-export-target-aliases))))
+ (push (caar target-alist) (cdr a)))))
+
+(defun org-wikinodes-process-links-for-export (_)
+ "Process Wiki links in the export preprocess buffer.
+Try to find target matches in the wiki scope and replace CamelCase words
+with working links."
+ (let ((re org-wikinodes-camel-regexp)
+ (case-fold-search nil)
+ link file)
+ (goto-char (point-min))
+ (while (re-search-forward re nil t)
+ (unless (save-match-data
+ (or (org-at-heading-p)
+ (org-in-regexp org-bracket-link-regexp)
+ (org-in-regexp org-plain-link-re)
+ (org-in-regexp "<<[^<>]+>>")))
+ (setq link (match-string 0))
+ (delete-region (match-beginning 0) (match-end 0))
+ (save-match-data
+ (cond
+ ((org-find-exact-headline-in-buffer link (current-buffer))
+ ;; Found in current buffer
+ (insert (format "[[*%s][%s]]" link link)))
+ ((eq org-wikinodes-scope 'file)
+ ;; No match in file, and other files are not allowed
+ (insert (format "%s" link)))
+ (t ;; No match for this link
+ (insert (format "%s" link)))))))))
+
+;;; Hook the WikiNode mechanism into Org
+
+;; `C-c C-o' should follow wiki links
+(add-hook 'org-open-at-point-functions 'org-wikinodes-open-at-point)
+
+;; `C-c C-c' should clear the cache
+(add-hook 'org-ctrl-c-ctrl-c-hook 'org-wikinodes-clear-cache-when-on-target)
+
+;; Make Wiki haeding create additional link names for headlines
+(add-hook 'org-export-before-parsing-hook
+ 'org-wikinodes-set-wiki-targets-during-export)
+
+;; Turn Wiki links into links the exporter will treat correctly
+(add-hook 'org-export-before-parsing-hook
+ 'org-wikinodes-process-links-for-export)
+
+;; Activate CamelCase words as part of Org mode font lock
+
+(defun org-wikinodes-add-to-font-lock-keywords ()
+ "Add wikinode CamelCase highlighting to `org-font-lock-extra-keywords'."
+ (let ((m (member '(org-activate-links) org-font-lock-extra-keywords)))
+ (if m (push '(org-wikinodes-activate-links) (cdr m))
+ (message "Failed to add wikinodes to `org-font-lock-extra-keywords'."))))
+
+(add-hook 'org-font-lock-set-keywords-hook
+ 'org-wikinodes-add-to-font-lock-keywords)
+
+(provide 'org-wikinodes)
+
+;;; org-wikinodes.el ends here
diff --git a/contrib/lisp/org-wl.el b/contrib/lisp/org-wl.el
new file mode 100644
index 0000000..4f74d47
--- /dev/null
+++ b/contrib/lisp/org-wl.el
@@ -0,0 +1,302 @@
+;;; org-wl.el --- Support for links to Wanderlust messages from within Org-mode
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Tokuya Kameshima <kames at fa2 dot so-net dot ne dot jp>
+;; David Maus <dmaus at ictsoc dot de>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to Wanderlust messages from within Org-mode.
+;; Org-mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+
+(defgroup org-wl nil
+ "Options concerning the Wanderlust link."
+ :tag "Org Startup"
+ :group 'org-link)
+
+(defcustom org-wl-link-to-refile-destination t
+ "Create a link to the refile destination if the message is marked as refile."
+ :group 'org-wl
+ :type 'boolean)
+
+(defcustom org-wl-link-remove-filter nil
+ "Remove filter condition if message is filter folder."
+ :group 'org-wl
+ :type 'boolean)
+
+(defcustom org-wl-shimbun-prefer-web-links nil
+ "If non-nil create web links for shimbun messages."
+ :group 'org-wl
+ :type 'boolean)
+
+(defcustom org-wl-nntp-prefer-web-links nil
+ "If non-nil create web links for nntp messages.
+When folder name contains string \"gmane\" link to gmane,
+googlegroups otherwise."
+ :type 'boolean
+ :group 'org-wl)
+
+(defcustom org-wl-disable-folder-check t
+ "Disable check for new messages when open a link."
+ :type 'boolean
+ :group 'org-wl)
+
+(defcustom org-wl-namazu-default-index nil
+ "Default namazu search index."
+ :type '(choice (const nil) (directory))
+ :group 'org-wl)
+
+;; Declare external functions and variables
+(declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
+(declare-function elmo-message-entity-field "ext:elmo-msgdb"
+ (entity field &optional type))
+(declare-function elmo-message-field "ext:elmo"
+ (folder number field &optional type) t)
+(declare-function elmo-msgdb-overview-get-entity "ext:elmo" (id msgdb) t)
+;; Backward compatibility to old version of wl
+(declare-function wl "ext:wl" () t)
+(declare-function wl-summary-buffer-msgdb "ext:wl-folder" () t)
+(declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary"
+ (&optional id))
+(declare-function wl-summary-jump-to-msg "ext:wl-summary"
+ (&optional number beg end))
+(declare-function wl-summary-line-from "ext:wl-summary" ())
+(declare-function wl-summary-line-subject "ext:wl-summary" ())
+(declare-function wl-summary-message-number "ext:wl-summary" ())
+(declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
+(declare-function wl-summary-registered-temp-mark "ext:wl-action" (number))
+(declare-function wl-folder-goto-folder-subr "ext:wl-folder"
+ (&optional folder sticky))
+(declare-function wl-folder-get-petname "ext:wl-folder" (name))
+(declare-function wl-folder-get-entity-from-buffer "ext:wl-folder"
+ (&optional getid))
+(declare-function wl-folder-buffer-group-p "ext:wl-folder")
+(defvar wl-init)
+(defvar wl-summary-buffer-elmo-folder)
+(defvar wl-summary-buffer-folder-name)
+(defvar wl-folder-group-regexp)
+(defvar wl-auto-check-folder-name)
+(defvar elmo-nntp-default-server)
+
+(defconst org-wl-folder-types
+ '(("%" . imap) ("-" . nntp) ("+" . mh) ("=" . spool)
+ ("$" . archive) ("&" . pop) ("@" . shimbun) ("[" . search)
+ ("*" . multi) ("/" . filter) ("|" . pipe) ("'" . internal))
+ "List of folder indicators. See Wanderlust manual, section 3.")
+
+;; Install the link type
+(org-link-set-parameters "wl" :follow #'org-wl-open :store #'org-wl-store-link)
+
+;; Implementation
+
+(defun org-wl-folder-type (folder)
+ "Return symbol that indicates the type of FOLDER.
+FOLDER is the wanderlust folder name. The first character of the
+folder name determines the folder type."
+ (let* ((indicator (substring folder 0 1))
+ (type (cdr (assoc indicator org-wl-folder-types))))
+ ;; maybe access or file folder
+ (when (not type)
+ (setq type
+ (cond
+ ((and (>= (length folder) 5)
+ (string= (substring folder 0 5) "file:"))
+ 'file)
+ ((and (>= (length folder) 7)
+ (string= (substring folder 0 7) "access:"))
+ 'access)
+ (t
+ nil))))
+ type))
+
+(defun org-wl-message-field (field entity)
+ "Return content of FIELD in ENTITY.
+FIELD is a symbol of a rfc822 message header field.
+ENTITY is a message entity."
+ (let ((content (elmo-message-entity-field entity field 'string)))
+ (if (listp content) (car content) content)))
+
+(defun org-wl-store-link ()
+ "Store a link to a WL message or folder."
+ (unless (eobp)
+ (cond
+ ((memq major-mode '(wl-summary-mode mime-view-mode))
+ (org-wl-store-link-message))
+ ((eq major-mode 'wl-folder-mode)
+ (org-wl-store-link-folder))
+ (t
+ nil))))
+
+(defun org-wl-store-link-folder ()
+ "Store a link to a WL folder."
+ (let* ((folder (wl-folder-get-entity-from-buffer))
+ (petname (wl-folder-get-petname folder))
+ (link (concat "wl:" folder)))
+ (save-excursion
+ (beginning-of-line)
+ (unless (and (wl-folder-buffer-group-p)
+ (looking-at wl-folder-group-regexp))
+ (org-store-link-props :type "wl" :description petname
+ :link link)
+ link))))
+
+(defun org-wl-store-link-message ()
+ "Store a link to a WL message."
+ (save-excursion
+ (let ((buf (if (eq major-mode 'wl-summary-mode)
+ (current-buffer)
+ (and (boundp 'wl-message-buffer-cur-summary-buffer)
+ wl-message-buffer-cur-summary-buffer))))
+ (when buf
+ (with-current-buffer buf
+ (let* ((msgnum (wl-summary-message-number))
+ (mark-info (wl-summary-registered-temp-mark msgnum))
+ (folder-name
+ (if (and org-wl-link-to-refile-destination
+ mark-info
+ (equal (nth 1 mark-info) "o")) ; marked as refile
+ (nth 2 mark-info)
+ wl-summary-buffer-folder-name))
+ (folder-type (org-wl-folder-type folder-name))
+ (wl-message-entity
+ (if (fboundp 'elmo-message-entity)
+ (elmo-message-entity
+ wl-summary-buffer-elmo-folder msgnum)
+ (elmo-msgdb-overview-get-entity
+ msgnum (wl-summary-buffer-msgdb))))
+ (message-id
+ (org-wl-message-field 'message-id wl-message-entity))
+ (message-id-no-brackets
+ (org-unbracket-string "<" ">" message-id))
+ (from (org-wl-message-field 'from wl-message-entity))
+ (to (org-wl-message-field 'to wl-message-entity))
+ (xref (org-wl-message-field 'xref wl-message-entity))
+ (subject (org-wl-message-field 'subject wl-message-entity))
+ (date (org-wl-message-field 'date wl-message-entity))
+ desc link)
+
+ ;; remove text properties of subject string to avoid possible bug
+ ;; when formatting the subject
+ ;; (Emacs bug #5306, fixed)
+ (set-text-properties 0 (length subject) nil subject)
+
+ ;; maybe remove filter condition
+ (when (and (eq folder-type 'filter) org-wl-link-remove-filter)
+ (while (eq (org-wl-folder-type folder-name) 'filter)
+ (setq folder-name
+ (replace-regexp-in-string "^/[^/]+/" "" folder-name))))
+
+ ;; maybe create http link
+ (cond
+ ((and (eq folder-type 'shimbun)
+ org-wl-shimbun-prefer-web-links xref)
+ (org-store-link-props :type "http" :link xref :description subject
+ :from from :to to :message-id message-id
+ :message-id-no-brackets message-id-no-brackets
+ :subject subject))
+ ((and (eq folder-type 'nntp) org-wl-nntp-prefer-web-links)
+ (setq link
+ (format
+ (if (string-match "gmane\\." folder-name)
+ "http://mid.gmane.org/%s"
+ "http://groups.google.com/groups/search?as_umsgid=%s")
+ (org-fixup-message-id-for-http message-id)))
+ (org-store-link-props :type "http" :link link :description subject
+ :from from :to to :message-id message-id
+ :message-id-no-brackets message-id-no-brackets
+ :subject subject))
+ (t
+ (org-store-link-props :type "wl" :from from :to to
+ :subject subject :message-id message-id
+ :message-id-no-brackets message-id-no-brackets)
+ (setq desc (org-email-link-description))
+ (setq link (concat "wl:" folder-name "#" message-id-no-brackets))
+ (org-add-link-props :link link :description desc)))
+ (org-add-link-props :date date)
+ (or link xref)))))))
+
+(defun org-wl-open-nntp (path)
+ "Follow the nntp: link specified by PATH."
+ (let* ((spec (split-string path "/"))
+ (server (split-string (nth 2 spec) "@"))
+ (group (nth 3 spec))
+ (article (nth 4 spec)))
+ (org-wl-open
+ (concat "-" group ":" (if (cdr server)
+ (car (split-string (car server) ":"))
+ "")
+ (if (string= elmo-nntp-default-server (nth 2 spec))
+ ""
+ (concat "@" (or (cdr server) (car server))))
+ (if article (concat "#" article) "")))))
+
+(defun org-wl-open (path)
+ "Follow the WL message link specified by PATH.
+When called with one prefix, open message in namazu search folder
+with `org-wl-namazu-default-index' as search index. When called
+with two prefixes or `org-wl-namazu-default-index' is nil, ask
+for namazu index."
+ (require 'wl)
+ (let ((wl-auto-check-folder-name
+ (if org-wl-disable-folder-check
+ 'none
+ wl-auto-check-folder-name)))
+ (unless wl-init (wl))
+ ;; XXX: The imap-uw's MH folder names start with "%#".
+ (if (not (string-match "\\`\\(\\(?:%#\\)?[^#]+\\)\\(#\\(.*\\)\\)?" path))
+ (error "Error in Wanderlust link"))
+ (let ((folder (match-string 1 path))
+ (article (match-string 3 path)))
+ ;; maybe open message in namazu search folder
+ (when current-prefix-arg
+ (setq folder (concat "[" article "]"
+ (if (and (equal current-prefix-arg '(4))
+ org-wl-namazu-default-index)
+ org-wl-namazu-default-index
+ (read-directory-name "Namazu index: ")))))
+ (if (not (elmo-folder-exists-p (with-no-warnings
+ (wl-folder-get-elmo-folder folder))))
+ (error "No such folder: %s" folder))
+ (let ((old-buf (current-buffer))
+ (old-point (point-marker)))
+ (wl-folder-goto-folder-subr folder)
+ (with-current-buffer old-buf
+ ;; XXX: `wl-folder-goto-folder-subr' moves point to the
+ ;; beginning of the current line. So, restore the point
+ ;; in the old buffer.
+ (goto-char old-point))
+ (when article
+ (if (string-match-p "@" article)
+ (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets
+ article))
+ (or (wl-summary-jump-to-msg (string-to-number article))
+ (error "No such message: %s" article)))
+ (wl-summary-redisplay))))))
+
+(provide 'org-wl)
+
+;;; org-wl.el ends here
diff --git a/contrib/lisp/orgtbl-sqlinsert.el b/contrib/lisp/orgtbl-sqlinsert.el
new file mode 100644
index 0000000..8fba18f
--- /dev/null
+++ b/contrib/lisp/orgtbl-sqlinsert.el
@@ -0,0 +1,118 @@
+;;; orgtbl-sqlinsert.el --- orgtbl to SQL insert statements.
+
+;; Copyright (C) 2008-2017 Free Software Foundation
+
+;; Author: Jason Riedy <jason@acm.org>
+;; Keywords: org, tables, sql
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Converts an orgtbl to a sequence of SQL insertion commands.
+;; Table cells are quoted and escaped very conservatively.
+
+;;; Code:
+
+(defun orgtbl-to-sqlinsert (table params)
+ "Convert the orgtbl-mode TABLE to SQL insert statements.
+TABLE is a list, each entry either the symbol `hline' for a horizontal
+separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the conversion.
+
+Names and strings are modified slightly by default. Single-ticks
+are doubled as per SQL's standard mechanism. Backslashes and
+dollar signs are deleted. And tildes are changed to spaces.
+These modifications were chosed for use with TeX. See
+ORGTBL-SQL-STRIP-AND-QUOTE.
+
+Supports all parameters from ORGTBL-TO-GENERIC. New to this function
+are:
+
+:sqlname The name of the database table; defaults to the name of the
+ target region.
+
+:nowebname If not nil, used as a wrapping noweb fragment name.
+
+The most important parameters of ORGTBL-TO-GENERIC for SQL are:
+
+:splice When set to t, return only insert statements, don't wrap
+ them in a transaction. Default is nil.
+
+:tstart, :tend
+ The strings used to begin and commit the transaction.
+
+:hfmt A function that gathers the quoted header names into a
+ dynamically scoped variable HDRLIST. Probably should
+ not be changed by the user.
+
+The general parameters :skip and :skipcols have already been applied when
+this function is called."
+ (let* (hdrlist
+ (alignment (mapconcat (lambda (x) (if x "r" "l"))
+ org-table-last-alignment ""))
+ (nowebname (plist-get params :nowebname))
+ (breakvals (plist-get params :breakvals))
+ (firstheader t)
+ (*orgtbl-default-fmt* 'orgtbl-sql-strip-and-quote)
+ (params2
+ (list
+ :sqlname (plist-get params :sqlname)
+ :tstart (lambda () (concat (if nowebname
+ (format "<<%s>>= \n" nowebname)
+ "")
+ "BEGIN TRANSACTION;"))
+ :tend (lambda () (concat "COMMIT;" (if nowebname "\n@ " "")))
+ :hfmt (lambda (f) (progn (if firstheader (push f hdrlist) "")))
+ :hlfmt (lambda (&rest cells) (setq firstheader nil))
+ :lstart (lambda () (concat "INSERT INTO "
+ sqlname "( "
+ (mapconcat 'identity (reverse hdrlist)
+ ", ")
+ " )" (if breakvals "\n" " ")
+ "VALUES ( "))
+ :lend " );"
+ :sep " , "
+ :hline nil
+ :remove-nil-lines t))
+ (params (org-combine-plists params2 params))
+ (sqlname (plist-get params :sqlname)))
+ (orgtbl-to-generic table params)))
+
+(defun orgtbl-sql-quote (str)
+ "Convert single ticks to doubled single ticks and wrap in single ticks."
+ (concat "'" (mapconcat 'identity (split-string str "'") "''") "'"))
+
+(defun orgtbl-sql-strip-dollars-escapes-tildes (str)
+ "Strip dollarsigns and backslash escapes, replace tildes with spaces."
+ (mapconcat 'identity
+ (split-string (mapconcat 'identity
+ (split-string str "\\$\\|\\\\")
+ "")
+ "~")
+ " "))
+
+(defun orgtbl-sql-strip-and-quote (str)
+ "Apply ORGBTL-SQL-QUOTE and ORGTBL-SQL-STRIP-DOLLARS-ESCAPES-TILDES
+to sanitize STR for use in SQL statements."
+ (cond ((stringp str)
+ (orgtbl-sql-quote (orgtbl-sql-strip-dollars-escapes-tildes str)))
+ ((sequencep str) (mapcar 'orgtbl-sql-strip-and-quote str))
+ (t nil)))
+
+(provide 'orgtbl-sqlinsert)
+
+;;; orgtbl-sqlinsert.el ends here
diff --git a/contrib/lisp/ox-bibtex.el b/contrib/lisp/ox-bibtex.el
new file mode 100644
index 0000000..fb34a5e
--- /dev/null
+++ b/contrib/lisp/ox-bibtex.el
@@ -0,0 +1,431 @@
+;;; ox-bibtex.el --- Export bibtex fragments
+
+;; Copyright (C) 2009-2014 Taru Karttunen
+
+;; Author: Taru Karttunen <taruti@taruti.net>
+;; Nicolas Goaziou <n dot goaziou at gmail dot com>
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING. If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;;
+;; This is an utility to handle BibTeX export to LaTeX, html and ascii
+;; exports. For HTML and ascii it uses the bibtex2html software from:
+;;
+;; http://www.lri.fr/~filliatr/bibtex2html/
+;;
+;; For ascii it uses the pandoc software from:
+;;
+;; http://johnmacfarlane.net/pandoc/
+;;
+;; It also introduces "cite" syntax for Org links.
+;;
+;; The usage is as follows:
+;;
+;; #+BIBLIOGRAPHY: bibfilename stylename optional-options
+;;
+;; e.g. given foo.bib and using style plain:
+;;
+;; #+BIBLIOGRAPHY: foo plain option:-d
+;;
+;; "stylename" can also be "nil", in which case no style will be used.
+;;
+;; Full filepaths are also possible:
+;;
+;; #+BIBLIOGRAPHY: /home/user/Literature/foo.bib plain option:-d
+;;
+;; Optional options are of the form:
+;;
+;; option:-foobar pass '-foobar' to bibtex2html
+;;
+;; e.g.,
+;;
+;; option:-d sort by date
+;; option:-a sort as BibTeX (usually by author) *default*
+;; option:-u unsorted i.e. same order as in .bib file
+;; option:-r reverse the sort
+;;
+;; See the bibtex2html man page for more. Multiple options can be
+;; combined like:
+;;
+;; option:-d option:-r
+;;
+;; Limiting to only the entries cited in the document:
+;;
+;; limit:t
+;;
+;; For LaTeX export this simply inserts the lines
+;;
+;; \bibliographystyle{plain}
+;; \bibliography{foo}
+;;
+;; into the TeX file when exporting.
+;;
+;; For HTML export it:
+;; 1) converts all \cite{foo} and [[cite:foo]] to links to the
+;; bibliography,
+;; 2) creates a foo.html and foo_bib.html,
+;; 3) includes the contents of foo.html in the exported HTML file.
+;;
+;; For ascii export it:
+;; 1) converts all \cite{foo} and [[cite:foo]] to links to the
+;; bibliography,
+;; 2) creates a foo.txt and foo_bib.html,
+;; 3) includes the contents of foo.txt in the exported ascii file.
+;;
+;; For LaTeX export it:
+;; 1) converts all [[cite:foo]] to \cite{foo}.
+
+;; Initialization
+
+(require 'cl-lib)
+
+;;; Internal Functions
+
+(defun org-bibtex-get-file (keyword)
+ "Return bibliography file as a string.
+KEYWORD is a \"BIBLIOGRAPHY\" keyword. If no file is found,
+return nil instead."
+ (let ((value (org-element-property :value keyword)))
+ (and value
+ (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
+ (match-string 1 value))))
+
+(defun org-bibtex-get-style (keyword)
+ "Return bibliography style as a string.
+KEYWORD is a \"BIBLIOGRAPHY\" keyword. If no style is found,
+return nil instead."
+ (let ((value (org-element-property :value keyword)))
+ (and value
+ (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
+ (match-string 2 value))))
+
+(defun org-bibtex-get-arguments (keyword)
+ "Return \"bibtex2html\" arguments specified by the user.
+KEYWORD is a \"BIBLIOGRAPHY\" keyword. Return value is a plist
+containing `:options' and `:limit' properties. The former
+contains a list of strings to be passed as options to
+\"bibtex2html\" process. The latter contains a boolean."
+ (let ((value (org-element-property :value keyword)))
+ (and value
+ (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
+ (let (options limit)
+ (dolist (arg (org-split-string (match-string 3 value))
+ ;; Return value.
+ (list :options (nreverse options) :limit limit))
+ (let* ((s (split-string arg ":"))
+ (key (car s))
+ (value (nth 1 s)))
+ (cond ((equal "limit" key)
+ (setq limit (not (equal "nil" value))))
+ ((equal "option" key) (push value options)))))))))
+
+(defun org-bibtex-citation-p (object)
+ "Non-nil when OBJECT is a citation."
+ (cl-case (org-element-type object)
+ (link (equal (org-element-property :type object) "cite"))
+ (latex-fragment
+ (string-match "\\`\\\\cite{" (org-element-property :value object)))))
+
+(defun org-bibtex-get-citation-key (citation)
+ "Return key for a given citation, as a string.
+CITATION is a `latex-fragment' or `link' type object satisfying
+to `org-bibtex-citation-p' predicate."
+ (if (eq (org-element-type citation) 'link)
+ (org-element-property :path citation)
+ (let ((value (org-element-property :value citation)))
+ (and (string-match "\\`\\\\cite{" value)
+ (substring value (match-end 0) -1)))))
+
+
+;;; Follow cite: links
+
+(defun org-bibtex-file nil "Org-mode file of bibtex entries.")
+
+(defun org-bibtex-goto-citation (&optional citation)
+ "Visit a citation given its ID."
+ (interactive)
+ (let ((citation (or citation (completing-read "Citation: " (obe-citations)))))
+ (find-file (or org-bibtex-file
+ (error "`org-bibtex-file' has not been configured")))
+ (goto-char (point-min))
+ (when (re-search-forward (format " :CUSTOM_ID: %s" citation) nil t)
+ (outline-previous-visible-heading 1)
+ t)))
+
+(let ((jump-fn (car (cl-remove-if-not #'fboundp '(ebib org-bibtex-goto-citation)))))
+ (org-add-link-type "cite" jump-fn))
+
+
+
+;;; Filters
+
+(defun org-bibtex-process-bib-files (tree backend info)
+ "Send each bibliography in parse tree to \"bibtex2html\" process.
+Return new parse tree."
+ (when (org-export-derived-backend-p backend 'ascii 'html)
+ ;; Initialize dynamically scoped variables. The first one
+ ;; contain an alist between keyword objects and their HTML
+ ;; translation. The second one will contain an alist between
+ ;; citation keys and names in the output (according to style).
+ (setq org-bibtex-html-entries-alist nil
+ org-bibtex-html-keywords-alist nil)
+ (org-element-map tree 'keyword
+ (lambda (keyword)
+ (when (equal (org-element-property :key keyword) "BIBLIOGRAPHY")
+ (let ((arguments (org-bibtex-get-arguments keyword))
+ (file (org-bibtex-get-file keyword))
+ temp-file
+ out-file)
+ ;; Test if filename is given with .bib-extension and strip
+ ;; it off. Filenames with another extensions will be
+ ;; untouched and will finally rise an error in bibtex2html.
+ (setq file (if (equal (file-name-extension file) "bib")
+ (file-name-sans-extension file) file))
+ ;; Outpufiles of bibtex2html will be put into current working directory
+ ;; so define a variable for this.
+ (setq out-file (file-name-sans-extension
+ (file-name-nondirectory file)))
+ ;; limit is set: collect citations throughout the document
+ ;; in TEMP-FILE and pass it to "bibtex2html" as "-citefile"
+ ;; argument.
+ (when (plist-get arguments :limit)
+ (let ((citations
+ (org-element-map tree '(latex-fragment link)
+ (lambda (object)
+ (and (org-bibtex-citation-p object)
+ (org-bibtex-get-citation-key object))))))
+ (with-temp-file (setq temp-file (make-temp-file "ox-bibtex"))
+ (insert (mapconcat 'identity citations "\n")))
+ (setq arguments
+ (plist-put arguments
+ :options
+ (append (plist-get arguments :options)
+ (list "-citefile" temp-file))))))
+ ;; Call "bibtex2html" on specified file.
+ (unless (eq 0 (apply
+ 'call-process
+ (append '("bibtex2html" nil nil nil)
+ '("-a" "-nodoc" "-noheader" "-nofooter")
+ (let ((style
+ (org-not-nil
+ (org-bibtex-get-style keyword))))
+ (and style (list "--style" style)))
+ (plist-get arguments :options)
+ (list (concat file ".bib")))))
+ (error "Executing bibtex2html failed"))
+ (and temp-file (delete-file temp-file))
+ ;; Open produced HTML file, and collect Bibtex key names
+ (with-temp-buffer
+ (insert-file-contents (concat out-file ".html"))
+ ;; Update `org-bibtex-html-entries-alist'.
+ (goto-char (point-min))
+ (while (re-search-forward
+ "a name=\"\\([-_a-zA-Z0-9:]+\\)\">\\([^<]+\\)" nil t)
+ (push (cons (match-string 1) (match-string 2))
+ org-bibtex-html-entries-alist)))
+ ;; Open produced HTML file, wrap references within a block and
+ ;; return it.
+ (with-temp-buffer
+ (cond
+ ((org-export-derived-backend-p backend 'html)
+ (insert (format "<div id=\"bibliography\">\n<h2>%s</h2>\n"
+ (org-export-translate "References" :html info)))
+ (insert-file-contents (concat out-file ".html"))
+ (goto-char (point-max))
+ (insert "\n</div>"))
+ ((org-export-derived-backend-p backend 'ascii)
+ ;; convert HTML references to text w/pandoc
+ (unless (eq 0 (call-process "pandoc" nil nil nil
+ (concat out-file ".html")
+ "-o"
+ (concat out-file ".txt")))
+ (error "Executing pandoc failed"))
+ (insert
+ (format
+ "%s\n==========\n\n"
+ (org-export-translate
+ "References"
+ (intern (format ":%s" (plist-get info :ascii-charset)))
+ info)))
+ (insert-file-contents (concat out-file ".txt"))
+ (goto-char (point-min))
+ (while (re-search-forward
+ "\\[ \\[bib\\][^ ]+ \\(\\]\\||[\n\r]\\)" nil t)
+ (replace-match ""))
+ (goto-char (point-min))
+ (while (re-search-forward "\\( \\]\\| \\]\\| |\\)" nil t)
+ (replace-match ""))
+ (goto-char (point-min))
+ (while (re-search-forward "[\n\r]\\([\n\r][\n\r]\\)" nil t)
+ (replace-match "\\1"))))
+ ;; Update `org-bibtex-html-keywords-alist'.
+ (push (cons keyword (buffer-string))
+ org-bibtex-html-keywords-alist)))))))
+ ;; Return parse tree unchanged.
+ tree)
+
+(defun org-bibtex-merge-contiguous-citations (tree backend info)
+ "Merge all contiguous citation in parse tree.
+As a side effect, this filter will also turn all \"cite\" links
+into \"\\cite{...}\" LaTeX fragments and will extract options.
+Cite options are placed into square brackets at the beginning of
+the \"\\cite\" command for the LaTeX backend, and are removed for
+the HTML and ASCII backends."
+ (when (org-export-derived-backend-p backend 'html 'latex 'ascii)
+ (org-element-map tree '(link latex-fragment)
+ (lambda (object)
+ (when (org-bibtex-citation-p object)
+ (let ((new-citation (list 'latex-fragment
+ (list :value ""
+ :post-blank (org-element-property
+ :post-blank object))))
+ option)
+ ;; Insert NEW-CITATION right before OBJECT.
+ (org-element-insert-before new-citation object)
+ ;; Remove all subsequent contiguous citations from parse
+ ;; tree, keeping only their citation key.
+ (let ((keys (list (org-bibtex-get-citation-key object)))
+ next)
+ (while (and (setq next (org-export-get-next-element object info))
+ (or (and (stringp next)
+ (not (string-match-p "\\S-" next)))
+ (org-bibtex-citation-p next)))
+ (unless (stringp next)
+ (push (org-bibtex-get-citation-key next) keys))
+ (org-element-extract-element object)
+ (setq object next))
+ ;; Find any options in keys, e.g., "(Chapter 2)key" has
+ ;; the option "Chapter 2".
+ (setq keys
+ (mapcar
+ (lambda (k)
+ (if (string-match "^(\\([^)]\+\\))\\(.*\\)" k)
+ (progn
+ (when (org-export-derived-backend-p backend 'latex)
+ (setq option (format "[%s]" (match-string 1 k))))
+ (match-string 2 k))
+ k))
+ keys))
+ (org-element-extract-element object)
+ ;; Eventually merge all keys within NEW-CITATION. Also
+ ;; ensure NEW-CITATION has the same :post-blank property
+ ;; as the last citation removed.
+ (org-element-put-property
+ new-citation
+ :post-blank (org-element-property :post-blank object))
+ (org-element-put-property
+ new-citation
+ :value (format "\\cite%s{%s}"
+ (or option "")
+ (mapconcat 'identity (nreverse keys) ",")))))))))
+ tree)
+
+(eval-after-load 'ox
+ '(progn (add-to-list 'org-export-filter-parse-tree-functions
+ 'org-bibtex-process-bib-files)
+ (add-to-list 'org-export-filter-parse-tree-functions
+ 'org-bibtex-merge-contiguous-citations)))
+
+
+
+;;; LaTeX Part
+
+(defadvice org-latex-keyword (around bibtex-keyword)
+ "Translate \"BIBLIOGRAPHY\" keywords into LaTeX syntax.
+Fallback to `latex' back-end for other keywords."
+ (let ((keyword (ad-get-arg 0)))
+ (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
+ ad-do-it
+ (let ((file (org-bibtex-get-file keyword))
+ (style (org-not-nil (org-bibtex-get-style keyword))))
+ (setq ad-return-value
+ (when file
+ (concat (and style (format "\\bibliographystyle{%s}\n" style))
+ (format "\\bibliography{%s}" file))))))))
+
+(ad-activate 'org-latex-keyword)
+
+
+
+;;; HTML Part
+
+(defvar org-bibtex-html-entries-alist nil) ; Dynamically scoped.
+(defvar org-bibtex-html-keywords-alist nil) ; Dynamically scoped.
+
+
+;;;; Advices
+
+(defadvice org-html-keyword (around bibtex-keyword)
+ "Translate \"BIBLIOGRAPHY\" keywords into HTML syntax.
+Fallback to `html' back-end for other keywords."
+ (let ((keyword (ad-get-arg 0)))
+ (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
+ ad-do-it
+ (setq ad-return-value
+ (cdr (assq keyword org-bibtex-html-keywords-alist))))))
+
+(defadvice org-html-latex-fragment (around bibtex-citation)
+ "Translate \"\\cite\" LaTeX fragments into HTML syntax.
+Fallback to `html' back-end for other keywords."
+ (let ((fragment (ad-get-arg 0)))
+ (if (not (org-bibtex-citation-p fragment)) ad-do-it
+ (setq ad-return-value
+ (format "[%s]"
+ (mapconcat
+ (lambda (key)
+ (format "<a href=\"#%s\">%s</a>"
+ key
+ (or (cdr (assoc key org-bibtex-html-entries-alist))
+ key)))
+ (org-split-string
+ (org-bibtex-get-citation-key fragment) ",") ","))))))
+
+(ad-activate 'org-html-keyword)
+(ad-activate 'org-html-latex-fragment)
+
+
+;;; Ascii Part
+(defadvice org-ascii-keyword (around bibtex-keyword)
+ "Translate \"BIBLIOGRAPHY\" keywords into ascii syntax.
+Fallback to `ascii' back-end for other keywords."
+ (let ((keyword (ad-get-arg 0)))
+ (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
+ ad-do-it
+ (setq ad-return-value
+ (cdr (assq keyword org-bibtex-html-keywords-alist))))))
+
+(defadvice org-ascii-latex-fragment (around bibtex-citation)
+ "Translate \"\\cite\" LaTeX fragments into ascii syntax.
+Fallback to `ascii' back-end for other keywords."
+ (let ((fragment (ad-get-arg 0)))
+ (if (not (org-bibtex-citation-p fragment)) ad-do-it
+ (setq ad-return-value
+ (format "[%s]"
+ (mapconcat
+ (lambda (key)
+ (or (cdr (assoc key org-bibtex-html-entries-alist))
+ key))
+ (org-split-string
+ (org-bibtex-get-citation-key fragment) ",") ","))))))
+
+(ad-activate 'org-ascii-keyword)
+(ad-activate 'org-ascii-latex-fragment)
+
+(provide 'ox-bibtex)
+
+;;; ox-bibtex.el ends here
diff --git a/contrib/lisp/ox-confluence.el b/contrib/lisp/ox-confluence.el
new file mode 100644
index 0000000..9de6ce7
--- /dev/null
+++ b/contrib/lisp/ox-confluence.el
@@ -0,0 +1,228 @@
+;;; ox-confluence --- Confluence Wiki Back-End for Org Export Engine
+
+;; Copyright (C) 2012, 2014 Sébastien Delafond
+
+;; Author: Sébastien Delafond <sdelafond@gmail.com>
+;; Keywords: outlines, confluence, wiki
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; ox-confluence.el lets you convert Org files to confluence files
+;; using the ox.el export engine.
+;;
+;; Put this file into your load-path and the following into your ~/.emacs:
+;; (require 'ox-confluence)
+;;
+;; Export Org files to confluence:
+;; M-x org-confluence-export-as-confluence RET
+;;
+;;; Code:
+
+(require 'ox)
+(require 'ox-ascii)
+
+;; Define the backend itself
+(org-export-define-derived-backend 'confluence 'ascii
+ :translate-alist '((bold . org-confluence-bold)
+ (example-block . org-confluence-example-block)
+ (fixed-width . org-confluence-fixed-width)
+ (footnote-definition . org-confluence-empty)
+ (footnote-reference . org-confluence-empty)
+ (headline . org-confluence-headline)
+ (italic . org-confluence-italic)
+ (item . org-confluence-item)
+ (link . org-confluence-link)
+ (paragraph . org-confluence-paragraph)
+ (property-drawer . org-confluence-property-drawer)
+ (section . org-confluence-section)
+ (src-block . org-confluence-src-block)
+ (strike-through . org-confluence-strike-through)
+ (table . org-confluence-table)
+ (table-cell . org-confluence-table-cell)
+ (table-row . org-confluence-table-row)
+ (template . org-confluence-template)
+ (timestamp . org-confluence-timestamp)
+ (underline . org-confluence-underline)))
+
+(defcustom org-confluence-lang-alist
+ '(("sh" . "bash"))
+ "Map from org-babel language name to confluence wiki language name"
+ :type '(alist :key-type string :value-type string))
+
+;; All the functions we use
+(defun org-confluence-bold (bold contents info)
+ (format "*%s*" contents))
+
+(defun org-confluence-empty (empty contents info)
+ "")
+
+(defun org-confluence-example-block (example-block contents info)
+ ;; FIXME: provide a user-controlled variable for theme
+ (let ((content (org-export-format-code-default example-block info)))
+ (org-confluence--block "none" "Confluence" content)))
+
+(defun org-confluence-italic (italic contents info)
+ (format "_%s_" contents))
+
+(defun org-confluence-item (item contents info)
+ (concat (make-string (1+ (org-confluence--li-depth item)) ?\-)
+ " "
+ (org-trim contents)))
+
+(defun org-confluence-fixed-width (fixed-width contents info)
+ (format "\{\{%s\}\}" contents))
+
+(defun org-confluence-headline (headline contents info)
+ (let* ((low-level-rank (org-export-low-level-p headline info))
+ (text (org-export-data (org-element-property :title headline)
+ info))
+ (todo (org-export-data (org-element-property :todo-keyword headline)
+ info))
+ (level (org-export-get-relative-level headline info))
+ (todo-text (if (or (not (plist-get info :with-todo-keywords))
+ (string= todo ""))
+ ""
+ (format "*{{%s}}* " todo))))
+ ;; Else: Standard headline.
+ (format "h%s. %s%s\n%s" level todo-text text
+ (if (org-string-nw-p contents) contents ""))))
+
+(defun org-confluence-link (link desc info)
+ (let ((raw-link (org-element-property :raw-link link)))
+ (concat "["
+ (when (org-string-nw-p desc) (format "%s|" desc))
+ (cond
+ ((string-match "^confluence:" raw-link)
+ (replace-regexp-in-string "^confluence:" "" raw-link))
+ (t
+ raw-link))
+ "]")))
+
+(defun org-confluence-paragraph (paragraph contents info)
+ "Transcode PARAGRAPH element for Confluence.
+CONTENTS is the paragraph contents. INFO is a plist used as
+a communication channel."
+ contents)
+
+(defun org-confluence-property-drawer (property-drawer contents info)
+ (and (org-string-nw-p contents)
+ (format "\{\{%s\}\}" contents)))
+
+(defun org-confluence-section (section contents info)
+ contents)
+
+(defun org-confluence-src-block (src-block contents info)
+ ;; FIXME: provide a user-controlled variable for theme
+ (let* ((lang (org-element-property :language src-block))
+ (language (or (cdr (assoc lang org-confluence-lang-alist)) lang))
+ (content (org-export-format-code-default src-block info)))
+ (org-confluence--block language "Emacs" content)))
+
+(defun org-confluence-strike-through (strike-through contents info)
+ (format "-%s-" contents))
+
+(defun org-confluence-table (table contents info)
+ contents)
+
+(defun org-confluence-table-row (table-row contents info)
+ (concat
+ (if (org-string-nw-p contents) (format "|%s" contents)
+ "")
+ (when (org-export-table-row-ends-header-p table-row info)
+ "|")))
+
+(defun org-confluence-table-cell (table-cell contents info)
+ (let ((table-row (org-export-get-parent table-cell)))
+ (concat (and (org-export-table-row-starts-header-p table-row info) "|")
+ (if (= (length contents) 0) " " contents)
+ "|")))
+
+(defun org-confluence-template (contents info)
+ (let ((depth (plist-get info :with-toc)))
+ (concat (when depth "\{toc\}\n\n") contents)))
+
+(defun org-confluence-timestamp (timestamp _contents _info)
+ "Transcode a TIMESTAMP object from Org to Confluence.
+CONTENTS and INFO are ignored."
+ (let ((translated (org-timestamp-translate timestamp)))
+ (if (string-prefix-p "[" translated)
+ (concat "(" (substring translated 1 -1) ")")
+ translated)))
+
+(defun org-confluence-underline (underline contents info)
+ (format "+%s+" contents))
+
+(defun org-confluence--block (language theme contents)
+ (concat "\{code:theme=" theme
+ (when language (format "|language=%s" language))
+ "}\n"
+ contents
+ "\{code\}\n"))
+
+(defun org-confluence--li-depth (item)
+ "Return depth of a list item; -1 means not a list item"
+ ;; FIXME check whether it's worth it to cache depth
+ ;; (it gets recalculated quite a few times while
+ ;; traversing a list)
+ (let ((depth -1)
+ (tag))
+ (while (and item
+ (setq tag (car item))
+ (or (eq tag 'item) ; list items interleave with plain-list
+ (eq tag 'plain-list)))
+ (when (eq tag 'item)
+ (incf depth))
+ (setq item (org-export-get-parent item)))
+ depth))
+
+;; main interactive entrypoint
+(defun org-confluence-export-as-confluence
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a text buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip title, table
+of contents and footnote definitions from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org CONFLUENCE Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'confluence "*org CONFLUENCE Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (text-mode))))
+
+(provide 'ox-confluence)
diff --git a/contrib/lisp/ox-deck.el b/contrib/lisp/ox-deck.el
new file mode 100644
index 0000000..427c7d7
--- /dev/null
+++ b/contrib/lisp/ox-deck.el
@@ -0,0 +1,585 @@
+;;; ox-deck.el --- deck.js Presentation Back-End for Org Export Engine
+
+;; Copyright (C) 2013, 2014 Rick Frankel
+
+;; Author: Rick Frankel <emacs at rickster dot com>
+;; Keywords: outlines, hypermedia, slideshow
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a deck.js presentation back-end for the Org
+;; generic exporter.
+
+;; Installation
+;; -------------
+;; Get a copy of deck.js from http://imakewebthings.com/deck.js/ or
+;; the gitub repository at https://github.com/imakewebthings/deck.js.
+;;
+;; Add the path to the extracted code to the variable
+;; `org-deck-directories' There are a number of customization in the
+;; org-export-deck group, most of which can be overrriden with buffer
+;; local customization (starting with DECK_.)
+
+;; See ox.el and ox-html.el for more details on how this exporter
+;; works (it is derived from ox-html.)
+
+;; TODOs
+;; ------
+;; The title page is formatted using format-spec. This is error prone
+;; when details are missing and may insert empty tags, like <h2></h2>,
+;; for missing values.
+
+(require 'ox-html)
+(eval-when-compile (require 'cl))
+
+(org-export-define-derived-backend 'deck 'html
+ :menu-entry
+ '(?d "Export to deck.js HTML Presentation"
+ ((?H "To temporary buffer" org-deck-export-as-html)
+ (?h "To file" org-deck-export-to-html)
+ (?o "To file and open"
+ (lambda (a s v b)
+ (if a (org-deck-export-to-html t s v b)
+ (org-open-file (org-deck-export-to-html nil s v b)))))))
+ :options-alist
+ '((:description "DESCRIPTION" nil nil newline)
+ (:keywords "KEYWORDS" nil nil space)
+ (:html-link-home "HTML_LINK_HOME" nil nil)
+ (:html-link-up "HTML_LINK_UP" nil nil)
+ (:deck-postamble "DECK_POSTAMBLE" nil org-deck-postamble newline)
+ (:deck-preamble "DECK_PREAMBLE" nil org-deck-preamble newline)
+ (:html-head-include-default-style "HTML_INCLUDE_DEFAULT_STYLE" "html-style" nil)
+ (:html-head-include-scripts "HTML_INCLUDE_SCRIPTS" nil nil)
+ (:deck-base-url "DECK_BASE_URL" nil org-deck-base-url)
+ (:deck-theme "DECK_THEME" nil org-deck-theme)
+ (:deck-transition "DECK_TRANSITION" nil org-deck-transition)
+ (:deck-include-extensions "DECK_INCLUDE_EXTENSIONS" nil
+ org-deck-include-extensions split)
+ (:deck-exclude-extensions "DECK_EXCLUDE_EXTENSIONS" nil
+ org-deck-exclude-extensions split))
+ :translate-alist
+ '((headline . org-deck-headline)
+ (inner-template . org-deck-inner-template)
+ (item . org-deck-item)
+ (link . org-deck-link)
+ (template . org-deck-template)))
+
+(defgroup org-export-deck nil
+ "Options for exporting Org mode files to deck.js HTML Presentations."
+ :tag "Org Export DECK"
+ :group 'org-export-html)
+
+(defcustom org-deck-directories '("./deck.js")
+ "Directories to search for deck.js components (jquery,
+modernizr; core, extensions and themes directories.)"
+ :group 'org-export-deck
+ :type '(repeat (string :tag "Directory")))
+
+(defun org-deck--cleanup-components (components)
+ (remove-duplicates
+ (car (remove 'nil components))
+ :test (lambda (x y)
+ (string= (file-name-nondirectory x)
+ (file-name-nondirectory y)))))
+
+(defun org-deck--find-extensions ()
+ "Returns a unique list of all extensions found in
+in the extensions directories under `org-deck-directories'"
+ (org-deck--cleanup-components
+ (mapcar ; extensions under existing dirs
+ (lambda (dir)
+ (when (file-directory-p dir) (directory-files dir t "^[^.]")))
+ (mapcar ; possible extension directories
+ (lambda (x) (expand-file-name "extensions" x))
+ org-deck-directories))))
+
+(defun org-deck--find-css (type)
+ "Return a unique list of all the css stylesheets in the themes/TYPE
+directories under `org-deck-directories'."
+ (org-deck--cleanup-components
+ (mapcar
+ (lambda (dir)
+ (let ((css-dir (expand-file-name
+ (concat (file-name-as-directory "themes") type) dir)))
+ (when (file-directory-p css-dir)
+ (directory-files css-dir t "\\.css$"))))
+ org-deck-directories)))
+
+(defun org-deck-list-components ()
+ "List all available deck extensions, styles and
+transitions (with full paths) to a temporary buffer."
+ (interactive)
+ (let ((outbuf (get-buffer-create "*deck.js Extensions*")))
+ (with-current-buffer outbuf
+ (erase-buffer)
+ (insert "Extensions\n----------\n")
+ (insert (mapconcat 'identity (org-deck--find-extensions) "\n"))
+ (insert "\n\nStyles\n------\n")
+ (insert (mapconcat 'identity (org-deck--find-css "style") "\n"))
+ (insert "\n\nTransitions\n----------\n")
+ (insert (mapconcat 'identity (org-deck--find-css "transition") "\n")))
+ (switch-to-buffer-other-window outbuf)))
+
+(defcustom org-deck-include-extensions nil
+ "If non-nil, list of extensions to include instead of all available.
+Can be overriden or set with the DECK_INCLUDE_EXTENSIONS property.
+During output generation, the extensions found by
+`org-deck--find-extensions' are searched for the appropriate
+files (scripts and/or stylesheets) to include in the generated
+html. The href/src attributes are created relative to `org-deck-base-url'."
+ :group 'org-export-deck
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-deck-exclude-extensions nil
+ "If non-nil, list of extensions to exclude.
+Can be overriden or set with the DECK_EXCLUDE_EXTENSIONS property."
+ :group 'org-export-deck
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-deck-theme "swiss.css"
+ "deck.js theme. Can be overriden with the DECK_THEME property.
+If this value contains a path component (\"/\"), it is used as a
+literal path (url). Otherwise it is prepended with
+`org-deck-base-url'/themes/style/."
+ :group 'org-export-deck
+ :type 'string)
+
+(defcustom org-deck-transition "fade.css"
+ "deck.js transition theme. Can be overriden with the
+DECK_TRANSITION property.
+If this value contains a path component (\"/\"), it is used as a
+literal path (url). Otherwise it is prepended with
+`org-deck-base-url'/themes/transition/."
+ :group 'org-export-deck
+ :type 'string)
+
+(defcustom org-deck-base-url "deck.js"
+ "Url prefix to deck.js base directory containing the core, extensions
+and themes directories.
+Can be overriden with the DECK_BASE_URL property."
+ :group 'org-export-deck
+ :type 'string)
+
+(defvar org-deck-pre/postamble-styles
+ `((both "left: 5px; width: 100%;")
+ (preamble "position: absolute; top: 10px;")
+ (postamble ""))
+ "Alist of css styles for the preamble, postamble and both respectively.
+Can be overriden in `org-deck-styles'. See also `org-html-divs'.")
+
+(defcustom org-deck-postamble "<h1>%a - %t</h1>"
+ "Non-nil means insert a postamble in HTML export.
+
+When set to a string, use this string
+as the postamble. When t, insert a string as defined by the
+formatting string in `org-html-postamble-format'.
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+This is included in the document at the bottom of the content
+section, and uses the postamble element and id from
+`org-html-divs'. The default places the author and presentation
+title at the bottom of each slide.
+
+The css styling is controlled by `org-deck-pre/postamble-styles'.
+
+Setting :deck-postamble in publishing projects will take
+precedence over this variable."
+ :group 'org-export-deck
+ :type '(choice (const :tag "No postamble" nil)
+ (const :tag "Default formatting string" t)
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defcustom org-deck-preamble nil
+ "Non-nil means insert a preamble in HTML export.
+
+When set to a string, use this string
+as the preamble. When t, insert a string as defined by the
+formatting string in `org-html-preamble-format'.
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+This is included in the document at the top of content section, and
+uses the preamble element and id from `org-html-divs'. The css
+styling is controlled by `org-deck-pre/postamble-styles'.
+
+Setting :deck-preamble in publishing projects will take
+precedence over this variable."
+ :group 'org-export-deck
+ :type '(choice (const :tag "No preamble" nil)
+ (const :tag "Default formatting string" t)
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defvar org-deck-toc-styles
+ (mapconcat
+ 'identity
+ (list
+ "#table-of-contents a {color: inherit;}"
+ "#table-of-contents ul {margin-bottom: 0;}"
+ "#table-of-contents li {padding: 0;}") "\n")
+ "Default css styles used for formatting a table of contents slide.
+Can be overriden in `org-deck-styles'.
+Note that when the headline numbering option is true, a \"list-style: none\"
+is automatically added to avoid both numbers and bullets on the toc entries.")
+
+(defcustom org-deck-styles
+ "
+#title-slide h1 {
+ position: static; padding: 0;
+ margin-top: 10%;
+ -webkit-transform: none;
+ -moz-transform: none;
+ -ms-transform: none;
+ -o-transform: none;
+ transform: none;
+}
+#title-slide h2 {
+ text-align: center;
+ border:none;
+ padding: 0;
+ margin: 0;
+}"
+ "Deck specific CSS styles to include in exported html.
+Defaults to styles for the title page."
+ :group 'org-export-deck
+ :type 'string)
+
+(defcustom org-deck-title-slide-template
+ "<h1>%t</h1>
+<h2>%s</h2>
+<h2>%a</h2>
+<h2>%e</h2>
+<h2>%d</h2>"
+ "Format template to specify title page section.
+See `org-html-postamble-format' for the valid elements which
+can be included.
+
+It will be wrapped in the element defined in the :html-container
+property, and defaults to the value of `org-html-container-element',
+and have the id \"title-slide\"."
+ :group 'org-export-deck
+ :type 'string)
+
+(defun org-deck-toc (depth info)
+ (concat
+ (format "<%s id='table-of-contents' class='slide'>\n"
+ (plist-get info :html-container))
+ (format "<h2>%s</h2>\n" (org-html--translate "Table of Contents" info))
+ (org-html--toc-text
+ (mapcar
+ (lambda (headline)
+ (let* ((class (org-element-property :HTML_CONTAINER_CLASS headline))
+ (section-number
+ (when
+ (and (not (org-export-low-level-p headline info))
+ (org-export-numbered-headline-p headline info))
+ (concat
+ (mapconcat
+ 'number-to-string
+ (org-export-get-headline-number headline info) ".") ". ")))
+ (title
+ (concat
+ section-number
+ (replace-regexp-in-string ; remove any links in headline...
+ "</?a[^>]*>" ""
+ (org-export-data
+ (org-element-property :title headline) info)))))
+ (cons
+ (if (and class (string-match-p "\\<slide\\>" class))
+ (format
+ "<a href='#outline-container-%s'>%s</a>"
+ (or (org-element-property :CUSTOM_ID headline)
+ (concat
+ "sec-"
+ (mapconcat
+ 'number-to-string
+ (org-export-get-headline-number headline info) "-")))
+ title)
+ title)
+ (org-export-get-relative-level headline info))))
+ (org-export-collect-headlines info depth)))
+ (format "</%s>\n" (plist-get info :html-container))))
+
+(defun org-deck--get-packages (info)
+ (let ((prefix (concat (plist-get info :deck-base-url) "/"))
+ (theme (plist-get info :deck-theme))
+ (transition (plist-get info :deck-transition))
+ (include (plist-get info :deck-include-extensions))
+ (exclude (plist-get info :deck-exclude-extensions))
+ (scripts '()) (sheets '()) (snippets '()))
+ (add-to-list 'scripts (concat prefix "jquery.min.js"))
+ (add-to-list 'scripts (concat prefix "core/deck.core.js"))
+ (add-to-list 'scripts (concat prefix "modernizr.custom.js"))
+ (add-to-list 'sheets (concat prefix "core/deck.core.css"))
+ (mapc
+ (lambda (extdir)
+ (let* ((name (file-name-nondirectory extdir))
+ (dir (file-name-as-directory extdir))
+ (path (concat prefix "extensions/" name "/"))
+ (base (format "deck.%s." name)))
+ (when (and (or (eq nil include) (member name include))
+ (not (member name exclude)))
+ (when (file-exists-p (concat dir base "js"))
+ (add-to-list 'scripts (concat path base "js")))
+ (when (file-exists-p (concat dir base "css"))
+ (add-to-list 'sheets (concat path base "css")))
+ (when (file-exists-p (concat dir base "html"))
+ (add-to-list 'snippets (concat dir base "html"))))))
+ (org-deck--find-extensions))
+ (if (not (string-match-p "^[[:space:]]*$" theme))
+ (add-to-list 'sheets
+ (if (file-name-directory theme) theme
+ (format "%sthemes/style/%s" prefix theme))))
+ (if (not (string-match-p "^[[:space:]]*$" transition))
+ (add-to-list
+ 'sheets
+ (if (file-name-directory transition) transition
+ (format "%sthemes/transition/%s" prefix transition))))
+ (list :scripts (nreverse scripts) :sheets (nreverse sheets)
+ :snippets snippets)))
+
+(defun org-deck-inner-template (contents info)
+ "Return body of document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (concat contents "\n"))
+
+(defun org-deck-headline (headline contents info)
+ (let ((org-html-toplevel-hlevel 2)
+ (class (or (org-element-property :HTML_CONTAINER_CLASS headline) ""))
+ (level (org-export-get-relative-level headline info)))
+ (when (and (= 1 level) (not (string-match-p "\\<slide\\>" class)))
+ (org-element-put-property headline :HTML_CONTAINER_CLASS (concat class " slide")))
+ (org-html-headline headline contents info)))
+
+(defun org-deck-item (item contents info)
+ "Transcode an ITEM element from Org to HTML.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information.
+If the containing headline has the property :STEP, then
+the \"slide\" class will be added to the to the list element,
+ which will make the list into a \"build\"."
+ (let ((text (org-html-item item contents info)))
+ (if (org-export-get-node-property :STEP item t)
+ (progn
+ (replace-regexp-in-string "^<li>" "<li class='slide'>" text)
+ (replace-regexp-in-string "^<li class='checkbox'>" "<li class='checkbox slide'>" text))
+ text)))
+
+(defun org-deck-link (link desc info)
+ (replace-regexp-in-string "href=\"#" "href=\"#outline-container-"
+ (org-export-with-backend 'html link desc info)))
+
+(defun org-deck-template (contents info)
+ "Return complete document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((pkg-info (org-deck--get-packages info))
+ (org-html--pre/postamble-class "deck-status")
+ (info (plist-put
+ (plist-put info :html-preamble (plist-get info :deck-preamble))
+ :html-postamble (plist-get info :deck-postamble))))
+ (mapconcat
+ 'identity
+ (list
+ (org-html-doctype info)
+ (let ((lang (plist-get info :language)))
+ (mapconcat
+ (lambda (x)
+ (apply
+ 'format
+ "<!--%s <html %s lang='%s' xmlns='http://www.w3.org/1999/xhtml'> %s<![endif]-->"
+ x))
+ (list `("[if lt IE 7]>" "class='no-js ie6'" ,lang "")
+ `("[if IE 7]>" "class='no-js ie7'" ,lang "")
+ `("[if IE 8]>" "class='no-js ie8'" ,lang "")
+ `("[if gt IE 8]><!-->" "" ,lang "<!--")) "\n"))
+ "<head>"
+ (org-deck--build-meta-info info)
+ (mapconcat
+ (lambda (sheet)
+ (format
+ "<link rel='stylesheet' href='%s' type='text/css' />" sheet))
+ (plist-get pkg-info :sheets) "\n")
+ (mapconcat
+ (lambda (script)
+ (format
+ "<script src='%s' type='text/javascript'></script>" script))
+ (plist-get pkg-info :scripts) "\n")
+ (org-html--build-mathjax-config info)
+ "<script type='text/javascript'>"
+ " $(document).ready(function () { $.deck('.slide'); });"
+ "</script>"
+ (org-html--build-head info)
+ "<style type='text/css'>"
+ org-deck-toc-styles
+ (when (plist-get info :section-numbers)
+ "#table-of-contents ul li {list-style-type: none;}")
+ (format "#%s, #%s {%s}"
+ (nth 2 (assq 'preamble org-html-divs))
+ (nth 2 (assq 'postamble org-html-divs))
+ (nth 1 (assq 'both org-deck-pre/postamble-styles)))
+ (format "#%s {%s}"
+ (nth 2 (assq 'preamble org-html-divs))
+ (nth 1 (assq 'preamble org-deck-pre/postamble-styles)))
+ (format "#%s {%s}"
+ (nth 2 (assq 'postamble org-html-divs))
+ (nth 1 (assq 'postamble org-deck-pre/postamble-styles)))
+ org-deck-styles
+ "</style>"
+ "</head>"
+ "<body>"
+ (format "<%s id='%s' class='deck-container'>"
+ (nth 1 (assq 'content org-html-divs))
+ (nth 2 (assq 'content org-html-divs)))
+ (org-html--build-pre/postamble 'preamble info)
+ ;; title page
+ (format "<%s id='title-slide' class='slide'>"
+ (plist-get info :html-container))
+ (format-spec org-deck-title-slide-template (org-html-format-spec info))
+ (format "</%s>" (plist-get info :html-container))
+ ;; toc page
+ (let ((depth (plist-get info :with-toc)))
+ (when depth (org-deck-toc depth info)))
+ contents
+ (mapconcat
+ (lambda (snippet)
+ (with-temp-buffer (insert-file-contents snippet)
+ (buffer-string)))
+ (plist-get pkg-info :snippets) "\n")
+ (org-html--build-pre/postamble 'postamble info)
+ (format "</%s>" (nth 1 (assq 'content org-html-divs)))
+ "</body>"
+ "</html>\n") "\n")))
+
+(defun org-deck--build-meta-info (info)
+ "Return meta tags for exported document.
+INFO is a plist used as a communication channel."
+ (let* ((title (org-export-data (plist-get info :title) info))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (date (and (plist-get info :with-date)
+ (let ((date (org-export-get-date info)))
+ (and date (org-export-data date info)))))
+ (description (plist-get info :description))
+ (keywords (plist-get info :keywords)))
+ (mapconcat
+ 'identity
+ (list
+ (format "<title>%s</title>" title)
+ (format "<meta http-equiv='Content-Type' content='text/html; charset=%s'/>"
+ (or (and org-html-coding-system
+ (fboundp 'coding-system-get)
+ (coding-system-get
+ org-html-coding-system 'mime-charset))
+ "iso-8859-1"))
+ (mapconcat
+ (lambda (attr)
+ (when (< 0 (length (car attr)))
+ (format "<meta name='%s' content='%s'/>\n"
+ (nth 1 attr) (car attr))))
+ (list '("Org-mode" "generator")
+ `(,author "author")
+ `(,description "description")
+ `(,keywords "keywords")) "")) "\n")))
+(defun org-deck-export-as-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to an HTML buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org deck.js Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'deck "*Org deck.js Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (nxml-mode))))
+
+(defun org-deck-export-to-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a deck.js HTML file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let* ((extension (concat "." org-html-extension))
+ (file (org-export-output-file-name extension subtreep))
+ (org-export-coding-system org-html-coding-system))
+ (org-export-to-file 'deck file
+ async subtreep visible-only body-only ext-plist)))
+
+(defun org-deck-publish-to-html (plist filename pub-dir)
+ "Publish an org file to deck.js HTML Presentation.
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory. Returns output file name."
+ (org-publish-org-to 'deck filename ".html" plist pub-dir))
+
+(provide 'ox-deck)
+
+;;; ox-deck.el ends here
diff --git a/contrib/lisp/ox-extra.el b/contrib/lisp/ox-extra.el
new file mode 100644
index 0000000..9cd6980
--- /dev/null
+++ b/contrib/lisp/ox-extra.el
@@ -0,0 +1,211 @@
+;;; ox-extra.el --- Convenience functions for org export
+
+;; Copyright (C) 2014 Aaron Ecay
+
+;; Author: Aaron Ecay <aaronecay@gmail.com>
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file contains some convenience functions for org export, which
+;; are not part of org's core. Call `ox-extras-activate' passing a
+;; list of symbols naming extras, which will be installed globally in
+;; your org session.
+;;
+;; For example, you could include the following in your .emacs file:
+;;
+;; (require 'ox-extra)
+;; (ox-extras-activate '(latex-header-blocks ignore-headlines))
+;;
+
+;; Currently available extras:
+
+;; - `latex-header-blocks' -- allow the use of latex blocks, the
+;; contents of which which will be interpreted as #+latex_header lines
+;; for export. These blocks should be tagged with #+header: :header
+;; yes. For example:
+;; #+header: :header yes
+;; #+begin_export latex
+;; ...
+;; #+end_export
+
+;; - `ignore-headlines' -- allow a headline (but not its children) to
+;; be ignored. Any headline tagged with the 'ignore' tag will be
+;; ignored (i.e. will not be included in the export), but any child
+;; headlines will not be ignored (unless explicitly tagged to be
+;; ignored), and will instead have their levels promoted by one.
+
+;; TODO:
+;; - add a function to org-mode-hook that looks for a ox-extras local
+;; variable and activates the specified extras buffer-locally
+;; - allow specification of desired extras to be activated via
+;; customize
+
+;;; Code:
+
+(require 'ox)
+(require 'cl-lib)
+
+(defun org-latex-header-blocks-filter (backend)
+ (when (org-export-derived-backend-p backend 'latex)
+ (let ((positions
+ (org-element-map (org-element-parse-buffer 'greater-element nil) 'export-block
+ (lambda (block)
+ (when (and (string= (org-element-property :type block) "LATEX")
+ (string= (org-export-read-attribute
+ :header block :header)
+ "yes"))
+ (list (org-element-property :begin block)
+ (org-element-property :end block)
+ (org-element-property :post-affiliated block)))))))
+ (mapc (lambda (pos)
+ (goto-char (nth 2 pos))
+ (cl-destructuring-bind
+ (beg end &rest ignore)
+ ;; FIXME: `org-edit-src-find-region-and-lang' was
+ ;; removed in 9c06f8cce (2014-11-11).
+ (org-edit-src-find-region-and-lang)
+ (let ((contents-lines (split-string
+ (buffer-substring-no-properties beg end)
+ "\n")))
+ (delete-region (nth 0 pos) (nth 1 pos))
+ (dolist (line contents-lines)
+ (insert (concat "#+latex_header: "
+ (replace-regexp-in-string "\\` *" "" line)
+ "\n"))))))
+ ;; go in reverse, to avoid wrecking the numeric positions
+ ;; earlier in the file
+ (reverse positions)))))
+
+
+;; During export headlines which have the "ignore" tag are removed
+;; from the parse tree. Their contents are retained (leading to a
+;; possibly invalid parse tree, which nevertheless appears to function
+;; correctly with most export backends) all children headlines are
+;; retained and are promoted to the level of the ignored parent
+;; headline.
+;;
+;; This makes it possible to add structure to the original Org-mode
+;; document which does not effect the exported version, such as in the
+;; following examples.
+;;
+;; Wrapping an abstract in a headline
+;;
+;; * Abstract :ignore:
+;; #+LaTeX: \begin{abstract}
+;; #+HTML: <div id="abstract">
+;;
+;; ...
+;;
+;; #+HTML: </div>
+;; #+LaTeX: \end{abstract}
+;;
+;; Placing References under a headline (using ox-bibtex in contrib)
+;;
+;; * References :ignore:
+;; #+BIBLIOGRAPHY: dissertation plain
+;;
+;; Inserting an appendix for LaTeX using the appendix package.
+;;
+;; * Appendix :ignore:
+;; #+LaTeX: \begin{appendices}
+;; ** Reproduction
+;; ...
+;; ** Definitions
+;; #+LaTeX: \end{appendices}
+;;
+(defun org-export-ignore-headlines (data backend info)
+ "Remove headlines tagged \"ignore\" retaining contents and promoting children.
+Each headline tagged \"ignore\" will be removed retaining its
+contents and promoting any children headlines to the level of the
+parent."
+ (org-element-map data 'headline
+ (lambda (object)
+ (when (member "ignore" (org-element-property :tags object))
+ (let ((level-top (org-element-property :level object))
+ level-diff)
+ (mapc (lambda (el)
+ ;; recursively promote all nested headlines
+ (org-element-map el 'headline
+ (lambda (el)
+ (when (equal 'headline (org-element-type el))
+ (unless level-diff
+ (setq level-diff (- (org-element-property :level el)
+ level-top)))
+ (org-element-put-property el
+ :level (- (org-element-property :level el)
+ level-diff)))))
+ ;; insert back into parse tree
+ (org-element-insert-before el object))
+ (org-element-contents object)))
+ (org-element-extract-element object)))
+ info nil)
+ (org-extra--merge-sections data backend info)
+ data)
+
+(defun org-extra--merge-sections (data _backend info)
+ (org-element-map data 'headline
+ (lambda (hl)
+ (let ((sections
+ (cl-loop
+ for el in (org-element-map (org-element-contents hl)
+ '(headline section) #'identity info)
+ until (eq (org-element-type el) 'headline)
+ collect el)))
+ (when (and sections
+ (> (length sections) 1))
+ (apply #'org-element-adopt-elements
+ (car sections)
+ (cl-mapcan (lambda (s) (org-element-contents s))
+ (cdr sections)))
+ (mapc #'org-element-extract-element (cdr sections)))))
+ info))
+
+(defconst ox-extras
+ '((latex-header-blocks org-latex-header-blocks-filter org-export-before-parsing-hook)
+ (ignore-headlines org-export-ignore-headlines org-export-filter-parse-tree-functions))
+ "A list of org export extras that can be enabled.
+
+Should be a list of items of the form (NAME FN HOOK). NAME is a
+symbol, which can be passed to `ox-extras-activate'. FN is a
+function which will be added to HOOK.")
+
+(defun ox-extras-activate (extras)
+ "Activate certain org export extras.
+
+EXTRAS should be a list of extras (defined in `ox-extras') which
+should be activated."
+ (dolist (extra extras)
+ (let* ((lst (assq extra ox-extras))
+ (fn (nth 1 lst))
+ (hook (nth 2 lst)))
+ (when (and fn hook)
+ (add-hook hook fn)))))
+
+(defun ox-extras-deactivate (extras)
+ "Deactivate certain org export extras.
+
+This function is the opposite of `ox-extras-activate'. EXTRAS
+should be a list of extras (defined in `ox-extras') which should
+be activated."
+ (dolist (extra extras)
+ (let* ((lst (assq extra ox-extras))
+ (fn (nth 1 lst))
+ (hook (nth 2 lst)))
+ (when (and fn hook)
+ (remove-hook hook fn)))))
+
+(provide 'ox-extra)
+;;; ox-extra.el ends here
diff --git a/contrib/lisp/ox-freemind.el b/contrib/lisp/ox-freemind.el
new file mode 100644
index 0000000..a2bf129
--- /dev/null
+++ b/contrib/lisp/ox-freemind.el
@@ -0,0 +1,527 @@
+;;; ox-freemind.el --- Freemind Mindmap Back-End for Org Export Engine
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: Jambunathan K <kjambunathan at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a Freemind Mindmap back-end for Org generic
+;; exporter.
+
+;; To test it, run:
+;;
+;; M-x org-freemind-export-to-freemind
+;;
+;; in an Org mode buffer. See ox.el for more details on how this
+;; exporter works.
+
+;;; Code:
+
+;;; Dependencies
+
+(require 'ox-html)
+
+
+
+;;; Define Back-End
+
+(org-export-define-derived-backend 'freemind 'html
+ :menu-entry
+ '(?f "Export to Freemind Mindmap"
+ ((?f "As Freemind Mindmap file" org-freemind-export-to-freemind)
+ (?o "As Freemind Mindmap file and open"
+ (lambda (a s v b)
+ (if a (org-freemind-export-to-freemind t s v b)
+ (org-open-file (org-freemind-export-to-freemind nil s v b)))))))
+ :translate-alist '((headline . org-freemind-headline)
+ (template . org-freemind-template)
+ (inner-template . org-freemind-inner-template)
+ (section . org-freemind-section)
+ (entity . org-freemind-entity))
+ :filters-alist '((:filter-options . org-freemind-options-function)
+ (:filter-final-output . org-freemind-final-function)))
+
+
+
+;;; User Configuration Variables
+
+(defgroup org-export-freemind nil
+ "Options for exporting Org mode files to Freemind Mindmap."
+ :tag "Org Export Freemind Mindmap"
+ :group 'org-export)
+
+(defcustom org-freemind-styles
+ '((default . "<node>\n</node>")
+ (0 . "<node COLOR=\"#000000\">\n<font NAME=\"SansSerif\" SIZE=\"20\"/>\n</node>")
+ (1 . "<node COLOR=\"#0033ff\">\n<edge STYLE=\"sharp_bezier\" WIDTH=\"8\"/>\n<font NAME=\"SansSerif\" SIZE=\"18\"/>\n</node>")
+ (2 . "<node COLOR=\"#00b439\">\n<edge STYLE=\"bezier\" WIDTH=\"thin\"/>\n<font NAME=\"SansSerif\" SIZE=\"16\"/>\n</node>")
+ (3 . "<node COLOR=\"#990000\" FOLDED=\"true\">\n<font NAME=\"SansSerif\" SIZE=\"14\"/>\n</node>")
+ (4 . "<node COLOR=\"#111111\">\n</node>"))
+ "List of Freemind node styles.
+Each entry is of the form (STYLE-NAME . STYLE-SPEC). STYLE-NAME
+can be one of an integer (signifying an outline level), a string
+or the symbol `default'. STYLE-SPEC, a string, is a Freemind
+node style."
+ :type '(alist :options (default 0 1 2 3)
+ :key-type (choice :tag "Style tag"
+ (integer :tag "Outline level")
+ (const :tag "Default value" default)
+ (string :tag "Node style"))
+ :value-type (string :tag "Style spec"))
+ :group 'org-export-freemind)
+
+(defcustom org-freemind-style-map-function 'org-freemind-style-map--automatic
+ "Function to map an Org element to it's node style.
+The mapping function takes two arguments an Org ELEMENT and INFO.
+ELEMENT can be one of the following types - `org-data',
+`headline' or `section'. INFO is a plist holding contextual
+information during export. The function must return a STYLE-SPEC
+to be applied to ELEMENT.
+
+See `org-freemind-style-map--automatic' for a sample style
+function. See `org-freemind-styles' for a list of named styles."
+ :type '(radio
+ (function-item org-freemind-style-map--automatic)
+ (function-item org-freemind-style-map--default)
+ function)
+ :group 'org-export-freemind)
+
+(defcustom org-freemind-section-format 'note
+ "Specify how outline sections are to be formatted.
+If `inline', append it to the contents of it's heading node. If
+`note', attach it as a note to it's heading node. If `node',
+attach it as a separate node to it's heading node.
+
+Use `note', if the input Org file contains large sections. Use
+`node', if the Org file contains mid-sized sections that need to
+stand apart. Otherwise, use `inline'."
+ :type '(choice
+ (const :tag "Append to outline title" inline)
+ (const :tag "Attach as a note" note)
+ (const :tag "Create a separate node" node))
+ :group 'org-export-freemind)
+
+;;;; Debugging
+
+(defcustom org-freemind-pretty-output nil
+ "Enable this to generate pretty Freemind Mindmap."
+ :type 'boolean
+ :group 'org-export-freemind)
+
+
+;;; Internal Functions
+
+;;;; XML Manipulation
+
+(defun org-freemind--serialize (parsed-xml &optional contents)
+ "Convert PARSED-XML in to XML string.
+PARSED-XML is a parse tree as returned by
+`libxml-parse-xml-region'. CONTENTS is an optional string.
+
+Ignore CONTENTS, if PARSED-XML is not a sole XML element.
+Otherwise, append CONTENTS to the contents of top-level element
+in PARSED-XML.
+
+This is an inverse function of `libxml-parse-xml-region'.
+
+For purposes of Freemind export, PARSED-XML is a node style
+specification - \"<node ...>...</node>\" - as a parse tree."
+ (when contents
+ (assert (symbolp (car parsed-xml))))
+ (cond
+ ((null parsed-xml) "")
+ ((stringp parsed-xml) parsed-xml)
+ ((symbolp (car parsed-xml))
+ (let ((attributes (mapconcat
+ (lambda (av)
+ (format "%s=\"%s\"" (car av) (cdr av)))
+ (cadr parsed-xml) " ")))
+ (if (or (cddr parsed-xml) contents)
+ (format "\n<%s%s>%s\n</%s>"
+ (car parsed-xml)
+ (if (string= attributes "") "" (concat " " attributes))
+ (concat (org-freemind--serialize (cddr parsed-xml))
+ contents )
+ (car parsed-xml))
+ (format "\n<%s%s/>"
+ (car parsed-xml)
+ (if (string= attributes "") "" (concat " " attributes))))))
+ (t (mapconcat #'org-freemind--serialize parsed-xml ""))))
+
+(defun org-freemind--parse-xml (xml-string)
+ "Return parse tree for XML-STRING using `libxml-parse-xml-region'.
+For purposes of Freemind export, XML-STRING is a node style
+specification - \"<node ...>...</node>\" - as a string."
+ (with-temp-buffer
+ (insert (or xml-string ""))
+ (libxml-parse-xml-region (point-min) (point-max))))
+
+
+;;;; Style mappers :: Default and Automatic layout
+
+(defun org-freemind-style-map--automatic (element info)
+ "Return a node style corresponding to relative outline level of ELEMENT.
+ELEMENT can be any of the following types - `org-data',
+`headline' or `section'. See `org-freemind-styles' for style
+mappings of different outline levels."
+ (let ((style-name
+ (case (org-element-type element)
+ (headline
+ (org-export-get-relative-level element info))
+ (section
+ (let ((parent (org-export-get-parent-headline element)))
+ (if (not parent) 1
+ (1+ (org-export-get-relative-level parent info)))))
+ (t 0))))
+ (or (assoc-default style-name org-freemind-styles)
+ (assoc-default 'default org-freemind-styles)
+ "<node></node>")))
+
+(defun org-freemind-style-map--default (element info)
+ "Return the default style for all ELEMENTs.
+ELEMENT can be any of the following types - `org-data',
+`headline' or `section'. See `org-freemind-styles' for current
+value of default style."
+ (or (assoc-default 'default org-freemind-styles)
+ "<node></node>"))
+
+
+;;;; Helpers :: Retrieve, apply Freemind styles
+
+(defun org-freemind--get-node-style (element info)
+ "Return Freemind node style applicable for HEADLINE.
+ELEMENT is an Org element of type `org-data', `headline' or
+`section'. INFO is a plist holding contextual information."
+ (unless (fboundp org-freemind-style-map-function)
+ (setq org-freemind-style-map-function 'org-freemind-style-map--default))
+ (let ((style (funcall org-freemind-style-map-function element info)))
+ ;; Sanitize node style.
+
+ ;; Loop through the attributes of node element and purge those
+ ;; attributes that look suspicious. This is an extra bit of work
+ ;; that allows one to copy verbatim node styles from an existing
+ ;; Freemind Mindmap file without messing with the exported data.
+ (let* ((data (org-freemind--parse-xml style))
+ (attributes (cadr data))
+ (ignored-attrs '(POSITION FOLDED TEXT CREATED ID
+ MODIFIED)))
+ (let (attr)
+ (while (setq attr (pop ignored-attrs))
+ (setq attributes (assq-delete-all attr attributes))))
+ (when data (setcar (cdr data) attributes))
+ (org-freemind--serialize data))))
+
+(defun org-freemind--build-stylized-node (style-1 style-2 &optional contents)
+ "Build a Freemind node with style STYLE-1 + STYLE-2 and add CONTENTS to it.
+STYLE-1 and STYLE-2 are Freemind node styles as a string.
+STYLE-1 is the base node style and STYLE-2 is the overriding
+style that takes precedence over STYLE-1. CONTENTS is a string.
+
+Return value is a Freemind node with following properties:
+
+ 1. The attributes of \"<node ...> </node>\" element is the union
+ of corresponding attributes of STYLE-1 and STYLE-2. When
+ STYLE-1 and STYLE-2 specify values for the same attribute
+ name, choose the attribute value from STYLE-2.
+
+ 2. The children of \"<node ...> </node>\" element is the union of
+ top-level children of STYLE-1 and STYLE-2 with CONTENTS
+ appended to it. When STYLE-1 and STYLE-2 share a child
+ element of same type, the value chosen is that from STYLE-2.
+
+For example, merging with following parameters
+
+ STYLE-1 =>
+ <node COLOR=\"#00b439\" STYLE=\"Bubble\">
+ <edge STYLE=\"bezier\" WIDTH=\"thin\"/>
+ <font NAME=\"SansSerif\" SIZE=\"16\"/>
+ </node>
+
+ STYLE-2 =>
+ <node COLOR=\"#990000\" FOLDED=\"true\">
+ <font NAME=\"SansSerif\" SIZE=\"14\"/>
+ </node>
+
+ CONTENTS =>
+ <attribute NAME=\"ORGTAG\" VALUE=\"@home\"/>
+
+will result in following node:
+
+ RETURN =>
+ <node STYLE=\"Bubble\" COLOR=\"#990000\" FOLDED=\"true\">
+ <edge STYLE=\"bezier\" WIDTH=\"thin\"/>
+ <font NAME=\"SansSerif\" SIZE=\"14\"/>
+ <attribute NAME=\"ORGTAG\" VALUE=\"@home\"/>
+ </node>."
+ (let* ((data1 (org-freemind--parse-xml (or style-1 "")))
+ (data2 (org-freemind--parse-xml (or style-2 "")))
+ (attr1 (cadr data1))
+ (attr2 (cadr data2))
+ (merged-attr attr2)
+ (children1 (cddr data1))
+ (children2 (cddr data2))
+ (merged-children children2))
+ (let (attr)
+ (while (setq attr (pop attr1))
+ (unless (assq (car attr) merged-attr)
+ (push attr merged-attr))))
+ (let (child)
+ (while (setq child (pop children1))
+ (when (or (stringp child) (not (assq (car child) merged-children)))
+ (push child merged-children))))
+ (let ((merged-data (nconc (list 'node merged-attr) merged-children)))
+ (org-freemind--serialize merged-data contents))))
+
+
+;;;; Helpers :: Node contents
+
+(defun org-freemind--richcontent (type contents &optional css-style)
+ (let* ((type (case type
+ (note "NOTE")
+ (node "NODE")
+ (t "NODE")))
+ (contents (org-trim contents)))
+ (if (string= (org-trim contents) "") ""
+ (format "\n<richcontent TYPE=\"%s\">%s\n</richcontent>"
+ type
+ (format "\n<html>\n<head>%s\n</head>\n%s\n</html>"
+ (or css-style "")
+ (format "<body>\n%s\n</body>" contents))))))
+
+(defun org-freemind--build-node-contents (element contents info)
+ (let* ((title (case (org-element-type element)
+ (headline
+ (org-element-property :title element))
+ (org-data
+ (plist-get info :title))
+ (t (error "Shouldn't come here"))))
+ (element-contents (org-element-contents element))
+ (section (assq 'section element-contents))
+ (section-contents
+ (let ((backend (org-export-create-backend
+ :parent (org-export-backend-name
+ (plist-get info :back-end))
+ :transcoders '((section . (lambda (e c i) c))))))
+ (org-export-data-with-backend section backend info)))
+ (itemized-contents-p (let ((first-child-headline
+ (org-element-map element-contents
+ 'headline 'identity info t)))
+ (when first-child-headline
+ (org-export-low-level-p first-child-headline
+ info))))
+ (node-contents (concat section-contents
+ (when itemized-contents-p
+ contents))))
+ (concat (let ((title (org-export-data title info)))
+ (case org-freemind-section-format
+ (inline
+ (org-freemind--richcontent
+ 'node (concat (format "\n<h2>%s</h2>" title)
+ node-contents) ))
+ (note
+ (concat (org-freemind--richcontent
+ 'node (format "\n<p>%s\n</p>" title))
+ (org-freemind--richcontent
+ 'note node-contents)))
+ (node
+ (concat
+ (org-freemind--richcontent
+ 'node (format "\n<p>%s\n</p>" title))
+ (when section
+ (org-freemind--build-stylized-node
+ (org-freemind--get-node-style section info) nil
+ (org-freemind--richcontent 'node node-contents)))))))
+ (unless itemized-contents-p
+ contents))))
+
+
+
+;;; Template
+
+(defun org-freemind-template (contents info)
+ "Return complete document string after Freemind Mindmap conversion.
+CONTENTS is the transcoded contents string. RAW-DATA is the
+original parsed data. INFO is a plist holding export options."
+ (format
+ "<map version=\"0.9.0\">\n%s\n</map>"
+ (org-freemind--build-stylized-node
+ (org-freemind--get-node-style nil info) nil
+ (let ((org-data (plist-get info :parse-tree)))
+ (org-freemind--build-node-contents org-data contents info)))))
+
+(defun org-freemind-inner-template (contents info)
+ "Return body of document string after Freemind Mindmap conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ contents)
+
+;;;; Tags
+
+(defun org-freemind--tags (tags)
+ (mapconcat (lambda (tag)
+ (format "\n<attribute NAME=\"%s\" VALUE=\"%s\"/>" tag ""))
+ tags "\n"))
+
+
+
+;;; Transcode Functions
+
+;;;; Entity
+
+(defun org-freemind-entity (entity contents info)
+ "Transcode an ENTITY object from Org to Freemind Mindmap.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :utf-8 entity))
+
+;;;; Headline
+
+(defun org-freemind-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to Freemind Mindmap.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ ;; Empty contents?
+ (setq contents (or contents ""))
+ (let* ((numberedp (org-export-numbered-headline-p headline info))
+ (level (org-export-get-relative-level headline info))
+ (text (org-export-data (org-element-property :title headline) info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ (section-number (and (not (org-export-low-level-p headline info))
+ (org-export-numbered-headline-p headline info)
+ (mapconcat 'number-to-string
+ (org-export-get-headline-number
+ headline info) ".")))
+ ;; Create the headline text.
+ (full-text (org-export-data (org-element-property :title headline)
+ info))
+ ;; Headline order (i.e, first digit of the section number)
+ (headline-order (car (org-export-get-headline-number headline info))))
+ (cond
+ ;; Case 1: This is a footnote section: ignore it.
+ ((org-element-property :footnote-section-p headline) nil)
+ ;; Case 2. This is a deep sub-tree, export it as a list item.
+ ;; Delegate the actual export to `html' backend.
+ ((org-export-low-level-p headline info)
+ (org-html-headline headline contents info))
+ ;; Case 3. Standard headline. Export it as a section.
+ (t
+ (let* ((section-number (mapconcat 'number-to-string
+ (org-export-get-headline-number
+ headline info) "-"))
+ (ids (remove 'nil
+ (list (org-element-property :CUSTOM_ID headline)
+ (concat "sec-" section-number)
+ (org-element-property :ID headline))))
+ (preferred-id (car ids))
+ (extra-ids (cdr ids))
+ (left-p (zerop (% headline-order 2))))
+ (org-freemind--build-stylized-node
+ (org-freemind--get-node-style headline info)
+ (format "<node ID=\"%s\" POSITION=\"%s\" FOLDED=\"%s\">\n</node>"
+ preferred-id
+ (if left-p "left" "right")
+ (if (= level 1) "true" "false"))
+ (concat (org-freemind--build-node-contents headline contents info)
+ (org-freemind--tags tags))))))))
+
+
+;;;; Section
+
+(defun org-freemind-section (section contents info)
+ "Transcode a SECTION element from Org to Freemind Mindmap.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ (let ((parent (org-export-get-parent-headline section)))
+ (when (and parent (org-export-low-level-p parent info))
+ contents)))
+
+
+
+;;; Filter Functions
+
+(defun org-freemind-final-function (contents backend info)
+ "Return CONTENTS as pretty XML using `indent-region'."
+ (if (not org-freemind-pretty-output) contents
+ (with-temp-buffer
+ (nxml-mode)
+ (insert contents)
+ (indent-region (point-min) (point-max))
+ (buffer-substring-no-properties (point-min) (point-max)))))
+
+(defun org-freemind-options-function (info backend)
+ "Install script in export options when appropriate.
+EXP-PLIST is a plist containing export options. BACKEND is the
+export back-end currently used."
+ ;; Freemind/Freeplane doesn't seem to like named html entities in
+ ;; richcontent. For now, turn off smart quote processing so that
+ ;; entities like "&rsquo;" & friends are avoided in the exported
+ ;; output.
+ (plist-put info :with-smart-quotes nil))
+
+
+
+;;; End-user functions
+
+;;;###autoload
+(defun org-freemind-export-to-freemind
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a Freemind Mindmap file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let* ((extension (concat ".mm" ))
+ (file (org-export-output-file-name extension subtreep))
+ (org-export-coding-system 'utf-8))
+ (org-export-to-file 'freemind file
+ async subtreep visible-only body-only ext-plist)))
+
+(provide 'ox-freemind)
+
+;;; ox-freemind.el ends here
diff --git a/contrib/lisp/ox-groff.el b/contrib/lisp/ox-groff.el
new file mode 100644
index 0000000..555a89d
--- /dev/null
+++ b/contrib/lisp/ox-groff.el
@@ -0,0 +1,1962 @@
+;;; ox-groff.el --- Groff Back-End for Org Export Engine
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Author: Luis R Anaya <papoanaya aroba hot mail punto com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+;;; Commentary:
+;;
+;; This library implements a Groff Memorandum Macro back-end for Org
+;; generic exporter.
+;;
+;; To test it, run
+;;
+;; M-: (org-export-to-buffer 'groff "*Test Groff*") RET
+;;
+;; in an org-mode buffer then switch to the buffer to see the Groff
+;; export. See ox.el for more details on how this exporter works.
+;;
+;; It introduces two new buffer keywords: "GROFF_CLASS" and
+;; "GROFF_CLASS_OPTIONS".
+
+;;; Code:
+
+(eval-when-compile (require 'cl))
+(require 'ox)
+
+(defvar orgtbl-exp-regexp)
+
+
+;;; Define Back-End
+
+(org-export-define-backend 'groff
+ '((bold . org-groff-bold)
+ (center-block . org-groff-center-block)
+ (clock . org-groff-clock)
+ (code . org-groff-code)
+ (drawer . org-groff-drawer)
+ (dynamic-block . org-groff-dynamic-block)
+ (entity . org-groff-entity)
+ (example-block . org-groff-example-block)
+ (export-block . org-groff-export-block)
+ (export-snippet . org-groff-export-snippet)
+ (fixed-width . org-groff-fixed-width)
+ (footnote-definition . org-groff-footnote-definition)
+ (footnote-reference . org-groff-footnote-reference)
+ (headline . org-groff-headline)
+ (horizontal-rule . org-groff-horizontal-rule)
+ (inline-src-block . org-groff-inline-src-block)
+ (inlinetask . org-groff-inlinetask)
+ (italic . org-groff-italic)
+ (item . org-groff-item)
+ (keyword . org-groff-keyword)
+ (line-break . org-groff-line-break)
+ (link . org-groff-link)
+ (node-property . org-groff-node-property)
+ (paragraph . org-groff-paragraph)
+ (plain-list . org-groff-plain-list)
+ (plain-text . org-groff-plain-text)
+ (planning . org-groff-planning)
+ (property-drawer . org-groff-property-drawer)
+ (quote-block . org-groff-quote-block)
+ (radio-target . org-groff-radio-target)
+ (section . org-groff-section)
+ (special-block . org-groff-special-block)
+ (src-block . org-groff-src-block)
+ (statistics-cookie . org-groff-statistics-cookie)
+ (strike-through . org-groff-strike-through)
+ (subscript . org-groff-subscript)
+ (superscript . org-groff-superscript)
+ (table . org-groff-table)
+ (table-cell . org-groff-table-cell)
+ (table-row . org-groff-table-row)
+ (target . org-groff-target)
+ (template . org-groff-template)
+ (timestamp . org-groff-timestamp)
+ (underline . org-groff-underline)
+ (verbatim . org-groff-verbatim)
+ (verse-block . org-groff-verse-block))
+ :menu-entry
+ '(?g "Export to GROFF"
+ ((?g "As GROFF file" org-groff-export-to-groff)
+ (?p "As PDF file" org-groff-export-to-pdf)
+ (?o "As PDF file and open"
+ (lambda (a s v b)
+ (if a (org-groff-export-to-pdf t s v b)
+ (org-open-file (org-groff-export-to-pdf nil s v b)))))))
+ :options-alist
+ '((:groff-class "GROFF_CLASS" nil org-groff-default-class t)
+ (:groff-class-options "GROFF_CLASS_OPTIONS" nil nil t)
+ (:groff-header-extra "GROFF_HEADER" nil nil newline)))
+
+
+
+;;; User Configurable Variables
+
+(defgroup org-export-groff nil
+ "Options for exporting Org mode files to Groff."
+ :tag "Org Export Groff"
+ :group 'org-export)
+
+;;; Preamble
+
+(defcustom org-groff-default-class "internal"
+ "The default Groff class."
+ :group 'org-export-groff
+ :type '(string :tag "Groff class"))
+
+(defcustom org-groff-classes
+ '(("file" ".MT 1"
+ (:heading 'default :type "memo" :last-section "toc"))
+ ("internal" ".MT 0"
+ (:heading 'default :type "memo" :last-section "toc"))
+ ("programmer" ".MT 2"
+ (:heading 'default :type "memo" :last-section "toc"))
+ ("engineer" ".MT 3"
+ (:heading 'default :type "memo" :last-section "toc"))
+ ("external" ".MT 4"
+ (:heading 'default :type "memo" :last-section "toc"))
+ ("letter" ".MT 5"
+ (:heading 'default :type "memo" :last-section "sign"))
+ ("custom" ".so file"
+ (:heading custom-function :type "custom" :last-section "toc"))
+ ("dummy" ""
+ (:heading 'default :type "memo"))
+ ("ms" "ms"
+ (:heading 'default :type "cover" :last-section "toc"))
+ ("se_ms" "se_ms"
+ (:heading 'default :type "cover" :last-section "toc"))
+ ("block" "BL"
+ (:heading 'default :type "letter" :last-section "sign"))
+ ("semiblock" "SB"
+ (:heading 'default :type "letter" :last-section "sign"))
+ ("fullblock" "FB"
+ (:heading 'default :type "letter" :last-section "sign"))
+ ("simplified" "SP"
+ (:heading 'default :type "letter" :last-section "sign"))
+ ("none" "" (:heading 'default :type "custom")))
+
+ ;; none means, no Cover or Memorandum Type and no calls to AU, AT, ND and TL
+ ;; This is to facilitate the creation of custom pages.
+
+ ;; dummy means, no Cover or Memorandum Type but calls to AU, AT, ND and TL
+ ;; are made. This is to facilitate Abstract Insertion.
+
+ "This list describes the attributes for the documents being created.
+ It allows for the creation of new "
+ :group 'org-export-groff
+ :type '(repeat
+ (list (string :tag "Document Type")
+ (string :tag "Header")
+ (repeat :tag "Options" :inline t
+ (choice
+ (list :tag "Heading")
+ (function :tag "Hook computing sectioning"))))))
+
+;;; Headline
+
+(defconst org-groff-special-tags
+ '("FROM" "TO" "ABSTRACT" "APPENDIX" "BODY" "NS"))
+
+(defcustom org-groff-format-headline-function nil
+ "Function to format headline text.
+
+This function will be called with 5 arguments:
+TODO the todo keyword (string or nil).
+TODO-TYPE the type of todo (symbol: `todo', `done', nil)
+PRIORITY the priority of the headline (integer or nil)
+TEXT the main headline text (string).
+TAGS the tags as a list of strings (list of strings or nil).
+
+The function result will be used in the section format string.
+
+As an example, one could set the variable to the following, in
+order to reproduce the default set-up:
+
+\(defun org-groff-format-headline (todo todo-type priority text tags)
+ \"Default format function for a headline.\"
+ \(concat (when todo
+ \(format \"\\fB%s\\fP \" todo))
+ \(when priority
+ \(format \"[\\#%c] \" priority))
+ text
+ \(when tags
+ \(format \" %s \"
+ \(mapconcat 'identity tags \":\"))))"
+ :group 'org-export-groff
+ :type 'function)
+
+;;; Timestamps
+
+(defcustom org-groff-active-timestamp-format "\\fI%s\\fP"
+ "A printf format string to be applied to active timestamps."
+ :group 'org-export-groff
+ :type 'string)
+
+(defcustom org-groff-inactive-timestamp-format "\\fI%s\\fP"
+ "A printf format string to be applied to inactive timestamps."
+ :group 'org-export-groff
+ :type 'string)
+
+(defcustom org-groff-diary-timestamp-format "\\fI%s\\fP"
+ "A printf format string to be applied to diary timestamps."
+ :group 'org-export-groff
+ :type 'string)
+
+;;; Links
+
+(defcustom org-groff-inline-image-rules
+ '(("file" . "\\.\\(jpg\\|png\\|pdf\\|ps\\|eps\\|pic\\)\\'")
+ ("fuzzy" . "\\.\\(jpg\\|png\\|pdf\\|ps\\|eps\\|pic\\)\\'"))
+ "Rules characterizing image files that can be inlined into Groff.
+
+A rule consists in an association whose key is the type of link
+to consider, and value is a regexp that will be matched against
+link's path.
+
+Note that, by default, the image extensions actually allowed
+depend on the way the Groff file is processed. When used with
+pdfgroff, pdf, jpg and png images are OK. When processing
+through dvi to Postscript, only ps and eps are allowed. The
+default we use here encompasses both."
+ :group 'org-export-groff
+ :type '(alist :key-type (string :tag "Type")
+ :value-type (regexp :tag "Path")))
+
+(defcustom org-groff-link-with-unknown-path-format "\\fI%s\\fP"
+ "Format string for links with unknown path type."
+ :group 'org-export-groff
+ :type 'string)
+
+;;; Tables
+
+(defcustom org-groff-tables-centered t
+ "When non-nil, tables are exported in a center environment."
+ :group 'org-export-groff
+ :type 'boolean)
+
+(defcustom org-groff-tables-verbatim nil
+ "When non-nil, tables are exported verbatim."
+ :group 'org-export-groff
+ :type 'boolean)
+
+(defcustom org-groff-table-scientific-notation "%sE%s"
+ "Format string to display numbers in scientific notation.
+The format should have \"%s\" twice, for mantissa and exponent
+\(i.e. \"%s\\\\times10^{%s}\").
+
+When nil, no transformation is made."
+ :group 'org-export-groff
+ :type '(choice
+ (string :tag "Format string")
+ (const :tag "No formatting")))
+
+;;; Text markup
+
+(defcustom org-groff-text-markup-alist
+ '((bold . "\\fB%s\\fP")
+ (code . "\\fC%s\\fP")
+ (italic . "\\fI%s\\fP")
+ (strike-through . "\\fC%s\\fP") ; Strike through and underline
+ (underline . "\\fI%s\\fP") ; need to be revised.
+ (verbatim . "protectedtexttt"))
+ "Alist of Groff expressions to convert text markup.
+
+The key must be a symbol among `bold', `code', `italic',
+`strike-through', `underline' and `verbatim'. The value is
+a formatting string to wrap fontified text with it.
+
+If no association can be found for a given markup, text will be
+returned as-is."
+ :group 'org-export-groff
+ :type 'alist
+ :options '(bold code italic strike-through underline verbatim))
+
+;;; Drawers
+
+(defcustom org-groff-format-drawer-function nil
+ "Function called to format a drawer in Groff code.
+
+The function must accept two parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+
+The function should return the string to be exported.
+
+For example, the variable could be set to the following function
+in order to mimic default behaviour:
+
+\(defun org-groff-format-drawer-default \(name contents\)
+ \"Format a drawer element for Groff export.\"
+ contents\)"
+ :group 'org-export-groff
+ :type 'function)
+
+;;; Inlinetasks
+
+(defcustom org-groff-format-inlinetask-function nil
+ "Function called to format an inlinetask in Groff code.
+
+The function must accept six parameters:
+ TODO the todo keyword, as a string
+ TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
+ PRIORITY the inlinetask priority, as a string
+ NAME the inlinetask name, as a string.
+ TAGS the inlinetask tags, as a list of strings.
+ CONTENTS the contents of the inlinetask, as a string.
+
+The function should return the string to be exported.
+
+For example, the variable could be set to the following function
+in order to mimic default behaviour:
+
+\(defun org-groff-format-inlinetask \(todo type priority name tags contents\)
+\"Format an inline task element for Groff export.\"
+ \(let ((full-title
+ \(concat
+ \(when todo
+ \(format \"\\fB%s\\fP \" todo))
+ \(when priority (format \"[\\#%c] \" priority))
+ title
+ \(when tags
+ \(format \":%s:\"
+ \(mapconcat 'identity tags \":\")))))
+ \(format (concat \".DS L\\n\"
+ \"%s\\n\\n\"
+ \"%s\"
+ \".DE\")
+ full-title contents))"
+ :group 'org-export-groff
+ :type 'function)
+
+;; Src blocks
+
+(defcustom org-groff-source-highlight nil
+ "Use GNU source highlight to embellish source blocks "
+ :group 'org-export-groff
+ :type 'boolean)
+
+(defcustom org-groff-source-highlight-langs
+ '((emacs-lisp "lisp") (lisp "lisp") (clojure "lisp")
+ (scheme "scheme")
+ (c "c") (cc "cpp") (csharp "csharp") (d "d")
+ (fortran "fortran") (cobol "cobol") (pascal "pascal")
+ (ada "ada") (asm "asm")
+ (perl "perl") (cperl "perl")
+ (python "python") (ruby "ruby") (tcl "tcl") (lua "lua")
+ (java "java") (javascript "javascript")
+ (tex "latex")
+ (shell-script "sh") (awk "awk") (diff "diff") (m4 "m4")
+ (ocaml "caml") (caml "caml")
+ (sql "sql") (sqlite "sql")
+ (html "html") (css "css") (xml "xml")
+ (bat "bat") (bison "bison") (clipper "clipper")
+ (ldap "ldap") (opa "opa")
+ (php "php") (postscript "postscript") (prolog "prolog")
+ (properties "properties") (makefile "makefile")
+ (tml "tml") (vala "vala") (vbscript "vbscript") (xorg "xorg"))
+ "Alist mapping languages to their listing language counterpart.
+The key is a symbol, the major mode symbol without the \"-mode\".
+The value is the string that should be inserted as the language
+parameter for the listings package. If the mode name and the
+listings name are the same, the language does not need an entry
+in this list - but it does not hurt if it is present."
+ :group 'org-export-groff
+ :type '(repeat
+ (list
+ (symbol :tag "Major mode ")
+ (string :tag "Listings language"))))
+
+(defcustom org-groff-source-highlight-options nil
+ "Association list of options for the groff listings package.
+
+These options are supplied as a comma-separated list to the
+\\lstset command. Each element of the association list should be
+a list containing two strings: the name of the option, and the
+value. For example,
+
+ (setq org-groff-source-highlight-options
+ '((\"basicstyle\" \"\\small\")
+ (\"keywordstyle\" \"\\color{black}\\bfseries\\underbar\")))
+
+will typeset the code in a small size font with underlined, bold
+black keywords.
+
+Note that the same options will be applied to blocks of all
+languages."
+ :group 'org-export-groff
+ :type '(repeat
+ (list
+ (string :tag "Listings option name ")
+ (string :tag "Listings option value"))))
+
+(defvar org-groff-custom-lang-environments nil
+ "Alist mapping languages to language-specific Groff environments.
+
+It is used during export of src blocks by the listings and
+groff packages. For example,
+
+ \(setq org-groff-custom-lang-environments
+ '\(\(python \"pythoncode\"\)\)\)
+
+would have the effect that if org encounters begin_src python
+during groff export it will use pythoncode as the source-highlight
+language.")
+
+;;; Plain text
+
+(defcustom org-groff-special-char
+ '(("(c)" . "\\\\(co")
+ ("(tm)" . "\\\\(tm")
+ ("(rg)" . "\\\\(rg"))
+ "CONS list in which the value of the car
+ is replace on the value of the CDR. "
+ :group 'org-export-groff
+ :type '(list
+ (cons :tag "Character Subtitute"
+ (string :tag "Original Character Group")
+ (string :tag "Replacement Character"))))
+
+;;; Compilation
+
+(defcustom org-groff-pdf-process
+ '("pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf")
+
+ "Commands to process a Groff file to a PDF file.
+This is a list of strings, each of them will be given to the
+shell as a command. %f in the command will be replaced by the
+full file name, %b by the file base name \(i.e. without
+extension) and %o by the base directory of the file."
+ :group 'org-export-pdf
+ :type '(choice
+ (repeat :tag "Shell command sequence"
+ (string :tag "Shell command"))
+ (const :tag "2 runs of pdfgroff"
+ ("pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"))
+ (const :tag "3 runs of pdfgroff"
+ ("pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "pic %f | tbl | eqn | groff -mm | ps2pdf - > %b.pdf"))
+ (function)))
+
+(defcustom org-groff-logfiles-extensions
+ '("aux" "idx" "log" "out" "toc" "nav" "snm" "vrb")
+ "The list of file extensions to consider as Groff logfiles."
+ :group 'org-export-groff
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-groff-remove-logfiles t
+ "Non-nil means remove the logfiles produced by PDF production.
+These are the .aux, .log, .out, and .toc files."
+ :group 'org-export-groff
+ :type 'boolean)
+
+(defcustom org-groff-organization "Org User"
+ "Name of the organization used to populate the .AF command."
+ :group 'org-export-groff
+ :type 'string)
+
+(defcustom org-groff-raster-to-ps nil
+ "Command used to convert raster to EPS. Nil for no conversion. Make sure that
+ `org-groff-inline-image-rules' is adjusted accordingly if not conversion is being
+ done. In this case, remove the entries for jpg and png in the file and fuzzy lists."
+ :group 'org-export-groff
+ :type '(choice
+ (repeat :tag "Shell Command Sequence" (string :tag "Shell Command"))
+ (const :tag "sam2p" "a=%s;b=%s;sam2p ${a} ${b} ;grep -v BeginData ${b} > b_${b};mv b_${b} ${b}" )
+ (const :tag "NetPNM" "a=%s;b=%s;pngtopnm ${a} | pnmtops -noturn > ${b}" )
+ (const :tag "None" nil)))
+
+(defvar org-groff-registered-references nil)
+(defvar org-groff-special-content nil)
+
+
+
+;;; Internal Functions
+
+(defun org-groff--caption/label-string (element info)
+ "Return caption and label Groff string for ELEMENT.
+
+INFO is a plist holding contextual information. If there's no
+caption nor label, return the empty string.
+
+For non-floats, see `org-groff--wrap-label'."
+ (let ((main (org-export-get-caption element))
+ (short (org-export-get-caption element t))
+ (label (org-element-property :name element)))
+ (cond ((and (not main) (not label)) "")
+ ((not main) (format "\\fI%s\\fP" label))
+ ;; Option caption format with short name.
+ (short (format "%s\n.br\n - %s\n"
+ (org-export-data short info)
+ (org-export-data main info)))
+ ;; Standard caption format.
+ (t (format "\\fR%s\\fP" (org-export-data main info))))))
+
+(defun org-groff--wrap-label (element output)
+ "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
+This function shouldn't be used for floats. See
+`org-groff--caption/label-string'."
+ (let ((label (org-element-property :name element)))
+ (if (or (not output) (not label) (string= output "") (string= label ""))
+ output
+ (concat (format "%s\n.br\n" label) output))))
+
+(defun org-groff--text-markup (text markup)
+ "Format TEXT depending on MARKUP text markup.
+See `org-groff-text-markup-alist' for details."
+ (let ((fmt (cdr (assq markup org-groff-text-markup-alist))))
+ (cond
+ ;; No format string: Return raw text.
+ ((not fmt) text)
+ ((string= "protectedtexttt" fmt)
+ (let ((start 0)
+ (trans '(("\\" . "\\")))
+ (rtn "")
+ char)
+ (while (string-match "[\\{}$%&_#~^]" text)
+ (setq char (match-string 0 text))
+ (if (> (match-beginning 0) 0)
+ (setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
+ (setq text (substring text (1+ (match-beginning 0))))
+ (setq char (or (cdr (assoc char trans)) (concat "\\" char))
+ rtn (concat rtn char)))
+ (setq text (concat rtn text))
+ (format "\\fC%s\\fP" text)))
+ ;; Else use format string.
+ (t (format fmt text)))))
+
+
+(defun org-groff--get-tagged-content (tag info)
+ (cdr (assoc tag org-groff-special-content)))
+
+(defun org-groff--mt-head (title contents attr info)
+ (concat
+
+ ;; 1. Insert Organization
+ (let ((firm-option (plist-get attr :firm)))
+ (cond
+ ((stringp firm-option)
+ (format ".AF \"%s\" \n" firm-option))
+ (t (format ".AF \"%s\" \n" (or org-groff-organization "")))))
+
+ ;; 2. Title
+ (let ((title (if (plist-get info :with-title) title ""))
+ (subtitle1 (plist-get attr :subtitle1))
+ (subtitle2 (plist-get attr :subtitle2)))
+
+ (cond
+ ((string= "" title)
+ (format ".TL \"%s\" \"%s\" \n%s\n"
+ (or subtitle1 "")
+ (or subtitle2 "") " "))
+
+ ((not (or subtitle1 subtitle2))
+ (format ".TL\n%s\n"
+ (or title "")))
+ (t
+ (format ".TL \"%s\" \"%s \" \n%s\n"
+ (or subtitle1 "")
+ (or subtitle2 "") title))))
+
+ ;; 3. Author.
+ ;; In Groff, .AU *MUST* be placed after .TL
+ ;; If From, populate with data from From else
+ ;;
+ (let ((author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (and (plist-get info :with-email)
+ (org-export-data (plist-get info :email) info)))
+ (from-data (org-groff--get-tagged-content "FROM" info))
+
+ (to-data (org-groff--get-tagged-content "TO" info)))
+
+ (cond
+ ((and author from-data)
+ (let ((au-line
+ (mapconcat
+ (lambda (from-line)
+ (format " \"%s\" " from-line))
+ (split-string
+ (setq from-data
+ (replace-regexp-in-string "\\.P\n" "" from-data)) "\n") "")))
+
+ (concat
+ (format ".AU \"%s\" " author) au-line "\n")))
+
+ ((and author email (not (string= "" email)))
+ (format ".AU \"%s\" \"%s\"\n" author email))
+
+ (author (format ".AU \"%s\"\n" author))
+
+ (t ".AU \"\" \n")))
+
+
+ ;; 4. Author Title, if present
+ (let ((at-item (plist-get attr :author-title)))
+ (if (and at-item (stringp at-item))
+ (format ".AT \"%s\" \n" at-item)
+ ""))
+
+ ;; 5. Date.
+ (when (plist-get info :with-date)
+ (let ((date (org-export-data (org-export-get-date info) info)))
+ (and (org-string-nw-p date) (format ".ND \"%s\"\n" date))))
+
+ ;;
+ ;; If Abstract, then Populate Abstract
+ ;;
+
+ (let ((abstract-data (org-groff--get-tagged-content "ABSTRACT" info))
+ (to-data (org-groff--get-tagged-content "TO" info)))
+ (cond
+ (abstract-data
+ (format ".AS\n%s\n.AE\n" abstract-data))
+ (to-data
+ (format ".AS\n%s\n.AE\n" to-data))))))
+
+(defun org-groff--letter-head (title contents attr info)
+ (let ((author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (and (plist-get info :with-email)
+ (org-export-data (plist-get info :email) info)))
+ (from-data (org-groff--get-tagged-content "FROM" info))
+ (at-item (plist-get attr :author-title))
+ (to-data (org-groff--get-tagged-content "TO" info)))
+
+
+ ;; If FROM then get data from FROM
+ (if from-data
+ (setq from-data
+ (replace-regexp-in-string "\\.P\n" "" from-data))
+ (setq from-data ""))
+
+ (if to-data
+ (setq to-data
+ (replace-regexp-in-string "\\.P\n" "" to-data))
+ (setq from-data ""))
+
+ (concat
+ (cond
+ (from-data
+ (format ".WA \"%s\" \"%s\" \n%s\n.WE\n" author (or at-item "") from-data))
+ ((and author email (not (string= "" email)))
+ (format ".WA \"%s\"\n \"%s\"\n.WE\n" author email))
+ (author (format ".WA \"%s\"\n.WE\n" author))
+ (t ".WA \"\" \n.WE\n"))
+
+ ;; If TO then get data from TO
+
+ (when to-data
+ (format ".IA \n%s\n.IE\n" to-data)))))
+
+
+;;; Template
+
+(defun org-groff-template (contents info)
+ "Return complete document string after Groff conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let* ((title (org-export-data (plist-get info :title) info))
+ (attr (read
+ (format "(%s)"
+ (mapconcat
+ #'identity
+ (list (plist-get info :groff-class-options))
+ " "))))
+ (class (plist-get info :groff-class))
+ (class-options (plist-get info :groff-class-options))
+ (classes (assoc class org-groff-classes))
+ (classes-options (car (last classes)))
+ (heading-option (plist-get classes-options :heading))
+ (type-option (plist-get classes-options :type))
+ (last-option (plist-get classes-options :last-section))
+ (hyphenate (plist-get attr :hyphenate))
+ (justify-right (plist-get attr :justify-right))
+
+ (document-class-string
+ (progn
+ (org-element-normalize-string
+ (let* ((header (nth 1 (assoc class org-groff-classes)))
+ (document-class-item (if (stringp header) header "")))
+ document-class-item)))))
+
+
+ (concat
+ (if justify-right
+ (case justify-right
+ ('yes ".SA 1 \n")
+ ('no ".SA 0 \n")
+ (t ""))
+ "")
+
+ (if hyphenate
+ (case hyphenate
+ ('yes ".nr Hy 1 \n")
+ ('no ".nr Hy 0 \n")
+ (t ""))
+ "")
+
+ (cond
+ ((string= type-option "custom") "")
+
+ ((and (stringp document-class-string)
+ (string= type-option "cover"))
+
+ (concat
+ (format ".COVER %s\n" document-class-string)
+ (org-groff--mt-head title contents attr info)
+ ".COVEND\n"))
+
+ ((string= type-option "memo")
+ (concat
+ (org-groff--mt-head title contents attr info)
+ document-class-string))
+ ((string= type-option "letter")
+ (concat
+ (org-groff--letter-head title contents attr info)
+ (let ((sa-item (plist-get attr :salutation))
+ (cn-item (plist-get attr :confidential))
+ (sj-item (plist-get attr :subject))
+ (rn-item (plist-get attr :reference))
+ (at-item (plist-get attr :attention)))
+
+ (concat
+
+ (if (stringp sa-item)
+ (format ".LO SA \"%s\" \n" sa-item)
+ ".LO SA\n")
+
+ (when cn-item
+ (if (stringp cn-item)
+ (format ".LO CN \"%s\"\n" cn-item)
+ ".LO CN\n"))
+
+ (when (and at-item (stringp at-item))
+ (format ".LO AT \"%s\" \n" at-item))
+ (when (and title rn-item)
+ (format ".LO RN \"%s\"\n" title))
+
+ (when (and sj-item (stringp sj-item))
+ (format ".LO SJ \"%s\" \n" sj-item))
+
+
+ ".LT " document-class-string "\n"))))
+
+ (t ""))
+
+ contents
+
+ (cond
+ ((string= last-option "toc")
+ ".TC")
+ ((string= last-option "sign")
+ (let ((fc-item (plist-get attr :closing)))
+ (concat (if (stringp fc-item)
+ (format ".FC \"%s\" \n" fc-item)
+ ".FC\n")
+ ".SG\n")))
+ (t ""))
+
+ (progn
+ (mapconcat
+ (lambda (item)
+ (when (string= (car item) "NS")
+ (replace-regexp-in-string
+ "\\.P\n" "" (cdr item))))
+ (reverse org-groff-special-content) "\n")))))
+
+
+
+;;; Transcode Functions
+
+;;; Babel Call
+;;
+;; Babel Calls are ignored.
+
+
+;;; Bold
+
+(defun org-groff-bold (bold contents info)
+ "Transcode BOLD from Org to Groff.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (org-groff--text-markup contents 'bold))
+
+;;; Center Block
+
+(defun org-groff-center-block (center-block contents info)
+ "Transcode a CENTER-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the center block. INFO is a plist
+holding contextual information."
+ (org-groff--wrap-label
+ center-block
+ (format ".DS C \n%s\n.DE" contents)))
+
+;;; Clock
+
+(defun org-groff-clock (clock contents info)
+ "Transcode a CLOCK element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ (format "\\fB%s\\fP " org-clock-string)
+ (format org-groff-inactive-timestamp-format
+ (concat (org-timestamp-translate (org-element-property :value clock))
+ (let ((time (org-element-property :duration clock)))
+ (and time (format " (%s)" time)))))))
+
+;;; Code
+
+(defun org-groff-code (code contents info)
+ "Transcode a CODE object from Org to Groff.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-groff--text-markup (org-element-property :value code) 'code))
+
+;;; Comments and Comment Blocks are ignored.
+
+;;; Drawer
+
+(defun org-groff-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to Groff.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((name (org-element-property :drawer-name drawer))
+ (output (if (functionp org-groff-format-drawer-function)
+ (funcall org-groff-format-drawer-function
+ name contents)
+ ;; If there's no user defined function: simply
+ ;; display contents of the drawer.
+ contents)))
+ (org-groff--wrap-label drawer output)))
+
+;;; Dynamic Block
+
+(defun org-groff-dynamic-block (dynamic-block contents info)
+ "Transcode a DYNAMIC-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information. See `org-export-data'."
+ (org-groff--wrap-label dynamic-block contents))
+
+;;; Entity
+
+(defun org-groff-entity (entity contents info)
+ "Transcode an ENTITY object from Org to Groff.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :utf-8 entity))
+
+;;; Example Block
+
+(defun org-groff-example-block (example-block contents info)
+ "Transcode an EXAMPLE-BLOCK element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-groff--wrap-label
+ example-block
+ (format ".DS L\n%s\n.DE"
+ (org-export-format-code-default example-block info))))
+
+;;; Export Block
+
+(defun org-groff-export-block (export-block contents info)
+ "Transcode a EXPORT-BLOCK element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "GROFF")
+ (org-remove-indentation (org-element-property :value export-block))))
+
+;;; Export Snippet
+
+(defun org-groff-export-snippet (export-snippet contents info)
+ "Transcode a EXPORT-SNIPPET object from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'groff)
+ (org-element-property :value export-snippet)))
+
+;;; Fixed Width
+
+(defun org-groff-fixed-width (fixed-width contents info)
+ "Transcode a FIXED-WIDTH element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-groff--wrap-label
+ fixed-width
+ (format "\\fC\n%s\\fP"
+ (org-remove-indentation
+ (org-element-property :value fixed-width)))))
+
+;;; Footnote Definition
+;;
+;; Footnote Definitions are ignored.
+;;
+;; Footnotes are handled automatically in GROFF. Although manual
+;; references can be added, not really required.
+
+(defun org-groff-footnote-reference (footnote-reference contents info)
+ ;; Changing from info to footnote-reference
+ (let* ((raw (org-export-get-footnote-definition footnote-reference info))
+ (n (org-export-get-footnote-number footnote-reference info))
+ (data (org-trim (org-export-data raw info)))
+ (ref-id (plist-get (nth 1 footnote-reference) :label)))
+ ;; It is a reference
+ (if (string-match "fn:rl" ref-id)
+ (if (member ref-id org-groff-registered-references)
+ (format "\\*[%s]" ref-id)
+ (progn
+ (push ref-id org-groff-registered-references)
+ (format "\\*(Rf\n.RS \"%s\" \n%s\n.RF\n" ref-id data)))
+ ;; else it is a footnote
+ (format "\\u\\s-2%s\\d\\s+2\n.FS %s\n%s\n.FE\n" n n data))))
+
+;;; Headline
+
+(defun org-groff-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to Groff.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ (let* ((class (plist-get info :groff-class))
+ (level (org-export-get-relative-level headline info))
+ (numberedp (org-export-numbered-headline-p headline info))
+ ;; Section formatting will set two placeholders: one for the
+ ;; title and the other for the contents.
+ (classes (assoc class org-groff-classes))
+ (classes-options (car (last classes)))
+ (heading-option (plist-get classes-options :heading))
+ (section-fmt
+ (progn
+ (cond
+ ((and (symbolp heading-option)
+ (fboundp heading-option))
+ (funcall heading-option level numberedp))
+ ((> level 7) nil)
+ (t (if numberedp
+ (concat ".H " (number-to-string level) " \"%s\"\n%s")
+ ".HU \"%s\"\n%s")))))
+ ;; End of section-fmt
+ (text (org-export-data (org-element-property :title headline) info))
+ (todo
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ ;; Create the headline text along with a no-tag version. The
+ ;; latter is required to remove tags from table of contents.
+ (full-text (if (functionp org-groff-format-headline-function)
+ ;; User-defined formatting function.
+ (funcall org-groff-format-headline-function
+ todo todo-type priority text tags)
+ ;; Default formatting.
+ (concat
+ (when todo
+ (format "\\fB%s\\fP " todo))
+ (when priority (format " [\\#%c] " priority))
+ text
+ (when tags
+ (format " \\fC:%s:\\fP "
+ (mapconcat 'identity tags ":"))))))
+ (full-text-no-tag
+ (if (functionp org-groff-format-headline-function)
+ ;; User-defined formatting function.
+ (funcall org-groff-format-headline-function
+ todo todo-type priority text nil)
+ ;; Default formatting.
+ (concat
+ (when todo (format "\\fB%s\\fP " todo))
+ (when priority (format " [\\#%c] " priority))
+ text)))
+ ;; Associate some \label to the headline for internal links.
+ ;; (headline-label
+ ;; (format "\\label{sec-%s}\n"
+ ;; (mapconcat 'number-to-string
+ ;; (org-export-get-headline-number headline info)
+ ;; "-")))
+ (headline-label "")
+ (pre-blanks
+ (make-string (org-element-property :pre-blank headline) 10)))
+
+ (cond
+ ;; Case 1: Special Tag
+ ((member (car tags) org-groff-special-tags)
+ (cond
+ ((string= (car tags) "BODY") contents)
+
+ ((string= (car tags) "NS")
+ (progn
+ (push (cons (car tags)
+ (format ".NS \"%s\" 1 \n%s"
+ (car (org-element-property :title headline))
+ (or contents " ")))
+ org-groff-special-content) nil))
+
+ (t
+ (progn
+ (push (cons (car tags) contents) org-groff-special-content)
+ nil))))
+
+ ;; Case 2: This is a footnote section: ignore it.
+ ((org-element-property :footnote-section-p headline) nil)
+
+ ;; Case 3: This is a deep sub-tree: export it as a list item.
+ ;; Also export as items headlines for which no section
+ ;; format has been found.
+ ((or (not section-fmt) (org-export-low-level-p headline info))
+ ;; Build the real contents of the sub-tree.
+ (let ((low-level-body
+ (concat
+ ;; If the headline is the first sibling, start a list.
+ (when (org-export-first-sibling-p headline info)
+ (format "%s\n" (if numberedp ".AL 1\n" ".DL \n")))
+ ;; Itemize headline
+ ".LI\n" full-text "\n" headline-label pre-blanks contents)))
+ ;; If headline is not the last sibling simply return
+ ;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
+ ;; blank line.
+ (if (not (org-export-last-sibling-p headline info)) low-level-body
+ (replace-regexp-in-string
+ "[ \t\n]*\\'"
+ (concat "\n.LE")
+ low-level-body))))
+
+ ;; Case 4. Standard headline. Export it as a section.
+ (t
+ (format section-fmt full-text
+ (concat headline-label pre-blanks contents))))))
+
+;;; Horizontal Rule
+;; Not supported
+
+;;; Inline Babel Call
+;;
+;; Inline Babel Calls are ignored.
+
+;;; Inline Src Block
+
+(defun org-groff-inline-src-block (inline-src-block contents info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((code (org-element-property :value inline-src-block)))
+ (cond
+ (org-groff-source-highlight
+ (let* ((tmpdir temporary-file-directory)
+ (in-file (make-temp-name
+ (expand-file-name "srchilite" tmpdir)))
+ (out-file (make-temp-name
+ (expand-file-name "reshilite" tmpdir)))
+ (org-lang (org-element-property :language inline-src-block))
+ (lst-lang (cadr (assq (intern org-lang)
+ org-groff-source-highlight-langs)))
+
+ (cmd (concat (expand-file-name "source-highlight")
+ " -s " lst-lang
+ " -f groff_mm_color "
+ " -i " in-file
+ " -o " out-file)))
+ (if lst-lang
+ (let ((code-block ""))
+ (with-temp-file in-file (insert code))
+ (shell-command cmd)
+ (setq code-block (org-file-contents out-file))
+ (delete-file in-file)
+ (delete-file out-file)
+ code-block)
+ (format ".DS I\n\\fC\\m[black]%s\\m[]\\fP\n.DE\n"
+ code))))
+
+ ;; Do not use a special package: transcode it verbatim.
+ (t
+ (concat ".DS I\n" "\\fC" code "\\fP\n.DE\n")))))
+
+;;; Inlinetask
+
+(defun org-groff-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to Groff.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((title (org-export-data (org-element-property :title inlinetask) info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (org-element-property :todo-type inlinetask))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags inlinetask info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask))))
+ ;; If `org-groff-format-inlinetask-function' is provided, call it
+ ;; with appropriate arguments.
+ (if (functionp org-groff-format-inlinetask-function)
+ (funcall org-groff-format-inlinetask-function
+ todo todo-type priority title tags contents)
+ ;; Otherwise, use a default template.
+ (org-groff--wrap-label
+ inlinetask
+ (let ((full-title
+ (concat
+ (when todo (format "\\fB%s\\fP " todo))
+ (when priority (format " [\\#%c] " priority))
+ title
+ (when tags (format " \\fC:%s:\\fP "
+ (mapconcat 'identity tags ":"))))))
+ (format (concat "\n.DS I\n"
+ "%s\n"
+ ".sp"
+ "%s\n"
+ ".DE")
+ full-title contents))))))
+
+;;; Italic
+
+(defun org-groff-italic (italic contents info)
+ "Transcode ITALIC from Org to Groff.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (org-groff--text-markup contents 'italic))
+
+;;; Item
+
+(defun org-groff-item (item contents info)
+ "Transcode an ITEM element from Org to Groff.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((bullet (org-element-property :bullet item))
+ (type (org-element-property
+ :type (org-element-property :parent item)))
+ (checkbox (case (org-element-property :checkbox item)
+ (on "\\o'\\(sq\\(mu'")
+ (off "\\(sq")
+ (trans "\\o'\\(sq\\(mi'")))
+ (tag (let ((tag (org-element-property :tag item)))
+ ;; Check-boxes must belong to the tag.
+ (and tag (format "%s"
+ (concat checkbox
+ (org-export-data tag info)))))))
+
+ (cond
+ ((or checkbox tag)
+ (concat ".LI ""\"" (or tag (concat "\\ " checkbox)) "\""
+ "\n"
+ (org-trim (or contents " "))))
+ ((eq type 'ordered)
+ (concat ".LI"
+ "\n"
+ (org-trim (or contents " "))))
+ (t
+ (let* ((bullet (org-trim bullet))
+ (marker (cond ((string= "-" bullet) "\\(em")
+ ((string= "*" bullet) "\\(bu")
+ (t "\\(dg"))))
+ (concat ".LI " marker "\n"
+ (org-trim (or contents " "))))))))
+
+;;; Keyword
+
+(defun org-groff-keyword (keyword contents info)
+ "Transcode a KEYWORD element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "GROFF") value)
+ (t nil))))
+
+;;; Line Break
+
+(defun org-groff-line-break (line-break contents info)
+ "Transcode a LINE-BREAK object from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ ".br\n")
+
+;;; Link
+;; Inline images just place a call to .PSPIC or .PS/.PE
+;; and load the graph.
+
+(defun org-groff-link--inline-image (link info)
+ "Return Groff code for an inline image.
+LINK is the link pointing to the inline image. INFO is a plist
+used as a communication channel."
+ (let* ((parent (org-export-get-parent-element link))
+ (path (let ((raw-path (org-element-property :path link)))
+ (if (not (file-name-absolute-p raw-path)) raw-path
+ (expand-file-name raw-path))))
+ (attr (org-export-read-attribute :attr_groff link))
+ (placement
+ (let ((pos (plist-get attr :position)))
+ (cond ((string= pos 'center) "")
+ ((string= pos 'left) "-L")
+ ((string= pos 'right) "-R")
+ (t ""))))
+ (width (or (plist-get attr :width) ""))
+ (height (or (plist-get attr :height) ""))
+ (caption (and (not (plist-get attr :disable-caption))
+ (org-groff--caption/label-string parent info))))
+ ;; Now clear ATTR from any special keyword and set a default value
+ ;; if nothing is left. Return proper string.
+ (concat
+ (cond
+ ((and org-groff-raster-to-ps
+ (or (string-match ".\.png$" path)
+ (string-match ".\.jpg$" path)))
+ (let ((eps-path (concat path ".eps")))
+ (shell-command (format org-groff-raster-to-ps path eps-path))
+ (format "\n.DS L F\n.PSPIC %s \"%s\" %s %s\n.DE "
+ placement eps-path width height)))
+ ((string-match ".\.pic$" path)
+ (format "\n.PS\ncopy \"%s\"\n.PE" path))
+ (t (format "\n.DS L F\n.PSPIC %s \"%s\" %s %s\n.DE "
+ placement path width height)))
+ (and caption (format "\n.FG \"%s\"" caption)))))
+
+(defun org-groff-link (link desc info)
+ "Transcode a LINK object from Org to Groff.
+
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+
+ (let* ((type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (and (not (string= desc "")) desc))
+ (imagep (org-export-inline-image-p
+ link org-groff-inline-image-rules))
+ (path (cond
+ ((member type '("http" "https" "ftp" "mailto"))
+ (concat type ":" raw-path))
+ ((string= type "file") (org-export-file-uri raw-path))
+ (t raw-path))))
+ (cond
+ ((org-export-custom-protocol-maybe link desc 'groff))
+ ;; Image file.
+ (imagep (org-groff-link--inline-image link info))
+ ;; import groff files
+ ((and (string= type "file")
+ (string-match ".\.groff$" raw-path))
+ (concat ".so " raw-path "\n"))
+ ;; Radio link: transcode target's contents and use them as link's
+ ;; description.
+ ((string= type "radio")
+ (let ((destination (org-export-resolve-radio-link link info)))
+ (if (not destination) desc
+ (format "\\fI [%s] \\fP"
+ (org-export-get-reference destination info)))))
+
+ ;; Links pointing to a headline: find destination and build
+ ;; appropriate referencing command.
+ ((member type '("custom-id" "fuzzy" "id"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (case (org-element-type destination)
+ ;; Id link points to an external file.
+ (plain-text
+ (if desc (format "%s \\fBat\\fP \\fIfile://%s\\fP" desc destination)
+ (format "\\fI file://%s \\fP" destination)))
+ ;; Fuzzy link points nowhere.
+ ('nil
+ (format org-groff-link-with-unknown-path-format
+ (or desc
+ (org-export-data
+ (org-element-property :raw-link link) info))))
+ ;; LINK points to a headline. If headlines are numbered and
+ ;; the link has no description, display headline's number.
+ ;; Otherwise, display description or headline's title.
+ (headline
+ (let ((label ""))
+ (if (and (plist-get info :section-numbers) (not desc))
+ (format "\\fI%s\\fP" label)
+ (format "\\fI%s\\fP"
+ (or desc
+ (org-export-data
+ (org-element-property :title destination) info))))))
+ ;; Fuzzy link points to a target. Do as above.
+ (otherwise
+ (let ((ref (org-export-get-reference destination info)))
+ (if (not desc) (format "\\fI%s\\fP" ref)
+ (format "%s \\fBat\\fP \\fI%s\\fP" desc ref)))))))
+ ;; External link with a description part.
+ ((and path desc) (format "%s \\fBat\\fP \\fI%s\\fP" path desc))
+ ;; External link without a description part.
+ (path (format "\\fI%s\\fP" path))
+ ;; No path, only description. Try to do something useful.
+ (t (format org-groff-link-with-unknown-path-format desc)))))
+
+;;; Node Property
+
+(defun org-groff-node-property (node-property contents info)
+ "Transcode a NODE-PROPERTY element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+;;; Paragraph
+
+(defun org-groff-paragraph (paragraph contents info)
+ "Transcode a PARAGRAPH element from Org to Groff.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ (let ((parent (plist-get (nth 1 paragraph) :parent)))
+ (when parent
+ (let* ((parent-type (car parent))
+ (fixed-paragraph "")
+ (class (plist-get info :groff-class))
+ (class-options (plist-get info :groff-class-options))
+ (classes (assoc class org-groff-classes))
+ (classes-options (car (last classes)))
+ (paragraph-option (plist-get classes-options :paragraph)))
+ (cond
+ ((and (symbolp paragraph-option)
+ (fboundp paragraph-option))
+ (funcall paragraph-option parent-type parent contents))
+ ((and (eq parent-type 'item)
+ (plist-get (nth 1 parent) :bullet))
+ (setq fixed-paragraph (concat "" contents)))
+ ((eq parent-type 'section)
+ (setq fixed-paragraph (concat ".P\n" contents)))
+ ((eq parent-type 'footnote-definition)
+ (setq fixed-paragraph (concat "" contents)))
+ (t (setq fixed-paragraph (concat "" contents))))
+ fixed-paragraph))))
+
+;;; Plain List
+
+(defun org-groff-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element from Org to Groff.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let* ((type (org-element-property :type plain-list))
+ (attr (mapconcat #'identity
+ (org-element-property :attr_groff plain-list)
+ " "))
+ (groff-type (cond
+ ((eq type 'ordered) ".AL")
+ ((eq type 'unordered) ".BL")
+ ((eq type 'descriptive) ".VL 2.0i"))))
+ (org-groff--wrap-label
+ plain-list
+ (format "%s\n%s\n.LE" groff-type contents))))
+
+;;; Plain Text
+
+(defun org-groff-plain-text (text info)
+ "Transcode a TEXT string from Org to Groff.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+(let ((output text))
+ ;; Protect various characters.
+ (setq output (replace-regexp-in-string
+ "\\(?:[^\\]\\|^\\)\\(\\\\\\)\\(?:[^%$#&{}~^_\\]\\|$\\)"
+ "$\\" output nil t 1))
+ ;; Activate smart quotes. Be sure to provide original TEXT string
+ ;; since OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
+ ;; Handle Special Characters
+ (if org-groff-special-char
+ (dolist (special-char-list org-groff-special-char)
+ (setq output
+ (replace-regexp-in-string (car special-char-list)
+ (cdr special-char-list) output))))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output (replace-regexp-in-string
+ "\\(\\\\\\\\\\)?[ \t]*\n" ".br\n" output)))
+ ;; Return value.
+ output))
+
+;;; Planning
+
+(defun org-groff-planning (planning contents info)
+ "Transcode a PLANNING element from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ (mapconcat
+ 'identity
+ (delq nil
+ (list
+ (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat
+ (format "\\fR %s \\fP" org-closed-string)
+ (format org-groff-inactive-timestamp-format
+ (org-timestamp-translate closed)))))
+ (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat
+ (format "\\fB %s \\fP" org-deadline-string)
+ (format org-groff-active-timestamp-format
+ (org-timestamp-translate deadline)))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat
+ (format "\\fR %s \\fP" org-scheduled-string)
+ (format org-groff-active-timestamp-format
+ (org-timestamp-translate scheduled)))))))
+ "")
+ ""))
+
+;;;; Property Drawer
+
+(defun org-groff-property-drawer (property-drawer contents info)
+ "Transcode a PROPERTY-DRAWER element from Org to Groff.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format "\\fC\n%s\\fP" contents)))
+
+;;; Quote Block
+
+(defun org-groff-quote-block (quote-block contents info)
+ "Transcode a QUOTE-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (org-groff--wrap-label
+ quote-block
+ (format ".DS I\n.I\n%s\n.R\n.DE" contents)))
+
+;;; Radio Target
+
+(defun org-groff-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object from Org to Groff.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (format "%s - %s" (org-export-get-reference radio-target info) text))
+
+;;; Section
+
+(defun org-groff-section (section contents info)
+ "Transcode a SECTION element from Org to Groff.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ contents)
+
+;;; Special Block
+
+(defun org-groff-special-block (special-block contents info)
+ "Transcode a SPECIAL-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((type (org-element-property :type special-block)))
+ (org-groff--wrap-label
+ special-block
+ (format "%s\n" contents))))
+
+;;; Src Block
+
+(defun org-groff-src-block (src-block contents info)
+ "Transcode a SRC-BLOCK element from Org to Groff.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((lang (org-element-property :language src-block))
+ (label (org-element-property :name src-block))
+ (code (org-element-property :value src-block))
+ (custom-env (and lang
+ (cadr (assq (intern lang)
+ org-groff-custom-lang-environments))))
+ (num-start (org-export-get-loc src-block info))
+ (retain-labels (org-element-property :retain-labels src-block))
+ (caption (and (not (org-export-read-attribute
+ :attr_groff src-block :disable-caption))
+ (org-groff--caption/label-string src-block info))))
+
+ (cond
+ ;; Case 1. No source fontification.
+ ((not org-groff-source-highlight)
+ (concat
+ (format ".DS I\n\\fC%s\\fP\n.DE\n"
+ (org-export-format-code-default src-block info))
+ (and caption (format ".EX \"%s\" " caption))))
+
+ ;; Case 2. Source fontification.
+ (org-groff-source-highlight
+ (let* ((tmpdir temporary-file-directory)
+ (in-file (make-temp-name
+ (expand-file-name "srchilite" tmpdir)))
+ (out-file (make-temp-name
+ (expand-file-name "reshilite" tmpdir)))
+
+ (org-lang (org-element-property :language src-block))
+ (lst-lang (cadr (assq (intern org-lang)
+ org-groff-source-highlight-langs)))
+
+ (cmd (concat "source-highlight"
+ " -s " lst-lang
+ " -f groff_mm_color "
+ " -i " in-file
+ " -o " out-file)))
+
+ (concat
+ (if lst-lang
+ (let ((code-block ""))
+ (with-temp-file in-file (insert code))
+ (shell-command cmd)
+ (setq code-block (org-file-contents out-file))
+ (delete-file in-file)
+ (delete-file out-file)
+ (format "%s\n" code-block))
+ (format ".DS I\n\\fC\\m[black]%s\\m[]\\fP\n.DE\n"
+ code))
+ (and caption (format ".EX \"%s\" " caption))))))))
+
+
+;;; Statistics Cookie
+
+(defun org-groff-statistics-cookie (statistics-cookie contents info)
+ "Transcode a STATISTICS-COOKIE object from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-element-property :value statistics-cookie))
+
+
+;;; Strike-Through
+
+(defun org-groff-strike-through (strike-through contents info)
+ "Transcode STRIKE-THROUGH from Org to Groff.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (org-groff--text-markup contents 'strike-through))
+
+;;; Subscript
+
+(defun org-groff-subscript (subscript contents info)
+ "Transcode a SUBSCRIPT object from Org to Groff.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "\\d\\s-2%s\\s+2\\u" contents))
+
+;;; Superscript "^_%s$
+
+(defun org-groff-superscript (superscript contents info)
+ "Transcode a SUPERSCRIPT object from Org to Groff.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "\\u\\s-2%s\\s+2\\d" contents))
+
+
+;;; Table
+;;
+;; `org-groff-table' is the entry point for table transcoding. It
+;; takes care of tables with a "verbatim" attribute. Otherwise, it
+;; delegates the job to `org-groff-table--org-table' function,
+;; depending of the type of the table.
+;;
+;; `org-groff-table--align-string' is a subroutine used to build
+;; alignment string for Org tables.
+
+(defun org-groff-table (table contents info)
+ "Transcode a TABLE element from Org to Groff.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (cond
+ ;; Case 1: verbatim table.
+ ((or org-groff-tables-verbatim
+ (let ((attr (read (format "(%s)"
+ (mapconcat
+ #'identity
+ (org-element-property :attr_groff table) " ")))))
+ (and attr (plist-get attr :verbatim))))
+
+ (format ".DS L\n\\fC%s\\fP\n.DE"
+ ;; Re-create table, without affiliated keywords.
+ (org-trim
+ (org-element-interpret-data
+ `(table nil ,@(org-element-contents table))))))
+
+ ;; Case 2: Standard table.
+ (t (org-groff-table--org-table table contents info))))
+
+(defun org-groff-table--align-string (divider table info)
+ "Return an appropriate Groff alignment string.
+TABLE is the considered table. INFO is a plist used as
+a communication channel."
+ (let (alignment)
+ ;; Extract column groups and alignment from first (non-rule) row.
+ (org-element-map
+ (org-element-map table 'table-row
+ (lambda (row)
+ (and (eq (org-element-property :type row) 'standard) row))
+ info 'first-match)
+ 'table-cell
+ (lambda (cell)
+ (let* ((borders (org-export-table-cell-borders cell info))
+ (raw-width (org-export-table-cell-width cell info))
+ (width-cm (when raw-width (/ raw-width 5)))
+ (width (if raw-width (format "w(%dc)"
+ (if (< width-cm 1) 1 width-cm)) "")))
+ ;; Check left border for the first cell only.
+ ;; Alignment is nil on assignment
+
+ (when (and (memq 'left borders) (not alignment))
+ (push "|" alignment))
+ (push
+ (case (org-export-table-cell-alignment cell info)
+ (left (concat "l" width divider))
+ (right (concat "r" width divider))
+ (center (concat "c" width divider)))
+ alignment)
+ (when (memq 'right borders) (push "|" alignment))))
+ info)
+ (apply 'concat (reverse alignment))))
+
+(defun org-groff-table--org-table (table contents info)
+ "Return appropriate Groff code for an Org table.
+
+TABLE is the table type element to transcode. CONTENTS is its
+contents, as a string. INFO is a plist used as a communication
+channel.
+
+This function assumes TABLE has `org' as its `:type' attribute."
+ (let* ((attr (org-export-read-attribute :attr_groff table))
+ (label (org-element-property :name table))
+ (caption (and (not (plist-get attr :disable-caption))
+ (org-groff--caption/label-string table info)))
+ (divider (if (plist-get attr :divider) "|" " "))
+
+ ;; Determine alignment string.
+ (alignment (org-groff-table--align-string divider table info))
+
+ ;; Extract others display options.
+
+ (lines (org-split-string contents "\n"))
+
+ (attr-list
+ (delq nil
+ (list (and (plist-get attr :expand) "expand")
+ (let ((placement (plist-get attr :placement)))
+ (cond ((string= placement 'center) "center")
+ ((string= placement 'left) nil)
+ (t (if org-groff-tables-centered "center" ""))))
+ (or (plist-get attr :boxtype) "box"))))
+
+ (title-line (plist-get attr :title-line))
+ (long-cells (plist-get attr :long-cells))
+
+ (table-format
+ (concat
+ (or (car attr-list) "")
+ (or
+ (let (output-list)
+ (when (cdr attr-list)
+ (dolist (attr-item (cdr attr-list))
+ (setq output-list (concat output-list
+ (format ",%s" attr-item)))))
+ output-list) "")))
+ (first-line
+ (when lines (org-split-string (car lines) "\t"))))
+ ;; Prepare the final format string for the table.
+
+
+ (cond
+ ;; Others.
+ (lines
+ (concat ".TS\n " table-format ";\n"
+ (format "%s.\n"
+ (let ((final-line ""))
+ (when title-line
+ (dotimes (i (length first-line))
+ (setq final-line (concat final-line "cb" divider))))
+
+ (setq final-line (concat final-line "\n"))
+
+ (if alignment
+ (setq final-line (concat final-line alignment))
+ (dotimes (i (length first-line))
+ (setq final-line (concat final-line "c" divider))))
+ final-line))
+
+ (format "%s.TE\n"
+ (let ((final-line "")
+ (long-line "")
+ (lines (org-split-string contents "\n")))
+
+ (dolist (line-item lines)
+ (setq long-line "")
+
+ (if long-cells
+ (progn
+ (if (string= line-item "_")
+ (setq long-line (format "%s\n" line-item))
+ ;; else string =
+ (let ((cell-item-list (org-split-string line-item "\t")))
+ (dolist (cell-item cell-item-list)
+
+ (cond ((eq cell-item (car (last cell-item-list)))
+ (setq long-line (concat long-line
+ (format "T{\n%s\nT}\t\n" cell-item))))
+ (t
+ (setq long-line (concat long-line
+ (format "T{\n%s\nT}\t" cell-item))))))
+ long-line))
+ ;; else long cells
+ (setq final-line (concat final-line long-line)))
+
+ (setq final-line (concat final-line line-item "\n"))))
+ final-line))
+
+ (if caption (format ".TB \"%s\"" caption) ""))))))
+
+;;; Table Cell
+
+(defun org-groff-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to Groff
+CONTENTS is the cell contents. INFO is a plist used as
+a communication channel."
+ (progn
+ (concat (if (and contents
+ org-groff-table-scientific-notation
+ (string-match orgtbl-exp-regexp contents))
+ ;; Use appropriate format string for scientific
+ ;; notation.
+ (format org-groff-table-scientific-notation
+ (match-string 1 contents)
+ (match-string 2 contents))
+ contents)
+ (when (org-export-get-next-element table-cell info) "\t"))))
+
+
+;;; Table Row
+
+(defun org-groff-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to Groff
+CONTENTS is the contents of the row. INFO is a plist used as
+a communication channel."
+ ;; Rules are ignored since table separators are deduced from
+ ;; borders of the current row.
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let* ((attr (mapconcat 'identity
+ (org-element-property
+ :attr_groff (org-export-get-parent table-row))
+ " "))
+ ;; TABLE-ROW's borders are extracted from its first cell.
+ (borders
+ (org-export-table-cell-borders
+ (car (org-element-contents table-row)) info)))
+ (concat
+ ;; Mark horizontal lines
+ (cond ((and (memq 'top borders) (memq 'above borders)) "_\n"))
+ contents
+ (cond
+ ;; When BOOKTABS are activated enforce bottom rule even when
+ ;; no hline was specifically marked.
+ ((and (memq 'bottom borders) (memq 'below borders)) "\n_")
+ ((memq 'below borders) "\n_"))))))
+
+;;; Target
+
+(defun org-groff-target (target contents info)
+ "Transcode a TARGET object from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "\\fI%s\\fP" (org-export-get-reference target info)))
+
+;;; Timestamp
+
+(defun org-groff-timestamp (timestamp contents info)
+ "Transcode a TIMESTAMP object from Org to Groff.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((value (org-groff-plain-text
+ (org-timestamp-translate timestamp) info)))
+ (case (org-element-property :type timestamp)
+ ((active active-range)
+ (format org-groff-active-timestamp-format value))
+ ((inactive inactive-range)
+ (format org-groff-inactive-timestamp-format value))
+ (t (format org-groff-diary-timestamp-format value)))))
+
+;;; Underline
+
+(defun org-groff-underline (underline contents info)
+ "Transcode UNDERLINE from Org to Groff.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (org-groff--text-markup contents 'underline))
+
+;;; Verbatim
+
+(defun org-groff-verbatim (verbatim contents info)
+ "Transcode a VERBATIM object from Org to Groff.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-groff--text-markup (org-element-property :value verbatim) 'verbatim))
+
+;;; Verse Block
+
+(defun org-groff-verse-block (verse-block contents info)
+ "Transcode a VERSE-BLOCK element from Org to Groff.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (format ".DS C\n.ft HI\n%s\n.ft\n.DE" contents))
+
+
+;;; Interactive functions
+
+(defun org-groff-export-to-groff
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a Groff file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".groff" subtreep))
+ (org-groff-registered-references nil)
+ (org-groff-special-content nil))
+ (org-export-to-file 'groff outfile
+ async subtreep visible-only body-only ext-plist)))
+
+(defun org-groff-export-to-pdf
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to Groff then process through to PDF.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".groff" subtreep)))
+ (org-export-to-file 'groff outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-groff-compile file)))))
+
+(defun org-groff-compile (file)
+ "Compile a Groff file.
+
+FILE is the name of the file being compiled. Processing is done
+through the command specified in `org-groff-pdf-process'.
+
+Return PDF file name or an error if it couldn't be produced."
+ (let* ((base-name (file-name-sans-extension (file-name-nondirectory file)))
+ (full-name (file-truename file))
+ (out-dir (file-name-directory file))
+ (time (current-time))
+ ;; Properly set working directory for compilation.
+ (default-directory (if (file-name-absolute-p file)
+ (file-name-directory full-name)
+ default-directory))
+ errors)
+ (message (format "Processing Groff file %s ..." file))
+ (save-window-excursion
+ (cond
+ ;; A function is provided: Apply it.
+ ((functionp org-groff-pdf-process)
+ (funcall org-groff-pdf-process (shell-quote-argument file)))
+ ;; A list is provided: Replace %b, %f and %o with appropriate
+ ;; values in each command before applying it. Output is
+ ;; redirected to "*Org PDF Groff Output*" buffer.
+ ((consp org-groff-pdf-process)
+ (let ((outbuf (get-buffer-create "*Org PDF Groff Output*")))
+ (mapc
+ (lambda (command)
+ (shell-command
+ (replace-regexp-in-string
+ "%b" (shell-quote-argument base-name)
+ (replace-regexp-in-string
+ "%f" (shell-quote-argument full-name)
+ (replace-regexp-in-string
+ "%o" (shell-quote-argument out-dir) command t t)
+ t t) t t)
+ outbuf))
+ org-groff-pdf-process)
+ ;; Collect standard errors from output buffer.
+ (setq errors (org-groff-collect-errors outbuf))))
+ (t (error "No valid command to process to PDF")))
+ (let ((pdffile (concat out-dir base-name ".pdf")))
+ ;; Check for process failure. Provide collected errors if
+ ;; possible.
+ (if (or (not (file-exists-p pdffile))
+ ;; Only compare times up to whole seconds as some
+ ;; filesystems (e.g. HFS+) do not retain any finer
+ ;; granularity.
+ (time-less-p (cl-subseq (nth 5 (file-attributes pdffile)) 0 2)
+ (cl-subseq time 0 2)))
+ (error (concat (format "PDF file %s wasn't produced" pdffile)
+ (when errors (concat ": " errors))))
+ ;; Else remove log files, when specified, and signal end of
+ ;; process to user, along with any error encountered.
+ (when org-groff-remove-logfiles
+ (dolist (ext org-groff-logfiles-extensions)
+ (let ((file (concat out-dir base-name "." ext)))
+ (when (file-exists-p file) (delete-file file)))))
+ (message (concat "Process completed"
+ (if (not errors) "."
+ (concat " with errors: " errors)))))
+ ;; Return output file name.
+ pdffile))))
+
+(defun org-groff-collect-errors (buffer)
+ "Collect some kind of errors from \"groff\" output
+BUFFER is the buffer containing output.
+Return collected error types as a string, or nil if there was
+none."
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char (point-max))
+ ;; Find final run
+ nil)))
+
+
+(provide 'ox-groff)
+;;; ox-groff.el ends here
diff --git a/contrib/lisp/ox-koma-letter.el b/contrib/lisp/ox-koma-letter.el
new file mode 100644
index 0000000..37da54c
--- /dev/null
+++ b/contrib/lisp/ox-koma-letter.el
@@ -0,0 +1,917 @@
+;;; ox-koma-letter.el --- KOMA Scrlttr2 Back-End for Org Export Engine
+
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou AT gmail DOT com>
+;; Alan Schmitt <alan.schmitt AT polytechnique DOT org>
+;; Viktor Rosenfeld <listuser36 AT gmail DOT com>
+;; Rasmus Pank Roulund <emacs AT pank DOT eu>
+;; Keywords: org, wp, tex
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements a KOMA Scrlttr2 back-end, derived from the
+;; LaTeX one.
+;;
+;; Depending on the desired output format, three commands are provided
+;; for export: `org-koma-letter-export-as-latex' (temporary buffer),
+;; `org-koma-letter-export-to-latex' ("tex" file) and
+;; `org-koma-letter-export-to-pdf' ("pdf" file).
+;;
+;; On top of buffer keywords supported by `latex' back-end (see
+;; `org-latex-options-alist'), this back-end introduces the following
+;; keywords:
+;; - CLOSING: see `org-koma-letter-closing',
+;; - FROM_ADDRESS: see `org-koma-letter-from-address',
+;; - LCO: see `org-koma-letter-class-option-file',
+;; - OPENING: see `org-koma-letter-opening',
+;; - PHONE_NUMBER: see `org-koma-letter-phone-number',
+;; - SIGNATURE: see `org-koma-letter-signature',
+;; - PLACE: see `org-koma-letter-place',
+;; - LOCATION: see `org-koma-letter-location',
+;; - TO_ADDRESS: If unspecified this is set to "\mbox{}".
+;;
+;; TO_ADDRESS, FROM_ADDRESS, LOCATION, CLOSING, and SIGNATURE can also
+;; be specified using "special headings" with the special tags
+;; specified in `org-koma-letter-special-tags-in-letter'. LaTeX line
+;; breaks are not necessary for TO_ADDRESS, FROM_ADDRESS and LOCATION.
+;; If both a headline and a keyword specify a to or from address the
+;; value is determined in accordance with
+;; `org-koma-letter-prefer-special-headings'.
+;;
+;; A number of OPTIONS settings can be set to change which contents is
+;; exported.
+;; - backaddress (see `org-koma-letter-use-backaddress')
+;; - foldmarks (see `org-koma-letter-use-foldmarks')
+;; - phone (see `org-koma-letter-use-phone')
+;; - email (see `org-koma-letter-use-email')
+;; - place (see `org-koma-letter-use-place')
+;; - location (see `org-koma-letter-use-location')
+;; - subject, a list of format options
+;; (see `org-koma-letter-subject-format')
+;; - after-closing-order, a list of the ordering of headings with
+;; special tags after closing (see
+;; `org-koma-letter-special-tags-after-closing')
+;; - after-letter-order, as above, but after the end of the letter
+;; (see `org-koma-letter-special-tags-after-letter').
+;;
+;; The following variables works differently from the main LaTeX class
+;; - AUTHOR: Default to user-full-name but may be disabled.
+;; (See also `org-koma-letter-author'),
+;; - EMAIL: Same as AUTHOR. (see also `org-koma-letter-email'),
+;;
+;; Headlines are in general ignored. However, headlines with special
+;; tags can be used for specified contents like postscript (ps),
+;; carbon copy (cc), enclosures (encl) and code to be inserted after
+;; \end{letter} (after_letter). Specials tags are defined in
+;; `org-koma-letter-special-tags-after-closing' and
+;; `org-koma-letter-special-tags-after-letter'. Currently members of
+;; `org-koma-letter-special-tags-after-closing' used as macros and the
+;; content of the headline is the argument.
+;;
+;; Headlines with to and from may also be used rather than the keyword
+;; approach described above. If both a keyword and a headline with
+;; information is present precedence is determined by
+;; `org-koma-letter-prefer-special-headings'.
+;;
+;; You need an appropriate association in `org-latex-classes' in order
+;; to use the KOMA Scrlttr2 class. By default, a sparse scrlttr2
+;; class is provided: "default-koma-letter". You can also add you own
+;; letter class. For instance:
+;;
+;; (add-to-list 'org-latex-classes
+;; '("my-letter"
+;; "\\documentclass\[%
+;; DIV=14,
+;; fontsize=12pt,
+;; parskip=half,
+;; subject=titled,
+;; backaddress=false,
+;; fromalign=left,
+;; fromemail=true,
+;; fromphone=true\]\{scrlttr2\}
+;; \[DEFAULT-PACKAGES]
+;; \[PACKAGES]
+;; \[EXTRA]"))
+;;
+;; Then, in your Org document, be sure to require the proper class
+;; with:
+;;
+;; #+LATEX_CLASS: my-letter
+;;
+;; Or by setting `org-koma-letter-default-class'.
+;;
+;; You may have to load (LaTeX) Babel as well, e.g., by adding
+;; it to `org-latex-packages-alist',
+;;
+;; (add-to-list 'org-latex-packages-alist '("AUTO" "babel" nil))
+
+;;; Code:
+
+(require 'ox-latex)
+
+;; Install a default letter class.
+(unless (assoc "default-koma-letter" org-latex-classes)
+ (add-to-list 'org-latex-classes
+ '("default-koma-letter" "\\documentclass[11pt]{scrlttr2}")))
+
+
+;;; User-Configurable Variables
+
+(defgroup org-export-koma-letter nil
+ "Options for exporting to KOMA scrlttr2 class in LaTeX export."
+ :tag "Org Koma-Letter"
+ :group 'org-export)
+
+(defcustom org-koma-letter-class-option-file "NF"
+ "Letter Class Option File.
+This option can also be set with the LCO keyword."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-author 'user-full-name
+ "Sender's name.
+
+This variable defaults to calling the function `user-full-name'
+which just returns the current function `user-full-name'.
+Alternatively a string, nil or a function may be given.
+Functions must return a string.
+
+This option can also be set with the AUTHOR keyword."
+ :group 'org-export-koma-letter
+ :type '(radio (function-item user-full-name)
+ (string)
+ (function)
+ (const :tag "Do not export author" nil)))
+
+(defcustom org-koma-letter-email 'org-koma-letter-email
+ "Sender's email address.
+
+This variable defaults to the value `org-koma-letter-email' which
+returns `user-mail-address'. Alternatively a string, nil or
+a function may be given. Functions must return a string.
+
+This option can also be set with the EMAIL keyword."
+ :group 'org-export-koma-letter
+ :type '(radio (function-item org-koma-letter-email)
+ (string)
+ (function)
+ (const :tag "Do not export email" nil)))
+
+(defcustom org-koma-letter-from-address ""
+ "Sender's address, as a string.
+This option can also be set with one or more FROM_ADDRESS
+keywords."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-phone-number ""
+ "Sender's phone number, as a string.
+This option can also be set with the PHONE_NUMBER keyword."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-place ""
+ "Place from which the letter is sent, as a string.
+This option can also be set with the PLACE keyword."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-location ""
+ "Sender's extension field, as a string.
+
+This option can also be set with the LOCATION keyword.
+Moreover, when:
+ (1) Either `org-koma-letter-prefer-special-headings' is non-nil
+ or there is no LOCATION keyword or the LOCATION keyword is
+ empty;
+ (2) the letter contains a headline with the special
+ tag \"location\";
+then the location will be set as the content of the location
+special heading.
+
+The location field is typically printed right of the address
+field (See Figure 4.9. in the English manual of 2015-10-03)."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-opening ""
+ "Letter's opening, as a string.
+
+This option can also be set with the OPENING keyword. Moreover,
+when:
+ (1) Either `org-koma-letter-prefer-special-headings' is non-nil
+ or the CLOSING keyword is empty
+ (2) `org-koma-letter-headline-is-opening-maybe' is non-nil;
+ (3) the letter contains a headline without a special
+ tag (e.g. \"to\" or \"ps\");
+then the opening will be implicitly set as the untagged headline title."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-closing ""
+ "Letter's closing, as a string.
+This option can also be set with the CLOSING keyword. Moreover,
+when:
+ (1) Either `org-koma-letter-prefer-special-headings' is non-nil
+ or the CLOSING keyword is empty;
+ (2) `org-koma-letter-headline-is-opening-maybe' is non-nil;
+ (3) the letter contains a headline with the special
+ tag \"closing\";
+then the opening will be set as the title of the closing special
+heading title."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-signature ""
+ "Signature, as a string.
+This option can also be set with the SIGNATURE keyword.
+Moreover, when:
+ (1) Either `org-koma-letter-prefer-special-headings' is non-nil
+ or there is no CLOSING keyword or the CLOSING keyword is empty;
+ (2) `org-koma-letter-headline-is-opening-maybe' is non-nil;
+ (3) the letter contains a headline with the special
+ tag \"closing\";
+then the signature will be set as the content of the
+closing special heading.
+
+Note if the content is empty the signature will not be set."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-prefer-special-headings nil
+ "Non-nil means prefer headlines over keywords for TO and FROM.
+This option can also be set with the OPTIONS keyword, e.g.:
+\"special-headings:t\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-subject-format t
+ "Non-nil means include the subject.
+
+Support formatting options.
+
+When t, insert a subject using default options. When nil, do not
+insert a subject at all. It can also be a list of symbols among
+the following ones:
+
+ `afteropening' Subject after opening
+ `beforeopening' Subject before opening
+ `centered' Subject centered
+ `left' Subject left-justified
+ `right' Subject right-justified
+ `titled' Add title/description to subject
+ `underlined' Set subject underlined
+ `untitled' Do not add title/description to subject
+
+Please refer to the KOMA-script manual (Table 4.16. in the
+English manual of 2012-07-22).
+
+This option can also be set with the OPTIONS keyword, e.g.:
+\"subject:(underlined centered)\"."
+ :type
+ '(choice
+ (const :tag "No export" nil)
+ (const :tag "Default options" t)
+ (set :tag "Configure options"
+ (const :tag "Subject after opening" afteropening)
+ (const :tag "Subject before opening" beforeopening)
+ (const :tag "Subject centered" centered)
+ (const :tag "Subject left-justified" left)
+ (const :tag "Subject right-justified" right)
+ (const :tag "Add title or description to subject" underlined)
+ (const :tag "Set subject underlined" titled)
+ (const :tag "Do not add title or description to subject" untitled)))
+ :group 'org-export-koma-letter)
+
+(defcustom org-koma-letter-use-backaddress nil
+ "Non-nil prints return address in line above to address.
+This option can also be set with the OPTIONS keyword, e.g.:
+\"backaddress:t\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-use-foldmarks t
+ "Configure appearance of folding marks.
+
+When t, activate default folding marks. When nil, do not insert
+folding marks at all. It can also be a list of symbols among the
+following ones:
+
+ `B' Activate upper horizontal mark on left paper edge
+ `b' Deactivate upper horizontal mark on left paper edge
+
+ `H' Activate all horizontal marks on left paper edge
+ `h' Deactivate all horizontal marks on left paper edge
+
+ `L' Activate left vertical mark on upper paper edge
+ `l' Deactivate left vertical mark on upper paper edge
+
+ `M' Activate middle horizontal mark on left paper edge
+ `m' Deactivate middle horizontal mark on left paper edge
+
+ `P' Activate punch or center mark on left paper edge
+ `p' Deactivate punch or center mark on left paper edge
+
+ `T' Activate lower horizontal mark on left paper edge
+ `t' Deactivate lower horizontal mark on left paper edge
+
+ `V' Activate all vertical marks on upper paper edge
+ `v' Deactivate all vertical marks on upper paper edge
+
+This option can also be set with the OPTIONS keyword, e.g.:
+\"foldmarks:(b l m t)\"."
+ :group 'org-export-koma-letter
+ :type '(choice
+ (const :tag "Activate default folding marks" t)
+ (const :tag "Deactivate folding marks" nil)
+ (set
+ :tag "Configure folding marks"
+ (const :tag "Activate upper horizontal mark on left paper edge" B)
+ (const :tag "Deactivate upper horizontal mark on left paper edge" b)
+ (const :tag "Activate all horizontal marks on left paper edge" H)
+ (const :tag "Deactivate all horizontal marks on left paper edge" h)
+ (const :tag "Activate left vertical mark on upper paper edge" L)
+ (const :tag "Deactivate left vertical mark on upper paper edge" l)
+ (const :tag "Activate middle horizontal mark on left paper edge" M)
+ (const :tag "Deactivate middle horizontal mark on left paper edge" m)
+ (const :tag "Activate punch or center mark on left paper edge" P)
+ (const :tag "Deactivate punch or center mark on left paper edge" p)
+ (const :tag "Activate lower horizontal mark on left paper edge" T)
+ (const :tag "Deactivate lower horizontal mark on left paper edge" t)
+ (const :tag "Activate all vertical marks on upper paper edge" V)
+ (const :tag "Deactivate all vertical marks on upper paper edge" v))))
+
+(defcustom org-koma-letter-use-phone nil
+ "Non-nil prints sender's phone number.
+This option can also be set with the OPTIONS keyword, e.g.:
+\"phone:t\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-use-email nil
+ "Non-nil prints sender's email address.
+This option can also be set with the OPTIONS keyword, e.g.:
+\"email:t\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-use-place t
+ "Non-nil prints the letter's place next to the date.
+This option can also be set with the OPTIONS keyword, e.g.:
+\"place:nil\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-default-class "default-koma-letter"
+ "Default class for `org-koma-letter'.
+The value must be a member of `org-latex-classes'."
+ :group 'org-export-koma-letter
+ :type 'string)
+
+(defcustom org-koma-letter-headline-is-opening-maybe t
+ "Non-nil means a headline may be used as an opening and closing.
+See also `org-koma-letter-opening' and
+`org-koma-letter-closing'."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defcustom org-koma-letter-prefer-subject nil
+ "Non-nil means title should be interpreted as subject if subject is missing.
+This option can also be set with the OPTIONS keyword,
+e.g. \"title-subject:t\"."
+ :group 'org-export-koma-letter
+ :type 'boolean)
+
+(defconst org-koma-letter-special-tags-in-letter '(to from closing location)
+ "Header tags related to the letter itself.")
+
+(defconst org-koma-letter-special-tags-after-closing '(after_closing ps encl cc)
+ "Header tags to be inserted in the letter after closing.")
+
+(defconst org-koma-letter-special-tags-as-macro '(ps encl cc)
+ "Header tags to be inserted as macros")
+
+(defconst org-koma-letter-special-tags-after-letter '(after_letter)
+ "Header tags to be inserted after the letter.")
+
+(defvar org-koma-letter-special-contents nil
+ "Holds special content temporarily.")
+
+(make-obsolete-variable 'org-koma-letter-use-title
+ 'org-export-with-title
+ "25.1" 'set)
+
+
+;;; Define Back-End
+
+(org-export-define-derived-backend 'koma-letter 'latex
+ :options-alist
+ '((:latex-class "LATEX_CLASS" nil org-koma-letter-default-class t)
+ (:lco "LCO" nil org-koma-letter-class-option-file)
+ (:author "AUTHOR" nil (org-koma-letter--get-value org-koma-letter-author) parse)
+ (:author-changed-in-buffer-p "AUTHOR" nil nil t)
+ (:from-address "FROM_ADDRESS" nil org-koma-letter-from-address newline)
+ (:phone-number "PHONE_NUMBER" nil org-koma-letter-phone-number)
+ (:email "EMAIL" nil (org-koma-letter--get-value org-koma-letter-email) t)
+ (:to-address "TO_ADDRESS" nil nil newline)
+ (:place "PLACE" nil org-koma-letter-place)
+ (:location "LOCATION" nil org-koma-letter-location)
+ (:subject "SUBJECT" nil nil parse)
+ (:opening "OPENING" nil org-koma-letter-opening parse)
+ (:closing "CLOSING" nil org-koma-letter-closing parse)
+ (:signature "SIGNATURE" nil org-koma-letter-signature newline)
+ (:special-headings nil "special-headings" org-koma-letter-prefer-special-headings)
+ (:special-tags-as-macro nil nil org-koma-letter-special-tags-as-macro)
+ (:special-tags-in-letter nil nil org-koma-letter-special-tags-in-letter)
+ (:special-tags-after-closing nil "after-closing-order"
+ org-koma-letter-special-tags-after-closing)
+ (:special-tags-after-letter nil "after-letter-order"
+ org-koma-letter-special-tags-after-letter)
+ (:with-backaddress nil "backaddress" org-koma-letter-use-backaddress)
+ (:with-email nil "email" org-koma-letter-use-email)
+ (:with-foldmarks nil "foldmarks" org-koma-letter-use-foldmarks)
+ (:with-phone nil "phone" org-koma-letter-use-phone)
+ (:with-place nil "place" org-koma-letter-use-place)
+ (:with-subject nil "subject" org-koma-letter-subject-format)
+ (:with-title-as-subject nil "title-subject" org-koma-letter-prefer-subject)
+ (:with-headline-opening nil nil org-koma-letter-headline-is-opening-maybe)
+ ;; Special properties non-nil when a setting happened in buffer.
+ ;; They are used to prioritize in-buffer settings over "lco"
+ ;; files. See `org-koma-letter-template'.
+ (:inbuffer-author "AUTHOR" nil 'koma-letter:empty)
+ (:inbuffer-from "FROM" nil 'koma-letter:empty)
+ (:inbuffer-email "EMAIL" nil 'koma-letter:empty)
+ (:inbuffer-phone-number "PHONE_NUMBER" nil 'koma-letter:empty)
+ (:inbuffer-place "PLACE" nil 'koma-letter:empty)
+ (:inbuffer-location "LOCATION" nil 'koma-letter:empty)
+ (:inbuffer-signature "SIGNATURE" nil 'koma-letter:empty)
+ (:inbuffer-with-backaddress nil "backaddress" 'koma-letter:empty)
+ (:inbuffer-with-email nil "email" 'koma-letter:empty)
+ (:inbuffer-with-foldmarks nil "foldmarks" 'koma-letter:empty)
+ (:inbuffer-with-phone nil "phone" 'koma-letter:empty)
+ (:inbuffer-with-place nil "place" 'koma-letter:empty))
+ :translate-alist '((export-block . org-koma-letter-export-block)
+ (export-snippet . org-koma-letter-export-snippet)
+ (headline . org-koma-letter-headline)
+ (keyword . org-koma-letter-keyword)
+ (template . org-koma-letter-template))
+ :menu-entry
+ '(?k "Export with KOMA Scrlttr2"
+ ((?L "As LaTeX buffer" org-koma-letter-export-as-latex)
+ (?l "As LaTeX file" org-koma-letter-export-to-latex)
+ (?p "As PDF file" org-koma-letter-export-to-pdf)
+ (?o "As PDF file and open"
+ (lambda (a s v b)
+ (if a (org-koma-letter-export-to-pdf t s v b)
+ (org-open-file (org-koma-letter-export-to-pdf nil s v b))))))))
+
+
+
+;;; Helper functions
+
+(defun org-koma-letter-email ()
+ "Return the current `user-mail-address'."
+ user-mail-address)
+
+;; The following is taken from/inspired by ox-grof.el
+;; Thanks, Luis!
+
+(defun org-koma-letter--get-tagged-contents (key)
+ "Get contents from a headline tagged with KEY.
+The contents is stored in `org-koma-letter-special-contents'."
+ (let ((value (cdr (assoc-string (org-koma-letter--get-value key)
+ org-koma-letter-special-contents))))
+ (when value (org-string-nw-p (org-trim value)))))
+
+(defun org-koma-letter--get-value (value)
+ "Turn value into a string whenever possible.
+Determines if VALUE is nil, a string, a function or a symbol and
+return a string or nil."
+ (when value
+ (cond ((stringp value) value)
+ ((functionp value) (funcall value))
+ ((symbolp value) (symbol-name value))
+ (t value))))
+
+(defun org-koma-letter--special-contents-inline (keywords info)
+ "Process KEYWORDS members of `org-koma-letter-special-contents'.
+KEYWORDS is a list of symbols. Return them as a string to be
+formatted.
+
+The function is used for inserting content of special headings
+such as the one tagged with PS.
+"
+ (mapconcat
+ (lambda (keyword)
+ (let* ((name (org-koma-letter--get-value keyword))
+ (value (org-koma-letter--get-tagged-contents name))
+ (macrop (memq keyword (plist-get info :special-tags-as-macro))))
+ (cond ((not value) nil)
+ (macrop (format "\\%s{%s}\n" name value))
+ (t value))))
+ keywords
+ "\n"))
+
+
+(defun org-koma-letter--add-latex-newlines (string)
+ "Replace regular newlines with LaTeX newlines (i.e. `\\\\')"
+ (let ((str (org-trim string)))
+ (when (org-string-nw-p str)
+ (replace-regexp-in-string "\n" "\\\\\\\\\n" str))))
+
+
+
+;;; Transcode Functions
+
+;;;; Export Block
+
+(defun org-koma-letter-export-block (export-block contents info)
+ "Transcode an EXPORT-BLOCK element into KOMA Scrlttr2 code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (when (member (org-element-property :type export-block) '("KOMA-LETTER" "LATEX"))
+ (org-remove-indentation (org-element-property :value export-block))))
+
+;;;; Export Snippet
+
+(defun org-koma-letter-export-snippet (export-snippet contents info)
+ "Transcode an EXPORT-SNIPPET object into KOMA Scrlttr2 code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (when (memq (org-export-snippet-backend export-snippet) '(latex koma-letter))
+ (org-element-property :value export-snippet)))
+
+;;;; Keyword
+
+(defun org-koma-letter-keyword (keyword contents info)
+ "Transcode a KEYWORD element into KOMA Scrlttr2 code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ ;; Handle specifically KOMA-LETTER keywords. Otherwise, fallback
+ ;; to `latex' back-end.
+ (if (equal key "KOMA-LETTER") value
+ (org-export-with-backend 'latex keyword contents info))))
+
+;; Headline
+
+(defun org-koma-letter-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to LaTeX.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information.
+
+Note that if a headline is tagged with a tag from
+`org-koma-letter-special-tags' it will not be exported, but
+stored in `org-koma-letter-special-contents' and included at the
+appropriate place."
+ (let ((special-tag (org-koma-letter--special-tag headline info)))
+ (if (not special-tag)
+ contents
+ (push (cons special-tag contents) org-koma-letter-special-contents)
+ "")))
+
+(defun org-koma-letter--special-tag (headline info)
+ "Non-nil if HEADLINE is a special headline.
+INFO is a plist holding contextual information. Return first
+special tag headline."
+ (let ((special-tags (append
+ (plist-get info :special-tags-in-letter)
+ (plist-get info :special-tags-after-closing)
+ (plist-get info :special-tags-after-letter))))
+ (catch 'exit
+ (dolist (tag (org-export-get-tags headline info))
+ (let ((tag (assoc-string tag special-tags)))
+ (when tag (throw 'exit tag)))))))
+
+(defun org-koma-letter--keyword-or-headline (plist-key pred info)
+ "Return the correct version of opening or closing.
+PLIST-KEY should be a key in info, typically :opening
+or :closing. PRED is a predicate run on headline to determine
+which title to use which takes two arguments, a headline element
+and an info plist. INFO is a plist holding contextual
+information. Return the preferred candidate for the exported of
+PLIST-KEY."
+ (let* ((keyword-candidate (plist-get info plist-key))
+ (headline-candidate (when (and (plist-get info :with-headline-opening)
+ (or (plist-get info :special-headings)
+ (not keyword-candidate)))
+ (org-element-map (plist-get info :parse-tree)
+ 'headline
+ (lambda (head)
+ (when (funcall pred head info)
+ (org-element-property :title head)))
+ info t))))
+ (org-export-data (or headline-candidate keyword-candidate "") info)))
+
+;;;; Template
+
+(defun org-koma-letter-template (contents info)
+ "Return complete document string after KOMA Scrlttr2 conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (concat
+ ;; Time-stamp.
+ (and (plist-get info :time-stamp-file)
+ (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
+ ;; LaTeX compiler
+ (org-latex--insert-compiler info)
+ ;; Document class and packages.
+ (org-latex-make-preamble info)
+ ;; Settings. They can come from three locations, in increasing
+ ;; order of precedence: global variables, LCO files and in-buffer
+ ;; settings. Thus, we first insert settings coming from global
+ ;; variables, then we insert LCO files, and, eventually, we insert
+ ;; settings coming from buffer keywords.
+ (org-koma-letter--build-settings 'global info)
+ (mapconcat #'(lambda (file) (format "\\LoadLetterOption{%s}\n" file))
+ (org-split-string (or (plist-get info :lco) "") " ")
+ "")
+ (org-koma-letter--build-settings 'buffer info)
+ ;; Date.
+ (format "\\date{%s}\n" (org-export-data (org-export-get-date info) info))
+ ;; Hyperref, document start, and subject and title.
+ (let* ((with-subject (plist-get info :with-subject))
+ (with-title (plist-get info :with-title))
+ (title-as-subject (and with-subject
+ (plist-get info :with-title-as-subject)))
+ (subject* (org-string-nw-p
+ (org-export-data (plist-get info :subject) info)))
+ (title* (and with-title
+ (org-string-nw-p
+ (org-export-data (plist-get info :title) info))))
+ (subject (cond ((not with-subject) nil)
+ (title-as-subject (or subject* title*))
+ (t subject*)))
+ (title (cond ((not with-title) nil)
+ (title-as-subject (and subject* title*))
+ (t title*)))
+ (hyperref-template (plist-get info :latex-hyperref-template))
+ (spec (append (list (cons ?t (or title subject "")))
+ (org-latex--format-spec info))))
+ (concat
+ (when (and with-subject (not (eq with-subject t)))
+ (format "\\KOMAoption{subject}{%s}\n"
+ (if (symbolp with-subject) with-subject
+ (mapconcat #'symbol-name with-subject ","))))
+ ;; Hyperref.
+ (format-spec hyperref-template spec)
+ ;; Document start.
+ "\\begin{document}\n\n"
+ ;; Subject and title.
+ (when subject (format "\\setkomavar{subject}{%s}\n" subject))
+ (when title (format "\\setkomavar{title}{%s}\n" title))
+ (when (or (org-string-nw-p title) (org-string-nw-p subject)) "\n")))
+ ;; Letter start.
+ (let ((keyword-val (plist-get info :to-address))
+ (heading-val (org-koma-letter--get-tagged-contents 'to)))
+ (format "\\begin{letter}{%%\n%s}\n\n"
+ (org-koma-letter--add-latex-newlines
+ (or (if (plist-get info :special-headings)
+ (or heading-val keyword-val)
+ (or keyword-val heading-val))
+ "\\\\mbox{}"))))
+ ;; Opening.
+ (format "\\opening{%s}\n\n"
+ (org-koma-letter--keyword-or-headline
+ :opening (lambda (h i) (not (org-koma-letter--special-tag h i)))
+ info))
+ ;; Letter body.
+ contents
+ ;; Closing.
+ (format "\\closing{%s}\n"
+ (org-koma-letter--keyword-or-headline
+ :closing (lambda (h i) (eq (org-koma-letter--special-tag h i)
+ 'closing))
+ info))
+ (org-koma-letter--special-contents-inline
+ (plist-get info :special-tags-after-closing) info)
+ ;; Letter end.
+ "\n\\end{letter}\n"
+ (org-koma-letter--special-contents-inline
+ (plist-get info :special-tags-after-letter) info)
+ ;; Document end.
+ "\n\\end{document}"))
+
+(defun org-koma-letter--build-settings (scope info)
+ "Build settings string according to type.
+SCOPE is either `global' or `buffer'. INFO is a plist used as
+a communication channel."
+ (let* ((check-scope
+ (function
+ ;; Non-nil value when SETTING was defined in SCOPE.
+ (lambda (setting)
+ (let ((property (intern (format ":inbuffer-%s" setting))))
+ (if (eq scope 'global)
+ (eq (plist-get info property) 'koma-letter:empty)
+ (not (eq (plist-get info property) 'koma-letter:empty)))))))
+ (heading-or-key-value
+ (function
+ (lambda (heading key &optional scoped)
+ (let* ((heading-val
+ (org-koma-letter--get-tagged-contents heading))
+ (key-val (org-string-nw-p (plist-get info key)))
+ (scopedp (funcall check-scope (or scoped heading))))
+ (and (or (and key-val scopedp) heading-val)
+ (not (and (eq scope 'global) heading-val))
+ (if scopedp key-val heading-val)))))))
+ (concat
+ ;; Name.
+ (let ((author (plist-get info :author)))
+ (and author
+ (funcall check-scope 'author)
+ (format "\\setkomavar{fromname}{%s}\n"
+ (org-export-data author info))))
+ ;; From.
+ (let ((from (funcall heading-or-key-value 'from :from-address)))
+ (and from
+ (format "\\setkomavar{fromaddress}{%s}\n"
+ (org-koma-letter--add-latex-newlines from))))
+ ;; Email.
+ (let ((email (plist-get info :email)))
+ (and email
+ (funcall check-scope 'email)
+ (format "\\setkomavar{fromemail}{%s}\n" email)))
+ (and (funcall check-scope 'with-email)
+ (format "\\KOMAoption{fromemail}{%s}\n"
+ (if (plist-get info :with-email) "true" "false")))
+ ;; Phone number.
+ (let ((phone-number (plist-get info :phone-number)))
+ (and (org-string-nw-p phone-number)
+ (funcall check-scope 'phone-number)
+ (format "\\setkomavar{fromphone}{%s}\n" phone-number)))
+ (and (funcall check-scope 'with-phone)
+ (format "\\KOMAoption{fromphone}{%s}\n"
+ (if (plist-get info :with-phone) "true" "false")))
+ ;; Signature.
+ (let* ((heading-val
+ (and (plist-get info :with-headline-opening)
+ (org-string-nw-p
+ (org-trim
+ (org-export-data
+ (org-koma-letter--get-tagged-contents 'closing)
+ info)))))
+ (signature (org-string-nw-p (plist-get info :signature)))
+ (signature-scope (funcall check-scope 'signature)))
+ (and (or (and signature signature-scope)
+ heading-val)
+ (not (and (eq scope 'global) heading-val))
+ (format "\\setkomavar{signature}{%s}\n"
+ (if signature-scope signature heading-val))))
+ ;; Back address.
+ (and (funcall check-scope 'with-backaddress)
+ (format "\\KOMAoption{backaddress}{%s}\n"
+ (if (plist-get info :with-backaddress) "true" "false")))
+ ;; Place.
+ (let ((with-place-set (funcall check-scope 'with-place))
+ (place-set (funcall check-scope 'place)))
+ (and (or (and with-place-set place-set)
+ (and (eq scope 'buffer) (or with-place-set place-set)))
+ (format "\\setkomavar{place}{%s}\n"
+ (if (plist-get info :with-place) (plist-get info :place)
+ ""))))
+ ;; Location.
+ (let ((location (funcall heading-or-key-value 'location :location)))
+ (and location
+ (format "\\setkomavar{location}{%s}\n" location)))
+ ;; Folding marks.
+ (and (funcall check-scope 'with-foldmarks)
+ (let ((foldmarks (plist-get info :with-foldmarks)))
+ (cond ((consp foldmarks)
+ (format "\\KOMAoptions{foldmarks=true,foldmarks=%s}\n"
+ (mapconcat #'symbol-name foldmarks "")))
+ (foldmarks "\\KOMAoptions{foldmarks=true}\n")
+ (t "\\KOMAoptions{foldmarks=false}\n")))))))
+
+
+
+;;; Commands
+
+;;;###autoload
+(defun org-koma-letter-export-as-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a KOMA Scrlttr2 letter.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{letter}\" and \"\\end{letter}\".
+
+EXT-PLIST, when provided, is a proeprty list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org KOMA-LETTER Export*\". It
+will be displayed if `org-export-show-temporary-export-buffer' is
+non-nil."
+ (interactive)
+ (let (org-koma-letter-special-contents)
+ (org-export-to-buffer 'koma-letter "*Org KOMA-LETTER Export*"
+ async subtreep visible-only body-only ext-plist
+ (lambda () (LaTeX-mode)))))
+
+;;;###autoload
+(defun org-koma-letter-export-to-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a KOMA Scrlttr2 letter (tex).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{letter}\" and \"\\end{letter}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+When optional argument PUB-DIR is set, use it as the publishing
+directory.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".tex" subtreep))
+ (org-koma-letter-special-contents))
+ (org-export-to-file 'koma-letter outfile
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-koma-letter-export-to-pdf
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a KOMA Scrlttr2 letter (pdf).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{letter}\" and \"\\end{letter}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name."
+ (interactive)
+ (let ((file (org-export-output-file-name ".tex" subtreep))
+ (org-koma-letter-special-contents))
+ (org-export-to-file 'koma-letter file
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))))
+
+
+(provide 'ox-koma-letter)
+;;; ox-koma-letter.el ends here
diff --git a/contrib/lisp/ox-rss.el b/contrib/lisp/ox-rss.el
new file mode 100644
index 0000000..a3ba274
--- /dev/null
+++ b/contrib/lisp/ox-rss.el
@@ -0,0 +1,419 @@
+;;; ox-rss.el --- RSS 2.0 Back-End for Org Export Engine
+
+;; Copyright (C) 2013-2015 Bastien Guerry
+
+;; Author: Bastien Guerry <bzg@gnu.org>
+;; Keywords: org, wp, blog, feed, rss
+
+;; This file is not yet part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a RSS 2.0 back-end for Org exporter, based on
+;; the `html' back-end.
+;;
+;; It requires Emacs 24.1 at least.
+;;
+;; It provides two commands for export, depending on the desired output:
+;; `org-rss-export-as-rss' (temporary buffer) and `org-rss-export-to-rss'
+;; (as a ".xml" file).
+;;
+;; This backend understands three new option keywords:
+;;
+;; #+RSS_EXTENSION: xml
+;; #+RSS_IMAGE_URL: http://myblog.org/mypicture.jpg
+;; #+RSS_FEED_URL: http://myblog.org/feeds/blog.xml
+;;
+;; It uses #+HTML_LINK_HOME: to set the base url of the feed.
+;;
+;; Exporting an Org file to RSS modifies each top-level entry by adding a
+;; PUBDATE property. If `org-rss-use-entry-url-as-guid', it will also add
+;; an ID property, later used as the guid for the feed's item.
+;;
+;; The top-level headline is used as the title of each RSS item unless
+;; an RSS_TITLE property is set on the headline.
+;;
+;; You typically want to use it within a publishing project like this:
+;;
+;; (add-to-list
+;; 'org-publish-project-alist
+;; '("homepage_rss"
+;; :base-directory "~/myhomepage/"
+;; :base-extension "org"
+;; :rss-image-url "http://lumiere.ens.fr/~guerry/images/faces/15.png"
+;; :html-link-home "http://lumiere.ens.fr/~guerry/"
+;; :html-link-use-abs-url t
+;; :rss-extension "xml"
+;; :publishing-directory "/home/guerry/public_html/"
+;; :publishing-function (org-rss-publish-to-rss)
+;; :section-numbers nil
+;; :exclude ".*" ;; To exclude all files...
+;; :include ("index.org") ;; ... except index.org.
+;; :table-of-contents nil))
+;;
+;; ... then rsync /home/guerry/public_html/ with your server.
+;;
+;; By default, the permalink for a blog entry points to the headline.
+;; You can specify a different one by using the :RSS_PERMALINK:
+;; property within an entry.
+
+;;; Code:
+
+(require 'ox-html)
+(declare-function url-encode-url "url-util" (url))
+
+;;; Variables and options
+
+(defgroup org-export-rss nil
+ "Options specific to RSS export back-end."
+ :tag "Org RSS"
+ :group 'org-export
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defcustom org-rss-image-url "http://orgmode.org/img/org-mode-unicorn-logo.png"
+ "The URL of the an image for the RSS feed."
+ :group 'org-export-rss
+ :type 'string)
+
+(defcustom org-rss-extension "xml"
+ "File extension for the RSS 2.0 feed."
+ :group 'org-export-rss
+ :type 'string)
+
+(defcustom org-rss-categories 'from-tags
+ "Where to extract items category information from.
+The default is to extract categories from the tags of the
+headlines. When set to another value, extract the category
+from the :CATEGORY: property of the entry."
+ :group 'org-export-rss
+ :type '(choice
+ (const :tag "From tags" from-tags)
+ (const :tag "From the category property" from-category)))
+
+(defcustom org-rss-use-entry-url-as-guid t
+ "Use the URL for the <guid> metatag?
+When nil, Org will create ids using `org-icalendar-create-uid'."
+ :group 'org-export-rss
+ :type 'boolean)
+
+;;; Define backend
+
+(org-export-define-derived-backend 'rss 'html
+ :menu-entry
+ '(?r "Export to RSS"
+ ((?R "As RSS buffer"
+ (lambda (a s v b) (org-rss-export-as-rss a s v)))
+ (?r "As RSS file" (lambda (a s v b) (org-rss-export-to-rss a s v)))
+ (?o "As RSS file and open"
+ (lambda (a s v b)
+ (if a (org-rss-export-to-rss t s v)
+ (org-open-file (org-rss-export-to-rss nil s v)))))))
+ :options-alist
+ '((:description "DESCRIPTION" nil nil newline)
+ (:keywords "KEYWORDS" nil nil space)
+ (:with-toc nil nil nil) ;; Never include HTML's toc
+ (:rss-extension "RSS_EXTENSION" nil org-rss-extension)
+ (:rss-image-url "RSS_IMAGE_URL" nil org-rss-image-url)
+ (:rss-feed-url "RSS_FEED_URL" nil nil t)
+ (:rss-categories nil nil org-rss-categories))
+ :filters-alist '((:filter-final-output . org-rss-final-function))
+ :translate-alist '((headline . org-rss-headline)
+ (comment . (lambda (&rest args) ""))
+ (comment-block . (lambda (&rest args) ""))
+ (timestamp . (lambda (&rest args) ""))
+ (plain-text . org-rss-plain-text)
+ (section . org-rss-section)
+ (template . org-rss-template)))
+
+;;; Export functions
+
+;;;###autoload
+(defun org-rss-export-as-rss (&optional async subtreep visible-only)
+ "Export current buffer to a RSS buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Export is done in a buffer named \"*Org RSS Export*\", which will
+be displayed when `org-export-show-temporary-export-buffer' is
+non-nil."
+ (interactive)
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (org-icalendar-create-uid file 'warn-user)
+ (org-rss-add-pubdate-property))
+ (org-export-to-buffer 'rss "*Org RSS Export*"
+ async subtreep visible-only nil nil (lambda () (text-mode))))
+
+;;;###autoload
+(defun org-rss-export-to-rss (&optional async subtreep visible-only)
+ "Export current buffer to a RSS file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Return output file's name."
+ (interactive)
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (org-icalendar-create-uid file 'warn-user)
+ (org-rss-add-pubdate-property))
+ (let ((outfile (org-export-output-file-name
+ (concat "." org-rss-extension) subtreep)))
+ (org-export-to-file 'rss outfile async subtreep visible-only)))
+
+;;;###autoload
+(defun org-rss-publish-to-rss (plist filename pub-dir)
+ "Publish an org file to RSS.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (let ((bf (get-file-buffer filename)))
+ (if bf
+ (with-current-buffer bf
+ (org-icalendar-create-uid filename 'warn-user)
+ (org-rss-add-pubdate-property)
+ (write-file filename))
+ (find-file filename)
+ (org-icalendar-create-uid filename 'warn-user)
+ (org-rss-add-pubdate-property)
+ (write-file filename) (kill-buffer)))
+ (org-publish-org-to
+ 'rss filename (concat "." org-rss-extension) plist pub-dir))
+
+;;; Main transcoding functions
+
+(defun org-rss-headline (headline contents info)
+ "Transcode HEADLINE element into RSS format.
+CONTENTS is the headline contents. INFO is a plist used as a
+communication channel."
+ (if (> (org-export-get-relative-level headline info) 1)
+ (org-export-data-with-backend headline 'html info)
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((email (org-export-data (plist-get info :email) info))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (htmlext (plist-get info :html-extension))
+ (hl-number (org-export-get-headline-number headline info))
+ (hl-home (file-name-as-directory (plist-get info :html-link-home)))
+ (hl-pdir (plist-get info :publishing-directory))
+ (hl-perm (org-element-property :RSS_PERMALINK headline))
+ (anchor (org-export-get-reference headline info))
+ (category (org-rss-plain-text
+ (or (org-element-property :CATEGORY headline) "") info))
+ (pubdate0 (org-element-property :PUBDATE headline))
+ (pubdate (let ((system-time-locale "C"))
+ (if pubdate0
+ (format-time-string
+ "%a, %d %b %Y %H:%M:%S %z"
+ (org-time-string-to-time pubdate0)))))
+ (title (org-rss-plain-text
+ (or (org-element-property :RSS_TITLE headline)
+ (replace-regexp-in-string
+ org-bracket-link-regexp
+ (lambda (m) (or (match-string 3 m)
+ (match-string 1 m)))
+ (org-element-property :raw-value headline))) info))
+ (publink
+ (or (and hl-perm (concat (or hl-home hl-pdir) hl-perm))
+ (concat
+ (or hl-home hl-pdir)
+ (file-name-nondirectory
+ (file-name-sans-extension
+ (plist-get info :input-file))) "." htmlext "#" anchor)))
+ (guid (if org-rss-use-entry-url-as-guid
+ publink
+ (org-rss-plain-text
+ (or (org-element-property :ID headline)
+ (org-element-property :CUSTOM_ID headline)
+ publink)
+ info))))
+ (if (not pubdate0) "" ;; Skip entries with no PUBDATE prop
+ (format
+ (concat
+ "<item>\n"
+ "<title>%s</title>\n"
+ "<link>%s</link>\n"
+ "<author>%s (%s)</author>\n"
+ "<guid isPermaLink=\"false\">%s</guid>\n"
+ "<pubDate>%s</pubDate>\n"
+ (org-rss-build-categories headline info) "\n"
+ "<description><![CDATA[%s]]></description>\n"
+ "</item>\n")
+ title publink email author guid pubdate contents))))))
+
+(defun org-rss-build-categories (headline info)
+ "Build categories for the RSS item."
+ (if (eq (plist-get info :rss-categories) 'from-tags)
+ (mapconcat
+ (lambda (c) (format "<category><![CDATA[%s]]></category>" c))
+ (org-element-property :tags headline)
+ "\n")
+ (let ((c (org-element-property :CATEGORY headline)))
+ (format "<category><![CDATA[%s]]></category>" c))))
+
+(defun org-rss-template (contents info)
+ "Return complete document string after RSS conversion.
+CONTENTS is the transcoded contents string. INFO is a plist used
+as a communication channel."
+ (concat
+ (format "<?xml version=\"1.0\" encoding=\"%s\"?>"
+ (symbol-name org-html-coding-system))
+ "\n<rss version=\"2.0\"
+ xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"
+ xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"
+ xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
+ xmlns:atom=\"http://www.w3.org/2005/Atom\"
+ xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"
+ xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"
+ xmlns:georss=\"http://www.georss.org/georss\"
+ xmlns:geo=\"http://www.w3.org/2003/01/geo/wgs84_pos#\"
+ xmlns:media=\"http://search.yahoo.com/mrss/\">"
+ "<channel>"
+ (org-rss-build-channel-info info) "\n"
+ contents
+ "</channel>\n"
+ "</rss>"))
+
+(defun org-rss-build-channel-info (info)
+ "Build the RSS channel information."
+ (let* ((system-time-locale "C")
+ (title (org-export-data (plist-get info :title) info))
+ (email (org-export-data (plist-get info :email) info))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (date (format-time-string "%a, %d %b %Y %H:%M:%S %z")) ;; RFC 882
+ (description (org-export-data (plist-get info :description) info))
+ (lang (plist-get info :language))
+ (keywords (plist-get info :keywords))
+ (rssext (plist-get info :rss-extension))
+ (blogurl (or (plist-get info :html-link-home)
+ (plist-get info :publishing-directory)))
+ (image (url-encode-url (plist-get info :rss-image-url)))
+ (ifile (plist-get info :input-file))
+ (publink
+ (or (plist-get info :rss-feed-url)
+ (concat (file-name-as-directory blogurl)
+ (file-name-nondirectory
+ (file-name-sans-extension ifile))
+ "." rssext))))
+ (format
+ "\n<title>%s</title>
+<atom:link href=\"%s\" rel=\"self\" type=\"application/rss+xml\" />
+<link>%s</link>
+<description><![CDATA[%s]]></description>
+<language>%s</language>
+<pubDate>%s</pubDate>
+<lastBuildDate>%s</lastBuildDate>
+<generator>%s</generator>
+<webMaster>%s (%s)</webMaster>
+<image>
+<url>%s</url>
+<title>%s</title>
+<link>%s</link>
+</image>
+"
+ title publink blogurl description lang date date
+ (concat (format "Emacs %d.%d"
+ emacs-major-version
+ emacs-minor-version)
+ " Org-mode " (org-version))
+ email author image title blogurl)))
+
+(defun org-rss-section (section contents info)
+ "Transcode SECTION element into RSS format.
+CONTENTS is the section contents. INFO is a plist used as
+a communication channel."
+ contents)
+
+(defun org-rss-timestamp (timestamp contents info)
+ "Transcode a TIMESTAMP object from Org to RSS.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-html-encode-plain-text
+ (org-timestamp-translate timestamp)))
+
+(defun org-rss-plain-text (contents info)
+ "Convert plain text into RSS encoded text."
+ (let (output)
+ (setq output (org-html-encode-plain-text contents)
+ output (org-export-activate-smart-quotes
+ output :html info))))
+
+;;; Filters
+
+(defun org-rss-final-function (contents backend info)
+ "Prettify the RSS output."
+ (with-temp-buffer
+ (xml-mode)
+ (insert contents)
+ (indent-region (point-min) (point-max))
+ (buffer-substring-no-properties (point-min) (point-max))))
+
+;;; Miscellaneous
+
+(defun org-rss-add-pubdate-property ()
+ "Set the PUBDATE property for top-level headlines."
+ (let (msg)
+ (org-map-entries
+ (lambda ()
+ (let* ((entry (org-element-at-point))
+ (level (org-element-property :level entry)))
+ (when (= level 1)
+ (unless (org-entry-get (point) "PUBDATE")
+ (setq msg t)
+ (org-set-property
+ "PUBDATE" (format-time-string
+ (cdr org-time-stamp-formats)))))))
+ nil nil 'comment 'archive)
+ (when msg
+ (message "Property PUBDATE added to top-level entries in %s"
+ (buffer-file-name))
+ (sit-for 2))))
+
+(provide 'ox-rss)
+
+;;; ox-rss.el ends here
diff --git a/contrib/lisp/ox-s5.el b/contrib/lisp/ox-s5.el
new file mode 100644
index 0000000..8f95010
--- /dev/null
+++ b/contrib/lisp/ox-s5.el
@@ -0,0 +1,432 @@
+;;; ox-s5.el --- S5 Presentation Back-End for Org Export Engine
+
+;; Copyright (C) 2011-2014 Rick Frankel
+
+;; Author: Rick Frankel <emacs at rickster dot com>
+;; Keywords: outlines, hypermedia, S5, wp
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements an S5 Presentation back-end for the Org
+;; generic exporter.
+
+;; Installation
+;; ------------
+;; Get the s5 scripts from
+;; http://meyerweb.com/eric/tools/s5/
+;; (Note that the default s5 version is set for using the alpha, 1.2a2.
+;; Copy the ui dir to somewhere reachable from your published presentation
+;; The default (`org-s5-ui-url') is set to "ui" (e.g., in the
+;; same directory as the html file).
+
+;; Usage
+;; -----
+;; Follow the general instructions at the above website. To generate
+;; incremental builds, you can set the HTML_CONTAINER_CLASS on an
+;; object to "incremental" to make it build. If you want an outline to
+;; build, set the :INCREMENTAL property on the parent headline.
+
+;; To test it, run:
+;;
+;; M-x org-s5-export-as-html
+;;
+;; in an Org mode buffer. See ox.el and ox-html.el for more details
+;; on how this exporter works.
+
+;; TODOs
+;; ------
+;; The title page is formatted using format-spec. This is error prone
+;; when details are missing and may insert empty tags, like <h2></h2>,
+;; for missing values.
+
+(require 'ox-html)
+(eval-when-compile (require 'cl))
+
+(org-export-define-derived-backend 's5 'html
+ :menu-entry
+ '(?s "Export to S5 HTML Presentation"
+ ((?H "To temporary buffer" org-s5-export-as-html)
+ (?h "To file" org-s5-export-to-html)
+ (?o "To file and open"
+ (lambda (a s v b)
+ (if a (org-s5-export-to-html t s v b)
+ (org-open-file (org-s5-export-to-html nil s v b)))))))
+ :options-alist
+ '((:html-link-home "HTML_LINK_HOME" nil nil)
+ (:html-link-up "HTML_LINK_UP" nil nil)
+ (:s5-postamble "S5_POSTAMBLE" nil org-s5-postamble newline)
+ (:s5-preamble "S5_PREAMBLE" nil org-s5-preamble newline)
+ (:html-head-include-default-style "HTML_INCLUDE_DEFAULT_STYLE" nil nil)
+ (:html-head-include-scripts "HTML_INCLUDE_SCRIPTS" nil nil)
+ (:s5-version "S5_VERSION" nil org-s5-version)
+ (:s5-theme-file "S5_THEME_FILE" nil org-s5-theme-file)
+ (:s5-ui-url "S5_UI_URL" nil org-s5-ui-url)
+ (:s5-default-view "S5_DEFAULT_VIEW" nil org-s5-default-view)
+ (:s5-control-visibility "S5_CONTROL_VISIBILITY" nil
+ org-s5-control-visibility))
+ :translate-alist
+ '((headline . org-s5-headline)
+ (plain-list . org-s5-plain-list)
+ (inner-template . org-s5-inner-template)
+ (template . org-s5-template)))
+
+(defgroup org-export-s5 nil
+ "Options for exporting Org mode files to S5 HTML Presentations."
+ :tag "Org Export S5"
+ :group 'org-export-html)
+
+(defcustom org-s5-version "1.2a2"
+ "Version of s5 being used (for version metadata.) Defaults to
+s5 v2 alpha 2.
+Can be overridden with S5_VERSION."
+ :group 'org-export-s5
+ :type 'string)
+
+(defcustom org-s5-theme-file nil
+"Url to S5 theme (slides.css) file. Can be overriden with the
+S5_THEME_FILE property. If nil, defaults to
+`org-s5-ui-url'/default/slides.css. If it starts with anything but
+\"http\" or \"/\", it is used as-is. Otherwise the link in generated
+relative to `org-s5-ui-url'.
+The links for all other required stylesheets and scripts will be
+generated relative to `org-s5-ui-url'/default."
+ :group 'org-export-s5
+ :type 'string)
+
+(defcustom org-s5-ui-url "ui"
+ "Base url to directory containing S5 \"default\" subdirectory
+and the \"s5-notes.html\" file.
+Can be overriden with the S5_UI_URL property."
+ :group 'org-export-s5
+ :type 'string)
+
+(defcustom org-s5-default-view 'slideshow
+ "Setting for \"defaultView\" meta info."
+ :group 'org-export-s5
+ :type '(choice (const slideshow) (const outline)))
+
+(defcustom org-s5-control-visibility 'hidden
+ "Setting for \"controlVis\" meta info."
+ :group 'org-export-s5
+ :type '(choice (const hidden) (const visibile)))
+
+(defvar org-s5--divs
+ '((preamble "div" "header")
+ (content "div" "content")
+ (postamble "div" "footer"))
+ "Alist of the three section elements for HTML export.
+The car of each entry is one of 'preamble, 'content or 'postamble.
+The cdrs of each entry are the ELEMENT_TYPE and ID for each
+section of the exported document.
+
+If you set `org-html-container-element' to \"li\", \"ol\" will be
+uses as the content ELEMENT_TYPE, generating an XOXO format
+slideshow.
+
+Note that changing the preamble or postamble will break the
+core S5 stylesheets.")
+
+(defcustom org-s5-postamble "<h1>%a - %t</h1>"
+ "Preamble inserted into the S5 layout section.
+When set to a string, use this string as the postamble.
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+Setting the S5_POSTAMBLE option -- or the :s5-postamble in publishing
+projects -- will take precedence over this variable.
+
+Note that the default css styling will break if this is set to nil
+or an empty string."
+ :group 'org-export-s5
+ :type '(choice (const :tag "No postamble" "&#x20;")
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defcustom org-s5-preamble "&#x20;"
+ "Peamble inserted into the S5 layout section.
+
+When set to a string, use this string as the preamble.
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+Setting S5_PREAMBLE option -- or the :s5-preamble in publishing
+projects -- will take precedence over this variable.
+
+Note that the default css styling will break if this is set to nil
+or an empty string."
+ :group 'org-export-s5
+ :type '(choice (const :tag "No preamble" "&#x20;")
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defcustom org-s5-title-slide-template
+ "<h1>%t</h1>
+<h2>%s</h2>
+<h2>%a</h2>
+<h3>%e</h3>
+<h4>%d</h4>"
+ "Format template to specify title page section.
+See `org-html-postamble-format' for the valid elements which
+can be included.
+
+It will be wrapped in the element defined in the :html-container
+property, and defaults to the value of `org-html-container-element',
+and have the id \"title-slide\"."
+ :group 'org-export-s5
+ :type 'string)
+
+(defun org-s5--format-toc-headline (headline info)
+ "Return an appropriate table of contents entry for HEADLINE.
+Note that (currently) the S5 exporter does not support deep links,
+so the table of contents is not \"active\".
+INFO is a plist used as a communication channel."
+ (let* ((headline-number (org-export-get-headline-number headline info))
+ (section-number
+ (and (not (org-export-low-level-p headline info))
+ (org-export-numbered-headline-p headline info)
+ (concat (mapconcat 'number-to-string headline-number ".") ". ")))
+ (tags (and (eq (plist-get info :with-tags) t)
+ (org-export-get-tags headline info))))
+ (concat section-number
+ (org-export-data
+ (org-export-get-alt-title headline info) info)
+ (and tags "&nbsp;&nbsp;&nbsp;") (org-html--tags tags info))))
+
+(defun org-s5-toc (depth info)
+ (let* ((headlines (org-export-collect-headlines info depth))
+ (toc-entries
+ (mapcar (lambda (headline)
+ (cons (org-s5--format-toc-headline headline info)
+ (org-export-get-relative-level headline info)))
+ (org-export-collect-headlines info depth))))
+ (when toc-entries
+ (concat
+ (format "<%s id='table-of-contents' class='slide'>\n"
+ (plist-get info :html-container))
+ (format "<h1>%s</h1>\n"
+ (org-html--translate "Table of Contents" info))
+ "<div id=\"text-table-of-contents\">"
+ (org-html--toc-text toc-entries)
+ "</div>\n"
+ (format "</%s>\n" (plist-get info :html-container))))))
+
+(defun org-s5--build-head (info)
+ (let* ((dir (plist-get info :s5-ui-url))
+ (theme (or (plist-get info :s5-theme-file) "default/slides.css")))
+ (mapconcat
+ 'identity
+ (list
+ "<!-- style sheet links -->"
+ (mapconcat
+ (lambda (list)
+ (format
+ (concat
+ "<link rel='stylesheet' href='%s/default/%s' type='text/css'"
+ " media='%s' id='%s' />")
+ dir (nth 0 list) (nth 1 list) (nth 2 list)))
+ (list
+ '("outline.css" "screen" "outlineStyle")
+ '("print.css" "print" "slidePrint")
+ '("opera.css" "projection" "operaFix")) "\n")
+ (format (concat
+ "<link rel='stylesheet' href='%s' type='text/css'"
+ " media='screen' id='slideProj' />")
+ (if (string-match-p "^\\(http\\|/\\)" theme) theme
+ (concat dir "/" theme)))
+ "<!-- S5 JS -->"
+ (concat
+ "<script src='" dir
+ "/default/slides.js' type='text/javascript'></script>")) "\n")))
+
+(defun org-s5--build-meta-info (info)
+ (concat
+ (org-html--build-meta-info info)
+ (format "<meta name=\"version\" content=\"S5 %s\" />\n"
+ (plist-get info :s5-version))
+ (format "<meta name='defaultView' content='%s' />\n"
+ (plist-get info :s5-default-view))
+ (format "<meta name='controlVis' content='%s' />"
+ (plist-get info :s5-control-visibility))))
+
+(defun org-s5-headline (headline contents info)
+ (let ((org-html-toplevel-hlevel 1)
+ (class (or (org-element-property :HTML_CONTAINER_CLASS headline) ""))
+ (level (org-export-get-relative-level headline info)))
+ (when (and (= 1 level) (not (string-match-p "\\<slide\\>" class)))
+ (org-element-put-property headline :HTML_CONTAINER_CLASS (concat class " slide")))
+ (org-html-headline headline contents info)))
+
+(defun org-s5-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element from Org to HTML.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information.
+If a containing headline has the property :INCREMENTAL,
+then the \"incremental\" class will be added to the to the list,
+which will make the list into a \"build\"."
+ (let* ((type (org-element-property :type plain-list))
+ (tag (case type
+ (ordered "ol")
+ (unordered "ul")
+ (descriptive "dl"))))
+ (format "%s\n%s%s"
+ (format
+ "<%s class='org-%s%s'>" tag tag
+ (if (org-export-get-node-property :INCREMENTAL plain-list t)
+ " incremental" ""))
+ contents (org-html-end-plain-list type))))
+
+(defun org-s5-inner-template (contents info)
+ "Return body of document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (concat contents "\n"))
+
+(defun org-s5-template (contents info)
+ "Return complete document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((info (plist-put
+ (plist-put
+ (plist-put info :html-preamble (plist-get info :s5-preamble))
+ :html-postamble
+ (plist-get info :s5-postamble))
+ :html-divs
+ (if (equal "li" (plist-get info :html-container))
+ (cons '(content "ol" "content") org-s5--divs)
+ org-s5--divs))))
+ (mapconcat
+ 'identity
+ (list
+ (org-html-doctype info)
+ (format "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"%s\" xml:lang=\"%s\">"
+ (plist-get info :language) (plist-get info :language))
+ "<head>"
+ (org-s5--build-meta-info info)
+ (org-s5--build-head info)
+ (org-html--build-head info)
+ (org-html--build-mathjax-config info)
+ "</head>"
+ "<body>"
+ "<div class=\"layout\">"
+ "<div id=\"controls\"><!-- no edit --></div>"
+ "<div id=\"currentSlide\"><!-- no edit --></div>"
+ (org-html--build-pre/postamble 'preamble info)
+ (org-html--build-pre/postamble 'postamble info)
+ "</div>"
+ (format "<%s id=\"%s\" class=\"presentation\">"
+ (nth 1 (assq 'content org-html-divs))
+ (nth 2 (assq 'content org-html-divs)))
+ ;; title page
+ (format "<%s id='title-slide' class='slide'>"
+ (plist-get info :html-container))
+ (format-spec org-s5-title-slide-template (org-html-format-spec info))
+ (format "</%s>" (plist-get info :html-container))
+ ;; table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth (org-s5-toc depth info)))
+ contents
+ (format "</%s>" (nth 1 (assq 'content org-html-divs)))
+ "</body>"
+ "</html>\n") "\n")))
+
+(defun org-s5-export-as-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to an HTML buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org S5 Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 's5 "*Org S5 Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (nxml-mode))))
+
+(defun org-s5-export-to-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a S5 HTML file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let* ((extension (concat "." org-html-extension))
+ (file (org-export-output-file-name extension subtreep))
+ (org-export-coding-system org-html-coding-system))
+ (org-export-to-file 's5 file
+ async subtreep visible-only body-only ext-plist)))
+
+(defun org-s5-publish-to-html (plist filename pub-dir)
+ "Publish an org file to S5 HTML Presentation.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 's5 filename ".html" plist pub-dir))
+
+(provide 'ox-s5)
+
+;;; ox-s5.el ends here
diff --git a/contrib/lisp/ox-taskjuggler.el b/contrib/lisp/ox-taskjuggler.el
new file mode 100644
index 0000000..d856878
--- /dev/null
+++ b/contrib/lisp/ox-taskjuggler.el
@@ -0,0 +1,1038 @@
+;;; ox-taskjuggler.el --- TaskJuggler Back-End for Org Export Engine
+;;
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+;;
+;; Emacs Lisp Archive Entry
+;; Filename: ox-taskjuggler.el
+;; Author: Christian Egli
+;; Nicolas Goaziou <n dot goaziou at gmail dot com>
+;; Maintainer: Christian Egli
+;; Keywords: org, taskjuggler, project planning
+;; Description: Converts an Org mode buffer into a TaskJuggler project plan
+
+;; This file is not part of GNU Emacs.
+
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements a TaskJuggler exporter for Org mode.
+;; TaskJuggler is a project planing tool that uses a text format to
+;; define projects, tasks and resources, so it is a natural fit for
+;; Org mode. It can produce all sorts of reports for tasks or
+;; resources in either HTML, CSV or PDF. TaskJuggler is implemented
+;; in Ruby and should therefore run on any platform.
+;;
+;; The exporter does not export all the nodes of a document or
+;; strictly follow the order of the nodes in the document.
+;;
+;; Instead the TaskJuggler exporter looks for a tree that defines the
+;; tasks and a optionally tree that defines the resources for this
+;; project. It then creates a TaskJuggler file based on these trees
+;; and the attributes defined in all the nodes.
+;;
+;; * Installation
+;;
+;; Put this file into your load-path and the following line into your
+;; ~/.emacs:
+;;
+;; (add-to-list 'org-export-backends 'taskjuggler)
+;;
+;; or customize `org-export-backends' variable.
+;;
+;; The interactive functions are the following:
+;;
+;; M-x `org-taskjuggler-export'
+;; M-x `org-taskjuggler-export-and-open'
+;;
+;; * Tasks
+;;
+;; Let's illustrate the usage with a small example. Create your tasks
+;; as you usually do with org-mode. Assign efforts to each task using
+;; properties (it's easiest to do this in the column view). You
+;; should end up with something similar to the example by Peter Jones
+;; in:
+;;
+;; http://www.devalot.com/assets/articles/2008/07/project-planning/project-planning.org.
+;;
+;; Now mark the top node of your tasks with a tag named
+;; "taskjuggler_project" (or whatever you customized
+;; `org-taskjuggler-project-tag' to). You are now ready to export the
+;; project plan with `org-taskjuggler-export-and-open' which will
+;; export the project plan and open a Gantt chart in TaskJugglerUI.
+;;
+;; * Resources
+;;
+;; Next you can define resources and assign those to work on specific
+;; tasks. You can group your resources hierarchically. Tag the top
+;; node of the resources with "taskjuggler_resource" (or whatever you
+;; customized `org-taskjuggler-resource-tag' to). You can optionally
+;; assign an identifier (named "resource_id") to the resources (using
+;; the standard org properties commands) or you can let the exporter
+;; generate identifiers automatically (the exporter picks the first
+;; word of the headline as the identifier as long as it is unique, see
+;; the documentation of `org-taskjuggler--build-unique-id'). Using that
+;; identifier you can then allocate resources to tasks. This is again
+;; done with the "allocate" property on the tasks. Do this in column
+;; view or when on the task type
+;;
+;; C-c C-x p allocate RET <resource_id> RET
+;;
+;; Once the allocations are done you can again export to TaskJuggler
+;; and check in the Resource Allocation Graph which person is working
+;; on what task at what time.
+;;
+;; * Export of properties
+;;
+;; The exporter also takes TODO state information into consideration,
+;; i.e. if a task is marked as done it will have the corresponding
+;; attribute in TaskJuggler ("complete 100"). Also it will export any
+;; property on a task resource or resource node which is known to
+;; TaskJuggler, such as limits, vacation, shift, booking, efficiency,
+;; journalentry, rate for resources or account, start, note, duration,
+;; end, journalentry, milestone, reference, responsible, scheduling,
+;; etc for tasks.
+;;
+;; * Dependencies
+;;
+;; The exporter will handle dependencies that are defined in the tasks
+;; either with the ORDERED attribute (see TODO dependencies in the Org
+;; mode manual) or with the BLOCKER attribute (see org-depend.el) or
+;; alternatively with a depends attribute. Both the BLOCKER and the
+;; depends attribute can be either "previous-sibling" or a reference
+;; to an identifier (named "task_id") which is defined for another
+;; task in the project. BLOCKER and the depends attribute can define
+;; multiple dependencies separated by either space or comma. You can
+;; also specify optional attributes on the dependency by simply
+;; appending it. The following examples should illustrate this:
+;;
+;; * Training material
+;; :PROPERTIES:
+;; :task_id: training_material
+;; :ORDERED: t
+;; :END:
+;; ** Markup Guidelines
+;; :PROPERTIES:
+;; :Effort: 2d
+;; :END:
+;; ** Workflow Guidelines
+;; :PROPERTIES:
+;; :Effort: 2d
+;; :END:
+;; * Presentation
+;; :PROPERTIES:
+;; :Effort: 2d
+;; :BLOCKER: training_material { gapduration 1d } some_other_task
+;; :END:
+;;
+;;;; * TODO
+;; - Look at org-file-properties, org-global-properties and
+;; org-global-properties-fixed
+;; - What about property inheritance and org-property-inherit-p?
+;; - Use TYPE_TODO as an way to assign resources
+;; - Add support for org-export-with-planning
+;;
+;;; Code:
+
+(eval-when-compile (require 'cl))
+
+(require 'ox)
+
+
+
+;;; User Variables
+
+(defgroup org-export-taskjuggler nil
+ "Options specific for TaskJuggler export back-end."
+ :tag "Org Export TaskJuggler"
+ :group 'org-export)
+
+(defcustom org-taskjuggler-extension ".tjp"
+ "Extension of TaskJuggler files."
+ :group 'org-export-taskjuggler
+ :type 'string)
+
+(defcustom org-taskjuggler-project-tag "taskjuggler_project"
+ "Tag marking project's tasks.
+This tag is used to find the tree containing all the tasks for
+the project."
+ :group 'org-export-taskjuggler
+ :type 'string)
+
+(defcustom org-taskjuggler-resource-tag "taskjuggler_resource"
+ "Tag marking project's resources.
+This tag is used to find the tree containing all the resources
+for the project."
+ :group 'org-export-taskjuggler
+ :type 'string)
+
+(defcustom org-taskjuggler-report-tag "taskjuggler_report"
+ "Tag marking project's reports.
+This tag is used to find the tree containing all the reports for
+the project."
+ :group 'org-export-taskjuggler
+ :type 'string)
+
+(defcustom org-taskjuggler-target-version 3.0
+ "Which version of TaskJuggler the exporter is targeting.
+By default a project plan is exported which conforms to version
+3.x of TaskJuggler. For a project plan that is compatible with
+versions of TaskJuggler older than 3.0 set this to 2.4.
+
+If you change this variable be sure to also change
+`org-taskjuggler-default-reports' as the format of reports has
+changed considerably between version 2.x and 3.x of TaskJuggler"
+ :group 'org-export-taskjuggler
+ :type 'number)
+
+(defcustom org-taskjuggler-default-project-version "1.0"
+ "Default version string for the project.
+This value can also be set with the \":VERSION:\" property
+associated to the headline defining the project."
+ :group 'org-export-taskjuggler
+ :type 'string)
+
+(defcustom org-taskjuggler-default-project-duration 280
+ "Default project duration.
+The value will be used if no start and end date have been defined
+in the root node of the task tree, i.e. the tree that has been
+marked with `org-taskjuggler-project-tag'"
+ :group 'org-export-taskjuggler
+ :type 'integer)
+
+(defcustom org-taskjuggler-default-reports
+ '("textreport report \"Plan\" {
+ formats html
+ header '== %title =='
+
+ center -8<-
+ [#Plan Plan] | [#Resource_Allocation Resource Allocation]
+ ----
+ === Plan ===
+ <[report id=\"plan\"]>
+ ----
+ === Resource Allocation ===
+ <[report id=\"resourceGraph\"]>
+ ->8-
+}
+
+# A traditional Gantt chart with a project overview.
+taskreport plan \"\" {
+ headline \"Project Plan\"
+ columns bsi, name, start, end, effort, chart
+ loadunit shortauto
+ hideresource 1
+}
+
+# A graph showing resource allocation. It identifies whether each
+# resource is under- or over-allocated for.
+resourcereport resourceGraph \"\" {
+ headline \"Resource Allocation Graph\"
+ columns no, name, effort, weekly
+ loadunit shortauto
+ hidetask ~(isleaf() & isleaf_())
+ sorttasks plan.start.up
+}")
+ "Default reports for the project.
+These are sensible default reports to give a good out-of-the-box
+result when exporting without defining any reports. \"%title\"
+anywhere in the reports will be replaced with the document title.
+If you want to define your own reports you can change them here
+or simply define the default reports so that they include an
+external report definition as follows:
+
+include reports.tji
+
+These default are made to work with tj3. If you are targeting
+TaskJuggler 2.4 (see `org-taskjuggler-target-version') please
+change these defaults to something like the following:
+
+taskreport \"Gantt Chart\" {
+ headline \"Project Gantt Chart\"
+ columns hierarchindex, name, start, end, effort, duration, completed, chart
+ timeformat \"%Y-%m-%d\"
+ hideresource 1
+ loadunit shortauto
+}
+
+resourcereport \"Resource Graph\" {
+ headline \"Resource Allocation Graph\"
+ columns no, name, utilization, freeload, chart
+ loadunit shortauto
+ sorttasks startup
+ hidetask ~isleaf()
+}"
+ :group 'org-export-taskjuggler
+ :type '(repeat (string :tag "Report")))
+
+(defcustom org-taskjuggler-default-global-header ""
+ "Default global header for the project.
+This goes before project declaration, and might be useful for
+early macros."
+ :group 'org-export-taskjuggler
+ :type '(string :tag "Preamble"))
+
+(defcustom org-taskjuggler-default-global-properties
+ "shift s40 \"Part time shift\" {
+ workinghours wed, thu, fri off
+}
+"
+ "Default global properties for the project.
+
+Here you typically define global properties such as shifts,
+accounts, rates, vacation, macros and flags. Any property that
+is allowed within the TaskJuggler file can be inserted. You
+could for example include another TaskJuggler file.
+
+The global properties are inserted after the project declaration
+but before any resource and task declarations."
+ :group 'org-export-taskjuggler
+ :type '(string :tag "Preamble"))
+
+(defcustom org-taskjuggler-valid-task-attributes
+ '(account start note duration endbuffer endcredit end
+ flags journalentry length limits maxend maxstart minend
+ minstart period reference responsible scheduling
+ startbuffer startcredit statusnote chargeset charge)
+ "Valid attributes for Taskjuggler tasks.
+If one of these appears as a property for a headline, it will be
+exported with the corresponding task.
+
+Note that multiline properties are not supported, so attributes
+like note or journalentry have to be on a single line."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-valid-project-attributes
+ '(timingresolution timezone alertlevels currency currencyformat
+ dailyworkinghours extend includejournalentry now numberformat
+ outputdir scenario shorttimeformat timeformat trackingscenario
+ weekstartsmonday weekstartssunday workinghours
+ yearlyworkingdays)
+ "Valid attributes for Taskjuggler project.
+If one of these appears as a property for a headline that is a
+project definition, it will be exported with the corresponding
+task. Attribute 'timingresolution' should be the first in the
+list."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-valid-resource-attributes
+ '(limits vacation shift booking efficiency journalentry rate
+ workinghours flags)
+ "Valid attributes for Taskjuggler resources.
+If one of these appears as a property for a headline, it will be
+exported with the corresponding resource."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-valid-report-attributes
+ '(headline columns definitions timeformat hideresource hidetask
+ loadunit sorttasks formats period)
+ "Valid attributes for Taskjuggler reports.
+If one of these appears as a property for a headline, it will be
+exported with the corresponding report."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-process-command
+ "tj3 --silent --no-color --output-dir %o %f"
+ "Command to process a Taskjuggler file.
+The command will be given to the shell as a command to process a
+Taskjuggler file. \"%f\" in the command will be replaced by the
+full file name, \"%o\" by the reports directory (see
+`org-taskjuggler-reports-directory').
+
+If you are targeting Taskjuggler 2.4 (see
+`org-taskjuggler-target-version') this setting is ignored."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-reports-directory "reports"
+ "Default directory to generate the Taskjuggler reports in.
+The command `org-taskjuggler-process-command' generates the
+reports and associated files such as CSS inside this directory.
+
+If the directory is not an absolute path it is relative to the
+directory of the exported file. The directory is created if it
+doesn't exist.
+
+If you are targeting Taskjuggler 2.4 (see
+`org-taskjuggler-target-version') this setting is ignored."
+ :group 'org-export-taskjuggler)
+
+(defcustom org-taskjuggler-keep-project-as-task t
+ "Non-nil keeps the project headline as an umbrella task for all tasks.
+Setting this to nil will allow maintaining completely separated
+task buckets, while still sharing the same resources pool."
+ :group 'org-export-taskjuggler
+ :type 'boolean)
+
+
+
+;;; Hooks
+
+(defvar org-taskjuggler-final-hook nil
+ "Hook run after a TaskJuggler files has been saved.
+This hook is run with the name of the file as argument.")
+
+
+
+;;; Back-End Definition
+
+(org-export-define-backend 'taskjuggler
+ '((template . org-taskjuggler-project-plan))
+ :menu-entry
+ '(?J "Export to TaskJuggler"
+ ((?j "As TJP file" (lambda (a s v b) (org-taskjuggler-export a s v)))
+ (?p "As TJP file and process"
+ (lambda (a s v b)
+ (if a (org-taskjuggler-export a s v)
+ (org-taskjuggler-export-and-process s v))))
+ (?o "As TJP file, process and open"
+ (lambda (a s v b)
+ (if a (org-taskjuggler-export a s v)
+ (org-taskjuggler-export-process-and-open s v))))))
+ ;; This property will be used to store unique ids in communication
+ ;; channel. Ids will be retrieved with `org-taskjuggler-get-id'.
+ :options-alist '((:taskjuggler-unique-ids nil nil nil)))
+
+
+
+;;; Unique IDs
+
+(defun org-taskjuggler-assign-task-ids (tasks info)
+ "Assign a unique ID to each task in TASKS.
+TASKS is a list of headlines. INFO is a plist used as a
+communication channel. Return value is an alist between
+headlines and their associated ID. IDs are hierarchical, which
+means they only need to be unique among the task siblings."
+ (let* (alist
+ build-id ; For byte-compiler.
+ (build-id
+ (lambda (tasks local-ids)
+ (org-element-map tasks 'headline
+ (lambda (task)
+ (let ((id (org-taskjuggler--build-unique-id task local-ids)))
+ (push id local-ids)
+ (push (cons task id) alist)
+ (funcall build-id (org-element-contents task) nil)))
+ info nil 'headline))))
+ (funcall build-id tasks nil)
+ alist))
+
+(defun org-taskjuggler-assign-resource-ids (resources info)
+ "Assign a unique ID to each resource within RESOURCES.
+RESOURCES is a list of headlines. INFO is a plist used as a
+communication channel. Return value is an alist between
+headlines and their associated ID."
+ (let (ids)
+ (org-element-map resources 'headline
+ (lambda (resource)
+ (let ((id (org-taskjuggler--build-unique-id resource ids)))
+ (push id ids)
+ (cons resource id)))
+ info)))
+
+
+
+;;; Accessors
+
+(defun org-taskjuggler-get-project (info)
+ "Return project in parse tree.
+INFO is a plist used as a communication channel. First headline
+in buffer with `org-taskjuggler-project-tag' defines the project.
+If no such task is defined, pick the first headline in buffer.
+If there is no headline at all, return nil."
+ (let ((tree (plist-get info :parse-tree)))
+ (or (org-element-map tree 'headline
+ (lambda (hl)
+ (and (member org-taskjuggler-project-tag
+ (org-export-get-tags hl info))
+ hl))
+ info t)
+ (org-element-map tree 'headline 'identity info t))))
+
+(defun org-taskjuggler-get-id (item info)
+ "Return id for task or resource ITEM.
+ITEM is a headline. INFO is a plist used as a communication
+channel. Return value is a string."
+ (cdr (assq item (plist-get info :taskjuggler-unique-ids))))
+
+(defun org-taskjuggler-get-name (item)
+ "Return name for task or resource ITEM.
+ITEM is a headline. Return value is a string."
+ ;; Quote double quotes in name.
+ (replace-regexp-in-string
+ "\"" "\\\"" (org-element-property :raw-value item) t t))
+
+(defun org-taskjuggler-get-start (item)
+ "Return start date for task or resource ITEM.
+ITEM is a headline. Return value is a string or nil if ITEM
+doesn't have any start date defined."
+ (let ((scheduled (org-element-property :scheduled item)))
+ (or
+ (and scheduled (org-timestamp-format scheduled "%Y-%02m-%02d"))
+ (and (memq 'start org-taskjuggler-valid-task-attributes)
+ (org-element-property :START item)))))
+
+(defun org-taskjuggler-get-end (item)
+ "Return end date for task or resource ITEM.
+ITEM is a headline. Return value is a string or nil if ITEM
+doesn't have any end date defined."
+ (let ((deadline (org-element-property :deadline item)))
+ (and deadline (org-timestamp-format deadline "%Y-%02m-%02d"))))
+
+
+
+;;; Internal Functions
+
+(defun org-taskjuggler--indent-string (s)
+ "Indent string S by 2 spaces.
+Return new string. If S is the empty string, return it."
+ (if (equal "" s) s (replace-regexp-in-string "^ *\\S-" " \\&" s)))
+
+(defun org-taskjuggler--build-attributes (item attributes)
+ "Return attributes string for ITEM.
+ITEM is a project, task, resource or report headline. ATTRIBUTES
+is a list of symbols representing valid attributes for ITEM."
+ (mapconcat
+ (lambda (attribute)
+ (let ((value (org-element-property
+ (intern (upcase (format ":%s" attribute)))
+ item)))
+ (and value (format "%s %s\n" attribute value))))
+ (remq nil attributes) ""))
+
+(defun org-taskjuggler--build-unique-id (item unique-ids)
+ "Return a unique id for a given task or a resource.
+ITEM is an `headline' type element representing the task or
+resource. Its id is derived from its name and made unique
+against UNIQUE-IDS. If the (downcased) first token of the
+headline is not unique try to add more (downcased) tokens of the
+headline or finally add more underscore characters (\"_\")."
+ (let ((id (org-string-nw-p (org-element-property :TASK_ID item))))
+ ;; If an id is specified, use it, as long as it's unique.
+ (if (and id (not (member id unique-ids))) id
+ (let* ((parts (org-split-string (org-element-property :raw-value item)))
+ (id (org-taskjuggler--clean-id (downcase (pop parts)))))
+ ;; Try to add more parts of the headline to make it unique.
+ (while (and (car parts) (member id unique-ids))
+ (setq id (concat id "_"
+ (org-taskjuggler--clean-id (downcase (pop parts))))))
+ ;; If it's still not unique, add "_".
+ (while (member id unique-ids)
+ (setq id (concat id "_")))
+ id))))
+
+(defun org-taskjuggler--clean-id (id)
+ "Clean and return ID to make it acceptable for TaskJuggler.
+ID is a string."
+ ;; Replace non-ascii by "_".
+ (replace-regexp-in-string
+ "[^a-zA-Z0-9_]" "_"
+ ;; Make sure id doesn't start with a number.
+ (replace-regexp-in-string "^\\([0-9]\\)" "_\\1" id)))
+
+
+
+;;; Dependencies
+
+(defun org-taskjuggler-resolve-dependencies (task info)
+ "Return a list of all tasks TASK depends on.
+TASK is a headline. INFO is a plist used as a communication
+channel."
+ (let ((deps-ids
+ ;; Get all dependencies specified in BLOCKER and DEPENDS task
+ ;; properties. Clean options from them.
+ (let ((deps (concat (org-element-property :BLOCKER task)
+ (org-element-property :DEPENDS task))))
+ (and deps
+ (org-split-string (replace-regexp-in-string "{.*?}" "" deps)
+ "[ ,]* +"))))
+ depends)
+ (when deps-ids
+ ;; Find tasks with :task_id: property matching id in DEPS-IDS.
+ ;; Add them to DEPENDS.
+ (let* ((project (org-taskjuggler-get-project info))
+ (tasks (if org-taskjuggler-keep-project-as-task project
+ (org-element-contents project))))
+ (setq depends
+ (org-element-map tasks 'headline
+ (lambda (task)
+ (let ((task-id (or (org-element-property :TASK_ID task)
+ (org-element-property :ID task))))
+ (and task-id (member task-id deps-ids) task)))
+ info)))
+ ;; Check BLOCKER and DEPENDS properties. If "previous-sibling"
+ ;; belongs to DEPS-ID, add it to DEPENDS.
+ (when (and (member-ignore-case "previous-sibling" deps-ids)
+ (not (org-export-first-sibling-p task info)))
+ (let ((prev (org-export-get-previous-element task info)))
+ (and (not (memq prev depends)) (push prev depends)))))
+ ;; Check ORDERED status of parent.
+ (let ((parent (org-export-get-parent task)))
+ (when (and parent
+ (org-element-property :ORDERED parent)
+ (not (org-export-first-sibling-p task info)))
+ (push (org-export-get-previous-element task info) depends)))
+ ;; Return dependencies.
+ depends))
+
+(defun org-taskjuggler-format-dependencies (dependencies task info)
+ "Format DEPENDENCIES to match TaskJuggler syntax.
+DEPENDENCIES is list of dependencies for TASK, as returned by
+`org-taskjuggler-resolve-depedencies'. TASK is a headline.
+INFO is a plist used as a communication channel. Return value
+doesn't include leading \"depends\"."
+ (let* ((dep-str (concat (org-element-property :BLOCKER task)
+ " "
+ (org-element-property :DEPENDS task)))
+ (get-path
+ (lambda (dep)
+ ;; Return path to DEP relatively to TASK.
+ (let ((parent (org-export-get-parent task))
+ (exclamations 1)
+ (option
+ (let ((id (org-element-property :TASK_ID dep)))
+ (and id
+ (string-match (concat id " +\\({.*?}\\)") dep-str)
+ (match-string-no-properties 1 dep-str))))
+ path)
+ ;; Compute number of exclamation marks by looking for the
+ ;; common ancestor between TASK and DEP.
+ (while (not (org-element-map parent 'headline
+ (lambda (hl) (eq hl dep))))
+ (incf exclamations)
+ (setq parent (org-export-get-parent parent)))
+ ;; Build path from DEP to PARENT.
+ (while (not (eq parent dep))
+ (push (org-taskjuggler-get-id dep info) path)
+ (setq dep (org-export-get-parent dep)))
+ ;; Return full path. Add dependency options, if any.
+ (concat (make-string exclamations ?!)
+ (mapconcat 'identity path ".")
+ (and option (concat " " option)))))))
+ ;; Return dependencies string, without the leading "depends".
+ (mapconcat (lambda (dep) (funcall get-path dep)) dependencies ", ")))
+
+
+
+;;; Translator Functions
+
+(defun org-taskjuggler-project-plan (contents info)
+ "Build TaskJuggler project plan.
+CONTENTS is ignored. INFO is a plist holding export options.
+Return complete project plan as a string in TaskJuggler syntax."
+ (let* ((tree (plist-get info :parse-tree))
+ (project (or (org-taskjuggler-get-project info)
+ (error "No project specified"))))
+ (concat
+ ;; 1. Insert header.
+ (org-element-normalize-string org-taskjuggler-default-global-header)
+ ;; 2. Insert project.
+ (org-taskjuggler--build-project project info)
+ ;; 3. Insert global properties.
+ (org-element-normalize-string org-taskjuggler-default-global-properties)
+ ;; 4. Insert resources. Provide a default one if none is
+ ;; specified.
+ (let ((main-resources
+ ;; Collect contents from various trees marked with
+ ;; `org-taskjuggler-resource-tag'. Only gather top level
+ ;; resources.
+ (apply 'append
+ (org-element-map tree 'headline
+ (lambda (hl)
+ (and (member org-taskjuggler-resource-tag
+ (org-export-get-tags hl info))
+ (org-element-map (org-element-contents hl) 'headline
+ 'identity info nil 'headline)))
+ info nil 'headline))))
+ ;; Assign a unique ID to each resource. Store it under
+ ;; `:taskjuggler-unique-ids' property in INFO.
+ (setq info
+ (plist-put info :taskjuggler-unique-ids
+ (org-taskjuggler-assign-resource-ids
+ main-resources info)))
+ (concat
+ (if main-resources
+ (mapconcat
+ (lambda (resource) (org-taskjuggler--build-resource resource info))
+ main-resources "")
+ (format "resource %s \"%s\" {\n}\n" (user-login-name) user-full-name))
+ ;; 5. Insert tasks.
+ (let ((main-tasks
+ ;; If `org-taskjuggler-keep-project-as-task' is
+ ;; non-nil, there is only one task. Otherwise, every
+ ;; direct children of PROJECT is a top level task.
+ (if org-taskjuggler-keep-project-as-task (list project)
+ (or (org-element-map (org-element-contents project) 'headline
+ 'identity info nil 'headline)
+ (error "No task specified")))))
+ ;; Assign a unique ID to each task. Add it to
+ ;; `:taskjuggler-unique-ids' property in INFO.
+ (setq info
+ (plist-put info :taskjuggler-unique-ids
+ (append
+ (org-taskjuggler-assign-task-ids main-tasks info)
+ (plist-get info :taskjuggler-unique-ids))))
+ ;; If no resource is allocated among tasks, allocate one to
+ ;; the first task.
+ (unless (org-element-map main-tasks 'headline
+ (lambda (task) (org-element-property :ALLOCATE task))
+ info t)
+ (org-element-put-property
+ (car main-tasks) :ALLOCATE
+ (or (org-taskjuggler-get-id (car main-resources) info)
+ (user-login-name))))
+ (mapconcat
+ (lambda (task) (org-taskjuggler--build-task task info))
+ main-tasks ""))
+ ;; 6. Insert reports. If no report is defined, insert default
+ ;; reports.
+ (let ((main-reports
+ ;; Collect contents from various trees marked with
+ ;; `org-taskjuggler-report-tag'. Only gather top level
+ ;; reports.
+ (apply 'append
+ (org-element-map tree 'headline
+ (lambda (hl)
+ (and (member org-taskjuggler-report-tag
+ (org-export-get-tags hl info))
+ (org-element-map (org-element-contents hl)
+ 'headline 'identity info nil 'headline)))
+ info nil 'headline))))
+ (if main-reports
+ (mapconcat
+ (lambda (report) (org-taskjuggler--build-report report info))
+ main-reports "")
+ ;; insert title in default reports
+ (let* ((title (org-export-data (plist-get info :title) info))
+ (report-title (if (string= title "")
+ (org-taskjuggler-get-name project)
+ title)))
+ (mapconcat
+ 'org-element-normalize-string
+ (mapcar
+ (function
+ (lambda (report)
+ (replace-regexp-in-string "%title" report-title report t t)))
+ org-taskjuggler-default-reports) "")))))))))
+
+(defun org-taskjuggler--build-project (project info)
+ "Return a project declaration.
+PROJECT is a headline. INFO is a plist used as a communication
+channel. If no start date is specified, start today. If no end
+date is specified, end `org-taskjuggler-default-project-duration'
+days from now."
+ (concat
+ ;; Opening project.
+ (format "project %s \"%s\" \"%s\" %s %s {\n"
+ (org-taskjuggler-get-id project info)
+ (org-taskjuggler-get-name project)
+ ;; Version is obtained through :TASKJUGGLER_VERSION:
+ ;; property or `org-taskjuggler-default-project-version'.
+ (or (org-element-property :VERSION project)
+ org-taskjuggler-default-project-version)
+ (or (org-taskjuggler-get-start project)
+ (format-time-string "%Y-%m-%d"))
+ (let ((end (org-taskjuggler-get-end project)))
+ (or (and end (format "- %s" end))
+ (format "+%sd"
+ org-taskjuggler-default-project-duration))))
+ ;; Add attributes.
+ (org-taskjuggler--indent-string
+ (org-taskjuggler--build-attributes
+ project org-taskjuggler-valid-project-attributes))
+ ;; Closing project.
+ "}\n"))
+
+(defun org-taskjuggler--build-resource (resource info)
+ "Return a resource declaration.
+
+RESOURCE is a headline. INFO is a plist used as a communication
+channel.
+
+All valid attributes from RESOURCE are inserted. If RESOURCE
+defines a property \"resource_id\" it will be used as the id for
+this resource. Otherwise it will use the ID property. If
+neither is defined a unique id will be associated to it."
+ (concat
+ ;; Opening resource.
+ (format "resource %s \"%s\" {\n"
+ (org-taskjuggler--clean-id
+ (or (org-element-property :RESOURCE_ID resource)
+ (org-element-property :ID resource)
+ (org-taskjuggler-get-id resource info)))
+ (org-taskjuggler-get-name resource))
+ ;; Add attributes.
+ (org-taskjuggler--indent-string
+ (org-taskjuggler--build-attributes
+ resource org-taskjuggler-valid-resource-attributes))
+ ;; Add inner resources.
+ (org-taskjuggler--indent-string
+ (mapconcat
+ 'identity
+ (org-element-map (org-element-contents resource) 'headline
+ (lambda (hl) (org-taskjuggler--build-resource hl info))
+ info nil 'headline)
+ ""))
+ ;; Closing resource.
+ "}\n"))
+
+(defun org-taskjuggler--build-report (report info)
+ "Return a report declaration.
+REPORT is a headline. INFO is a plist used as a communication
+channel."
+ (concat
+ ;; Opening report.
+ (format "%s \"%s\" {\n"
+ (or (org-element-property :REPORT_KIND report) "taskreport")
+ (org-taskjuggler-get-name report))
+ ;; Add attributes.
+ (org-taskjuggler--indent-string
+ (org-taskjuggler--build-attributes
+ report org-taskjuggler-valid-report-attributes))
+ ;; Add inner reports.
+ (org-taskjuggler--indent-string
+ (mapconcat
+ 'identity
+ (org-element-map (org-element-contents report) 'headline
+ (lambda (hl) (org-taskjuggler--build-report hl info))
+ info nil 'headline)
+ ""))
+ ;; Closing report.
+ "}\n"))
+
+(defun org-taskjuggler--build-task (task info)
+ "Return a task declaration.
+
+TASK is a headline. INFO is a plist used as a communication
+channel.
+
+All valid attributes from TASK are inserted. If TASK defines
+a property \"task_id\" it will be used as the id for this task.
+Otherwise it will use the ID property. If neither is defined
+a unique id will be associated to it."
+ (let* ((allocate (org-element-property :ALLOCATE task))
+ (complete
+ (if (eq (org-element-property :todo-type task) 'done) "100"
+ (org-element-property :COMPLETE task)))
+ (depends (org-taskjuggler-resolve-dependencies task info))
+ (effort (let ((property
+ (intern (concat ":" (upcase org-effort-property)))))
+ (org-element-property property task)))
+ (milestone
+ (or (org-element-property :MILESTONE task)
+ (not (or (org-element-map (org-element-contents task) 'headline
+ 'identity info t) ; Has task any child?
+ effort
+ (org-element-property :LENGTH task)
+ (org-element-property :DURATION task)
+ (and (org-taskjuggler-get-start task)
+ (org-taskjuggler-get-end task))
+ (org-element-property :PERIOD task)))))
+ (priority
+ (let ((pri (org-element-property :priority task)))
+ (and pri
+ (max 1 (/ (* 1000 (- org-lowest-priority pri))
+ (- org-lowest-priority org-highest-priority)))))))
+ (concat
+ ;; Opening task.
+ (format "task %s \"%s\" {\n"
+ (org-taskjuggler-get-id task info)
+ (org-taskjuggler-get-name task))
+ ;; Add default attributes.
+ (and depends
+ (format " depends %s\n"
+ (org-taskjuggler-format-dependencies depends task info)))
+ (and allocate
+ (format " purge %s\n allocate %s\n"
+ ;; Compatibility for previous TaskJuggler versions.
+ (if (>= org-taskjuggler-target-version 3.0) "allocate"
+ "allocations")
+ allocate))
+ (and complete (format " complete %s\n" complete))
+ (and effort
+ (format " effort %s\n"
+ (let* ((minutes (org-duration-string-to-minutes effort))
+ (hours (/ minutes 60.0)))
+ (format "%.1fh" hours))))
+ (and priority (format " priority %s\n" priority))
+ (and milestone " milestone\n")
+ ;; Add other valid attributes.
+ (org-taskjuggler--indent-string
+ (org-taskjuggler--build-attributes
+ task org-taskjuggler-valid-task-attributes))
+ ;; Add inner tasks.
+ (org-taskjuggler--indent-string
+ (mapconcat 'identity
+ (org-element-map (org-element-contents task) 'headline
+ (lambda (hl) (org-taskjuggler--build-task hl info))
+ info nil 'headline)
+ ""))
+ ;; Closing task.
+ "}\n")))
+
+
+
+;;; Interactive Functions
+
+;;;###autoload
+(defun org-taskjuggler-export (&optional async subtreep visible-only)
+ "Export current buffer to a TaskJuggler file.
+
+The exporter looks for a tree with tag that matches
+`org-taskjuggler-project-tag' and takes this as the tasks for
+this project. The first node of this tree defines the project
+properties such as project name and project period.
+
+If there is a tree with tag that matches
+`org-taskjuggler-resource-tag' this tree is taken as resources
+for the project. If no resources are specified, a default
+resource is created and allocated to the project.
+
+Also the TaskJuggler project will be created with default reports
+as defined in `org-taskjuggler-default-reports'.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile
+ (org-export-output-file-name org-taskjuggler-extension subtreep)))
+ (org-export-to-file 'taskjuggler outfile
+ async subtreep visible-only nil nil
+ (lambda (file)
+ (run-hook-with-args 'org-taskjuggler-final-hook file) nil))))
+
+;;;###autoload
+(defun org-taskjuggler-export-and-process (&optional subtreep visible-only)
+ "Export current buffer to a TaskJuggler file and process it.
+
+The exporter looks for a tree with tag that matches
+`org-taskjuggler-project-tag' and takes this as the tasks for
+this project. The first node of this tree defines the project
+properties such as project name and project period.
+
+If there is a tree with tag that matches
+`org-taskjuggler-resource-tag' this tree is taken as resources
+for the project. If no resources are specified, a default
+resource is created and allocated to the project.
+
+Also the TaskJuggler project will be created with default reports
+as defined in `org-taskjuggler-default-reports'.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Return a list of reports."
+ (interactive)
+ (let ((file (org-taskjuggler-export nil subtreep visible-only)))
+ (org-taskjuggler-compile file)))
+
+;;;###autoload
+(defun org-taskjuggler-export-process-and-open (&optional subtreep visible-only)
+ "Export current buffer to a TaskJuggler file, process and open it.
+
+Export and process the file using
+`org-taskjuggler-export-and-process' and open the generated
+reports with a browser.
+
+If you are targeting TaskJuggler 2.4 (see
+`org-taskjuggler-target-version') the processing and display of
+the reports is done using the TaskJuggler GUI."
+ (interactive)
+ (if (< org-taskjuggler-target-version 3.0)
+ (let* ((process-name "TaskJugglerUI")
+ (command
+ (concat process-name " "
+ (org-taskjuggler-export nil subtreep visible-only))))
+ (start-process-shell-command process-name nil command))
+ (dolist (report (org-taskjuggler-export-and-process subtreep visible-only))
+ (org-open-file report))))
+
+(defun org-taskjuggler-compile (file)
+ "Compile a TaskJuggler file.
+
+FILE is the name of the file being compiled. Processing is done
+through the command given in `org-taskjuggler-process-command'.
+
+Return a list of reports."
+ (let* ((full-name (file-truename file))
+ (out-dir
+ (expand-file-name
+ org-taskjuggler-reports-directory (file-name-directory file)))
+ errors)
+ (message (format "Processing TaskJuggler file %s..." file))
+ (save-window-excursion
+ (let ((outbuf (get-buffer-create "*Org Taskjuggler Output*")))
+ (unless (file-directory-p out-dir)
+ (make-directory out-dir t))
+ (with-current-buffer outbuf (erase-buffer))
+ (shell-command
+ (replace-regexp-in-string
+ "%f" (shell-quote-argument full-name)
+ (replace-regexp-in-string
+ "%o" (shell-quote-argument out-dir)
+ org-taskjuggler-process-command t t) t t) outbuf)
+ ;; Collect standard errors from output buffer.
+ (setq errors (org-taskjuggler--collect-errors outbuf)))
+ (if (not errors)
+ (message "Process completed.")
+ (error (format "TaskJuggler failed with errors: %s" errors))))
+ (file-expand-wildcards (format "%s/*.html" out-dir))))
+
+(defun org-taskjuggler--collect-errors (buffer)
+ "Collect some kind of errors from \"tj3\" command output.
+
+BUFFER is the buffer containing output.
+
+Return collected error types as a string, or nil if there was
+none."
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char (point-min))
+ (let ((case-fold-search t)
+ (errors ""))
+ (while (re-search-forward "^.+:[0-9]+: \\(.*\\)$" nil t)
+ (setq errors (concat errors " " (match-string 1))))
+ (and (org-string-nw-p errors) (org-trim errors))))))
+
+
+(provide 'ox-taskjuggler)
+
+;; Local variables:
+;; sentence-end-double-space: t
+;; End:
+
+;;; ox-taskjuggler.el ends here
diff --git a/contrib/scripts/.gitignore b/contrib/scripts/.gitignore
new file mode 100644
index 0000000..20d5925
--- /dev/null
+++ b/contrib/scripts/.gitignore
@@ -0,0 +1 @@
+plantuml.jar
diff --git a/contrib/scripts/StartOzServer.oz b/contrib/scripts/StartOzServer.oz
new file mode 100644
index 0000000..df3ebe6
--- /dev/null
+++ b/contrib/scripts/StartOzServer.oz
@@ -0,0 +1,231 @@
+%%% *************************************************************
+%%% Copyright (C) 2009-2013 Torsten Anders (www.torsten-anders.de)
+%%% This program is free software; you can redistribute it and/or
+%%% modify it under the terms of the GNU General Public License
+%%% as published by the Free Software Foundation; either version 2
+%%% of the License, or (at your option) any later version.
+%%% This program is distributed in the hope that it will be useful,
+%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
+%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+%%% GNU General Public License for more details.
+%%% *************************************************************
+
+%%
+%% This code implements the Oz-side of the Org-babel Oz interface. It
+%% creates a socket server (to which org-babel-oz.el then
+%% connects). Any input to this socket must be an Oz expression. The
+%% input is fed to the OPI oz compiler, and the results are send back
+%% via the socket.
+%%
+
+
+declare
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Accessing the OPI compiler
+%%
+
+MyCompiler = Emacs.condSend.compiler
+
+
+/* % testing
+
+%% Feed an expression (result browsed)
+{MyCompiler enqueue(setSwitch(expression true))}
+{Browse
+ {MyCompiler enqueue(feedVirtualString("1 + 2" return(result: $)))}}
+{MyCompiler enqueue(setSwitch(expression false))}
+
+%% It is really the OPI: I can use declare!
+{MyCompiler enqueue(setSwitch(expression false))}
+{MyCompiler enqueue(feedVirtualString("declare X=3\n{Browse X*X}"))}
+
+%% Note: expressions starting with keyword declare need keyword in
+{MyCompiler enqueue(setSwitch(expression true))}
+{Browse
+ {MyCompiler enqueue(feedVirtualString("declare X=3\nin X*X" return(result: $)))}}
+{MyCompiler enqueue(setSwitch(expression false))}
+
+%% Alternatively you use a session with multiple feeds: first declare (statement), and then feed an expression
+{MyCompiler enqueue(setSwitch(expression false))}
+{MyCompiler enqueue(feedVirtualString("declare X=7" return))}
+{MyCompiler enqueue(setSwitch(expression true))}
+{Browse
+ {MyCompiler enqueue(feedVirtualString("X*X" return(result: $)))}}
+{MyCompiler enqueue(setSwitch(expression false))}
+
+%% !!?? does not work?
+%% return nil in case of any error (division by 0)
+{MyCompiler enqueue(setSwitch(expression true))}
+{Browse
+ {MyCompiler enqueue(feedVirtualString(
+ {Accum ["try\n"
+% "skip\n" % do something in any case..
+ "1 div 0" % my code
+% "1" % my code
+ "\ncatch E then {Error.printException E}\n"
+ "error\n" % always return nil
+ "end\n"]
+ List.append}
+ return(result: $)))}}
+{MyCompiler enqueue(setSwitch(expression false))}
+
+
+%% !! catching some exceptions does not work??
+
+%% exception is not catched
+try {Bla} catch E then {Error.printException E} {Browse nil} end
+
+%% exception is catched
+try {Browse 1 div 0} catch E then {Error.printException E} {Browse nil} end
+{Browse ok}
+
+
+*/
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Socket interface
+%%
+
+
+%%
+%% Create socket
+%%
+
+MyPort = 6001
+
+/** %% Creates a TCP socket server. Expects a Host (e.g., 'localhost') and a PortNo and returns a server plus its corresponding client. This client is an instance of Open.socket, and is the interface for reading and writing into the socket.
+%% MakeServer blocks until the server listens. However, waiting until a connection has been accepted happens in its own thread (i.e. MakeServer does only block until the server listens).
+%% NB: A port can be used only once, so assign it carefully. In case this postnnumber was shortly used before, you may need to wait a bit before reusing it.
+%% */
+%% !! Alternatively, let it assign automatically and output the port number..
+%%
+%% NOTE: for supporting multiple connections see http://www.mozart-oz.org/documentation/op/node13.html#section.sockets.accept
+proc {MakeServer Host PortNo ?MyServer ?MyClient}
+ proc {Accept MyClient}
+ thread H in % P
+ %% suspends until a connection has been accepted
+ {MyServer accept(host:H
+ acceptClass:Open.socket
+ accepted:?MyClient)}
+% {Myserver accept(host:H port:P)} % suspends until a connection has been accepted
+ %% !!?? port number of client is usually created randomly..
+ {System.showInfo "% connection accepted from host "#H}
+ end
+ %% !!???
+ %% If Accept is called recursively, then server accepts multiple connections. These share the same compiler instance (e.g. variable bindings are shared). For multiple independent compiler instances call the OzServer application multiple times.
+ %% However, how shall the output for multiple connections be sorted?? Would using the different client sockets created with the Server accept method work?
+ %% NB: The number of clients accepted concurrently must be limited to the number set by {MyServer listen}
+ % {Accept}
+ end
+in
+ MyServer = {New Open.socket init}
+ %% To avoid problems with portnumbers, the port could be assigned automatically and then output..
+ %%{MyServer bind(port:PortNo)}
+ {MyServer bind(host:Host takePort:PortNo)}
+ {MyServer listen}
+ {System.showInfo "% OzServer started at host "#Host#" and port "#PortNo}
+ MyClient = {Accept}
+end
+%%
+MySocket = {MakeServer localhost MyPort _/*MyServer*/}
+
+
+%%
+%% Read socket input
+%%
+
+declare
+%% Copied from OzServer/source/Socket.oz
+local
+ proc {Aux Socket Size Stream}
+ In = {Socket read(list:$
+ size:Size)}
+ in
+ {Wait In}
+ %% !! Is this the right way to stop the processing??
+ %%
+ %% abort condition when client stream ended (i.e. nothing was sent)
+ if In == nil
+ then {System.showInfo "socket stream ended"}
+ Stream = nil
+ else Stream = In | {Aux Socket Size}
+ end
+ end
+in
+ /** %% The socket Server returns a stream of the strings it receives. The Server always waits until someone writes something into the socket, then the input is immediately written to a stream and the Server waits again.
+ %% */
+ proc {ReadToStream Socket Size Xs}
+ thread {Aux Socket Size Xs} end
+ end
+end
+
+/* % test
+
+MyStream = {ReadToStream MySocket 1024}
+
+*/
+
+/* % test
+
+%% writing
+{MySocket write(vs:"this is a test")}
+
+*/
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Send socket input to compiler and send results back to socket
+%%
+
+%% NOTE: Input code must be expression
+thread
+ {ForAll {ReadToStream MySocket 1024}
+ proc {$ Code}
+ Result
+ %% Catch any exception (so the will not cause blocking) and return nil in that case
+ FullCode = {Accum ["try\n"
+% "skip\n" % do something in any case..
+ Code
+ "\ncatch E then {Error.printException E}\n"
+ "error\n" % in case of an error, return 'error'
+ "end\n"]
+ List.append}
+ in
+ %% ?? Should I make setting switches etc atomic?
+ {MyCompiler enqueue(setSwitch(expression true))}
+ {MyCompiler enqueue(feedVirtualString(FullCode return(result: ?Result)))}
+ {MyCompiler enqueue(setSwitch(expression false))}
+ %%
+ {Wait Result}
+ {MySocket write(vs: if {VirtualString.is Result}
+ then Result
+ else {Value.toVirtualString Result 1000 1000}
+ end)}
+ {Show 'Org-babel result: '#Result}
+ end}
+end
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%
+%% Aux defs
+%%
+
+/** %% Binds the accumulation of the binary function Fn on all neighbors in Xs to Y. E.g., Accum returns the sum in Xs if Fn is Number.'+'.
+%% */
+proc {Accum Xs Fn Y}
+ {List.foldL Xs.2 Fn Xs.1 Y}
+end
+
+
+
+
+
+
+
diff --git a/contrib/scripts/dir2org.zsh b/contrib/scripts/dir2org.zsh
new file mode 100755
index 0000000..f91ff17
--- /dev/null
+++ b/contrib/scripts/dir2org.zsh
@@ -0,0 +1,56 @@
+#!/usr/bin/env zsh
+
+# desc:
+#
+# Output an org compatible structure representing the filesystem from
+# the point passed on the command line (or . by default).
+#
+# options:
+# none
+#
+# usage:
+# dir2org.zsh [DIR]...
+#
+# author:
+# Phil Jackson (phil@shellarchive.co.uk)
+
+set -e
+
+function headline {
+ local depth="${1}"
+ local text="${2}"
+
+ printf "%${depth}s %s" "" | tr ' ' '*'
+ echo " ${text}"
+}
+
+function scan_and_populate {
+ local depth="${1}"
+ local dir="${2}"
+
+ headline ${depth} "${dir}"
+
+ # if there is no files in dir then just move on
+ [[ $(ls "${dir}" | wc -l) -eq 0 ]] && return
+
+ (( depth += 1 ))
+
+ for f in $(ls -d "${dir}"/*); do
+ if [ -d "${f}" ]; then
+ scan_and_populate ${depth} "${f}"
+ else
+ headline ${depth} "[[file://${f}][${${f##*/}%.*}]]"
+ fi
+ done
+
+ (( depth -= 1 ))
+}
+
+function main {
+ local scan_dir="${1:-$(pwd)}"
+ local depth=0
+
+ scan_and_populate ${depth} "${scan_dir}"
+}
+
+main "${@}"
diff --git a/contrib/scripts/docco.css b/contrib/scripts/docco.css
new file mode 100644
index 0000000..9030b6c
--- /dev/null
+++ b/contrib/scripts/docco.css
@@ -0,0 +1,185 @@
+/*--------------------- Layout and Typography ----------------------------*/
+body {
+ font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif;
+ font-size: 15px;
+ line-height: 22px;
+ color: #252519;
+ margin: 0; padding: 0;
+}
+a {
+ color: #261a3b;
+}
+ a:visited {
+ color: #261a3b;
+ }
+p {
+ margin: 0 0 15px 0;
+}
+h1, h2, h3, h4, h5, h6 {
+ margin: 0px 0 15px 0;
+}
+ h1 {
+ margin-top: 40px;
+ }
+#container {
+ position: relative;
+}
+#background {
+ position: fixed;
+ top: 0; left: 525px; right: 0; bottom: 0;
+ background: #f5f5ff;
+ border-left: 1px solid #e5e5ee;
+ z-index: -1;
+}
+#jump_to, #jump_page {
+ background: white;
+ -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777;
+ -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px;
+ font: 10px Arial;
+ text-transform: uppercase;
+ cursor: pointer;
+ text-align: right;
+}
+#jump_to, #jump_wrapper {
+ position: fixed;
+ right: 0; top: 0;
+ padding: 5px 10px;
+}
+ #jump_wrapper {
+ padding: 0;
+ display: none;
+ }
+ #jump_to:hover #jump_wrapper {
+ display: block;
+ }
+ #jump_page {
+ padding: 5px 0 3px;
+ margin: 0 0 25px 25px;
+ }
+ #jump_page .source {
+ display: block;
+ padding: 5px 10px;
+ text-decoration: none;
+ border-top: 1px solid #eee;
+ }
+ #jump_page .source:hover {
+ background: #f5f5ff;
+ }
+ #jump_page .source:first-child {
+ }
+table td {
+ border: 0;
+ outline: 0;
+}
+ td.docs, th.docs {
+ max-width: 450px;
+ min-width: 450px;
+ min-height: 5px;
+ padding: 10px 25px 1px 50px;
+ overflow-x: hidden;
+ vertical-align: top;
+ text-align: left;
+ }
+ .docs pre {
+ margin: 15px 0 15px;
+ padding-left: 15px;
+ }
+ .docs p tt, .docs p code {
+ background: #f8f8ff;
+ border: 1px solid #dedede;
+ font-size: 12px;
+ padding: 0 0.2em;
+ }
+ .pilwrap {
+ position: relative;
+ }
+ .pilcrow {
+ font: 12px Arial;
+ text-decoration: none;
+ color: #454545;
+ position: absolute;
+ top: 3px; left: -20px;
+ padding: 1px 2px;
+ opacity: 0;
+ -webkit-transition: opacity 0.2s linear;
+ }
+ td.docs:hover .pilcrow {
+ opacity: 1;
+ }
+ td.code, th.code {
+ padding: 14px 15px 16px 25px;
+ width: 100%;
+ vertical-align: top;
+ border-left: 1px solid #e5e5ee;
+ }
+ pre, tt, code {
+ font-size: 12px; line-height: 18px;
+ font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace;
+ margin: 0; padding: 0;
+ }
+
+
+/*---------------------- Syntax Highlighting -----------------------------*/
+td.linenos { background-color: #f0f0f0; padding-right: 10px; }
+span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }
+body .hll { background-color: #ffffcc }
+body .c { color: #408080; font-style: italic } /* Comment */
+body .err { border: 1px solid #FF0000 } /* Error */
+body .k { color: #954121 } /* Keyword */
+body .o { color: #666666 } /* Operator */
+body .cm { color: #408080; font-style: italic } /* Comment.Multiline */
+body .cp { color: #BC7A00 } /* Comment.Preproc */
+body .c1 { color: #408080; font-style: italic } /* Comment.Single */
+body .cs { color: #408080; font-style: italic } /* Comment.Special */
+body .gd { color: #A00000 } /* Generic.Deleted */
+body .ge { font-style: italic } /* Generic.Emph */
+body .gr { color: #FF0000 } /* Generic.Error */
+body .gh { color: #000080; font-weight: bold } /* Generic.Heading */
+body .gi { color: #00A000 } /* Generic.Inserted */
+body .go { color: #808080 } /* Generic.Output */
+body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
+body .gs { font-weight: bold } /* Generic.Strong */
+body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
+body .gt { color: #0040D0 } /* Generic.Traceback */
+body .kc { color: #954121 } /* Keyword.Constant */
+body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */
+body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */
+body .kp { color: #954121 } /* Keyword.Pseudo */
+body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */
+body .kt { color: #B00040 } /* Keyword.Type */
+body .m { color: #666666 } /* Literal.Number */
+body .s { color: #219161 } /* Literal.String */
+body .na { color: #7D9029 } /* Name.Attribute */
+body .nb { color: #954121 } /* Name.Builtin */
+body .nc { color: #0000FF; font-weight: bold } /* Name.Class */
+body .no { color: #880000 } /* Name.Constant */
+body .nd { color: #AA22FF } /* Name.Decorator */
+body .ni { color: #999999; font-weight: bold } /* Name.Entity */
+body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
+body .nf { color: #0000FF } /* Name.Function */
+body .nl { color: #A0A000 } /* Name.Label */
+body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
+body .nt { color: #954121; font-weight: bold } /* Name.Tag */
+body .nv { color: #19469D } /* Name.Variable */
+body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
+body .w { color: #bbbbbb } /* Text.Whitespace */
+body .mf { color: #666666 } /* Literal.Number.Float */
+body .mh { color: #666666 } /* Literal.Number.Hex */
+body .mi { color: #666666 } /* Literal.Number.Integer */
+body .mo { color: #666666 } /* Literal.Number.Oct */
+body .sb { color: #219161 } /* Literal.String.Backtick */
+body .sc { color: #219161 } /* Literal.String.Char */
+body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */
+body .s2 { color: #219161 } /* Literal.String.Double */
+body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
+body .sh { color: #219161 } /* Literal.String.Heredoc */
+body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
+body .sx { color: #954121 } /* Literal.String.Other */
+body .sr { color: #BB6688 } /* Literal.String.Regex */
+body .s1 { color: #219161 } /* Literal.String.Single */
+body .ss { color: #19469D } /* Literal.String.Symbol */
+body .bp { color: #954121 } /* Name.Builtin.Pseudo */
+body .vc { color: #19469D } /* Name.Variable.Class */
+body .vg { color: #19469D } /* Name.Variable.Global */
+body .vi { color: #19469D } /* Name.Variable.Instance */
+body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file
diff --git a/contrib/scripts/org-docco.org b/contrib/scripts/org-docco.org
new file mode 100644
index 0000000..cb75359
--- /dev/null
+++ b/contrib/scripts/org-docco.org
@@ -0,0 +1,206 @@
+#+Title: Org-Docco
+#+Author: Eric Schulte
+#+Style: <link rel="stylesheet" href="docco.css" type="text/css">
+#+Property: tangle yes
+
+The =docco= tool (see http://jashkenas.github.com/docco/) generates
+HTML from JavaScript source code providing an attractive side-by-side
+display of source code and comments. This file (see [[http://orgmode.org/cgit.cgi/org-mode.git/plain/contrib/scripts/org-docco.org][org-docco.org]])
+generates the same type of output from Org-mode documents with code
+embedded in code blocks.
+
+The way this works is an Org-mode document with embedded code blocks
+is exported to html using the standard Org-mode export functions.
+This file defines a new function named =org-docco-buffer= which, when
+added to the =org-export-html-final-hook=, will be run automatically
+as part of the Org-mod export process doccoizing your Org-mode
+document.
+
+A pure source code file can be extracted (or "/tangled/") from the
+Org-mode document using the normal =org-babel-tangle= function. See
+[[http://orgmode.org/manual/Working-With-Source-Code.html][Working With Source Code]] chapter of the Org-mode manual for more
+information on using code blocks in Org-mode files.
+
+*Disclaimer*: this currently only works on /very/ simple Org-mode
+files which have no headings but rather are just a collection of
+alternating text and code blocks. It wouldn't be difficult to
+generalize the following code so that it could be run in particular
+sub-trees but I simply don't have the time to do so myself, and this
+version perfectly satisfies my own limit needs. I make no promises to
+support this code moving forward. /Caveat Emptor/
+
+#+begin_src emacs-lisp :padline no
+;;; org-docco.el --- docco type html generation from Org-mode
+
+;; Copyright (C) 2012 Eric Schulte
+
+;; Author: Eric Schulte
+;; Keywords: org-mode, literate programming, html
+;; Homepage: http://orgmode.org/worg/org-contrib/org-mime.php
+;; Version: 0.01
+
+;; This file is not part of GNU Emacs.
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;; <- look over there
+#+end_src
+
+The =cl= package provides all of the state-changing functions used
+below e.g., =push= and =incf=. It looks like a namespace-safe version
+of =cl= may soon be permissible for use in official Emacs packages.
+#+begin_src emacs-lisp
+;;; Code:
+(require 'cl)
+#+end_src
+
+This is a function which returns the buffer positions of matching
+regular expressions. It has two special features...
+1. It only counts matched instances of =beg-re= and =end-re= which are
+ properly nested, so for example if =beg-re= and =end-re= are set to
+ =(= and =)= respectively and we run this against the following,
+ : 1 2 3 4 5 6
+ : | | | | | |
+ : v v v v v v
+ : (foo (bar baz) (qux) quux)
+ it will return 1 and 6 rather than 1 and 3.
+2. It uses [[www.gnu.org/s/emacs/manual/html_node/elisp/Markers.html][markers]] which save their position in a buffer even as the
+ buffer is changed (e.g., by me adding in extra HTML text).
+#+begin_src emacs-lisp
+(defun org-docco-balanced-re (beg-re end-re)
+ "Return the beginning and of a balanced regexp."
+ (save-excursion
+ (save-match-data
+ (let ((both-re (concat "\\(" beg-re "\\|" end-re "\\)"))
+ (beg-count 0) (end-count 0)
+ beg end)
+ (when (re-search-forward beg-re nil t)
+ (goto-char (match-beginning 0))
+ (setq beg (point-marker))
+ (incf beg-count)
+ (goto-char (match-end 0))
+ (while (and (not end) (re-search-forward both-re nil t))
+ (goto-char (match-beginning 0))
+ (cond ((looking-at beg-re) (incf beg-count))
+ ((looking-at end-re) (incf end-count))
+ (:otherwise (error "miss-matched")))
+ (goto-char (match-end 0))
+ (when (= beg-count end-count) (setq end (point-marker))))
+ (when end (cons beg end)))))))
+#+end_src
+
+This ugly large function does the actual conversion. It wraps the
+entire main content =div= of the exported Org-mode html into a single
+large table. Each row of the table has documentation on the left side
+and code on the right side. This function has two parts.
+1. We use =(org-docco-balanced-re "<div" "</div>")= to find the
+ beginning and end of the main content div. We then break up this
+ div at =<pre></pre>= boundaries with multiple calls to
+ =(org-docco-balanced-re "<pre class\"src" "</pre>")=.
+2. With all documentation/code boundaries in hand we step through the
+ buffer inserting the table html code at boundary locations.
+#+begin_src emacs-lisp
+(defun org-docco-buffer ()
+ "Call from within an HTML buffer to doccoize it."
+ (interactive)
+ (let ((table-start "<table>\n")
+ (doc-row-start "<tr><th class=\"docs\">\n") (doc-row-end "</th>\n")
+ (code-row-start " <td class=\"code\">\n") (code-row-end "</td></tr>\n")
+ (table-end "</table>" )
+ pair transition-points next)
+ (save-excursion
+ (save-match-data
+ (goto-char (point-min))
+ (when (re-search-forward "<div id=\"content\">" nil t)
+ (goto-char (match-end 0))
+ (push (point-marker) transition-points)
+ (goto-char (match-beginning 0))
+ (setq pair (org-docco-balanced-re "<div" "</div>"))
+ (while (setq next (org-docco-balanced-re "<pre class=\"src" "</pre>"))
+ (goto-char (cdr next))
+ (push (car next) transition-points)
+ (push (cdr next) transition-points))
+ (goto-char (cdr pair))
+ (push (and (re-search-backward "</div>" nil t) (point-marker))
+ transition-points)
+ ;; collected transitions, so build the table
+ (setq transition-points (nreverse transition-points))
+ (goto-char (pop transition-points))
+ (insert table-start doc-row-start)
+ (while (> (length transition-points) 1)
+ (goto-char (pop transition-points))
+ (insert doc-row-end code-row-start)
+ (goto-char (pop transition-points))
+ (insert code-row-end doc-row-start))
+ (goto-char (pop transition-points))
+ (insert code-row-end table-end)
+ (unless (null transition-points)
+ (error "leftover points")))))))
+#+end_src
+
+We'll use Emacs [[http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html][File Local Variables]] and the
+=org-export-html-final-hook= to control which buffers have
+=org-docco-buffer= run as part of their export process.
+#+begin_src emacs-lisp
+ (defvar org-docco-doccoize-me nil
+ "File local variable controlling if html export should be doccoized.")
+ (make-local-variable 'org-docco-doccoize-me)
+#+end_src
+
+A simple function will conditionally process HTML output based on the
+value of this variable.
+#+begin_src emacs-lisp
+ (defun org-docco-buffer-maybe ()
+ (when org-docco-doccoize-me (org-docco-buffer)))
+#+end_src
+
+Finally this function is added to the =org-export-html-final-hook=.
+#+begin_src emacs-lisp
+ (add-hook 'org-export-html-final-hook #'org-docco-buffer-maybe)
+#+end_src
+
+That's it. To use this simply;
+1. Checkout this file from https://github.com/eschulte/org-docco,
+ : git clone git://github.com/eschulte/org-docco.git
+ and open it using Emacs.
+2. Tangle =org-docco.el= out of this file by calling
+ =org-babel-tangle= or =C-c C-v t=.
+3. Load the resulting Emacs Lisp file.
+4. Execute the following in any Org-mode buffer to add file local
+ variable declarations which will enable post-processed with
+ =org-docco-buffer=.
+ : (add-file-local-variable 'org-export-html-postamble nil)
+ : (add-file-local-variable 'org-export-html-style-include-default nil)
+ : (add-file-local-variable 'org-docco-doccoize-me t)
+ And add the following style declaration to make use of the
+ =docco.css= style sheet taken directly from
+ https://github.com/jashkenas/docco.
+ : #+Style: <link rel="stylesheet" href="docco.css" type="text/css">
+
+#+begin_src emacs-lisp
+(provide 'org-docco)
+;;; org-docco.el ends here
+#+end_src
+
+# Local Variables:
+# org-export-html-postamble: nil
+# org-export-html-style-include-default: nil
+# org-docco-doccoize-me: t
+# End:
diff --git a/contrib/scripts/org2hpda b/contrib/scripts/org2hpda
new file mode 100755
index 0000000..07f29d9
--- /dev/null
+++ b/contrib/scripts/org2hpda
@@ -0,0 +1,106 @@
+# org2hpda - a small utility to generate hipster pda style printouts from org mode
+# Copyright (C) 2007-2013 Christian Egli
+#
+# Version: 0.6
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+# Commentary:
+# ===========
+#
+# set cal-tex-diary to true so that diary entries show up in the calendar
+#
+# Usage:
+# ======
+#
+# run this makefile with
+#
+# make -f org2hpda
+#
+# The makfile will take the entries from your diary file and generate
+# two PDFs containing nicely printed weekly and monthly calendars. One
+# is done in the style of a pocketMod (http://www.pocketmod.com/) and
+# the other is done in the style of the Hipster PDA
+# (http://en.wikipedia.org/wiki/Hipster_PDA).
+#
+# Requirements:
+# =============
+#
+# the pdf* commands are part of the pdfjam package which can be found
+# at http://www.warwick.ac.uk/go/pdfjam
+
+EMACS = emacs -batch -l ~/.emacs
+LATEX = latex
+DIARY = $($(EMACS) -eval "diary-file")
+
+# Number of weeks to be printed. Should be a multiple of 4, because 4
+# of them are merged on one page. Can be set when invoking the script
+# as follows: make NUMBER_OF_WEEKS=8 -f org2hpda
+NUMBER_OF_WEEKS = 4
+
+hipsterFiles = weekCalendar.pdf yearCalendar.pdf monthCalendar3.pdf monthCalendar2.pdf monthCalendar1.pdf
+pocketModFiles = weekCalendar.pdf yearCalendar-rotated.pdf \
+ monthCalendar3-rotated.pdf monthCalendar2-rotated.pdf monthCalendar1-rotated.pdf
+
+all: pocketMod.pdf hipsterPDA.pdf
+
+%.dvi: %.tex
+ # Quick hack to massage the LaTeX produced by cal-tex
+ # quote '@', then increase font size of week calendars,
+ # increase font of diary entries in moth calendar and
+ # finally reduce links to their destination, i.e.
+ # change '[[http://foo][bar]]' to 'bar'
+ sed -e 's/\\verb|@|/\@/g' \
+ -e 's/documentclass\[11pt\]/documentclass[12pt]/g' \
+ -e 's/{\\tiny \\raggedright #3}/{\\small \\raggedright #3}/g' \
+ -e 's/\[\[[^]]\+\]\[\([^]]\+\)\]\]/\1/g' \
+ < $< > /tmp/temp-org-file.$$$$; mv /tmp/temp-org-file.$$$$ $<
+ $(LATEX) $^
+
+%.pdf: %.dvi
+ dvipdf $^
+
+%-rotated.pdf: %.pdf
+ cp $^ $@
+ for n in 1 2 3; do \
+ pdf90 --quiet --outfile tmp.pdf $@; mv tmp.pdf $@; \
+ done
+
+weekCalendar.tex: $(DIARY)
+ $(EMACS) -eval "(progn (calendar) (cal-tex-cursor-week-iso $(NUMBER_OF_WEEKS)) (with-current-buffer cal-tex-buffer (write-file \"$@\")))"
+
+monthCalendar1.tex: $(DIARY)
+ $(EMACS) -eval "(progn (calendar) (cal-tex-cursor-month-landscape 1) (with-current-buffer cal-tex-buffer (write-file \"$@\")))"
+
+monthCalendar2.tex: $(DIARY)
+ $(EMACS) -eval "(progn (calendar) (calendar-forward-month 1) (cal-tex-cursor-month-landscape 1) (with-current-buffer cal-tex-buffer (write-file \"$@\")))"
+
+monthCalendar3.tex: $(DIARY)
+ $(EMACS) -eval "(progn (calendar) (calendar-forward-month 2) (cal-tex-cursor-month-landscape 1) (with-current-buffer cal-tex-buffer (write-file \"$@\")))"
+
+yearCalendar.tex: $(DIARY)
+ $(EMACS) -eval "(progn (calendar) (calendar-forward-month 2) (cal-tex-cursor-year-landscape 1) (with-current-buffer cal-tex-buffer (write-file \"$@\")))"
+
+pocketMod.pdf: $(pocketModFiles)
+ pdfjoin --quiet --outfile tmp.pdf $^
+ pdfnup tmp.pdf --quiet --outfile $@ --nup 4x2 --frame true
+
+hipsterPDA.pdf: $(hipsterFiles)
+ pdfnup weekCalendar.pdf --quiet --outfile page1.pdf --batch --nup 2x2 --frame true --no-landscape
+ pdfjoin --quiet --outfile tmp.pdf monthCalendar[1-3]-rotated.pdf yearCalendar-rotated.pdf
+ pdfnup tmp.pdf --quiet --outfile page2.pdf --batch --nup 2x2 --frame true --no-landscape
+ pdfjoin --quiet --outfile $@ page1.pdf page2.pdf
+
+clean:
+ rm -rf *.aux *.dvi *.tex *.log *.pdf
diff --git a/contrib/scripts/staticmathjax/.gitignore b/contrib/scripts/staticmathjax/.gitignore
new file mode 100644
index 0000000..b25c15b
--- /dev/null
+++ b/contrib/scripts/staticmathjax/.gitignore
@@ -0,0 +1 @@
+*~
diff --git a/contrib/scripts/staticmathjax/README.org b/contrib/scripts/staticmathjax/README.org
new file mode 100644
index 0000000..d28fc90
--- /dev/null
+++ b/contrib/scripts/staticmathjax/README.org
@@ -0,0 +1,79 @@
+Static MathJax v0.1 README
+#+AUTHOR: Jan Böcker <jan.boecker@jboecker.de>
+
+Static MathJax is a XULRunner application which loads a HTML input
+file that uses MathJax into a browser, waits until MathJax is done
+processing, and then writes the formatted result to an output HTML
+file.
+
+I have only tested exports from Emacs Org-mode as input files. (As of
+2010-08-14, MathJax is used by default with HTML exports in the
+current Org development version.)
+
+Optionally, references to the math fonts used will be converted to
+"data:" URIs, thus embedding the font data into the HTML file itself.
+(see [[http://en.wikipedia.org/wiki/Data_URI_scheme]])
+
+The code is licensed under the GNU General Public License version
+2, or, at your option, any later version.
+
+
+* Usage
+ To run Static MathJax, an existing XULRunner installation is
+ required. From the directory to which you unpacked Static MathJax,
+ run:
+
+ xulrunner application.ini <--embed-fonts | --final-mathjax-url <URL>>
+ <input file> <output file>
+
+ If you prefer to call "staticmathjax" instead of "xulrunner
+ application.ini", link xulrunner-stub into the directory:
+ ln /usr/lib/xulrunner-1.9.2.8/xulrunner-stub ./staticmathjax
+
+ - input file ::
+ name of the input file (the result of a HTML export
+ from Org-mode). It is assumed that this file uses the
+ UTF-8 character encoding.
+
+ - output file ::
+ name of the output file.
+
+ - --embed-fonts ::
+ if specified, the math fonts will be embedded into
+ the output file using data: URIs
+
+ - --final-mathjax-url <URL> ::
+ if --embed-fonts is not specified, this
+ must be the URL to a MathJax installation folder (e.g. "MathJax"
+ if MathJax is installed in a subdirectory, or
+ "http://orgmode.org/mathjax" to use the version hosted on the Org
+ website.
+
+ All references to math fonts in the output file will point to
+ this directory.
+
+* Caveats
+
+ The input file must not use a MathJax installation on the
+ web. Otherwise, due to a security feature of Firefox, MathJax will
+ fallback to image fonts. If you have unpacked MathJax to a
+ subdirectory "MathJax", specify the following in your Org file:
+
+ #+MathJax: path:"MathJax"
+
+ The math is rendered in Firefox, so MathJax applies its
+ Firefox-specific settings. When viewing the output files in other
+ browsers, it will look slightly different than the result that
+ running MathJax in that browser would produce.
+
+ Internet Explorer does not use the correct font, because it only
+ supports the EOT font format. For all other browsers (including
+ Firefox), MathJax uses the OTF font format.
+
+ Embedding fonts into the HTML file wastes some space due to the
+ base64 encoding used in data: URIs.
+
+ I have found no way to access stdout or set an exit code in an
+ XULRunner app, so any code which calls Static MathJax has no idea if
+ processing was successful and when an error occurs, graphical
+ message boxes are displayed.
diff --git a/contrib/scripts/staticmathjax/application.ini b/contrib/scripts/staticmathjax/application.ini
new file mode 100644
index 0000000..522376d
--- /dev/null
+++ b/contrib/scripts/staticmathjax/application.ini
@@ -0,0 +1,11 @@
+[App]
+Vendor=Jan Boecker
+Name=StaticMathJax
+Version=0.2
+BuildID=2
+Copyright=Copyright (c) 2010, 2013 Jan Boecker
+ID=xulapp@jboecker.de
+
+[Gecko]
+MinVersion=1.8
+
diff --git a/contrib/scripts/staticmathjax/chrome/chrome.manifest b/contrib/scripts/staticmathjax/chrome/chrome.manifest
new file mode 100644
index 0000000..a05d8c8
--- /dev/null
+++ b/contrib/scripts/staticmathjax/chrome/chrome.manifest
@@ -0,0 +1 @@
+content staticmathjax file:content/
diff --git a/contrib/scripts/staticmathjax/chrome/content/main.js b/contrib/scripts/staticmathjax/chrome/content/main.js
new file mode 100644
index 0000000..2e71f3b
--- /dev/null
+++ b/contrib/scripts/staticmathjax/chrome/content/main.js
@@ -0,0 +1,198 @@
+var docFrame;
+var logtextbox;
+var destFile;
+var embedFonts = false;
+var finalMathJaxURL = null;
+
+function log(text)
+{
+ logtextbox.setAttribute("value", logtextbox.getAttribute("value") + "\n" + text);
+}
+
+function init()
+{
+ try {
+ docFrame = document.getElementById("docFrame");
+ logtextbox = document.getElementById("logtextbox");
+
+ // parse command line arguments
+ var cmdLine = window.arguments[0];
+ cmdLine = cmdLine.QueryInterface(Components.interfaces.nsICommandLine);
+
+ embedFonts = cmdLine.handleFlag("embed-fonts", false);
+ finalMathJaxURL = cmdLine.handleFlagWithParam("final-mathjax-url", false);
+
+ if (!embedFonts && !finalMathJaxURL) {
+ alert("You must eiher specify --embed-fonts or --final-mathjax-url");
+ window.close();
+ return;
+ }
+
+ sourceFilePath = cmdLine.getArgument(0);
+ destFilePath = cmdLine.getArgument(1);
+ if ( !sourceFilePath || !destFilePath ) {
+ alert("Not enough parameters, expecting two arguments:\nInput file, output file");
+ window.close();
+ return;
+ }
+
+ sourceFile = cmdLine.resolveFile(sourceFilePath);
+ if (! (sourceFile.exists() && sourceFile.isFile()) ) {
+ alert("Invalid source file path.");
+ window.close();
+ return;
+ }
+ sourceURI = cmdLine.resolveURI(sourceFilePath);
+
+ // create a nsIFile object for the output file
+ try{
+ destFile = cmdLine.resolveURI(destFilePath).QueryInterface(Components.interfaces.nsIFileURL).file;
+ }catch(e){
+ alert("Invalid destination file.\n\nException:\n" + e);
+ window.close();
+ return;
+ }
+
+ // add iframeLoaded() as an onload event handler, then navigate to the source file
+ docFrame.addEventListener("DOMContentLoaded", iframeLoaded, true);
+ docFrame.setAttribute("src", sourceURI.spec);
+
+ } catch (e) {
+ alert("Error in init():\n\n" + e);
+ window.close();
+ return;
+ }
+}
+
+function iframeLoaded()
+{
+ /*
+ // print every MathJax signal to the log
+ docFrame.contentWindow.MathJax.Hub.Startup.signal.Interest(
+ function (message) {log("Startup: "+message)}
+ );
+ docFrame.contentWindow.MathJax.Hub.signal.Interest(
+ function (message) {log("Hub: "+message)}
+ );
+ */
+
+ // tell MathJax to call serialize() when finished
+ docFrame.contentWindow.MathJax.Hub.Register.StartupHook("End", function() {serialize();});
+}
+
+function fileURLtoDataURI(url)
+{
+ var ios = Components.classes["@mozilla.org/network/io-service;1"]
+ .getService(Components.interfaces.nsIIOService);
+ var url_object = ios.newURI(url, "", null);
+ var file = url_object.QueryInterface(Components.interfaces.nsIFileURL).file;
+
+ var data = "";
+ var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
+ createInstance(Components.interfaces.nsIFileInputStream);
+ fstream.init(file, -1, -1, false);
+ var bstream = Components.classes["@mozilla.org/binaryinputstream;1"].
+ createInstance(Components.interfaces.nsIBinaryInputStream);
+ bstream.setInputStream(fstream);
+
+ var bytes = bstream.readBytes(bstream.available());
+ b64bytes = btoa(bytes);
+
+ return "data:;base64," + b64bytes;
+
+}
+
+function serialize()
+{
+ var MathJaxURL = docFrame.contentWindow.MathJax.Hub.config.root;
+
+ var searchURIList = new Array();
+ var replacementURIList = new Array();
+
+ log("serialize: preprocessing");
+
+ // remove the MathJax status message window
+ msgdiv = docFrame.contentDocument.getElementById("MathJax_Message");
+ msgdiv.parentNode.removeChild(msgdiv);
+
+ /* Loop through all CSS rules to find all @font-face rules.
+ At this point, they refer to local absolute paths using file:// URLs.
+ Replace them either with appropriate URLs relative to finalMathJaxURL
+ or with data URIs. */
+
+ for (var i = 0; i<docFrame.contentDocument.styleSheets.length; i++) {
+ var stylesheet = docFrame.contentDocument.styleSheets[i];
+
+ for (var j=0; j< stylesheet.cssRules.length; j++) {
+ var rule = stylesheet.cssRules[j];
+ if (rule.cssText.match("font-face")) {
+
+ url = rule.style.getPropertyValue("src");
+ url = url.match(/url\(\"(.+)\"\)/)[1];
+
+ // Since the properties seem read-only here, we populate
+ // searchURIList and replacementURIList to do text substitution
+ // after serialization
+ searchURIList.push(url);
+ if (embedFonts) {
+ replacementURIList.push(fileURLtoDataURI(url));
+ } else {
+ replacementURIList.push(url.replace(MathJaxURL, finalMathJaxURL));
+ }
+ }
+ }
+ }
+
+
+ // find and remove the MathJax <script> tag
+ try{
+ var scriptTags = docFrame.contentDocument.getElementsByTagName("script");
+ for (var i=0; i<scriptTags.length; i++) {
+ if (scriptTags[i].getAttribute("src") && scriptTags[i].getAttribute("src").match(/MathJax.js/i))
+ scriptTags[i].parentNode.removeChild(scriptTags[i]);
+ }
+ }catch(e){alert(e);}
+
+ log("serialize: serializing");
+
+ var serializer = new XMLSerializer();
+ var xhtml = serializer.serializeToString(docFrame.contentDocument);
+
+ log("serialize: postprocessing");
+ // make the MathJax URL relative again
+ // xhtml = xhtml.replace(findMathJaxURL, "MathJax");
+
+ try{
+ r1 = RegExp("&lt;!--/\\*--&gt;&lt;!\\[CDATA\\[/\\*&gt;&lt;!--\\*/", "g");
+ xhtml = xhtml.replace(r1, "");
+ r2 = RegExp("/\\*\\]\\]&gt;\\*/--&gt;", "g");
+ xhtml = xhtml.replace(r2, "");
+ r3 = RegExp("/\\*\\]\\]&gt;\\*///--&gt;", "g");
+ xhtml = xhtml.replace(r3, "");
+ }catch(e){alert(e);}
+ for (var i=0; i<searchURIList.length; i++)
+ xhtml = xhtml.replace(searchURIList[i], replacementURIList[i]);
+
+ save(xhtml);
+ window.close();
+}
+
+function save(xhtml)
+{
+ try {
+ var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
+ createInstance(Components.interfaces.nsIFileOutputStream);
+
+ foStream.init(destFile, 0x02 | 0x08 | 0x20, 0666, 0);
+ // write, create, truncate
+
+ // write in UTF-8 encoding
+ var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
+ createInstance(Components.interfaces.nsIConverterOutputStream);
+ converter.init(foStream, "UTF-8", 0, 0);
+ converter.writeString(xhtml);
+ converter.close(); // this closes foStream
+ } catch (e) {
+ alert("Error in save():\n\n" + e);
+ }
+}
diff --git a/contrib/scripts/staticmathjax/chrome/content/main.xul b/contrib/scripts/staticmathjax/chrome/content/main.xul
new file mode 100644
index 0000000..35a00f2
--- /dev/null
+++ b/contrib/scripts/staticmathjax/chrome/content/main.xul
@@ -0,0 +1,11 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+
+<window onload="init();" id="main" title="Static MathJax" width="300" height="300"
+xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+
+<script language="JavaScript" src="chrome://staticmathjax/content/main.js"/>
+
+ <browser flex="1" id="docFrame" src="" style="background-color:white;"/>
+ <textbox flex="1" id="logtextbox" multiline="true" style="display:none;"/>
+</window>
diff --git a/contrib/scripts/staticmathjax/defaults/preferences/prefs.js b/contrib/scripts/staticmathjax/defaults/preferences/prefs.js
new file mode 100644
index 0000000..0532ce0
--- /dev/null
+++ b/contrib/scripts/staticmathjax/defaults/preferences/prefs.js
@@ -0,0 +1 @@
+pref("toolkit.defaultChromeURI", "chrome://staticmathjax/content/main.xul");
diff --git a/contrib/scripts/x11idle.c b/contrib/scripts/x11idle.c
new file mode 100644
index 0000000..22cefe1
--- /dev/null
+++ b/contrib/scripts/x11idle.c
@@ -0,0 +1,28 @@
+#include <X11/extensions/scrnsaver.h>
+#include <stdio.h>
+
+/* Based on code from
+ * http://coderrr.wordpress.com/2008/04/20/getting-idle-time-in-unix/
+ *
+ * compile with 'gcc -l Xss x11idle.c -o x11idle' and copy x11idle into your
+ * path
+ */
+main() {
+ XScreenSaverInfo *info = XScreenSaverAllocInfo();
+ //open the display specified by the DISPLAY environment variable
+ Display *display = XOpenDisplay(0);
+
+ //display could be null if there is no X server running
+ if (info == NULL || display == NULL) {
+ return -1;
+ }
+
+ //X11 is running, try to retrieve info
+ if (XScreenSaverQueryInfo(display, DefaultRootWindow(display), info) == 0) {
+ return -1;
+ }
+
+ //info was retrieved successfully, print idle time
+ printf("%lu\n", info->idle);
+ return 0;
+}
diff --git a/etc/Makefile b/etc/Makefile
new file mode 100644
index 0000000..8b06158
--- /dev/null
+++ b/etc/Makefile
@@ -0,0 +1,31 @@
+ETCDIRS = styles schema
+-include local.mk # optional local customization
+
+.NOTPARALLEL: # always run this make serially
+.SUFFIXES: # we don't need default suffix rules
+ifeq ($(MAKELEVEL), 0)
+ $(error This make needs to be started as a sub-make from the toplevel directory.)
+endif
+
+.PHONY: all install clean cleanall clean-install
+
+all:
+
+install: $(ETCDIRS)
+ for dir in $? ; do \
+ if [ ! -d $(DESTDIR)$(datadir)/$${dir} ] ; then \
+ $(MKDIR) $(DESTDIR)$(datadir)/$${dir} ; \
+ fi ; \
+ $(CP) $${dir}/* $(DESTDIR)$(datadir)/$${dir} ; \
+ done ;
+
+clean:
+
+cleanall:
+
+clean-install: $(ETCDIRS)
+ for dir in $? ; do \
+ if [ -d $(DESTDIR)$(datadir)/$${dir} ] ; then \
+ $(RMR) $(DESTDIR)$(datadir)/$${dir} ; \
+ fi ; \
+ done ;
diff --git a/etc/ORG-NEWS b/etc/ORG-NEWS
new file mode 100644
index 0000000..8c21d07
--- /dev/null
+++ b/etc/ORG-NEWS
@@ -0,0 +1,3824 @@
+ORG NEWS -- history of user-visible changes. -*- org -*-
+
+#+LINK: doc http://orgmode.org/worg/doc.html#%s
+#+LINK: git http://orgmode.org/cgit.cgi/org-mode.git/commit/?id=%s
+
+Copyright (C) 2012-2017 Free Software Foundation, Inc.
+See the end of the file for license conditions.
+
+Please send Org bug reports to mailto:emacs-orgmode@gnu.org.
+
+* Version 9.0
+
+** Incompatible changes
+
+*** Emacs 23 support has been dropped
+
+From now on, Org expects at least Emacs 24.3, although Emacs 24.4 or
+above is suggested.
+
+*** XEmacs support has been dropped
+
+Incomplete compatibility layer with XEmacs has been removed. If you
+want to take over maintainance of this compatibility, please contact
+our mailing list.
+
+*** New syntax for export blocks
+
+Export blocks are explicitly marked as such at the syntax level to
+disambiguate their parsing from special blocks. The new syntax is
+
+#+BEGIN_SRC org
+,#+BEGIN_EXPORT backend
+...
+,#+END_EXPORT
+#+END_SRC
+
+instead of
+
+#+BEGIN_SRC org
+,#+BEGIN_backend
+...
+,#+END_backend
+#+END_SRC
+
+As a consequence, =INCLUDE= keywords syntax is modified, e.g.,
+
+#+BEGIN_SRC org
+,#+INCLUDE: "file.org" HTML
+#+END_SRC
+
+becomes
+
+#+BEGIN_SRC org
+,#+INCLUDE: "file.org" export html
+#+END_SRC
+
+The following function repairs export blocks and =INCLUDE= keywords
+using previous syntax:
+
+#+BEGIN_SRC emacs-lisp
+(defun org-repair-export-blocks ()
+ "Repair export blocks and INCLUDE keywords in current buffer."
+ (interactive)
+ (when (eq major-mode 'org-mode)
+ (let ((case-fold-search t)
+ (back-end-re (regexp-opt
+ '("HTML" "ASCII" "LATEX" "ODT" "MARKDOWN" "MD" "ORG"
+ "MAN" "BEAMER" "TEXINFO" "GROFF" "KOMA-LETTER")
+ t)))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((block-re (concat "^[ \t]*#\\+BEGIN_" back-end-re)))
+ (save-excursion
+ (while (re-search-forward block-re nil t)
+ (let ((element (save-match-data (org-element-at-point))))
+ (when (eq (org-element-type element) 'special-block)
+ (save-excursion
+ (goto-char (org-element-property :end element))
+ (save-match-data (search-backward "_"))
+ (forward-char)
+ (insert "EXPORT")
+ (delete-region (point) (line-end-position)))
+ (replace-match "EXPORT \\1" nil nil nil 1))))))
+ (let ((include-re
+ (format "^[ \t]*#\\+INCLUDE: .*?%s[ \t]*$" back-end-re)))
+ (while (re-search-forward include-re nil t)
+ (let ((element (save-match-data (org-element-at-point))))
+ (when (and (eq (org-element-type element) 'keyword)
+ (string= (org-element-property :key element) "INCLUDE"))
+ (replace-match "EXPORT \\1" nil nil nil 1)))))))))
+#+END_SRC
+
+Moreover, ~:export-block~ keyword used in ~org-export-define-backend~ and
+~org-export-define-derived-backend~ is no longer used and needs to be
+removed.
+
+*** Footnotes
+
+**** [1]-like constructs are not valid footnotes
+
+Using =[1]= as a footnote was already discouraged in the manual, since
+it introduced too many false-positives in many Org documents. These
+constructs are now unsupported.
+
+If you used =[N]= in some of your documents, consider turning them into
+=[fn:N]=.
+
+**** /Org Footnote/ library doesn't handle non-Org buffers
+
+Commands for footnotes in an Org document no longer try to do
+something in non-Org ones. If you need to have footnotes there,
+consider using the =footnote.el= library, shipped with Emacs.
+
+In particular, ~org-footnote-tag-for-non-org-mode-files~ no longer
+exists.
+
+*** ~org-file-apps~ no longer accepts S-expressions as commands
+
+The variable now accepts functions of two arguments instead of plain
+S-expressions. Replacing a S-expresion with an appropriate function
+is straightforward. For example
+
+: ("pdf" . (foo))
+
+becomes
+
+: ("pdf" . (lambda (file link) (foo)))
+
+*** The ~{{{modification-time}}}~ macro can get time via =vc=
+
+The modification time will be determined via =vc.el= if the second
+argument is non-nil. See the manual for details.
+
+*** Preparation and completion functions in publishing projects change signature
+
+Preparation and completion functions are now called with an argument,
+which is the project property list. It used to be dynamically scoped
+through the ~project-plist~ variable.
+
+*** Old Babel header properties are no longer supported
+
+Using header arguments as property names is no longer possible. As
+such, the following
+
+#+BEGIN_EXAMPLE
+,* Headline
+:PROPERTIES:
+:exports: code
+:var: a=1 b=2
+:var+: c=3
+:END:
+#+END_EXAMPLE
+
+should be written instead
+
+#+BEGIN_EXAMPLE
+,* Headline
+:PROPERTIES:
+:header-args: :exports code
+:header-args: :var a=1 b=2
+:header-args+: :var c=3
+:END:
+#+END_EXAMPLE
+
+Please note that, however, old properties were defined at the source
+block definition. Current ones are defined where the block is called.
+
+** New features
+
+*** ~org-eww~ has been moved into core
+*** New org-protocol key=value syntax
+
+Org-protocol can now handle query-style parameters such as:
+
+#+begin_example
+org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title
+org-protocol://capture?template=x&title=Hello&body=World&url=http:%2F%2Fexample.com
+#+end_example
+
+Old-style links such as
+: org-protocol://store-link:/http:%2F%2Flocalhost%2Findex.html/The%20title
+continue to be supported.
+
+If you have defined your own handler functions for
+~org-protocol-protocol-alist~, change them to accept either a property
+list (for new-style links) or a string (for old-style links). Use
+~org-protocol-parse-parameters~ to convert old-style links into property
+lists.
+
+*** New Org linter library
+
+~org-lint~ can check syntax and report common issues in Org documents.
+
+*** New option ~date-tree-last~ for ~org-agenda-insert-diary-strategy~
+
+When ~org-agenda-insert-diary-strategy~ is set to ~date-tree-last~, diary
+entries are added to last in the date tree.
+
+*** New ~vbar~ entity
+
+~\vbar~ or ~\vbar{}~ will be exported unconditionnally as a =|=,
+unlike to existing ~\vert~, which is expanded as ~&vert;~ when using
+a HTML derived export back-end.
+
+*** Export
+
+**** New =#+latex_compiler= keyword to set LaTeX compiler.
+
+PDFLaTeX, XeLaTeX, and LuaLaTeX are supported. See the manual for
+details.
+
+**** New option ~org-export-with-broken-links~
+
+This option tells the export process how to behave when encountering
+a broken internal link. See its docstring for more information.
+
+**** Attributes support in custom language environments for LaTeX export
+
+Custom language environments for LaTeX export can now define the
+string to be inserted during export, using attributes to indicate the
+position of the elements. See variable ~org-latex-custom-lang-environments~
+for more details.
+
+**** New Texinfo ~options~ attribute on special blocks
+
+Using ~:options~ as a Texinfo attribute, it is possible to add
+information to custom environments. See manual for details.
+
+**** New HTML ~id~ attributes on special, example and quote blocks
+
+If the block has a =#+NAME:= attribute assigned, then the HTML element
+will have an ~id~ attribute with that name in the HTML export. This
+enables one to create links to these elements in other places, e.g.,
+~<a href="#name">text</a>~.
+
+**** Listings with captions are now numbered in HTML export
+
+The class associated to the numbering is "listing-number". If you
+don't want these blocks to be numbered, as it was the case until now,
+You may want to add ~.listing-number { display: none; }~ to the CSS
+used.
+
+**** Line Numbering in SRC/EXAMPLE blocks support arbitrary start number
+
+The ~-n~ option to ~SRC~ and ~EXAMPLE~ blocks can now take a numeric
+argument to specify the staring line number for the source or example
+block. The ~+n~ option can now take a numeric argument that will be
+added to the last line number from the previous block as the starting
+point for the SRC/EXAMPLE block.
+
+#+BEGIN_SRC org
+,#+BEGIN_SRC emacs-lisp -n 20
+;; this will export with line number 20
+(message "This is line 21")
+,#+END_SRC
+,#+BEGIN_SRC emacs-lisp +n 10
+;; This will be listed as line 31
+(message "This is line 32")
+,#+END_SRC
+#+END_SRC
+
+**** Allow toggling center for images in LaTeX export
+
+With the global variable ~org-latex-images-centered~ or the local
+attribute ~:center~ it is now possible to center an image in LaTeX
+export.
+
+**** Default CSS class ~org-svg~ for SVG images in HTML export
+
+SVG images exported in HTML are now by default assigned a CSS class
+~org-svg~ if no CSS class is specified with the ~:class~ attribute. By
+default, the CSS styling of class ~org-svg~ specifies an image width of
+90\thinsp{}% of the container the image.
+
+**** Markdown footnote export customization
+
+Variables ~org-md-footnotes-section~ and ~org-md-footnote-format~
+introduced for =ox-md.el=. Both new variables define template strings
+which can be used to customize the format of the exported footnotes
+section and individual footnotes, respectively.
+
+*** Babel
+
+**** Blocks with coderefs labels can now be evaluated
+
+The labels are removed prior to evaluating the block.
+
+**** Support for Lua language
+**** Support for SLY in Lisp blocks
+
+See ~org-babel-lisp-eval-fn~ to activate it.
+
+**** Support for Stan language
+
+New ob-stan.el library.
+
+Evaluating a Stan block can produce two different results.
+
+1. Dump the source code contents to a file.
+
+ This file can then be used as a variable in other blocks, which
+ allows interfaces like RStan to use the model.
+
+2. Compile the contents to a model file.
+
+ This provides access to the CmdStan interface. To use this, set
+ ~org-babel-stan-cmdstan-directory~ and provide a ~:file~ argument
+ that does not end in ".stan".
+
+For more information and usage examples, visit
+http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-stan.html
+
+**** Support for Oracle databases via ~sqlplus~
+
+=ob-sql= library supports running SQL blocks against an Oracle
+database using ~sqlplus~. Use with properties like this (all
+mandatory):
+
+#+BEGIN_EXAMPLE
+:engine oracle
+:dbhost <host.com>
+:dbport <1521>
+:dbuser <username>
+:database <database>
+:dbpassword <secret>
+#+END_EXAMPLE
+
+**** Improved support to Microsoft SQL Server via ~sqlcmd~
+
+=ob-sql= library removes support to the ~msosql~ engine which uses the
+deprecated ~osql~ command line tool, and replaces it with ~mssql~
+engine which uses the ~sqlcmd~ command line tool. Use with properties
+like this:
+
+#+BEGIN_EXAMPLE
+:engine mssql
+:dbhost <host.com>
+:dbuser <username>
+:dbpassword <secret>
+:database <database>
+#+END_EXAMPLE
+
+If you want to use the *trusted connection* feature, omit *both* the
+=dbuser= and =dbpassword= properties and add =cmdline -E= to the properties.
+
+If your Emacs is running in a Cygwin environment, the =ob-sql= library
+can pass the converted path to the =sqlcmd= tool.
+
+**** Improved support of header arguments for postgresql
+
+The postgresql engine in a sql code block supports now ~:dbport~ nd
+~:dbpassword~ as header arguments.
+
+**** Support for additional plantuml output formats
+
+The support for output formats of [[http://plantuml.com/][plantuml]] has been extended to now
+include:
+
+All Diagrams:
+- png ::
+- svg ::
+- eps ::
+- pdf ::
+- vdx ::
+- txt :: ASCII art
+- utxt :: ASCII art using unicode characters
+
+Class Diagrams:
+- xmi ::
+- html ::
+
+State Diagrams:
+- scxml ::
+
+The output formats are determined by the file extension specified
+using the :file property, e.g.:
+
+#+begin_src plantuml :file diagram.png
+@startuml
+Alice -> Bob: Authentication Request
+Bob --> Alice: Authentication Response
+
+Alice -> Bob: Another authentication Request
+Alice <-- Bob: another authentication Response
+@enduml
+#+end_src
+
+Please note that *pdf* *does not work out of the box* and needs additional
+setup in addition to plantuml. See [[http://plantuml.com/pdf.html]] for
+details and setup information.
+
+*** Rewrite of radio lists
+
+Radio lists, i.e, Org plain lists in foreign buffers, have been
+rewritten to be on par with Radio tables. You can use a large set of
+parameters to control how a given list should be rendered. See manual
+for details.
+
+*** org-bbdb-anniversaries-future
+
+Used like ~org-bbdb-anniversaries~, it provides a few days warning for
+upcoming anniversaries (default: 7 days).
+
+*** Clear non-repeated SCHEDULED upon repeating a task
+
+If the task is repeated, and therefore done at least one, scheduling
+information is no longer relevant. It is therefore removed.
+
+See [[git:481719fbd5751aaa9c672b762cb43aea8ee986b0][commit message]] for more information.
+
+*** Support for ISO week trees
+
+ISO week trees are an alternative date tree format that orders entries
+by ISO week and not by month.
+
+For example:
+
+: * 2015
+: ** 2015-W35
+: ** 2015-W36
+: *** 2015-08-31 Monday
+
+They are supported in org-capture via ~file+weektree~ and
+~file+weektree+prompt~ target specifications.
+
+*** Accept ~:indent~ parameter when capturing column view
+
+When defining a "columnview" dynamic block, it is now possible to add
+an :indent parameter, much like the one in the clock table.
+
+On the other hand, stars no longer appear in an ITEM field.
+
+*** Columns view
+
+**** ~org-columns~ accepts a prefix argument
+
+When called with a prefix argument, ~org-columns~ apply to the whole
+buffer unconditionally.
+
+**** New variable : ~org-agenda-view-columns-initially~
+
+The variable used to be a ~defvar~, it is now a ~defcustom~.
+
+**** Allow custom summaries
+
+It is now possible to add new summary types, or override those
+provided by Org by customizing ~org-columns-summary-types~, which see.
+
+**** Allow multiple summaries for any property
+
+Columns can now summarize the same property using different summary
+types.
+
+*** Preview LaTeX snippets in buffers not visiting files
+*** New option ~org-attach-commit~
+
+When non-nil, commit attachments with git, assuming the document is in
+a git repository.
+
+*** Allow conditional case-fold searches in ~org-occur~
+
+When set to ~smart~, the new variable ~org-occur-case-fold-search~ allows
+to mimic =isearch.el=: if the regexp searched contains any upper case
+character (or character class), the search is case sensitive.
+Otherwise, it is case insensitive.
+
+*** More robust repeated =ox-latex= footnote handling
+
+Repeated footnotes are now numbered by referring to a label in the
+first footnote.
+
+*** The ~org-block~ face is inherited by ~src-blocks~
+
+This works also when =org-src-fontify-natively= is non-nil. It is also
+possible to specify per-languages faces. See =org-src-block-faces= and
+the manual for details.
+
+*** Links are now customizable
+
+Links can now have custom colors, tooltips, keymaps, display behavior,
+etc. Links are now centralized in ~org-link-parameters~.
+
+** New functions
+
+*** ~org-next-line-empty-p~
+
+It replaces the deprecated ~next~ argument to ~org-previous-line-empty-p~.
+
+*** ~org-show-children~
+
+It is a faster implementation of ~outline-show-children~.
+
+** Removed functions
+
+*** ~org-agenda-filter-by-tag-refine~ has been removed.
+
+Use ~org-agenda-filter-by-tag~ instead.
+
+*** ~org-agenda-todayp~ is deprecated.
+
+Use ~org-agenda-today-p~ instead.
+
+*** ~org-babel-get-header~ is removed.
+
+Use ~org-babel--get-vars~ or ~assq~ instead, as applicable.
+
+*** ~org-babel-trim~ is deprecated.
+
+Use ~org-trim~ instead.
+
+*** ~org-element-remove-indentation~ is deprecated.
+
+Use ~org-remove-indentation~ instead.
+
+*** ~org-image-file-name-regexp~ is deprecated
+
+Use ~image-file-name-regexp~ instead.
+The never-used-in-core ~extensions~ argument has been dropped.
+
+*** ~org-list-parse-list~ is deprecated
+
+Use ~org-list-to-lisp~ instead.
+
+*** ~org-on-heading-p~ is deprecated
+
+A comment to this effect was in the source code since 7.8.03, but
+now a byte-compiler warning will be generated as well.
+
+*** ~org-table-p~ is deprecated
+
+Use ~org-at-table-p~ instead.
+
+*** ~org-table-recognize-table.el~ is deprecated
+
+It was not called by any org code since 2010.
+
+*** Various reimplementations of cl-lib functions are deprecated
+
+The affected functions are:
+- ~org-count~
+- ~org-remove-if~
+- ~org-remove-if-not~
+- ~org-reduce~
+- ~org-every~
+- ~org-some~
+
+Additionally, ~org-sublist~ is deprecated in favor of ~cl-subseq~. Note
+the differences in indexing conventions: ~org-sublist~ is 1-based and
+end-inclusive; ~cl-subseq~ is 0-based and end-exclusive.
+
+** Removed options
+
+*** Remove all options related to ~ido~ or ~iswitchb~
+
+This includes ~org-completion-use-iswitchb~ and ~org-completion-use-ido~.
+Instead Org uses regular functions, e.g., ~completion-read~ so as to
+let those libraries operate.
+
+*** Remove ~org-list-empty-line-terminates-plain-lists~
+
+Two consecutive blank lines always terminate all levels of current
+plain list.
+
+*** ~fixltx2e~ is removed from ~org-latex-default-packages-alist~
+
+fixltx2e is obsolete, see LaTeX News 22.
+
+** Miscellaneous
+*** Add Icelandic smart quotes
+*** Allow multiple receiver locations in radio tables and lists
+*** Allow angular links within link descriptions
+
+It is now allowed to write, e.g.,
+~[[http:orgmode.org][<file:unicorn.png>]]~ as an equivalent to
+~[[http:orgmode.org][file:unicorn.png]]~. The advantage of the former
+is that spaces are allowed within the path.
+
+*** Beamer export back-ends uses ~org-latex-prefer-user-labels~
+*** ~:preparation-function~ called earlier during publishing
+
+Functions in this list are called before any file is associated to the
+current projet. Thus, they can be used to generate to be published
+Org files.
+
+*** Function ~org-remove-indentation~ changes.
+
+The new algorithm doesn't remove TAB characters not used for
+indentation.
+
+*** Secure placeholders in capture templates
+
+Placeholders in capture templates are no longer expanded recursively.
+However, ~%(...)~ constructs are expanded very late, so you can fill
+the contents of the S-exp with the replacement text of non-interactive
+placeholders. As before, interactive ones are still expanded as the
+very last step, so the previous statement doesn't apply to them.
+
+Note that only ~%(...)~ placeholders initially present in the
+template, or introduced using a file placeholder, i.e., ~%[...]~ are
+expanded. This prevents evaluating potentially malicious code when
+another placeholder, e.g., ~%i~ expands to a S-exp.
+
+*** Links stored by ~org-gnus-store-link~ in nnir groups
+
+Since gnus nnir groups are temporary, ~org-gnus-store-link~ now refers
+to the article's original group.
+
+*** ~org-babel-check-confirm-evaluate~ is now a function instead of a macro
+
+The calling convention has changed.
+
+*** HTML export table row customization changes
+
+Variable ~org-html-table-row-tags~ has been split into
+~org-html-table-row-open-tag~ and ~org-html-table-row-close-tag~.
+Both new variables can be either a string or a function which will be
+called with 6 parameters.
+
+*** =ITEM= special property returns headline without stars
+*** Rename ~org-insert-columns-dblock~ into ~org-columns-insert-dblock~
+
+The previous name is, for the time being, kept as an obsolete alias.
+
+*** ~org-trim~ can preserve leading indentation.
+
+When setting a new optional argument to a non-nil value, ~org-trim~
+preserves leading indentation while removing blank lines at the
+beginning of the string. The behavior is identical for white space at
+the end of the string.
+
+*** Function ~org-info-export~ changes.
+
+HTML links created from certain info links now point to =gnu.org= URL's rather
+than just to local files. For example info links such as =info:emacs#List
+Buffers= used to be converted to HTML links like this:
+
+: <a href="emacs.html#List-Buffers">emacs#List Buffers</a>
+
+where local file =emacs.html= is referenced.
+For most folks this file does not exist.
+Thus the new behavior is to generate this HTML link instead:
+
+: <a href="http://www.gnu.org/software/emacs/manual/html_mono/emacs.html#List-Buffers">emacs#List Buffers</a>
+
+All emacs related info links are similarly translated plus few other
+=gnu.org= manuals.
+
+*** Repeaters with a ~++~ interval and a time can be shifted to later today
+
+Previously, if a recurring task had a timestamp of
+~<2016-01-01 Fri 20:00 ++1d>~ and was completed on =2016-01-02= at
+=08:00=, the task would skip =2016-01-02= and would be rescheduled for
+=2016-01-03=. Timestamps with ~++~ cookies and a specific time will
+now shift to the first possible future occurrence, even if the
+occurrence is later the same day the task is completed. (Timestamps
+already in the future are still shifted one time further into the
+future.)
+
+*** ~org-mobile-action-alist~ is now a defconst
+
+It used to be a defcustom, with a warning that it shouldn't be
+modified anyway.
+
+*** ~file+emacs~ and ~file+sys~ link types are deprecated
+
+They are still supported in Org 9.0 but will eventually be removed in
+a later release. Use ~file~ link type along with universal arguments
+to force opening it in either Emacs or with system application.
+
+*** New defcustom ~org-babel-J-command~ stores the j command
+*** New defalias ~org-babel-execute:j~
+
+Allows J source blocks be indicated by letter j. Previously the
+indication letter was solely J.
+
+*** ~org-open-line~ ignores tables at the very beginning of the buffer
+
+When ~org-special-ctrl-o~ is non-nil, it is impractical to create
+a blank line above a table at the beginning of the document. Now, as
+a special case, ~org-open-line~ behaves normally in this situation.
+
+*** ~org-babel-hash-show-time~ is now customizable
+
+The experimental variable used to be more or less confidential, as
+a ~defvar~.
+
+*** New ~:format~ property to parsed links
+
+It defines the format of the original link. Possible values are:
+~plain~, ~bracket~ and ~angle~.
+
+* Version 8.3
+
+** Incompatible changes
+
+*** Properties drawers syntax changes
+
+Properties drawers are now required to be located right after a
+headline and its planning line, when applicable.
+
+It will break some documents as TODO states changes were sometimes
+logged before the property drawer.
+
+The following function will repair them:
+
+#+BEGIN_SRC emacs-lisp
+(defun org-repair-property-drawers ()
+ "Fix properties drawers in current buffer.
+Ignore non Org buffers."
+ (when (eq major-mode 'org-mode)
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((case-fold-search t)
+ (inline-re (and (featurep 'org-inlinetask)
+ (concat (org-inlinetask-outline-regexp)
+ "END[ \t]*$"))))
+ (org-map-entries
+ (lambda ()
+ (unless (and inline-re (org-looking-at-p inline-re))
+ (save-excursion
+ (let ((end (save-excursion (outline-next-heading) (point))))
+ (forward-line)
+ (when (org-looking-at-p org-planning-line-re) (forward-line))
+ (when (and (< (point) end)
+ (not (org-looking-at-p org-property-drawer-re))
+ (save-excursion
+ (and (re-search-forward org-property-drawer-re end t)
+ (eq (org-element-type
+ (save-match-data (org-element-at-point)))
+ 'drawer))))
+ (insert (delete-and-extract-region
+ (match-beginning 0)
+ (min (1+ (match-end 0)) end)))
+ (unless (bolp) (insert "\n"))))))))))))
+#+END_SRC
+
+*** Using "COMMENT" is now equivalent to commenting with "#"
+
+If you used "COMMENT" in headlines to prevent a subtree from being
+exported, you can still do it but all information within the subtree
+is now commented out, i.e. no #+OPTIONS line will be parsed or taken
+into account when exporting.
+
+If you want to exclude a headline from export while using its contents
+for setting options, use =:noexport:= (see =org-export-exclude-tags=.)
+
+*** =#+CATEGORY= keywords no longer apply partially to document
+
+It was possible to use several such keywords and have them apply to
+the text below until the next one, but strongly deprecated since Org
+5.14 (2008).
+
+=#+CATEGORY= keywords are now global to the document. You can use node
+properties to set category for a subtree, e.g.,
+
+#+BEGIN_SRC org
+,* Headline
+ :PROPERTIES:
+ :CATEGORY: some category
+ :END:
+#+END_SRC
+
+*** New variable to control visibility when revealing a location
+
+~org-show-following-heading~, ~org-show-siblings~, ~org-show-entry-below~
+and ~org-show-hierarchy-above~ no longer exist. Instead, visibility is
+controlled through a single variable: ~org-show-context-detail~, which
+see.
+
+*** Replace disputed keys again when reading a date
+
+~org-replace-disputed-keys~ has been ignored when reading date since
+version 8.1, but the former behavior is restored again.
+
+Keybinding for reading date can be customized with a new variable
+~org-read-date-minibuffer-local-map~.
+
+*** No default title is provided when =TITLE= keyword is missing
+
+Skipping =TITLE= keyword no longer provides the current file name, or
+buffer name, as the title. Instead, simply ignore the title.
+
+*** Default bindings of =C-c C-n= and =C-c C-p= changed
+
+The key sequences =C-c C-n= and =C-c C-p= are now bound to
+~org-next-visible-heading~ and ~org-previous-visible-heading~
+respectively, rather than the =outline-mode= versions of these
+functions. The Org version of these functions skips over inline tasks
+(and even-level headlines when ~org-odd-levels-only~ is set).
+
+*** ~org-element-context~ no longer return objects in keywords
+
+~org-element-context~ used to return objects on some keywords, i.e.,
+=TITLE=, =DATE= and =AUTHOR=. It now returns only the keyword.
+
+*** ~org-timer-default-timer~ type changed from number to string
+
+If you have, in your configuration, something like =(setq
+org-timer-default-timer 10)= replace it with =(setq
+org-timer-default-timer "10")=.
+
+*** Functions signature changes
+
+The following functions require an additional argument. See their
+docstring for more information.
+
+- ~org-export-collect-footnote-definitions~
+- ~org-html-format-headline-function~
+- ~org-html-format-inlinetask-function~
+- ~org-latex-format-headline-function~
+- ~org-latex-format-inlinetask-function~
+- ~org-link-search~
+
+** New features
+
+*** Default lexical evaluation of emacs-lisp src blocks
+
+Emacs-lisp src blocks in babel are now evaluated using lexical
+scoping. There is a new header to control this behavior.
+
+The default results in an eval with lexical scoping.
+:lexical yes
+
+This turns lexical scoping off in the eval (the former behavior).
+:lexical no
+
+This uses the lexical environment with x=42 in the eval.
+:lexical '((x . 42))
+
+*** Behavior of ~org-return~ changed
+
+If point is before or after the headline title, insert a new line
+without changing the headline.
+
+*** Hierarchies of tags
+
+The functionality of nesting tags in hierarchies is added to org-mode.
+This is the generalization of what was previously called "Tag groups"
+in the manual. That term is now changed to "Tag hierarchy".
+
+The following in-buffer definition:
+
+#+BEGIN_SRC org
+ ,#+TAGS: [ Group : SubOne SubTwo ]
+ ,#+TAGS: [ SubOne : SubOne1 SubOne2 ]
+ ,#+TAGS: [ SubTwo : SubTwo1 SubTwo2 ]
+#+END_SRC
+
+Should be seen as the following tree of tags:
+
+- Group
+ - SubOne
+ - SubOne1
+ - SubOne2
+ - SubTwo
+ - SubTwo1
+ - SubTwo2
+
+Searching for "Group" should return all tags defined above. Filtering
+on SubOne filters also it's sub-tags. Etc.
+
+There is no limit on the depth for the tag hierarchy.
+
+*** Additional syntax for non-unique grouptags
+
+Additional syntax is defined for grouptags if the tags in the group
+don't have to be distinct on a heading.
+
+Grouptags had to previously be defined with { }. This syntax is
+already used for exclusive tags and Grouptags need their own,
+non-exclusive syntax. This behaviour is achieved with [ ]. Note: { }
+can still be used also for Grouptags but then only one of the given
+tags can be used on the headline at the same time. Example:
+
+[ group : sub1 sub2 ]
+
+#+BEGIN_SRC org
+,* Test :sub1:sub2:
+#+END_SRC
+
+This is a more general case than the already existing syntax for
+grouptags; { }.
+
+*** Define regular expression patterns as tags
+
+Tags can be defined as grouptags with regular expressions as
+"sub-tags".
+
+The regular expressions in the group must be marked up within { }.
+Example use:
+
+: #+TAGS: [ Project : {P@.+} ]
+
+Searching for the tag Project will now list all tags also including
+regular expression matches for P@.+. This is good for example for
+projects tagged with a common identifier, i.e. P@2014_OrgTags.
+
+*** Filtering in the agenda on grouptags (Tag hierarchies)
+
+Filtering in the agenda on grouptags filters all of the related tags.
+Except if a filter is applied with a (double) prefix-argument.
+
+Filtering in the agenda on subcategories does not filter the "above"
+levels anymore.
+
+If a grouptag contains a regular expression the regular expression
+is also used as a filter.
+
+*** Minor refactoring of ~org-agenda-filter-by-tag~
+
+Now uses the argument ARG and optional argument exclude instead of
+strip and narrow. ARG because the argument has multiple purposes and
+makes more sense than strip now. The term "narrowing" is changed to
+exclude.
+
+The main purpose is for the function to make more logical sense when
+filtering on tags now when tags can be structured in hierarchies.
+
+*** Babel: support for sed scripts
+
+Thanks to Bjarte Johansen for this feature.
+
+*** Babel: support for Processing language
+
+New ob-processing.el library.
+
+This library implements necessary functions for implementing editing
+of Processing code blocks, viewing the resulting sketches in an
+external viewer, and HTML export of the sketches.
+
+Check the documentation for more details.
+
+Thanks to Jarmo Hurri for this feature.
+
+*** New behaviour for ~org-toggle-latex-fragment~
+
+The new behaviour is the following:
+
+- With a double prefix argument or with a single prefix argument when
+ point is before the first headline, toggle overlays in the whole
+ buffer;
+
+- With a single prefix argument, toggle overlays in the current
+ subtree;
+
+- On latex code, toggle overlay at point;
+
+- Otherwise, toggle overlays in the current section.
+
+*** Additional markup with =#+INCLUDE= keyword
+
+The content of the included file can now be optionally marked up, for
+instance as HTML. See the documentation for details.
+
+*** File links with =#+INCLUDE= keyword
+
+Objects can be extracted via =#+INCLUDE= using file links. It is
+possible to include only the contents of the object. See manual for
+more information.
+
+*** Drawers do not need anymore to be referenced in =#+DRAWERS=
+
+One can use a drawer without listing it in the =#+DRAWERS= keyword,
+which is now obsolete. As a consequence, this change also deprecates
+~org-drawers~ variable.
+
+*** ~org-edit-special~ can edit export blocks
+
+Using C-c ' on an export block now opens a sub-editing buffer. Major
+mode in that buffer is determined by export backend name (e.g.,
+"latex" \to "latex-mode"). You can define exceptions to this rule by
+configuring ~org-src-lang-modes~, which see.
+
+*** Additional =:hline= processing to ob-shell
+
+If the argument =:hlines yes= is present in a babel call, an optional
+argument =:hlines-string= can be used to define a string to use as a
+representation for the lisp symbol ='hline= in the shell program. The
+default is =hline=.
+
+*** Markdown export supports switches in source blocks
+
+For example, it is now possible to number lines using the =-n= switch in
+a source block.
+
+*** New option in ASCII export
+
+Plain lists can have an extra margin by setting ~org-ascii-list-margin~
+variable to an appopriate integer.
+
+*** New blocks in ASCII export
+
+ASCII export now supports =#+BEGIN_JUSTIFYRIGHT= and =#+BEGIN_JUSTIFYLEFT=
+blocks. See documentation for details.
+
+*** More back-end specific publishing options
+
+The number of publishing options specific to each back-end has been
+increased. See manual for details.
+
+*** Export inline source blocks
+
+Inline source code was used to be removed upon exporting. They are
+now handled as standard code blocks, i.e., the source code can appear
+in the output, depending on the parameters.
+
+*** Extend ~org-export-first-sibling-p~ and ~org-export-last-sibling-p~
+
+These functions now support any element or object, not only headlines.
+
+*** New function: ~org-export-table-row-in-header-p~
+
+*** New function: ~org-export-get-reference~
+
+*** New function: ~org-element-lineage~
+
+This function deprecates ~org-export-get-genealogy~. It also provides
+more features. See docstring for details.
+
+*** New function: ~org-element-copy~
+
+*** New filter: ~org-export-filter-body-functions~
+
+Functions in this filter are applied on the body of the exported
+document, befor wrapping it within the template.
+
+*** New :environment parameter when exporting example blocks to LaTeX
+
+: #+ATTR_LATEX: :environment myverbatim
+: #+BEGIN_EXAMPLE
+: This sentence is false.
+: #+END_EXAMPLE
+
+will be exported using =@samp(myverbatim)= instead of =@samp(verbatim)=.
+
+*** Various improvements on radio tables
+
+Radio tables feature now relies on Org's export framework ("ox.el").
+~:no-escape~ parameter no longer exists, but additional global
+parameters are now supported: ~:raw~, ~:backend~. Moreover, there are new
+parameters specific to some pre-defined translators, e.g.,
+~:environment~ and ~:booktabs~ for ~orgtbl-to-latex~. See translators
+docstrings (including ~orgtbl-to-generic~) for details.
+
+*** Non-floating minted listings in Latex export
+
+It is not possible to specify =#+attr_latex: :float nil= in conjunction
+with source blocks exported by the minted package.
+
+*** Field formulas can now create columns as needed
+
+Previously, evaluating formulas that referenced out-of-bounds columns
+would throw an error. A new variable ~org-table-formula-create-columns~
+was added to adjust this behavior. It is now possible to silently add
+new columns, to do so with a warning or to explicitly ask the user
+each time.
+
+*** ASCII plot
+
+Ability to plot values in a column through ASCII-art bars. See manual
+for details.
+
+*** New hook: ~org-archive-hook~
+
+This hook is called after successfully archiving a subtree, with point
+on the original subtree, not yet deleted.
+
+*** New option: ~org-attach-archive-delete~
+
+When non-nil, attachments from archived subtrees are removed.
+
+*** New option: ~org-latex-caption-above~
+
+This variable generalizes ~org-latex-table-caption-above~, which is now
+deprecated. In addition to tables, it applies to source blocks,
+special blocks and images. See docstring for more information.
+
+*** New option: ~org-latex-prefer-user-labels~
+
+See the docstring for more information.
+
+*** Export unnumbered headlines
+
+Headlines, for which the property ~UNNUMBERED~ is non-nil, are now
+exported without section numbers irrespective of their levels. The
+property is inherited by children.
+
+*** Tables can be sorted with an arbitrary function
+
+It is now possible to specify a function, both programatically,
+through a new optional argument, and interactively with ~f~ or ~F~ keys,
+to sort a table.
+
+*** Table of contents can be local to a section
+
+The ~TOC~ keywords now accepts an optional ~local~ parameter. See manual
+for details.
+
+*** Countdown timers can now be paused
+
+~org-timer-pause-time~ now pauses and restarts both relative and
+countdown timers.
+
+*** New option ~only-window~ for ~org-agenda-window-setup~
+
+When ~org-agenda-window-setup~ is set to ~only-window~, the agenda is
+displayed as the sole window of the current frame.
+
+*** ~{{{date}}}~ macro supports optional formatting argument
+
+It is now possible to supply and optional formatting argument to
+~{{{date}}}~. See manual for details.
+
+*** ~{{{property}}}~ macro supports optional search argument
+
+It is now possible to supply an optional search option to
+~{{{property}}}~ in order to retrieve remote properties optional. See
+manual for details.
+
+*** New option ~org-export-with-title~
+
+It is possible to suppress the title insertion with ~#+OPTIONS:
+title:nil~ or globally using the variable ~org-export-with-title~.
+
+*** New entities family: "\_ "
+
+"\_ " are used to insert up to 20 contiguous spaces in various
+back-ends. In particular, this family can be used to introduce
+leading spaces within table cells.
+
+*** New MathJax configuration options
+
+Org uses the MathJax CDN by default. See the manual and the docstring
+of ~org-html-mathjax-options~ for details.
+
+*** New behaviour in `org-export-options-alist'
+
+When defining a back-end, it is now possible to specify to give
+`parse' behaviour on a keyword. It is equivalent to call
+`org-element-parse-secondary-string' on the value.
+
+However, parsed =KEYWORD= is automatically associated to an
+=:EXPORT_KEYWORD:= property, which can be used to override the keyword
+value during a subtree export. Moreover, macros are expanded in such
+keywords and properties.
+
+*** Viewport support in html export
+
+Viewport for mobile-optimized website is now automatically inserted
+when exporting to html. See ~org-html-viewport~ for details.
+
+*** New ~#+SUBTITLE~ export keyword
+
+Org can typeset a subtitle in some export backends. See the manual
+for details.
+
+*** Remotely edit a footnote definition
+
+Calling ~org-edit-footnote-reference~ (C-c ') on a footnote reference
+allows to edit its definition, as long as it is not anonymous, in a
+dedicated buffer. It works even if buffer is currently narrowed.
+
+*** New function ~org-delete-indentation~ bound to ~M-^~
+
+Work as ~delete-indentation~ unless at heading, in which case text is
+added to headline text.
+
+*** Support for images in Texinfo export
+
+~Texinfo~ back-end now handles images. See the manual for details.
+
+*** Support for captions in Texinfo export
+
+Tables and source blocks can now have captions. Additionally, lists
+of tables and lists of listings can be inserted in the document with
+=#+TOC= keyword.
+
+*** Countdown timer support hh:mm:ss format
+
+In addition to setting countdown timers in minutes, they can also be
+set using the hh:mm:ss format.
+
+*** Extend ~org-clone-subtree-with-time-shift~
+
+~org-clone-subtree-with-time-shift~ now accepts 0 as an argument for the
+number of clones, which removes the repeater from the original subtree
+and creates one shifted, repeating clone.
+
+*** New time block for clock tables: ~untilnow~
+
+It encompasses all past closed clocks.
+
+*** Support for the ~polyglossia~ LaTeX package
+
+See the docstring of ~org-latex-classes~ and
+~org-latex-guess-polyglossia-language~ for details.
+
+*** None-floating tables, graphics and blocks can have captions
+
+*** `org-insert-heading' can be forced to insert top-level headline
+
+** Removed functions
+
+*** Removed function ~org-translate-time~
+
+Use ~org-timestamp-translate~ instead.
+
+*** Removed function ~org-beamer-insert-options-template~
+
+This function inserted a Beamer specific template at point or in
+current subtree. Use ~org-export-insert-default-template~ instead, as
+it provides more features and covers all export back-ends. It is also
+accessible from the export dispatcher.
+
+*** Removed function ~org-timer-cancel-timer~
+
+~org-timer-stop~ now stops both relative and countdown timers.
+
+*** Removed function ~org-export-solidify-link-text~
+
+This function, being non-bijective, introduced bug in internal
+references. Use ~org-export-get-reference~ instead.
+
+*** Removed function ~org-end-of-meta-data-and-drawers~
+
+The function is superseded by ~org-end-of-meta-data~, called with an
+optional argument.
+
+*** Removed functions ~org-table-colgroup-line-p~, ~org-table-cookie-line-p~
+
+These functions were left-over from pre 8.0 era. They are not correct
+anymore. Since they are not needed, they have no replacement.
+
+** Removed options
+
+*** ~org-list-empty-line-terminates-plain-lists~ is deprecated
+
+It will be kept in code base until next release, for backward
+compatibility.
+
+If you need to separate consecutive lists with blank lines, always use
+two of them, as if this option was nil (default value).
+
+*** ~org-export-with-creator~ is a boolean
+
+Special ~comment~ value is no longer allowed. It is possible to use a
+body filter to add comments about the creator at the end of the
+document instead.
+
+*** Removed option =org-html-use-unicode-chars=
+
+Setting this to non-nil was problematic as it converted characters
+everywhere in the buffer, possibly corrupting URLs.
+
+*** Removed option =org-babel-sh-command=
+
+This undocumented option defaulted to the value of =shell-file-name= at
+the time of loading =ob-shell=. The new behaviour is to use the value
+of =shell-file-name= directly when the shell langage is =shell=. To chose
+a different shell, either customize =shell-file-name= or bind this
+variable locally.
+
+*** Removed option =org-babel-sh-var-quote-fmt=
+
+This undocumented option was supposed to provide different quoting
+styles when changing the shell type. Changing the shell type can now
+be done directly from the source block and the quoting style has to be
+compatible across all shells, so a customization doesn't make sense
+anymore. The chosen hard coded quoting style conforms to POSIX.
+
+*** Removed option ~org-insert-labeled-timestamps-at-point~
+
+Setting this option to anything else that the default value (nil)
+would create invalid planning info. This dangerous option is now
+removed.
+
+*** Removed option ~org-koma-letter-use-title~
+
+Use org-export-with-title instead. See also below.
+
+*** Removed option ~org-entities-ascii-explanatory~
+
+This variable has no effect since Org 8.0.
+
+*** Removed option ~org-table-error-on-row-ref-crossing-hline~
+
+This variable has no effect since August 2009.
+
+*** Removed MathML-related options from ~org-html-mathjax-options~
+
+MathJax automatically chooses the best display technology based on the
+end-users browser. You may force initial usage of MathML via
+~org-html-mathjax-template~ or by setting the ~path~ property of
+~org-html-mathjax-options~.
+
+*** Removed comment-related filters
+
+~org-export-filter-comment-functions~ and
+~org-export-filter-comment-block-functions~ variables do not exist
+anymore.
+
+** Miscellaneous
+
+*** Strip all meta data from ITEM special property
+
+ITEM special property does not contain TODO, priority or tags anymore.
+
+*** File names in links accept are now compatible with URI syntax
+
+Absolute file names can now start with =///= in addition to =/=. E.g.,
+=[[file:///home/me/unicorn.jpg]]=.
+
+*** Footnotes in included files are now local to the file
+
+As a consequence, it is possible to include multiple Org files with
+footnotes in a master document without being concerned about footnote
+labels colliding.
+
+*** Mailto links now use regular URI syntax
+
+This change deprecates old Org syntax for mailto links:
+=mailto:user@domain::Subject=.
+
+*** =QUOTE= keywords do not exist anymore
+
+=QUOTE= keywords have been deprecated since Org 8.2.
+
+*** Select tests to perform with the build system
+
+The build system has been enhanced to allow test selection with a
+regular expression by defining =BTEST_RE= during the test invocation.
+This is especially useful during bisection to find just when a
+particular test failure was introduced.
+
+*** Exact heading search for external links ignore spaces and cookies
+
+Exact heading search for links now ignore spaces and cookies. This is
+the case for links of the form ~file:projects.org::*task title~, as well
+as links of the form ~file:projects.org::some words~ when
+~org-link-search-must-match-exact-headline~ is not nil.
+
+*** ~org-latex-hyperref-template~, ~org-latex-title-command~ formatting
+
+New formatting keys are supported. See the respective docstrings.
+Note, ~org-latex-hyperref-template~ has a new default value.
+
+*** ~float, wasysym, marvosym~ are removed from ~org-latex-default-packages-alist~
+
+If you require any of these package add them to your preamble via
+~org-latex-packages-alist~. Org also uses default LaTeX ~\tolerance~ now.
+
+*** When exporting, throw an error on unresolved id/fuzzy links and code refs
+
+This helps spotting wrong links.
+
+* Version 8.2
+
+** Incompatible changes
+*** =ob-sh.el= renamed to =ob-shell=
+This may require two changes in user config.
+
+1. In =org-babel-do-load-languages=, change =(sh . t)= to =(shell . t)=.
+2. Edit =local.mk= files to change the value of =BTEST_OB_LANGUAGES=
+ to remove "sh" and include "shell".
+
+*** Combine org-mac-message.el and org-mac-link-grabber into org-mac-link.el
+
+Please remove calls to =(require 'org-mac-message)= and =(require
+'org-mac-link-grabber)= in your =.emacs= initialization file. All you
+need now is =(require 'org-mac-link)=.
+
+Additionally, replace any calls to =ogml-grab-link= to
+=org-mac-grab-link=. For example, replace this line:
+
+: (define-key org-mode-map (kbd "C-c g") 'omgl-grab-link)
+
+with this:
+
+: (define-key org-mode-map (kbd "C-c g") 'org-mac-grab-link)
+
+*** HTML export: Replace =HTML_HTML5_FANCY= by =:html-html5-fancy= (...)
+
+Some of the HTML specific export options in Org <8.1 are either nil or
+t, like =#+HTML_INCLUDE_STYLE=. We replaced these binary options with
+option keywords like :html-include-style.
+
+So you need to replace
+
+: #+HTML_INCLUDE_STYLE: t
+
+by
+
+: #+OPTIONS: :html-include-style t
+
+Options affected by this change: =HTML5_FANCY=, =HTML_INCLUDE_SCRIPTS=
+and =HTML_INCLUDE_STYLE=.
+
+*** Add an argument to ~org-export-to-file~ and ~org-export-to-buffer~
+
+~org-export-to-file~ and ~org-export-to-file~ can run in a different
+process when provided a non-nil =ASYNC= optional argument, without
+relying on ~org-export-async-start~ macro.
+
+Since =ASYNC= is the first of optional arguments, you have to shift
+the other optional arguments accordingly.
+
+*** Export back-ends are now structures
+
+Export back-ends are now structures, and stored as such in the
+communication channel during an export process. In other words, from
+now on, ~(plist-get info :back-end)~ will return a structure instead
+of a symbol.
+
+Arguments in hooks and in filters are still symbols, though.
+
+** Important bugfixes
+
+*** [[doc:org-insert-heading][org-insert-heading]] has been rewritten and bugs are now fixed
+*** The replacement of disputed keys is now turned of when reading a date
+
+*** Match string for sparse trees can now contain a slash in a property value
+
+ You can now have searches like SOMEPROP="aaa/bbb". Until now,
+ this would break because the slash would be interpreted as the
+ separator starting a TOTO match string.
+** New features
+
+*** =C-c ^ x= will now sort checklist items by their checked status
+
+See [[doc:org-sort-list][org-sort-list]]: hitting =C-c ^ x= will put checked items at the end
+of the list.
+*** Various LaTeX export enhancements
+
+- Support SVG images
+- Support for .pgf files
+- LaTeX Babel blocks can now be exported as =.tikz= files
+- Allow =latexmk= as an option for [[doc:org-latex-pdf-process][org-latex-pdf-process]]
+- When using =\usepackage[AUTO]{babel}=, AUTO will automatically be
+ replaced with a value compatible with ~org-export-default-language~
+ or ~LANGUAGE~ keyword.
+- The dependency on the =latexsym= LaTeX package has been removed, we
+ now use =amssymb= symbols by default instead.
+
+*** New functions for paragraph motion
+
+ The commands =C-down= and =C-up= now invoke special commands
+ that use knowledge from the org-elements parser to move the cursor
+ in a paragraph-like way.
+
+*** New entities in =org-entities.el=
+
+Add support for ell, imath, jmath, varphi, varpi, aleph, gimel, beth,
+dalet, cdots, S (§), dag, ddag, colon, therefore, because, triangleq,
+leq, geq, lessgtr, lesseqgtr, ll, lll, gg, ggg, prec, preceq,
+preccurlyeq, succ, succeq, succurlyeq, setminus, nexist(s), mho,
+check, frown, diamond. Changes loz, vert, checkmark, smile and tilde.
+
+*** Anonymous export back-ends
+
+~org-export-create-backend~ can create anonymous export back-ends,
+which can then be passed to export functions like
+~org-export-to-file~, ~org-export-to-buffer~ or ~org-export-as~.
+
+It allows for quick translation of Org syntax without the overhead of
+registering a new back-end.
+
+*** New agenda fortnight view
+
+ The agenda has not, in addition to day, week, month, and year
+ views, also a fortnight view covering 14 days.
+** New options
+
+*** New option [[doc:org-bookmark-names-plist][org-bookmark-names-plist]]
+
+This allows to specify the names of automatic bookmarks.
+*** New option [[doc:org-agenda-ignore-drawer-properties][org-agenda-ignore-drawer-properties]]
+
+This allows more flexibility when optimizing the agenda generation.
+See http://orgmode.org/worg/agenda-optimization.html for details.
+*** New option: [[doc:org-html-link-use-abs-url][org-html-link-use-abs-url]] to force using absolute URLs
+
+This is an export/publishing option, and should be used either within
+the =#+OPTIONS= line(s) or within a [[doc:org-publish-project-alist][org-publish-project-alist]].
+
+Setting this option to =t= is needed when the HTML output does not
+allow relative URLs. For example, the =contrib/lisp/ox-rss.el=
+library produces a RSS feed, and RSS feeds need to use absolute URLs,
+so a combination of =:html-link-home "..." and :html-link-use-abs-url
+t= is required---see the configuration example in the comment section
+of =ox-rss.el=.
+
+*** New option [[doc:org-babel-ditaa-java-cmd][org-babel-ditaa-java-cmd]]
+
+This makes java executable configurable for ditaa blocks.
+
+*** New options [[doc:org-babel-latex-htlatex][org-babel-latex-htlatex]] and [[doc:org-babel-latex-htlatex-packages][org-babel-latex-htlatex-packages]]
+
+This enables SVG generation from latex code blocks.
+
+*** New option: [[doc:org-habit-show-done-always-green][org-habit-show-done-always-green]]
+
+See [[http://lists.gnu.org/archive/html/emacs-orgmode/2013-05/msg00214.html][this message]] from Max Mikhanosha.
+
+*** New option: [[doc:org-babel-inline-result-wrap][org-babel-inline-result-wrap]]
+
+If you set this to the following
+
+: (setq org-babel-inline-result-wrap "$%s$")
+
+then inline code snippets will be wrapped into the formatting string.
+
+*** New option: [[doc:org-special-ctrl-o][org-special-ctrl-o]]
+
+ This variable can be used to turn off the special behavior of
+ =C-o= in tables.
+** New contributed packages
+
+- =ox-bibtex.el= by Nicolas Goaziou :: an utility to handle BibTeX
+ export to both LaTeX and HTML exports. It uses the [[http://www.lri.fr/~filliatr/bibtex2html/][bibtex2html]]
+ software.
+
+- =org-screenshot.el= by Max Mikhanosha :: an utility to handle
+ screenshots easily from Org, using the external tool [[http://freecode.com/projects/scrot][scrot]].
+
+** Miscellaneous
+
+*** "QUOTE" keywords in headlines are deprecated
+
+"QUOTE" keywords are an undocumented feature in Org. When a headline
+starts with the keyword "QUOTE", its contents are parsed as
+a ~quote-section~ and treated as an example block. You can achieve
+the same with example blocks.
+
+This feature is deprecated and will be removed in the next Org
+release.
+
+* Version 8.0.1
+
+** Installation
+
+Installation instructions have been updated and simplified.
+
+If you have troubles installing or updating Org, focus on these
+instructions:
+
+- when updating via a =.zip/.tar.gz= file, you only need to set the
+ =load-path= in your =.emacs=. Set it before any other Org
+ customization that would call autoloaded Org functions.
+
+- when updating by pulling Org's Git repository, make sure to create the
+ correct autoloads. You can do this by running =~$ make autoloads= (to
+ only create the autoloads) or by running =~$ make= (to also compile
+ the Emacs lisp files.) =~$ make help= and =~$ make helpall= gives you
+ detailed explanations.
+
+- when updating through ELPA (either from GNU ELPA or from Org ELPA),
+ you have to install Org's ELPA package in a session where no Org
+ function has been called already.
+
+When in doubt, run =M-x org-version RET= and see if you have a mixed-up
+installation.
+
+See http://orgmode.org/org.html#Installation for details.
+
+** Incompatible changes
+
+Org 8.0 is the most disruptive major version of Org.
+
+If you configured export options, you will have to update some of them.
+
+If you used =#+ATTR_*= keywords, the syntax of the attributes changed and
+you will have to update them.
+
+Below is a list of changes for which you need to take action.
+
+See http://orgmode.org/worg/org-8.0.html for the most recent version of
+this list and for detailed instructions on how to migrate.
+
+**** New export engine
+
+Org 8.0 comes with a new export engine written by Nicolas Goaziou. This
+export engine relies on ~org-element.el~ (Org's syntax parser), which was
+already in Org's core. This new export engine triggered the rewriting of
+/all/ export back-ends.
+
+The most visible change is the export dispatcher, accessible through the
+keybinding =C-c C-e=. By default, this menu only shows some of the
+built-in export formats, but you can add more formats by loading them
+directly (e.g., =(require 'ox-texinfo)= or by configuring the option
+[[doc:org-export-backends][org-export-backends]].
+
+More contributed back-ends are available from the =contrib/= directory, the
+corresponding files start with the =ox-= prefix.
+
+If you customized an export back-end (like HTML or LaTeX), you will need to
+rename some options so that your customization is not lost. Typically, an
+option starting with =org-export-html-= is now named =org-html-=. See the
+manual for details and check [[http://orgmode.org/worg/org-8.0.html][this Worg page]] for directions.
+
+**** New syntax for #+ATTR_HTML/LaTeX/... options
+
+ : #+ATTR_HTML width="200px"
+
+ should now be written
+
+ : #+ATTR_HTML :width 200px
+
+ Keywords like =#+ATTR_HTML= and =#+ATTR_LaTeX= are defined in their
+ respective back-ends, and the list of supported parameters depends on
+ each backend. See Org's manual for details.
+
+**** ~org-remember.el~ has been removed
+
+ You cannot use =remember.el= anymore to capture notes.
+
+ Support for remember templates has been obsoleted since long, it is
+ now fully removed.
+
+ Use =M-x org-capture-import-remember-templates RET= to import your
+ remember templates into capture templates.
+
+**** ~org-jsinfo.el~ has been merged into ~ox-html.el~
+
+ If you were requiring ~ox-jsinfo.el~ in your ~.emacs.el~ file, you
+ will have to remove this requirement from your initialization file.
+
+**** Note for third-party developers
+
+ The name of the files for export back-end have changed: we now use the
+ prefix =ox-= for those files (like we use the =ob-= prefix for Babel
+ files.) For example ~org-html.el~ is now ~ox-html.el~.
+
+ If your code relies on these files, please update the names in your
+ code.
+
+**** Packages moved from core to contrib
+
+ Since packages in Org's core are meant to be part of GNU Emacs, we try
+ to be minimalist when it comes to adding files into core. For 8.0, we
+ moved some contributions into the =contrib/= directory.
+
+ The rationale for deciding that these files should live in =contrib/=
+ is either because they rely on third-party software that is not
+ included in Emacs, or because they are not targeting a significant
+ user-base.
+
+ - org-colview-xemacs.el
+ - org-mac-message.el
+ - org-mew.el
+ - org-wl.el
+ - ox-freedmind.el
+ - ox-taskjuggler.el
+
+ Note that ~ox-freedmind.el~ has been rewritten by Jambunathan,
+ ~org-mew.el~ has been enhanced by Tokuya Kameshima and
+ ~ox-taskjuggler.el~ by Nicolas Goaziou and others.
+
+ Also, the Taskjuggler exporter now uses TJ3 by default. John Hendy
+ wrote [[http://orgmode.org/worg/org-tutorials/org-taskjuggler3.html][a tutorial on Worg]] for the TJ3 export.
+
+** New packages in core
+
+*** ~ob-makefile.el~ by Eric Schulte and Thomas S. Dye
+
+ =ob-makefile.el= implements Org Babel support for Makefile tangling.
+
+*** ~ox-man.el~ by Luis Anaya
+
+ =ox-man.el= allows you to export Org files to =man= pages.
+
+*** ~ox-md.el~ by Nicolas Goaziou
+
+ =ox-md.el= allows you to export Org files to Markdown files, using the
+ vanilla [[http://daringfireball.net/projects/markdown/][Markdown syntax]].
+
+*** ~ox-texinfo.el~ by Jonathan Leech-Pepin
+
+ =ox-texinfo.el= allows you to export Org files to [[http://www.gnu.org/software/texinfo/][Texinfo]] files.
+
+** New packages in contrib
+
+*** ~ob-julia.el~ by G. Jay Kerns
+
+ [[http://julialang.org/][Julia]] is a new programming language.
+
+ =ob-julia.el= provides Org Babel support for evaluating Julia source
+ code.
+
+*** ~ob-mathomatic.el~ by Luis Anaya
+
+ [[http://www.mathomatic.org/][mathomatic]] a portable, command-line, educational CAS and calculator
+ software, written entirely in the C programming language.
+
+ ~ob-mathomatic.el~ provides Org Babel support for evaluating mathomatic
+ entries.
+
+*** ~ob-tcl.el~ by Luis Anaya
+
+ ~ob-tcl.el~ provides Org Babel support for evaluating [[http://www.tcl.tk/][Tcl]] source code.
+
+*** ~org-bullets.el~ by Evgeni Sabof
+
+ Display bullets instead of stars for headlines.
+
+ Also see [[http://orgmode.org/worg/org-faq.html#sec-8-12][this updated FAQ]] on how to display another character than "*"
+ for starting headlines.
+
+*** ~org-favtable.el~ by Marc-Oliver Ihm
+
+ ~org-favtable.el~ helps you to create and update a table of favorite
+ locations in org, keeping the most frequently visited lines right at
+ the top. This table is called "favtable". See the documentation on
+ [[http://orgmode.org/worg/org-contrib/org-favtable.html][Worg]].
+
+*** ~ox-confluence.el~ by Sébastien Delafond
+
+ ~ox-confluence.el~ lets you convert Org files to [[https://confluence.atlassian.com/display/DOC/Confluence%2BWiki%2BMarkup][Confluence Wiki]] files.
+
+*** ~ox-deck.el~ and ~ox-s5.el~ by Rick Frankel
+
+ [[http://imakewebthings.com/deck.js/][deck.js]] is a javascript library for displaying HTML ages as
+ presentations. ~ox-deck.el~ exports Org files to HTML presentations
+ using =deck.js=.
+
+ [[http://meyerweb.com/eric/tools/s5/][s5]] is a set of scripts which also allows to display HTML pages as
+ presentations. ~ox-s5.el~ exports Org files to HTML presentations
+ using =s5=.
+
+*** ~ox-groff.el~ by Luis Anaya and Nicolas Goaziou
+
+ The [[http://www.gnu.org/software/groff/][groff]] (GNU troff) software is a typesetting package which reads
+ plain text mixed with formatting commands and produces formatted
+ output.
+
+ Luis Anaya and Nicolas Goaziou implemented ~ox-groff.el~ to allow
+ conversion from Org files to groff.
+
+*** ~ox-koma-letter.el~ by Nicolas Goaziou and Alan Schmitt
+
+ This back-end allow to export Org pages to the =KOMA Scrlttr2= format.
+
+*** ~ox-rss.el~ by Bastien
+
+ This back-end lets you export Org pages to RSS 2.0 feeds. Combined
+ with the HTML publishing feature, this allows you to build a blog
+ entirely with Org.
+
+** New features
+
+*** Export
+
+**** New export generic options
+
+If you use Org exporter, we advise you to re-read [[http://orgmode.org/org.html#Exporting][the manual section about
+it]]. It has been updated and includes new options.
+
+Among the new/updated export options, three are of particular importance:
+
+- [[doc:org-export-allow-bind-keywords][org-export-allow-bind-keywords]] :: This option replaces the old option
+ =org-export-allow-BIND= and the default value is =nil=, not =confirm=.
+ You will need to explicitly set this to =t= in your initialization
+ file if you want to allow =#+BIND= keywords.
+
+- [[doc:org-export-with-planning][org-export-with-planning]] :: This new option controls the export of
+ =SCHEDULED:, DEADLINE:, CLOSED:= lines, and planning information is
+ now skipped by default during export. This use to be the job of
+ [[doc:org-export-with-timestamps][org-export-with-timestamps]], but this latter option has been given a
+ new role: it controls the export of /standalone time-stamps/. When
+ set to =nil=, Org will not export active and inactive time-stamps
+ standing on a line by themselves or within a paragraph that only
+ contains time-stamps.
+
+To check if an option has been introduced or its default value changed in
+Org 8.0, do =C-h v [option] RET= and check if the documentation says that
+the variable has been introduced (or changed) in version 24.4 of Emacs.
+
+**** Enhanced default stylesheet for the HTML exporter
+
+See the new default value of [[doc:org-html-style-default][org-html-style-default]].
+
+**** New tags, classes and ids for the HTML exporter
+
+See the new default value of [[doc:org-html-divs][org-html-divs]].
+
+**** Support for tikz pictures in LaTeX export
+**** ~org-man.el~: New export function for "man" links
+**** ~org-docview.el~: New export function for docview links
+*** Structure editing
+
+**** =C-u C-u M-RET= inserts a heading at the end of the parent subtree
+**** Cycling to the =CONTENTS= view keeps inline tasks folded
+
+[[doc:org-cycle-hook][org-cycle-hook]] as a new function [[doc:org-cycle-hide-inline-tasks][org-cycle-hide-inline-tasks]] which
+prevents the display of inline tasks when showing the content of a subtree.
+
+**** =C-c -= in a region makes a list item for each line
+
+This is the opposite of the previous behavior, where =C-c -= on a region
+would create one item for the whole region, and where =C-u C-c -= would
+create an item for each line. Now =C-c -= on the selected region creates
+an item per line, and =C-u C-c -= creates a single item for the whole
+region.
+
+**** When transposing words, markup characters are now part of the words
+
+In Emacs, you can transpose words with =M-t=. Transposing =*these*
+_words__= will preserve markup.
+
+**** New command [[doc:org-set-property-and-value][org-set-property-and-value]] bound to =C-c C-x P=
+
+This command allows you to quickly add both the property and its value. It
+is useful in buffers where there are many properties and where =C-c C-x p=
+can slow down the flow of editing too much.
+
+**** New commands [[doc:org-next-block][org-next-block]] and [[doc:org-previous-block][org-previous-block]]
+
+These commands allow you to go to the previous block (=C-c M-b= or the
+speedy key =B=) or to the next block (=C-c M-f= or the speedy key =F=.)
+
+**** New commands [[doc:org-drag-line-forward][org-drag-line-forward]] and [[doc:org-drag-line-backward][org-drag-line-backward]]
+
+These commands emulate the old behavior of =M-<down>= and =M-<up>= but are
+now bound to =S-M-<down>= and =S-M-<up>= respectively, since =M-<down>= and
+=M-<up>= now drag the whole element at point (a paragraph, a table, etc.)
+forward and backward.
+
+**** When a list item has a checkbox, inserting a new item uses a checkbox too
+**** When sorting entries/items, only the description of links is considered
+
+Now Org will sort this list
+
+: - [[http://abc.org][B]]
+: - [[http://def.org][A]]
+
+like this:
+
+: - [[http://def.org][A]]
+: - [[http://abc.org][B]]
+
+by comparing the descriptions, not the links.
+Same when sorting headlines instead of list items.
+**** New option =orgstruct-heading-prefix-regexp=
+
+For example, setting this option to "^;;; " in Emacs lisp files and using
+=orgstruct-mode= in those files will allow you to cycle through visibility
+states as if lines starting with ";;; *..." where headlines.
+
+In general, you want to set =orgstruct-heading-prefix-regexp= as a file
+local variable.
+
+**** New behavior of [[doc:org-clone-subtree-with-time-shift][org-clone-subtree-with-time-shift]]
+
+The default is now to ask for a time-shift only when there is a time-stamp.
+When called with a universal prefix argument =C-u=, it will not ask for a
+time-shift even if there is a time-stamp.
+
+**** New option [[doc:org-agenda-restriction-lock-highlight-subtree][org-agenda-restriction-lock-highlight-subtree]]
+
+This defaults to =t= so that the whole subtree is highlighted when you
+restrict the agenda view to it with =C-c C-x <= (or the speed command =<=).
+The default setting helps ensuring that you are not adding tasks after the
+restricted region. If you find this highlighting too intrusive, set this
+option to =nil=.
+**** New option [[doc:org-closed-keep-when-no-todo][org-closed-keep-when-no-todo]]
+
+When switching back from a =DONE= keyword to a =TODO= keyword, Org now
+removes the =CLOSED= planning information, if any. It also removes this
+information when going back to a non-TODO state (e.g., with =C-c C-t SPC=).
+If you want to keep the =CLOSED= planning information when removing the
+TODO keyword, set [[doc:org-closed-keep-when-no-todo][org-closed-keep-when-no-todo]] to =t=.
+
+**** New option [[doc:org-image-actual-width][org-image-actual-width]]
+
+This option allows you to change the width of in-buffer displayed images.
+The default is to use the actual width of the image, but you can use a
+fixed value for all images, or fall back on an attribute like
+
+: #+attr_html: :width 300px
+*** Scheduled/deadline
+
+**** Implement "delay" cookies for scheduled items
+
+If you want to delay the display of a scheduled task in the agenda, you can
+now use a delay cookie like this: =SCHEDULED: <2004-12-25 Sat -2d>=. The
+task is still scheduled on the 25th but will appear in your agenda starting
+from two days later (i.e. from March 27th.)
+
+Imagine for example that your co-workers are not done in due time and tell
+you "we need two more days". In that case, you may want to delay the
+display of the task in your agenda by two days, but you still want the task
+to appear as scheduled on March 25th.
+
+In case the task contains a repeater, the delay is considered to affect all
+occurrences; if you want the delay to only affect the first scheduled
+occurrence of the task, use =--2d= instead. See [[doc:org-scheduled-delay-days][org-scheduled-delay-days]]
+and [[doc:org-agenda-skip-scheduled-delay-if-deadline][org-agenda-skip-scheduled-delay-if-deadline]] for details on how to
+control this globally or per agenda.
+
+**** Use =C-u C-u C-c C-s= will insert a delay cookie for scheduled tasks
+
+See the previous section for why delay cookies may be useful.
+
+**** Use =C-u C-u C-c C-d= will insert a warning delay for deadline tasks
+
+=C-u C-u C-c C-d= now inserts a warning delay to deadlines.
+*** Calendar, diary and appts
+
+**** New variable [[doc:org-read-date-minibuffer-local-map][org-read-date-minibuffer-local-map]]
+
+By default, this new local map uses "." to go to today's date, like in the
+normal =M-x calendar RET=. If you want to deactivate this and to reassign
+the "@" key to =calendar-goto-today=, use this:
+
+#+BEGIN_SRC emacs-lisp
+ ;; Unbind "." in Org's calendar:
+ (define-key org-read-date-minibuffer-local-map (kbd ".") nil)
+
+ ;; Bind "@" to `calendar-goto-today':
+ (define-key org-read-date-minibuffer-local-map
+ (kbd "@")
+ (lambda () (interactive) (org-eval-in-calendar '(calendar-goto-today))))
+#+END_SRC
+
+**** In Org's calendar, =!= displays diary entries of the date at point
+
+This is useful when you want to check if you don't already have an
+appointment when setting new ones with =C-c .= or =C-c s=. =!= will
+call =diary-view-entries= and display the diary in a separate buffer.
+
+**** [[doc:org-diary][org-diary]]: only keep the descriptions of links
+
+[[doc:org-diary][org-diary]] returns diary information from Org files, but it returns it
+in a diary buffer, not in an Org mode buffer. When links are displayed,
+only show their description, not the full links.
+*** Agenda
+
+**** New agenda type =agenda*= and entry types =:scheduled* :deadline*=
+
+When defining agenda custom commands, you can now use =agenda*=: this will
+list entries that have both a date and a time. This is useful when you
+want to build a list of appointments.
+
+You can also set [[doc:org-agenda-entry-types][org-agenda-entry-types]] either globally or locally in
+each agenda custom command and use =:timestamp*= and/or =:deadline*= there.
+
+Another place where this is useful is your =.diary= file:
+
+: %%(org-diary :scheduled*) ~/org/rdv.org
+
+This will list only entries from =~/org/rdv.org= that are scheduled with a
+time value (i.e. appointments).
+
+**** New agenda sorting strategies
+
+[[doc:org-agenda-sorting-strategy][org-agenda-sorting-strategy]] allows these new sorting strategies:
+
+| Strategy | Explanations |
+|----------------+------------------------------------------|
+| timestamp-up | Sort by any timestamp, early first |
+| timestamp-down | Sort by any timestamp, late first |
+| scheduled-up | Sort by scheduled timestamp, early first |
+| scheduled-down | Sort by scheduled timestamp, late first |
+| deadline-up | Sort by deadline timestamp, early first |
+| deadline-down | Sort by deadline timestamp, late first |
+| ts-up | Sort by active timestamp, early first |
+| ts-down | Sort by active timestamp, late first |
+| tsia-up | Sort by inactive timestamp, early first |
+| tsia-down | Sort by inactive timestamp, late first |
+
+**** New options to limit the number of agenda entries
+
+You can now limit the number of entries in an agenda view. This is
+different from filters: filters only /hide/ the entries in the agenda,
+while limits are set while generating the list of agenda entries.
+
+These new options are available:
+
+- [[doc:org-agenda-max-entries][org-agenda-max-entries]] :: limit by number of entries.
+- [[doc:org-agenda-max-todos][org-agenda-max-todos]] :: limit by number of TODOs.
+- [[doc:org-agenda-max-tags][org-agenda-max-tags]] :: limit by number of tagged entries.
+- [[doc:org-agenda-max-effort][org-agenda-max-effort]] :: limit by effort (minutes).
+
+For example, if you locally set [[doc:org-agenda-max-todos][org-agenda-max-todos]] to 3 in an agenda
+view, the agenda will be limited to the first three todos. Other entries
+without a TODO keyword or beyond the third TODO headline will be ignored.
+
+When setting a limit (e.g. about an effort's sum), the default behavior is
+to exclude entries that cannot be checked against (e.g. entries that have
+no effort property.) To include other entries too, you can set the limit
+to a negative number. For example =(setq org-agenda-max-tags -3)= will not
+show the fourth tagged headline (and beyond), but it will also show
+non-tagged headlines.
+
+**** =~= in agenda view sets temporary limits
+
+You can hit =~= in the agenda to temporarily set limits: this will
+regenerate the agenda as if the limits were set. This is useful for
+example when you want to only see a list of =N= tasks, or a list of tasks
+that take only =N= minutes.
+
+**** "=" in agenda view filters by regular expressions
+
+You can now filter agenda entries by regular expressions using ~=~. =C-u
+== will filter entries out. Regexp filters are cumulative. You can set
+[[doc:org-agenda-regexp-filter-preset][org-agenda-regexp-filter-preset]] to suit your needs in each agenda view.
+
+**** =|= in agenda view resets all filters
+
+Since it's common to combine tag filters, category filters, and now regexp
+filters, there is a new command =|= to reset all filters at once.
+
+**** Allow writing an agenda to an =.org= file
+
+You can now write an agenda view to an =.org= file. It copies the
+headlines and their content (but not subheadings) into the new file.
+
+This is useful when you want to quickly share an agenda containing the full
+list of notes.
+
+**** New commands to drag an agenda line forward (=M-<down>=) or backward (=M-<up>=)
+
+It sometimes handy to move agenda lines around, just to quickly reorganize
+your tasks, or maybe before saving the agenda to a file. Now you can use
+=M-<down>= and =M-<up>= to move the line forward or backward.
+
+This does not persist after a refresh of the agenda, and this does not
+change the =.org= files who contribute to the agenda.
+
+**** Use =%b= for displaying "breadcrumbs" in the agenda view
+
+[[doc:org-agenda-prefix-format][org-agenda-prefix-format]] now allows to use a =%b= formatter to tell Org
+to display "breadcrumbs" in the agenda view.
+
+This is useful when you want to display the task hierarchy in your agenda.
+
+**** Use =%l= for displaying the headline's level in the agenda view
+
+[[doc:org-agenda-prefix-format][org-agenda-prefix-format]] allows to use a =%l= formatter to tell Org to
+display entries with additional spaces corresponding to their level in the
+outline tree.
+
+**** [[doc:org-agenda-write][org-agenda-write]] will ask before overwriting an existing file
+
+=M-x org-agenda-write RET= (or =C-c C-w= from an agenda buffer) used to
+overwrite preexisting file with the same name without confirmation. It now
+asks for a confirmation.
+
+**** New commands =M-m= and =M-*= to toggle (all) mark(s) for bulk action
+
+- [[doc:org-agenda-bulk-toggle][org-agenda-bulk-toggle]] :: this command is bound to =M-m= and toggles
+ the mark of the entry at point.
+
+- [[doc:org-agenda-bulk-toggle-all][org-agenda-bulk-toggle-all]] :: this command is bound to =M-*= and
+ toggles all the marks in the current agenda.
+
+**** New option [[doc:org-agenda-search-view-max-outline-level][org-agenda-search-view-max-outline-level]]
+
+This option sets the maximum outline level to display in search view.
+E.g. when this is set to 1, the search view will only show headlines of
+level 1.
+
+**** New option [[doc:org-agenda-todo-ignore-time-comparison-use-seconds][org-agenda-todo-ignore-time-comparison-use-seconds]]
+
+This allows to compare times using seconds instead of days when honoring
+options like =org-agenda-todo-ignore-*= in the agenda display.
+
+**** New option [[doc:org-agenda-entry-text-leaders][org-agenda-entry-text-leaders]]
+
+This allows you to get rid of the ">" character that gets added in front of
+entries excerpts when hitting =E= in the agenda view.
+
+**** New formatting string for past deadlines in [[doc:org-agenda-deadline-leaders][org-agenda-deadline-leaders]]
+
+The default formatting for past deadlines is ="%2d d. ago: "=, which makes
+it explicit that the deadline is in the past. You can configure this via
+[[doc:org-agenda-deadline-leaders][org-agenda-deadline-leaders]]. Note that the width of the formatting
+string is important to keep the agenda alignment clean.
+
+**** New allowed value =repeated-after-deadline= for [[doc:org-agenda-skip-scheduled-if-deadline-is-shown][org-agenda-skip-scheduled-if-deadline-is-shown]]
+
+When [[doc:org-agenda-skip-scheduled-if-deadline-is-shown][org-agenda-skip-scheduled-if-deadline-is-shown]] is set to
+=repeated-after-deadline=, the agenda will skip scheduled items if they are
+repeated beyond the current deadline.
+
+**** New option for [[doc:org-agenda-skip-deadline-prewarning-if-scheduled][org-agenda-skip-deadline-prewarning-if-scheduled]]
+
+This variable may be set to nil, t, the symbol `pre-scheduled', or a number
+which will then give the number of days before the actual deadline when the
+prewarnings should resume. The symbol `pre-scheduled' eliminates the
+deadline prewarning only prior to the scheduled date.
+
+Read the full docstring for details.
+
+**** [[doc:org-class][org-class]] now supports holiday strings in the skip-weeks parameter
+
+For example, this task will now be skipped only on new year's day:
+
+ : * Task
+ : <%%(org-class 2012 1 1 2013 12 12 2 "New Year's Day")>
+*** Capture
+
+**** Allow =C-1= as a prefix for [[doc:org-agenda-capture][org-agenda-capture]] and [[doc:org-capture][org-capture]]
+
+With a =C-1= prefix, the capture mechanism will use the =HH:MM= value at
+point (if any) or the current =HH:MM= time as the default time for the
+capture template.
+
+**** Expand keywords within %(sexp) placeholder in capture templates
+
+If you use a =%:keyword= construct within a =%(sexp)= construct, Org will
+expand the keywords before expanding the =%(sexp)=.
+
+**** Allow to contextualize capture (and agenda) commands by checking the name of the buffer
+
+[[doc:org-capture-templates-contexts][org-capture-templates-contexts]] and [[doc:org-agenda-custom-commands-contexts][org-agenda-custom-commands-contexts]]
+allow you to define what capture templates and what agenda commands should
+be available in various contexts. It is now possible for the context to
+check against the name of the buffer.
+*** Tag groups
+
+Using =#+TAGS: { Tag1 : Tag2 Tag3 }= will define =Tag1= as a /group tag/
+(note the colon after =Tag1=). If you search for =Tag1=, it will return
+headlines containing either =Tag1=, =Tag2= or =Tag3= (or any combination
+of those tags.)
+
+You can use group tags for sparse tree in an Org buffer, for creating
+agenda views, and for filtering.
+
+See http://orgmode.org/org.html#Tag-groups for details.
+
+*** Links
+
+**** =C-u C-u M-x org-store-link RET= will ignore non-core link functions
+
+Org knows how to store links from Org buffers, from info files and from
+other Emacs buffers. Org can be taught how to store links from any buffer
+through new link protocols (see [[http://orgmode.org/org.html#Adding-hyperlink-types]["Adding hyperlink types"]] in the manual.)
+
+Sometimes you want Org to ignore added link protocols and store the link
+as if the protocol was not known.
+
+You can now do this with =C-u C-u M-x org-store-link RET=.
+
+**** =C-u C-u C-u M-x org-store-link RET= on an active region will store links for each lines
+
+Imagine for example that you want to store a link for every message in a
+Gnus summary buffer. In that case =C-x h C-u C-u C-u M-x org-store-link
+RET= will store a link for every line (i.e. message) if the region is
+active.
+
+**** =C-c C-M-l= will add a default description for links which don't have one
+
+=C-c C-M-l= inserts all stored links. If a link does not have a
+description, this command now adds a default one, so that we are not mixing
+with-description and without-description links when inserting them.
+
+**** No curly braces to bracket links within internal links
+
+When storing a link to a headline like
+
+: * See [[http://orgmode.org][Org website]]
+
+[[doc:org-store-link][org-store-link]] used to convert the square brackets into curly brackets.
+It does not anymore, taking the link description or the link path, when
+there is no description.
+*** Table
+
+**** Switching between #+TBLFM lines
+
+If you have several =#+TBLFM= lines below a table, =C-c C-c= on a line will
+apply the formulas from this line, and =C-c C-c= on another line will apply
+those other formulas.
+
+**** You now use "nan" for empty fields in Calc formulas
+
+If empty fields are of interest, it is recommended to reread the section
+[[http://orgmode.org/org.html#Formula-syntax-for-Calc][3.5.2 Formula syntax for Calc]] of the manual because the description for the
+mode strings has been clarified and new examples have been added towards
+the end.
+
+**** Handle localized time-stamps in formulas evaluation
+
+If your =LOCALE= is set so that Org time-stamps use another language than
+english, and if you make time computations in Org's table, it now works by
+internally converting the time-stamps with a temporary =LOCALE=C= before
+doing computation.
+
+**** New lookup functions
+
+There are now three lookup functions:
+
+- [[doc:org-loopup-first][org-loopup-first]]
+- [[doc:org-loopup-last][org-loopup-last]]
+- [[doc:org-loopup-all][org-loopup-all]]
+
+See [[http://orgmode.org/org.html#Lookup-functions][the manual]] for details.
+*** Startup keywords
+
+These new startup keywords are now available:
+
+| Startup keyword | Option |
+|----------------------------------+---------------------------------------------|
+| =#+STARTUP: logdrawer= | =(setq org-log-into-drawer t)= |
+| =#+STARTUP: nologdrawer= | =(setq org-log-into-drawer nil)= |
+|----------------------------------+---------------------------------------------|
+| =#+STARTUP: logstatesreversed= | =(setq org-log-states-order-reversed t)= |
+| =#+STARTUP: nologstatesreversed= | =(setq org-log-states-order-reversed nil)= |
+|----------------------------------+---------------------------------------------|
+| =#+STARTUP: latexpreview= | =(setq org-startup-with-latex-preview t)= |
+| =#+STARTUP: nolatexpreview= | =(setq org-startup-with-latex-preview nil)= |
+
+*** Clocking
+
+**** New option [[doc:org-clock-rounding-minutes][org-clock-rounding-minutes]]
+
+E.g. if [[doc:org-clock-rounding-minutes][org-clock-rounding-minutes]] is set to 5, time is 14:47 and you
+clock in: then the clock starts at 14:45. If you clock out within the next
+5 minutes, the clock line will be removed; if you clock out 8 minutes after
+your clocked in, the clock out time will be 14:50.
+
+**** New option [[doc:org-time-clocksum-use-effort-durations][org-time-clocksum-use-effort-durations]]
+
+When non-nil, =C-c C-x C-d= uses effort durations. E.g., by default, one
+day is considered to be a 8 hours effort, so a task that has been clocked
+for 16 hours will be displayed as during 2 days in the clock display or in
+the clocktable.
+
+See [[doc:org-effort-durations][org-effort-durations]] on how to set effort durations and
+[[doc:org-time-clocksum-format][org-time-clocksum-format]] for more on time clock formats.
+
+**** New option [[doc:org-clock-x11idle-program-name][org-clock-x11idle-program-name]]
+
+This allows to set the name of the program which prints X11 idle time in
+milliseconds. The default is to use =x11idle=.
+
+**** New option [[doc:org-use-last-clock-out-time-as-effective-time][org-use-last-clock-out-time-as-effective-time]]
+
+When non-nil, use the last clock out time for [[doc:org-todo][org-todo]]. Note that this
+option has precedence over the combined use of [[doc:org-use-effective-time][org-use-effective-time]] and
+[[doc:org-extend-today-until][org-extend-today-until]].
+
+**** =S-<left/right>= on a clocksum column will update the sum by updating the last clock
+**** =C-u 3 C-S-<up/down>= will update clock timestamps synchronously by 3 units
+**** New parameter =:wstart= for clocktables to define the week start day
+**** New parameter =:mstart= to state the starting day of the month
+**** Allow relative times in clocktable tstart and tend options
+**** The clocktable summary is now a caption
+**** =:tstart= and =:tend= and friends allow relative times like "<-1w>" or "<now>"
+*** Babel
+
+**** You can now use =C-c C-k= for [[doc:org-edit-src-abort][org-edit-src-abort]]
+
+This allows you to quickly cancel editing a source block.
+
+**** =C-u C-u M-x org-babel-tangle RET= tangles by the target file of the block at point
+
+This is handy if you want to tangle all source code blocks that have the
+same target than the block at point.
+
+**** New options for auto-saving the base buffer or the source block editing buffer
+
+When [[doc:org-edit-src-turn-on-auto-save][org-edit-src-turn-on-auto-save]] is set to =t=, editing a source block
+in a new window will turn on =auto-save-mode= and save the code in a new
+file under the same directory than the base Org file.
+
+When [[doc:org-edit-src-auto-save-idle-delay][org-edit-src-auto-save-idle-delay]] is set to a number of minutes =N=,
+the base Org buffer will be saved after this number of minutes of idle
+time.
+
+**** New =:post= header argument post-processes results
+
+ This header argument may be used to pass the results of the current
+ code block through another code block for post-processing. See the
+ manual for a usage example.
+
+**** Commented out heading are ignored when collecting blocks for tangling
+
+If you comment out a heading (with =C-c ;= anywhere on the heading or in
+the subtree), code blocks from within this heading are now ignored when
+collecting blocks for tangling.
+
+**** New option [[doc:org-babel-hash-show-time][org-babel-hash-show-time]] to show a time-stamp in the result hash
+**** Do not ask for confirmation if cached value is current
+
+Do not run [[doc:org-babel-confirm-evaluate][org-babel-confirm-evaluate]] if source block has a cache and the
+cache value is current as there is no evaluation involved in this case.
+**** =ob-sql.el= and =ob-python.el= have been improved.
+**** New Babel files only need to =(require 'ob)=
+
+When writing a new Babel file, you now only need to use =(require 'ob)=
+instead of requiring each Babel library one by one.
+*** Faces
+
+- Org now fontifies radio link targets by default
+- In the agenda, use [[doc:org-todo-keyword-faces][org-todo-keyword-faces]] to highlight selected TODO keywords
+- New face [[doc:org-priority][org-priority]], enhanced fontification of priority cookies in agenda
+- New face [[doc:org-tag-group][org-tag-group]] for group tags
+
+** Miscellaneous
+
+- New speedy key =s= pour [[doc:org-narrow-to-subtree][org-narrow-to-subtree]]
+- Handling of [[doc:org-html-table-row][org-html-table-row]] has been updated (incompatible change)
+- [[doc:org-export-html-table-tag][org-export-html-table-tag]] is replaced by [[doc:org-html-table-default-attributes][org-html-table-default-attributes]]
+- Support using =git-annex= with Org attachments
+- org-protocol: Pass optional value using query in url to capture from protocol
+- When the refile history is empty, use the current filename as default
+- When you cannot change the TODO state of a task, Org displays the blocking task
+- New option [[doc:org-mobile-allpriorities][org-mobile-allpriorities]]
+- org-bibtex.el now use =visual-line-mode= instead of the deprecated =longlines-mode=
+- [[doc:org-format-latex-options][org-format-latex-options]] allows to set the foreground/background colors automatically
+- New option [[doc:org-archive-file-header-format][org-archive-file-header-format]]
+- New "neg" entity in [[doc:org-entities][org-entities]]
+- New function [[doc:org-docview-export][org-docview-export]] to export docview links
+- New =:eps= header argument for ditaa code blocks
+- New option [[doc:org-gnus-no-server][org-gnus-no-server]] to start Gnus with =gnus-no-server=
+- Org is now distributed with =htmlize.el= version 1.43
+- ~org-drill.el~ has been updated to version 2.3.7
+- ~org-mac-iCal.el~ now supports MacOSX version up to 10.8
+- Various improvements to ~org-contacts.el~ and =orgpan.el=
+
+** Outside Org
+
+*** Spanish translation of the Org guide by David Arroyo Menéndez
+
+David (and others) translated the Org compact guide in spanish:
+
+You can read the [[http://orgmode.org/worg/orgguide/orgguide.es.pdf][PDF guide]].
+
+*** ~poporg.el~ and ~outorg.el~
+
+Two new libraries (~poporg.el~ by François Pinard and ~outorg.el~ by
+Thorsten Jolitz) now enable editing of comment-sections from source-code
+buffers in temporary Org-mode buffers, making the full editing power of
+Org-mode available. ~outorg.el~ comes together with ~outshine.el~ and
+~navi-mode.el~, two more libraries by Thorsten Jolitz with the goal to give
+source-code buffers the /look & feel/ of Org-mode buffers while greatly
+improving navigation and structure editing. A detailed description can be
+found here: http://orgmode.org/worg/org-tutorials/org-outside-org.html
+
+Here are two screencasts demonstrating Thorsten's tools:
+
+- [[http://youtu.be/nqE6YxlY0rw]["Modern conventions for Emacs Lisp files"]]
+- [[http://www.youtube.com/watch?v%3DII-xYw5VGFM][Exploring Bernt Hansen's Org-mode tutorial with 'navi-mode']]
+
+*** MobileOrg for iOS
+
+MobileOrg for iOS back in the App Store The 1.6.0 release was focused on
+the new Dropbox API and minor bug fixes but also includes a new ability to
+launch in Capture mode. Track development and contribute [[https://github.com/MobileOrg/mobileorg/issues][on github]].
+
+* Version 7.9.3
+
+** New option [[doc::org-agenda-use-tag-inheritance][org-agenda-use-tag-inheritance]]
+
+[[doc::org-use-tag-inheritance][org-use-tag-inheritance]] controls whether tags are inherited when
+org-tags-view is called (either in =tags=, =tags-tree= or =tags-todo=
+agenda views.)
+
+When generating other agenda types such as =agenda=, =todo= and
+=todo-tree=, tags inheritance is not used when selecting the entries
+to display. Still, you might want to have all tag information correct
+in the agenda buffer, e.g. for tag filtering. In that case, add the
+agenda type to this variable.
+
+Setting this variable to nil should considerably speeds up the agenda
+generation.
+
+Note that the default was to display inherited tags in the agenda
+lines even if `org-use-tag-inheritance' was nil. The default is now
+to *never* display inherited tags in agenda lines, but to /know/ about
+them when the agenda type is listed in [[doc::org-agenda-use-tag-inheritance][org-agenda-use-tag-inheritance]].
+
+** New default value nil for [[doc::org-agenda-dim-blocked-tasks][org-agenda-dim-blocked-tasks]]
+
+Using `nil' as the default value speeds up the agenda generation. You
+can hit `#' (or `C-u #') in agenda buffers to temporarily dim (or turn
+invisible) blocked tasks.
+
+** New speedy keys for [[doc::org-speed-commands-default][org-speed-commands-default]]
+
+You can now use `:' (instead of `;') for setting tags---this is
+consistent with using the `:' key in agenda view.
+
+You can now use `=' for [[doc::org-columns][org-columns]].
+
+** =org-float= is now obsolete, use =diary-float= instead
+** No GPL manual anymore
+
+There used to be a GPL version of the Org manual, but this is not the
+case anymore, the Free Software Foundation does not permit this.
+
+The GNU FDL license is now included in the manual directly.
+
+** Enhanced compatibility with Emacs 22 and XEmacs
+
+Thanks to Achim for his work on enhancing Org's compatibility with
+various Emacsen. Things may not be perfect, but Org should work okay
+in most environments.
+
+* Version 7.9.2
+
+** New ELPA repository for Org packages
+
+You can now add the Org ELPA repository like this:
+
+#+BEGIN_SRC emacs-lisp
+(add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/") t)
+#+END_SRC
+
+It contains both the =org-*.tar= package (the core Org distribution, also
+available through http://elpa.gnu.org) and the =org-plus*.tar= package (the
+extended Org distribution, with non-GNU packages from the =contrib/=
+directory.)
+
+See http://orgmode.org/elpa/
+
+** Overview of the new keybindings
+
+ | Keybinding | Speedy | Command |
+ |-----------------+--------+-----------------------------|
+ | =C-c C-x C-z= | | [[doc::org-clock-resolve][org-clock-resolve]] |
+ | =C-c C-x C-q= | | [[doc::org-clock-cancel][org-clock-cancel]] |
+ | =C-c C-x C-x= | | [[doc::org-clock-in-last][org-clock-in-last]] |
+ | =M-h= | | [[doc::org-mark-element][org-mark-element]] |
+ | =*= | | [[doc::org-agenda-bulk-mark-all][org-agenda-bulk-mark-all]] |
+ | =C-c C-M-l= | | [[doc::org-insert-all-links][org-insert-all-links]] |
+ | =C-c C-x C-M-v= | | [[doc::org-redisplay-inline-images][org-redisplay-inline-images]] |
+ | =C-c C-x E= | =E= | [[doc::org-inc-effort][org-inc-effort]] |
+ | | =#= | [[doc::org-toggle-comment][org-toggle-comment]] |
+ | | =:= | [[doc::org-columns][org-columns]] |
+ | | =W= | Set =APPT_WARNTIME= |
+ | =k= | | [[doc::org-agenda-capture][org-agenda-capture]] |
+ | C-c , | , | [[doc::org-priority][org-priority]] |
+
+** New package and Babel language
+
+*** =org-eshell.el= by Konrad Hinsen is now in Org
+
+ =org-eshell.el= allows you to create links from [[http://www.gnu.org/software/emacs/manual/html_node/eshell/index.html][Eshell]].
+
+*** Support for execution of Scala code blocks (see ob-scala.el)
+*** Support for execution of IO code blocks (see ob-io.el)
+
+** Incompatible changes
+
+ - If your code relies on =org-write-agenda=, please use
+ [[doc::org-agenda-write][org-agenda-write]] from now on.
+
+ - If your code relies on =org-make-link=, please use =concat=
+ instead.
+
+ - =org-link-to-org-use-id= has been renamed to
+ =org-id-link-to-org-use-id= and its default value is nil. The
+ previous default was =create-if-interactive-and-no-custom-id=.
+
+** New features and user-visible changes
+
+*** Org Element
+
+ =org-element.el= is a toolbox for parsing and analyzing "elements"
+ in an Org-mode buffer. This has been written by Nicolas Goaziou
+ and has been tested for quite some time. It is now part of Org's
+ core and many core functions rely on this package.
+
+ Two functions might be particularly handy for users:
+ =org-element-at-point= and =org-element-context=.
+
+ See the docstrings for more details.
+
+ Below is a list of editing and navigating commands that now rely
+ on =org-element.el=.
+
+**** [[doc::org-fill-paragraph][org-fill-paragraph]] has been completely rewritten
+
+ The filling mechanisms now rely on org-element, trying to do the
+ right thing on each element in various contexts. E.g. filling in
+ a list item will preserve indentation; filling in message-mode
+ will fall back on the relevant filling functions; etc.
+
+**** [[doc::org-metaup][org-metaup]] and [[doc::org-metadown][org-metadown]] will drag the element backward/forward
+
+ If you want to get the old behavior (i.e. moving a line up and
+ down), you can first select the line as an active region, then
+ =org-metaup= or =org-metadown= to move the region backward or
+ forward. This also works with regions bigger than just one line.
+
+**** [[doc::org-up-element][org-up-element]] and [[doc::org-down-element][org-down-element]] (respectively =C-c C-^= and =C-c C-_=)
+
+ This will move the point up/down in the hierarchy of elements.
+
+**** [[doc::org-backward-element][org-backward-element]] and [[doc::org-forward-element][org-forward-element]] (respectively =M-{= and =M-}=)
+
+ This will move the point backward/forward in the hierarchy of
+ elements.
+
+**** [[doc::org-narrow-to-element][org-narrow-to-element]] will narrow to the element at point
+**** [[doc::org-mark-element][org-mark-element]] will mark the element at point
+
+ This command is bound to =M-h= and will mark the element at
+ point. If the point is at a paragraph, it will mark the
+ paragraph. If the point is at a list item, it will mark the list
+ item. Etc.
+
+ Note that if point is at the beginning of a list, it will mark
+ the whole list.
+
+ To mark a subtree, you can either use =M-h= on the headline
+ (since there is no ambiguity about the element you're at) or
+ [[doc::org-mark-subtree][org-mark-subtree]] (=C-c @=) anywhere in the subtree.
+
+ Invoking [[doc::org-mark-element][org-mark-element]] repeatedly will try to mark the next
+ element on top of the previous one(s). E.g. hitting =M-h= twice
+ on a headline will mark the current subtree and the next one on
+ the same level.
+
+*** Org Agenda
+
+**** New option [[doc::org-agenda-sticky][org-agenda-sticky]]
+
+ There is a new option =org-agenda-sticky= which enables "sticky"
+ agendas. Sticky agendas remain opened in the background so that
+ you don't need to regenerate them each time you hit the
+ corresponding keystroke. This is a big time saver.
+
+ When [[doc::org-agenda-sticky][org-agenda-sticky]] is =non-nil=, the agenda buffer will be
+ named using the agenda key and its description. In sticky
+ agendas, the =q= key will just bury the agenda buffers and
+ further agenda commands will show existing buffer instead of
+ generating new ones.
+
+ If [[doc::org-agenda-sticky][org-agenda-sticky]] is set to =nil=, =q= will kill the single
+ agenda buffer.
+
+**** New option [[doc::org-agenda-custom-commands-contexts][org-agenda-custom-commands-contexts]]
+
+ Setting this option allows you to define specific context where
+ agenda commands should be available from. For example, when set
+ to this value
+
+ #+BEGIN_SRC emacs-lisp
+ (setq org-agenda-custom-commands-contexts
+ '(("p" (in-file . "\\.txt"))))
+#+END_SRC
+
+ then the =p= agenda command will only be available from buffers
+ visiting *.txt files. See the docstring and the manual for more
+ details on how to use this.
+
+**** Changes in bulk actions
+
+ The set of commands starting with =k ...= as been deleted and the
+ features have been merged into the "bulk action" feature.
+
+ After you marked some entries in the agenda, if you call =B s=,
+ the agenda entries will be rescheduled using the date at point if
+ on a date header. If you are on an entry with a timestamp, you
+ will be prompted for a date to reschedule your marked entries to,
+ using the timestamp at point as the default prompt.
+
+ You can now use =k= to capture the marked entry and use the date
+ at point as an overriding date for the capture template.
+
+ To bind this behavior to =M-x org-capture RET= (or its
+ keybinding), set the new option [[doc::org-capture-use-agenda-date][org-capture-use-agenda-date]] to
+ =t=.
+
+**** =N= and =P= in the agenda will move to the next/previous item
+
+**** New command [[doc::org-agenda-bulk-mark-all][org-agenda-bulk-mark-all]] to mark all items
+
+ This new command is bound to =*= in agenda mode.
+
+ There is also a new option [[doc::org-agenda-bulk-mark-char][org-agenda-bulk-mark-char]] to set the
+ character to use as a mark for bulk actions.
+
+**** New option [[doc::org-agenda-persistent-marks][org-agenda-persistent-marks]]
+
+ When set to =non-nil=, marks will remain visible after a bulk
+ action. You can temporarily toggle this by pressing =p= when
+ invoking [[doc::org-agenda-bulk-action][org-agenda-bulk-action]]. Marks are deleted if your
+ rebuild the agenda buffer or move to another date/span (e.g. with
+ =f= or =w=).
+
+**** New option [[doc::org-agenda-skip-timestamp-if-deadline-is-shown][org-agenda-skip-timestamp-if-deadline-is-shown]]
+
+ =Non-nil= means skip timestamp line if same entry shows because
+ of deadline.
+
+ In the agenda of today, an entry can show up multiple times
+ because it has both a plain timestamp and has a nearby deadline.
+ When this variable is t, then only the deadline is shown and the
+ fact that the entry has a timestamp for or including today is not
+ shown. When this variable is =nil=, the entry will be shown
+ several times.
+
+**** New =todo-unblocked= and =nottodo-unblocked= skip conditions
+
+ See the [[http://orgmode.org/cgit.cgi/org-mode.git/commit/?id=f426da][git commit]] for more explanations.
+
+**** Allow category filtering in the agenda
+
+ You can now filter the agenda by category. Pressing "<" will
+ filter by the category of the item on the current line, and
+ pressing "<" again will remove the filter. You can combine tag
+ filters and category filters.
+
+ You can use =org-agenda-category-filter= in your custom agenda
+ views and =org-agenda-category-filter-preset= in your main
+ configuration.
+
+ See also the new command [[doc::org-agenda-filter-by-top-category][org-agenda-filter-by-top-category]]:
+ hitting =^= will filter by "Top" category: only show entries that
+ are of the same category than the Top category of the entry at
+ point.
+
+*** Org Links
+
+**** Inserting links
+
+ When inserting links through [[doc::org-insert-link][org-insert-link]], the description is
+ now displayed first, followed by the literal link, as the
+ description is often more useful when you look for the link you
+ want to insert.
+
+ Completion now complete both literal links and description. If
+ you complete a description, the literal link and its description
+ will be inserted directly, whereas when you complete the literal
+ link, you will be prompted for a description (as with Org 7.8.)
+
+ In the completion buffer, links to the current buffer are now
+ highlighted.
+
+**** New templates =%h= and =%(sexp)= for abbreviated links
+
+ On top of =%s= template, which is replaced by the link tag in
+ abbreviated links, you can now use =%h= (which does the same than =%s=
+ but does not hexify the tag) and =%(sexp)= (which can run a function
+ that takes the tag as its own argument.)
+
+**** New link type =help=
+
+ You can now create links from =help= buffers.
+
+ For example, if you request help for the command [[doc::org-agenda][org-agenda]] with
+ =C-h f org-agenda RET=, creating a link from this buffer will let
+ you go back to the same buffer.
+
+**** New command [[doc::org-insert-all-links][org-insert-all-links]]
+
+ This will insert all links as list items. With a universal
+ prefix argument, links will not be deleted from the variable
+ =org-stored-links=.
+
+ This new command is bound to =C-c C-M-l=.
+
+**** New option [[doc::org-url-hexify-p][org-url-hexify-p]]
+
+ When set to =nil=, the =URL= part of a link will not be hexified.
+
+**** Org can now open multiple shell links
+
+**** New option [[doc::org-doi-server-url][org-doi-server-url]] to specify an alternate DOI server
+
+**** RET now follows time stamps links
+
+*** Org Editing
+
+**** [[doc::org-todo][org-todo]] and =org-archive-*= can now loop in the active region
+
+ When [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is =non-nil=, using
+ [[doc::org-todo][org-todo]] or =org-archive-*= commands in the active region will
+ loop over headlines. This is handy if you want to set the TODO
+ keyword for several items, or archive them quickly.
+
+**** You can now set tags for headlines in a region
+
+ If [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is =non-nil=, then
+ selecting the region and hitting =C-c C-q= will set the tags for
+ all headlines in the region.
+
+**** New command [[doc::org-insert-drawer][org-insert-drawer]] to insert a drawer interactively
+
+**** Comments start with "^[ \t]*# " anywhere on a line
+
+ Note that the space after the hashtag is mandatory. Comments
+ with "^#+" are not supported anymore.
+
+**** New speed key =#= to toggle the COMMENT cookie on a headline
+
+**** =indent-region-function= is now set to [[doc::org-indent-region][org-indent-region]]
+
+ =C-M-\= should now produce useful results.
+
+ You can unindent the buffer with [[doc::org-unindent-buffer][org-unindent-buffer]].
+
+**** New option [[doc::org-allow-promoting-top-level-subtree][org-allow-promoting-top-level-subtree]]
+
+ When =non-nil=, =S-M-<left>= will promote level-1 subtrees
+ containing other subtrees. The level-1 headline will be
+ commented out. You can revert to the previous state with =M-x
+ undo RET=.
+
+*** Org Clock
+
+**** New keybinding =C-c C-x C-z= for [[doc::org-clock-resolve][org-clock-resolve]]
+
+**** New keybinding =C-c C-x C-q= for [[doc::org-clock-cancel][org-clock-cancel]]
+
+**** New command [[doc::org-clock-in-last][org-clock-in-last]] to clock in the last clocked item
+
+ This command is bound to =C-c C-x C-x= and will clock in the last
+ clocked entry, if any.
+
+**** =C-u M-x= [[doc::org-clock-out][org-clock-out]] =RET= now prompts for a state to switch to
+
+**** =S-M-<up/down>= on a clock timestamps adjusts the previous/next clock
+
+**** New option [[doc::org-clock-continuously][org-clock-continuously]]
+
+ When set to =nil=, clocking in a task will first try to find the
+ last clocked out task and restart from when that task was clocked
+ out.
+
+ You can temporarily activate continuous clocking with =C-u C-u
+ C-u M-x= [[doc::org-clock-in][org-clock-in]] =RET= (three universal prefix arguments)
+ and =C-u C-u M-x= [[org-clock-in-last][org-clock-in-last]] =RET= (two universal prefix
+ arguments).
+
+
+**** New option [[doc::org-clock-frame-title-format][org-clock-frame-title-format]]
+
+ This option sets the value of =frame-title-format= when clocking
+ in.
+
+**** New options for controlling the clockreport display
+
+ [[doc::org-clock-file-time-cell-format][org-clock-file-time-cell-format]]: Format string for the file time
+ cells in clockreport.
+
+ [[doc::org-clock-total-time-cell-format][org-clock-total-time-cell-format]]: Format string for the total
+ time cells in clockreport.
+
+
+**** New options for controlling the clock/timer display
+
+ [[doc::org-clock-clocked-in-display][org-clock-clocked-in-display]]: control whether the current clock
+ is displayed in the mode line and/or frame title.
+
+ [[doc::org-timer-display][org-timer-display]]: control whether the current timer is displayed
+ in the mode line and/or frame title.
+
+ This allows the clock and timer to be displayed in the frame
+ title instead of, or as well as, the mode line. This is useful
+ for people with limited space in the mode line but with ample
+ space in the frame title.
+
+*** Org Appearance
+
+**** New option [[doc::org-custom-properties][org-custom-properties]]
+
+ The visibility of properties listed in this options can be turn
+ on/off with [[doc::org-toggle-custom-properties-visibility][org-toggle-custom-properties-visibility]]. This might
+ be useful for properties used by third-part tools or that you
+ don't want to see temporarily.
+
+**** New command [[doc::org-redisplay-inline-images][org-redisplay-inline-images]]
+
+ This will redisplay all images. It is bound to =C-c C-x C-M-v=.
+
+**** New entities in =org-entities.el=
+
+ There are these new entities:
+
+ : ("tilde" "\\~{}" nil "&tilde;" "~" "~" "~")
+ : ("slash" "/" nil "/" "/" "/" "/")
+ : ("plus" "+" nil "+" "+" "+" "+")
+ : ("under" "\\_" nil "_" "_" "_" "_")
+ : ("equal" "=" nil "=" "=" "=" "=")
+ : ("asciicirc" "\\textasciicircum{}" nil "^" "^" "^" "^")
+
+**** New face =org-list-dt= for definition terms
+**** New face =org-date-selected= for the selected calendar day
+**** New face value for =org-document-title=
+
+ The face is back to a normal height.
+
+*** Org Columns
+
+**** New speed command =:= to activate the column view
+**** New special property =CLOCKSUM_T= to display today's clocked time
+
+ You can use =CLOCKSUM_T= the same way you use =CLOCKSUM=. It
+ will display the time spent on tasks for today only.
+
+**** Use the =:COLUMNS:= property in columnview dynamic blocks
+
+ If the =:COLUMNS:= is set in a subtree, the columnview dynamic
+ block will use its value as the column format.
+
+**** Consider inline tasks when computing a sum
+
+*** Org Dates and Time Stamps
+
+**** Enhanced [[doc::org-sparse-tree][org-sparse-tree]]
+
+ =C-c /= can now check for time ranges.
+
+ When checking for dates with =C-c /= it is useful to change the
+ type of dates that you are interested in. You can now do this
+ interactively with =c= after =C-c /= and/or by setting
+ [[doc::org-sparse-tree-default-date-type][org-sparse-tree-default-date-type]] to the default value you want.
+
+**** Support for hourly repeat cookies
+
+ You can now use
+
+ : SCHEDULED: <2012-08-20 lun. 08:00 +1h>
+
+ if you want to add an hourly repeater to an entry.
+
+**** =C-u C-u C-c .= inserts a time-stamp with no prompt
+
+**** When (setq [[doc::org-read-date-prefer-future][org-read-date-prefer-future]] 'time), accept days in the prompt
+
+ "8am Wed" and "Wed 8am" are now acceptable values when entering a
+ date from the prompt. If [[doc::org-read-date-prefer-future][org-read-date-prefer-future]] is set to
+ =time=, this will produce the expected prompt indication.
+
+**** New option [[doc::org-datetree-add-timestamp][org-datetree-add-timestamp]]
+
+ When set to =non-nil=, datetree entries will also have a
+ timestamp. This is useful if you want to see these entries in a
+ sparse tree with =C-c /=.
+
+*** Org Capture
+
+**** New command [[doc::org-capture-string][org-capture-string]]
+
+ M-x [[doc::org-capture-string][org-capture-string]] RET will prompt for a string and a capture
+ template. The string will be used as an annotation for the
+ template. This is useful when capturing in batch mode as it lets
+ you define the content of the template without being in Emacs.
+
+**** New option [[doc::org-capture-templates-contexts][org-capture-templates-contexts]]
+
+ Setting this option allows you to define specific context where
+ capture templates should be available from. For example, when
+ set to this value
+
+ #+BEGIN_SRC emacs-lisp
+ (setq org-capture-templates-contexts
+ '(("c" (in-mode . "message-mode"))))
+#+END_SRC
+
+ then the =c= capture template will only be available from
+ =message-mode= buffers. See the docstring and the manual for
+ more details on how to use this.
+
+**** New =%l= template to insert the literal link
+**** New option [[doc::org-capture-bookmark][org-capture-bookmark]]
+
+ Org used to automatically add a bookmark with capture a note.
+ You can now turn this on by setting [[doc::org-capture-bookmark][org-capture-bookmark]] to
+ =nil=.
+
+**** Expand =%<num>= escape sequences into text entered for <num>'th =%^{PROMPT}= escape
+
+ See the manual for more explanations.
+
+**** More control over empty lines
+
+ You can use =:empty-lines-before= and =:empty-lines-after= to
+ control the insertion of empty lines. Check the manual for more
+ explanations.
+
+**** New hook [[doc::org-capture-prepare-finalize-hook][org-capture-prepare-finalize-hook]]
+
+ This new hook runs before the finalization process starts.
+
+*** Org Export
+
+**** New functions =orgtbl-to-table.el= and =orgtbl-to-unicode=
+
+ =orgtbl-to-table.el= convert the table to a =table.el= table, and
+ =orgtbl-to-unicode= will use =ascii-art-to-unicode.el= (when
+ available) to print beautiful tables.
+
+**** [[doc::org-table-export][org-table-export]] now a bit clever about the target format
+
+ When you specify a file name like =table.csv=, [[doc::org-table-export][org-table-export]]
+ will now suggest =orgtbl-to-csv= the default method for exporting
+ the table.
+
+**** New option [[doc::org-export-date-timestamp-format][org-export-date-timestamp-format]]
+
+ The option allows to set a time string format for Org timestamps
+ in the #+DATE option.
+
+**** LaTeX: New options for exporting table rules :tstart, :hline and :tend
+
+ See [[doc::org-export-latex-tables-hline][org-export-latex-tables-hline]] and [[doc::org-export-latex-tables-tend][org-export-latex-tables-tend]].
+
+**** LaTeX: You can now set =:hfmt= from =#+ATTR_LaTeX=
+**** Beamer: Add support and keybinding for the =exampleblock= environment
+
+ Add support for these languages in [[doc::org-export-language-setup][org-export-language-setup]].
+ More languages are always welcome.
+
+**** Beamer: New option [[doc::org-beamer-inherited-properties][org-beamer-inherited-properties]]
+
+ This option allows Beamer export to inherit some properties.
+ Thanks to Carsten for implementing this.
+
+**** ODT: Add support for ODT export in org-bbdb.el
+**** ODT: Add support for indented tables (see [[http://orgmode.org/cgit.cgi/org-mode.git/commit/?id=e9fd33][this commit]] for details)
+**** ODT: Improve the conversion from ODT to other formats
+**** ASCII: Swap the level-1/level-2 characters to underline the headlines
+**** Support for Chinese, simplified Chinese, Russian, Ukrainian and Japanese
+**** HTML: New option [[doc::org-export-html-date-format-string][org-export-html-date-format-string]]
+
+ Format string to format the date and time in HTML export. Thanks
+ to Sébastien Vauban for this patch.
+
+*** Org Babel
+
+**** New =:results drawer= parameter
+
+=:results drawer= replaces =:results wrap=, which is deprecated but still
+supported.
+
+**** =:results org= now put results in a =#+BEGIN_SRC org= block
+
+=:results org= used to put results in a =#+BEGIN_ORG= block but it now puts
+results in a =#+BEGIN_SRC org= block, with comma-escaped lines.
+
+=#+BEGIN_ORG= blocks are obsolete.
+
+**** Exporting =#+BEGIN_SRC org= blocks exports the code
+
+It used to exports the results of the code.
+
+*** Miscellaneous
+
+**** New menu entry for [[doc::org-refile][org-refile]]
+**** Allow capturing to encrypted entries
+
+If you capture to an encrypted entry, it will be decrypted before
+inserting the template then re-encrypted after finalizing the capture.
+
+**** Inactive timestamps are now handled in tables
+
+Calc can do computation on active time-stamps like <2012-09-29 sat.>.
+Inactive time-stamps in a table's cell are now internally deactivated so
+that Calc formulas can operate on them.
+
+**** [[doc::org-table-number-regexp][org-table-number-regexp]] can now accept comma as decimal mark
+**** Org allows a new property =APPT_WARNTIME=
+
+ You can set it with the =W= speedy key or set it manually. When
+ set, exporting to iCalendar and [[doc::org-agenda-to-appt][org-agenda-to-appt]] will use the
+ value of this property as the number of minutes for the warning
+ alarm.
+
+**** New command [[doc::org-inc-effort][org-inc-effort]]
+
+ This will increment the effort value.
+
+ It is bound to =C-c C-x E= and to =E= as a speedy command.
+
+**** Attach: Add support for creating symbolic links
+
+ =org-attach-method= now supports a new method =lns=, allowing to
+ attach symbolic links.
+
+**** Archive: you can now archive to a datetree
+
+**** New option [[doc::org-inlinetask-show-first-star][org-inlinetask-show-first-star]]
+
+ =Non-nil= means display the first star of an inline task as
+ additional marker. When =nil=, the first star is not shown.
+
+**** New option [[doc::org-latex-preview-ltxpng-directory][org-latex-preview-ltxpng-directory]]
+
+ This lets you define the path for the =ltxpng/= directory.
+
+**** You can now use imagemagick instead of dvipng to preview LaTeX fragments
+**** You can now turn off [[doc::orgstruct++-mode][orgstruct++-mode]] safely
+**** =C-u C-c C-c= on list items to add check boxes
+
+ =C-u C-c C-c= will add an empty check box on a list item.
+
+ When hit from the top of the list, it will add check boxes for
+ all top level list items.
+
+**** =org-list-ending-method= and =org-list-end-regexp= are now obsolete
+
+ Fall back on using =org-list-end-re= only, which see.
+
+**** org-feed.el now expands =%(sexp)= templates
+**** New option [[doc::org-protocol-data-separator][org-protocol-data-separator]]
+
+**** New option [[doc::org-ditaa-jar-option][org-ditaa-jar-option]] to specify the ditaa jar file
+
+**** New possible value for [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]]
+
+ When [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is set to
+ =start-level=, the command will loop over the active region but
+ will only act upon entries that are of the same level than the
+ first headline in the region.
+
+**** New option [[doc::org-habit-show-all-today][org-habit-show-all-today]]
+
+ When set to =t=, show all (even unscheduled) habits on today's
+ agenda.
+
+** Important bug fixes
+
+*** M-TAB on options keywords perform completion correctly again
+
+ If you hit =M-TAB= on keywords like =#+TITLE=, Org will try to
+ perform completion with meaningful values.
+
+*** Add licenses to javascript embedded and external code snippets
+
+ Embedded javascript code produced when exporting an Org file to
+ HTML is now licensed under GPLv3 (or later), and the copyright is
+ owned by the Free Software Foundation, Inc.
+
+ The javascript code for embedding MathJax in the browser mentions
+ the MathJax copyright and the Apache 2.0 license.
+
+ The javascript code for embedding =org-injo.js= in the browser
+ mentions the copyright of Sebastian Rose and the GPLv3 (or later)
+ license.
+
+ =org-export-html-scripts= is now a variable, so that you can adapt
+ the code and the license to your needs.
+
+ See http://www.gnu.org/philosophy/javascript-trap.html for
+ explanations on why these changes were necessary.
+
+* Version 7.8.11
+
+** Incompatible changes
+
+*** Emacs 21 support has been dropped
+
+ Do not use Org mode 7.xx with Emacs 21, use [[http://orgmode.org/org-6.36c.zip][version 6.36c]] instead.
+
+*** XEmacs support requires the XEmacs development version
+
+ To use Org mode 7.xx with XEmacs, you need to run the developer
+ version of XEmacs. We were about to drop XEmacs support entirely,
+ but Michael Sperber stepped in and made changes to XEmacs that
+ made it easier to keep the support. Thanks to Michael for this
+ last-minute save.
+
+*** New keys for TODO sparse trees
+
+ The key =C-c C-v= is now reserved for Org Babel action. TODO
+ sparse trees can still be made with =C-c / t= (all not-done
+ states) and =C-c / T= (specific states).
+
+*** The Agenda =org-agenda-ndays= is now obsolete
+
+ The variable =org-agenda-ndays= is obsolete - please use
+ =org-agenda-span= instead.
+
+ Thanks to Julien Danjou for this.
+
+*** Changes to the intended use of =org-export-latex-classes=
+
+ So far this variable has been used to specify the complete header
+ of the LaTeX document, including all the =\usepackage= calls
+ necessary for the document. This setup makes it difficult to
+ maintain the list of packages that Org itself would like to call,
+ for example for the special symbol support it needs.
+
+ First of all, you can *opt out of this change* in the following
+ way: You can say: /I want to have full control over headers, and I
+ will take responsibility to include the packages Org needs/. If
+ that is what you want, add this to your configuration and skip the
+ rest of this section (except maybe for the description of the
+ =[EXTRA]= place holder):
+
+ #+begin_src emacs-lisp
+ (setq org-export-latex-default-packages-alist nil
+ org-export-latex-packages-alist nil)
+ #+end_src
+
+ /Continue to read here if you want to go along with the modified
+ setup./
+
+ There are now two variables that should be used to list the LaTeX
+ packages that need to be included in all classes. The header
+ definition in =org-export-latex-classes= should then not contain
+ the corresponding =\usepackage= calls (see below).
+
+ The two new variables are:
+
+ 1. =org-export-latex-default-packages-alist= :: This is the
+ variable where Org-mode itself puts the packages it needs.
+ Normally you should not change this variable. The only
+ reason to change it anyway is when one of these packages
+ causes a conflict with another package you want to use. Then
+ you can remove that packages and hope that you are not using
+ Org-mode functionality that needs it.
+
+ 2. =org-export-latex-packages-alist= :: This is the variable where
+ you can put the packages that you'd like to use across all
+ classes.
+
+ The sequence how these customizations will show up in the LaTeX
+ document are:
+
+ 1. Header from =org-export-latex-classes=
+ 2. =org-export-latex-default-packages-alist=
+ 3. =org-export-latex-packages-alist=
+ 4. Buffer-specific things set with =#+LaTeX_HEADER:=
+
+ If you want more control about which segment is placed where, or
+ if you want, for a specific class, have full control over the
+ header and exclude some of the automatic building blocks, you can
+ put the following macro-like place holders into the header:
+
+ #+begin_example
+ [DEFAULT-PACKAGES] \usepackage statements for default packages
+ [NO-DEFAULT-PACKAGES] do not include any of the default packages
+ [PACKAGES] \usepackage statements for packages
+ [NO-PACKAGES] do not include the packages
+ [EXTRA] the stuff from #+LaTeX_HEADER
+ [NO-EXTRA] do not include #+LaTeX_HEADER stuff
+ #+end_example
+
+ If you have currently customized =org-export-latex-classes=, you
+ should revise that customization and remove any package calls that
+ are covered by =org-export-latex-default-packages-alist=. This
+ applies to the following packages:
+
+ - inputenc
+ - fontenc
+ - fixltx2e
+ - graphicx
+ - longtable
+ - float
+ - wrapfig
+ - soul
+ - t1enc
+ - textcomp
+ - marvosym
+ - wasysym
+ - latexsym
+ - amssymb
+ - hyperref
+
+ If one of these packages creates a conflict with another package
+ you are using, you can remove it from
+ =org-export-latex-default-packages-alist=. But then you risk that
+ some of the advertised export features of Org will not work
+ properly.
+
+ You can also consider moving packages that you use in all classes
+ to =org-export-latex-packages-alist=. If necessary, put the place
+ holders so that the packages get loaded in the right sequence. As
+ said above, for backward compatibility, if you omit the place
+ holders, all the variables will dump their content at the end of
+ the header.
+
+*** The constant =org-html-entities= is obsolete
+
+ Its content is now part of the new constant =org-entities=, which
+ is defined in the file org-entities.el. =org-html-entities= was
+ an internal variable, but it is possible that some users did write
+ code using it.
+
+*** =org-bbdb-anniversary-format-alist= has changed
+
+ Please check the docstring and update your settings accordingly.
+
+*** Deleted =org-mode-p=
+
+ This function has been deleted: please update your code.
+
+** Important new features
+
+*** New Org to ODT exporter
+
+ Jambunathan's Org to ODT exporter is now part of Org.
+
+ To use it, it `C-c C-e o' in an Org file. See the documentation
+ for more information on how to customize it.
+
+*** org-capture.el is now the default capture system
+
+ This replaces the earlier system org-remember. The manual only
+ describes org-capture, but for people who prefer to continue to
+ use org-remember, we keep a static copy of the former manual
+ section [[http://orgmode.org/org-remember.pdf][chapter about remember]].
+
+ The new system has a technically cleaner implementation and more
+ possibilities for capturing different types of data. See
+ [[http://thread.gmane.org/gmane.emacs.orgmode/26441/focus%3D26441][Carsten's announcement]] for more details.
+
+ To switch over to the new system:
+
+ 1. Run
+
+ : M-x org-capture-import-remember-templates RET
+
+ to get a translated version of your remember templates into the
+ new variable =org-capture-templates=. This will "mostly" work,
+ but maybe not for all cases. At least it will give you a good
+ place to modify your templates. After running this command,
+ enter the customize buffer for this variable with
+
+ : M-x customize-variable RET org-capture-templates RET
+
+ and convince yourself that everything is OK. Then save the
+ customization.
+
+ 2. Bind the command =org-capture= to a key, similar to what you did
+ with org-remember:
+
+ : (define-key global-map "\C-cc" 'org-capture)
+
+ If your fingers prefer =C-c r=, you can also use this key once
+ you have decided to move over completely to the new
+ implementation. During a test time, there is nothing wrong
+ with using both system in parallel.
+
+** New libraries
+
+*** New Org libraries
+**** org-eshell.el (Konrad Hinsen)
+
+ Implement links to eshell buffers.
+
+**** org-special-blocks (Carsten Dominik)
+
+ This package generalizes the #+begin_foo and #+end_foo tokens.
+
+ To use, put the following in your init file:
+
+ #+BEGIN_EXAMPLE
+(require 'org-special-blocks)
+#+END_EXAMPLE
+
+ The tokens #+begin_center, #+begin_verse, etc. existed
+ previously. This package generalizes them (at least for the
+ LaTeX and html exporters). When a #+begin_foo token is
+ encountered by the LaTeX exporter, it is expanded
+ into \begin{foo}. The text inside the environment is not
+ protected, as text inside environments generally is.
+ When #+begin_foo is encountered by the html exporter, a div with
+ class foo is inserted into the HTML file. It is up to the user
+ to add this class to his or her stylesheet if this div is to mean
+ anything.
+
+**** org-taskjuggler.el (Christian Egli)
+
+ Christian Egli's /org-taskjuggler.el/ module is now part of Org.
+ He also wrote a [[http://orgmode.org/worg/org-tutorials/org-taskjuggler.php][tutorial]] for it.
+
+**** org-ctags.el (Paul Sexton)
+
+ Targets like =<<my target>>= can now be found by Emacs' etag
+ functionality, and Org-mode links can be used to to link to
+ etags, also in non-Org-mode files. For details, see the file
+ /org-ctags.el/.
+
+ This feature uses a new hook =org-open-link-functions= which will
+ call function to do something special with text links.
+
+ Thanks to Paul Sexton for this contribution.
+
+**** org-docview.el (Jan Böcker)
+
+ This new module allows links to various file types using docview, where
+ Emacs displays images of document pages. Docview link types can point
+ to a specific page in a document, for example to page 131 of the
+ Org-mode manual:
+
+ : [[docview:~/.elisp/org/doc/org.pdf::131][Org-Mode Manual]]
+
+ Thanks to Jan Böcker for this contribution.
+
+*** New Babel libraries
+
+- ob-picolisp.el (Thorsten Jolitz)
+- ob-fortran.el (Sergey Litvinov)
+- ob-shen.el (Eric Schulte)
+- ob-maxima.el (Eric S Fraga)
+- ob-java.el (Eric Schulte)
+- ob-lilypond.el (Martyn Jago)
+- ob-awk.el (Eric Schulte)
+
+** Other new features and various enhancements
+
+*** Hyperlinks
+
+**** Org-Bibtex -- major improvements
+
+ Provides support for managing bibtex bibliographical references
+ data in headline properties. Each headline corresponds to a
+ single reference and the relevant bibliographic meta-data is
+ stored in headline properties, leaving the body of the headline
+ free to hold notes and comments. Org-bibtex is aware of all
+ standard bibtex reference types and fields.
+
+ The key new functions are
+
+ - org-bibtex-check :: queries the user to flesh out all required
+ (and with prefix argument optional) bibtex fields available
+ for the specific reference =type= of the current headline.
+
+ - org-bibtex-create :: Create a new entry at the given level,
+ using org-bibtex-check to flesh out the relevant fields.
+
+ - org-bibtex-yank :: Yank a bibtex entry on the kill ring as a
+ formatted Org-mode headline into the current buffer
+
+ - org-bibtex-export-to-kill-ring :: Export the current headline
+ to the kill ring as a formatted bibtex entry.
+
+**** org-gnus.el now allows link creation from messages
+
+ You can now create links from messages. This is particularly
+ useful when the user wants to stored messages that he sends, for
+ later check. Thanks to Ulf Stegemann for the patch.
+
+**** Modified link escaping
+
+ David Maus worked on `org-link-escape'. See [[http://article.gmane.org/gmane.emacs.orgmode/37888][his message]]:
+
+ : Percent escaping is used in Org mode to escape certain characters
+ : in links that would either break the parser (e.g. square brackets
+ : in link target oder description) or are not allowed to appear in
+ : a particular link type (e.g. non-ascii characters in a http:
+ : link).
+ :
+ : With this change in place Org will apply percent escaping and
+ : unescaping more consistently especially for non-ascii characters.
+ : Additionally some of the outstanding bugs or glitches concerning
+ : percent escaped links are solved.
+
+ Thanks a lot to David for this work.
+
+**** Make =org-store-link= point to directory in a dired buffer
+
+ When, in a dired buffer, the cursor is not in a line listing a
+ file, `org-store-link' will store a link to the directory.
+
+ Patch by Stephen Eglen.
+
+**** Allow regexps in =org-file-apps= to capture link parameters
+
+ The way extension regexps in =org-file-apps= are handled has
+ changed. Instead of matching against the file name, the regexps
+ are now matched against the whole link, and you can use grouping
+ to extract link parameters which you can then use in a command
+ string to be executed.
+
+ For example, to allow linking to PDF files using the syntax
+ =file:/doc.pdf::<page number>=, you can add the following entry
+ to org-file-apps:
+
+ #+begin_example
+ Extension: \.pdf::\([0-9]+\)\'
+ Command: evince "%s" -p %1
+ #+end_example
+
+ Thanks to Jan Böcker for a patch to this effect.
+
+*** Dates and time
+
+**** Allow relative time when scheduling/adding a deadline
+
+ You can now use relative duration strings like "-2d" or "++3w"
+ when calling =org-schedule= or =org-deadline=: it will schedule
+ (or set the deadline for) the item respectively two days before
+ today and three weeks after the current timestamp, if any.
+
+ You can use this programmatically: =(org-schedule nil "+2d")=
+ will work on the current entry.
+
+ You can also use this while (bulk-)rescheduling and
+ (bulk-)resetting the deadline of (several) items from the agenda.
+
+ Thanks to Memnon Anon for a heads up about this!
+
+**** American-style dates are now understood by =org-read-date=
+
+ So when you are prompted for a date, you can now answer like this
+
+ #+begin_example
+ 2/5/3 --> 2003-02-05
+ 2/5 --> <CURRENT-YEAR>-02-05
+ #+end_example
+
+*** Agenda
+
+**** =org-agenda-custom-commands= has a default value
+
+ This option used to be `nil' by default. This now has a default
+ value, displaying an agenda and all TODOs. See the docstring for
+ details. Thanks to Carsten for this.
+
+**** Improved filtering through =org-agenda-to-appt=
+
+ The new function allows the user to refine the scope of entries
+ to pass to =org-agenda-get-day-entries= and allows to filter out
+ entries using a function.
+
+ Thanks to Peter Münster for raising a related issue and to
+ Tassilo Horn for this idea. Also thanks to Peter Münster for
+ [[git:68ffb7a7][fixing a small bug]] in the final implementation.
+
+**** Allow ap/pm times in agenda time grid
+
+ Times in the agenda can now be displayed in am/pm format. See
+ the new variable =org-agenda-timegrid-use-ampm=. Thanks to
+ C. A. Webber for a patch to this effect.
+
+**** Agenda: Added a bulk "scattering" command
+
+ =B S= in the agenda buffer will cause tasks to be rescheduled a
+ random number of days into the future, with 7 as the default.
+ This is useful if you've got a ton of tasks scheduled for today,
+ you realize you'll never deal with them all, and you just want
+ them to be distributed across the next N days. When called with
+ a prefix arg, rescheduling will avoid weekend days.
+
+ Thanks to John Wiegley for this.
+
+*** Exporting
+
+**** Simplification of org-export-html-preamble/postamble
+
+ When set to `t', export the preamble/postamble as usual, honoring
+ the =org-export-email/author/creator-info= variables.
+
+ When set to a formatting string, insert this string. See the
+ docstring of these variable for details about available
+ %-sequences.
+
+ You can set =:html-preamble= in publishing project in the same
+ way: `t' means to honor =:email/creator/author-info=, and a
+ formatting string will insert a string.
+
+**** New exporters to Latin-1 and UTF-8
+
+ While Ulf Stegemann was going through the entities list to
+ improve the LaTeX export, he had the great idea to provide
+ representations for many of the entities in Latin-1, and for all
+ of them in UTF-8. This means that we can now export files rich
+ in special symbols to Latin-1 and to UTF-8 files. These new
+ exporters can be reached with the commands =C-c C-e n= and =C-c
+ C-e u=, respectively.
+
+ When there is no representation for a given symbol in the
+ targeted coding system, you can choose to keep the TeX-macro-like
+ representation, or to get an "explanatory" representation. For
+ example, =\simeq= could be represented as "[approx. equal to]".
+ Please use the variable =org-entities-ascii-explanatory= to state
+ your preference.
+
+**** HTML export: Add class to outline containers using property
+
+ The =HTML_CONTAINER_CLASS= property can now be used to add a
+ class name to the outline container of a node in HTML export.
+
+**** Throw an error when creating an image from a LaTeX snippet fails
+
+ This behavior can be configured with the new option variable
+ =org-format-latex-signal-error=.
+
+**** Support for creating BEAMER presentations from Org-mode documents
+
+ Org-mode documents or subtrees can now be converted directly in
+ to BEAMER presentation. Turning a tree into a simple
+ presentations is straight forward, and there is also quite some
+ support to make richer presentations as well. See the [[http://orgmode.org/manual/Beamer-class-export.html#Beamer-class-export][BEAMER
+ section]] in the manual for more details.
+
+ Thanks to everyone who has contributed to the discussion about
+ BEAMER support and how it should work. This was a great example
+ for how this community can achieve a much better result than any
+ individual could.
+
+*** Refiling
+
+**** Refile targets can now be cached
+
+ You can turn on caching of refile targets by setting the variable
+ =org-refile-use-cache=. This should speed up refiling if you
+ have many eligible targets in many files. If you need to update
+ the cache because Org misses a newly created entry or still
+ offers a deleted one, press =C-0 C-c C-w=.
+
+**** New logging support for refiling
+
+ Whenever you refile an item, a time stamp and even a note can be
+ added to this entry. For details, see the new option
+ =org-log-refile=.
+
+ Thanks to Charles Cave for this idea.
+
+*** Completion
+
+**** In-buffer completion is now done using John Wiegley's pcomplete.el
+
+ Thanks to John Wiegley for much of this code.
+
+*** Tables
+
+**** New command =org-table-transpose-table-at-point=
+
+ See the docstring. This hack from Juan Pechiar is now part of
+ Org's core. Thanks to Juan!
+
+**** Display field's coordinates when editing it with =C-c `=
+
+ When editing a field with =C-c `=, the field's coordinate will
+ the displayed in the buffer.
+
+ Thanks to Michael Brand for a patch to this effect.
+
+**** Spreadsheet computation of durations and time values
+
+ If you want to compute time values use the =T= flag, either in
+ Calc formulas or Elisp formulas:
+
+ | Task 1 | Task 2 | Total |
+ |--------+--------+---------|
+ | 35:00 | 35:00 | 1:10:00 |
+ #+TBLFM: @2$3=$1+$2;T
+
+ Values must be of the form =[HH:]MM:SS=, where hours are
+ optional.
+
+ Thanks to Martin Halder, Eric Schulte and Carsten for code and
+ feedback on this.
+
+**** Implement formulas applying to field ranges
+
+ Carsten implemented this field-ranges formulas.
+
+ : A frequently requested feature for tables has been to be able to define
+ : row formulas in a way similar to column formulas. The patch below allows
+ : things like
+ :
+ : @3=
+ : @2$2..@5$7=
+ : @I$2..@II$4=
+ :
+ : as the left hand side for table formulas in order to write a formula that
+ : is valid for an entire column or for a rectangular section in a
+ : table.
+
+ Thanks a lot to Carsten for this.
+
+**** Sending radio tables from org buffers is now allowed
+
+ Org radio tables can no also be sent inside Org buffers. Also,
+ there is a new hook which get called after a table has been sent.
+
+ Thanks to Seweryn Kokot.
+
+*** Lists
+
+**** Improved handling of lists
+
+ Nicolas Goaziou extended and improved the way Org handles lists.
+
+ 1. Indentation of text determines again end of items in
+ lists. So, some text less indented than the previous item
+ doesn't close the whole list anymore, only all items more
+ indented than it.
+
+ 2. Alphabetical bullets are implemented, through the use of the
+ variable `org-alphabetical-lists'. This also adds alphabetical
+ counters like [@c] or [@W].
+
+ 3. Lists can now safely contain drawers, inline tasks, or various
+ blocks, themselves containing lists. Two variables are
+ controlling this: `org-list-forbidden-blocks', and
+ `org-list-export-context'.
+
+ 4. Improve `newline-and-indent' (C-j): used in an item, it will
+ keep text from moving at column 0. This allows to split text
+ and make paragraphs and still not break the list.
+
+ 5. Improve `org-toggle-item' (C-c -): used on a region with
+ standard text, it will change the region into one item. With a
+ prefix argument, it will fallback to the previous behavior and
+ make every line in region an item. It permits to easily
+ integrate paragraphs inside a list.
+
+ 6. `fill-paragraph' (M-q) now understands lists. It can freely be
+ used inside items, or on text just after a list, even with no
+ blank line around, without breaking list structure.
+
+ Thanks a lot to Nicolas for all this!
+
+*** Inline display of linked images
+
+ Images can now be displayed inline. The key C-c C-x C-v does
+ toggle the display of such images. Note that only image links
+ that have no description part will be inlined.
+
+*** Implement offsets for ordered lists
+
+ If you want to start an ordered plain list with a number different
+ from 1, you can now do it like this:
+
+ : 1. [@start:12] will star a lit a number 12
+
+*** Babel: code block body expansion for table and preview
+
+ In org-babel, code is "expanded" prior to evaluation. I.e. the
+ code that is actually evaluated comprises the code block contents,
+ augmented with the extra code which assigns the referenced data to
+ variables. It is now possible to preview expanded contents, and
+ also to expand code during during tangling. This expansion takes
+ into account all header arguments, and variables.
+
+ A new keybinding `C-c M-b p' bound to `org-babel-expand-src-block'
+ can be used from inside of a source code block to preview its
+ expanded contents (which can be very useful for debugging).
+ tangling
+
+ The expanded body can now be tangled, this includes variable
+ values which may be the results of other source-code blocks, or
+ stored in headline properties or tables. One possible use for this
+ is to allow those using org-babel for their emacs initialization
+ to store values (e.g. usernames, passwords, etc...) in headline
+ properties or in tables.
+
+ Org-babel now supports three new header arguments, and new default
+ behavior for handling horizontal lines in tables (hlines), column
+ names, and rownames across all languages.
+
+*** Editing Convenience and Appearance
+
+**** New command =org-copy-visible= (=C-c C-x v=)
+
+ This command will copy the visible text in the region into the
+ kill ring. Thanks to Florian Beck for this function and to
+ Carsten for adding it to org.el and documenting it!
+
+**** Make it possible to protect hidden subtrees from being killed by =C-k=
+
+ See the new variable =org-ctrl-k-protect-subtree=. This was a
+ request by Scott Otterson.
+
+**** Implement pretty display of entities, sub-, and superscripts.
+
+ The command =C-c C-x \= toggles the display of Org's special
+ entities like =\alpha= as pretty unicode characters. Also, sub
+ and superscripts are displayed in a pretty way (raised/lower
+ display, in a smaller font). If you want to exclude sub- and
+ superscripts, see the variable
+ =org-pretty-entities-include-sub-superscripts=.
+
+ Thanks to Eric Schulte and Ulf Stegeman for making this possible.
+
+**** New faces for title, date, author and email address lines
+
+ The keywords in these lines are now dimmed out, and the title is
+ displayed in a larger font, and a special font is also used for
+ author, date, and email information. This is implemented by the
+ following new faces:
+
+ =org-document-title=
+ =org-document-info=
+ =org-document-info-keyword=
+
+ In addition, the variable =org-hidden-keywords= can be used to
+ make the corresponding keywords disappear.
+
+ Thanks to Dan Davison for this feature.
+
+**** Simpler way to specify faces for tags and todo keywords
+
+ The variables =org-todo-keyword-faces=, =org-tag-faces=, and
+ =org-priority-faces= now accept simple color names as
+ specifications. The colors will be used as either foreground or
+ background color for the corresponding keyword. See also the
+ variable =org-faces-easy-properties=, which governs which face
+ property is affected by this setting.
+
+ This is really a great simplification for setting keyword faces.
+ The change is based on an idea and patch by Ryan Thompson.
+
+**** <N> in tables now means fixed width, not maximum width
+
+ Requested by Michael Brand.
+
+**** Better level cycling function
+
+ =TAB= in an empty headline cycles the level of that headline
+ through likely states. Ryan Thompson implemented an improved
+ version of this function, which does not depend upon when exactly
+ this command is used. Thanks to Ryan for this improvement.
+
+**** Adaptive filling
+
+ For paragraph text, =org-adaptive-fill-function= did not handle
+ the base case of regular text which needed to be filled. This is
+ now fixed. Among other things, it allows email-style ">"
+ comments to be filled correctly.
+
+ Thanks to Dan Hackney for this patch.
+
+**** `org-reveal' (=C-c C-r=) also decrypts encrypted entries (org-crypt.el)
+
+ Thanks to Richard Riley for triggering this change.
+
+**** Better automatic letter selection for TODO keywords
+
+ When all first letters of keywords have been used, Org now
+ assigns more meaningful characters based on the keywords.
+
+ Thanks to Mikael Fornius for this patch.
+
+*** Clocking
+
+**** Clock: Allow synchronous update of timestamps in CLOCK log
+
+ Using =S-M-<up/down>= on CLOCK log timestamps will
+ increase/decrease the two timestamps on this line so that
+ duration will keep the same. Note that duration can still be
+ slightly modified in case a timestamp needs some rounding.
+
+ Thanks to Rainer Stengele for this idea.
+
+**** Localized clock tables
+
+ Clock tables now support a new new =:lang= parameter, allowing
+ the user to customize the localization of the table headers. See
+ the variable =org-clock-clocktable-language-setup= which controls
+ available translated strings.
+
+**** Show clock overruns in mode line
+
+ When clocking an item with a planned effort, overrunning the
+ planned time is now made visible in the mode line, for example
+ using the new face =org-mode-line-clock-overrun=, or by adding an
+ extra string given by =org-task-overrun-text=.
+
+ Thanks to Richard Riley for a patch to this effect.
+
+**** Clock reports can now include the running, incomplete clock
+
+ If you have a clock running, and the entry being clocked falls
+ into the scope when creating a clock table, the time so far spent
+ can be added to the total. This behavior depends on the setting
+ of =org-clock-report-include-clocking-task=. The default is
+ =nil=.
+
+ Thanks to Bernt Hansen for this useful addition.
+
+*** Misc
+
+**** Improvements with inline tasks and indentation
+
+ There is now a configurable way on how to export inline tasks.
+ See the new variable =org-inlinetask-export-templates=.
+
+ Thanks to Nicolas Goaziou for coding these changes.
+
+**** A property value of "nil" now means to unset a property
+
+ This can be useful in particular with property inheritance, if
+ some upper level has the property, and some grandchild of it
+ would like to have the default settings (i.e. not overruled by a
+ property) back.
+
+ Thanks to Robert Goldman and Bernt Hansen for suggesting this
+ change.
+
+**** New helper functions in org-table.el
+
+ There are new functions to access and write to a specific table field.
+ This is for hackers, and maybe for the org-babel people.
+
+ #+begin_example
+ org-table-get
+ org-table-put
+ org-table-current-line
+ org-table-goto-line
+ #+end_example
+
+**** Archiving: Allow to reverse order in target node
+
+ The new option =org-archive-reversed-order= allows to have
+ archived entries inserted in a last-on-top fashion in the target
+ node.
+
+ This was requested by Tom.
+
+**** Org-reveal: Double prefix arg shows the entire subtree of the parent
+
+ This can help to get out of an inconsistent state produced for
+ example by viewing from the agenda.
+
+ This was a request by Matt Lundin.
+
+* License
+
+ This file is part of GNU Emacs.
+
+ GNU Emacs is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ GNU Emacs is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
diff --git a/etc/schema/od-manifest-schema-v1.2-os.rnc b/etc/schema/od-manifest-schema-v1.2-os.rnc
new file mode 100644
index 0000000..554f321
--- /dev/null
+++ b/etc/schema/od-manifest-schema-v1.2-os.rnc
@@ -0,0 +1,88 @@
+# Open Document Format for Office Applications (OpenDocument) Version 1.2
+# OASIS Standard, 29 September 2011
+# Manifest Relax-NG Schema
+# Source: http://docs.oasis-open.org/office/v1.2/os/
+# Copyright (c) OASIS Open 2002-2011, 2013. All Rights Reserved.
+#
+# All capitalized terms in the following text have the meanings assigned to them
+# in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The
+# full Policy may be found at the OASIS website.
+#
+# This document and translations of it may be copied and furnished to others, and
+# derivative works that comment on or otherwise explain it or assist in its
+# implementation may be prepared, copied, published, and distributed, in whole or
+# in part, without restriction of any kind, provided that the above copyright
+# notice and this section are included on all such copies and derivative works.
+# However, this document itself may not be modified in any way, including by
+# removing the copyright notice or references to OASIS, except as needed for the
+# purpose of developing any document or deliverable produced by an OASIS
+# Technical Committee (in which case the rules applicable to copyrights, as set
+# forth in the OASIS IPR Policy, must be followed) or as required to translate it
+# into languages other than English.
+#
+# The limited permissions granted above are perpetual and will not be revoked by
+# OASIS or its successors or assigns.
+#
+# This document and the information contained herein is provided on an "AS IS"
+# basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+# LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT
+# INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
+# FITNESS FOR A PARTICULAR PURPOSE.
+
+namespace manifest =
+ "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"
+
+start = manifest
+manifest = element manifest:manifest { manifest-attlist, file-entry+ }
+manifest-attlist = attribute manifest:version { "1.2" }
+file-entry =
+ element manifest:file-entry { file-entry-attlist, encryption-data? }
+file-entry-attlist =
+ attribute manifest:full-path { \string }
+ & attribute manifest:size { nonNegativeInteger }?
+ & attribute manifest:media-type { \string }
+ & attribute manifest:preferred-view-mode {
+ "edit" | "presentation-slide-show" | "read-only" | namespacedToken
+ }?
+ & attribute manifest:version { \string }?
+encryption-data =
+ element manifest:encryption-data {
+ encryption-data-attlist,
+ algorithm,
+ start-key-generation?,
+ key-derivation
+ }
+encryption-data-attlist =
+ attribute manifest:checksum-type { "SHA1/1K" | anyURI }
+ & attribute manifest:checksum { base64Binary }
+algorithm =
+ element manifest:algorithm { algorithm-attlist, anyElements }
+algorithm-attlist =
+ attribute manifest:algorithm-name { "Blowfish CFB" | anyURI }
+ & attribute manifest:initialisation-vector { base64Binary }
+anyAttListOrElements =
+ attribute * { text }*,
+ anyElements
+anyElements =
+ element * {
+ mixed { anyAttListOrElements }
+ }*
+key-derivation =
+ element manifest:key-derivation { key-derivation-attlist, empty }
+key-derivation-attlist =
+ attribute manifest:key-derivation-name { "PBKDF2" | anyURI }
+ & attribute manifest:salt { base64Binary }
+ & attribute manifest:iteration-count { nonNegativeInteger }
+ & attribute manifest:key-size { nonNegativeInteger }?
+start-key-generation =
+ element manifest:start-key-generation {
+ start-key-generation-attlist, empty
+ }
+start-key-generation-attlist =
+ attribute manifest:start-key-generation-name { "SHA1" | anyURI }
+ & attribute manifest:key-size { nonNegativeInteger }?
+base64Binary = xsd:base64Binary
+namespacedToken = xsd:QName { pattern = "[^:]+:[^:]+" }
+nonNegativeInteger = xsd:nonNegativeInteger
+\string = xsd:string
+anyURI = xsd:anyURI
diff --git a/etc/schema/od-schema-v1.2-os.rnc b/etc/schema/od-schema-v1.2-os.rnc
new file mode 100644
index 0000000..c019fba
--- /dev/null
+++ b/etc/schema/od-schema-v1.2-os.rnc
@@ -0,0 +1,6280 @@
+# Open Document Format for Office Applications (OpenDocument) Version 1.2
+# OASIS Standard, 29 September 2011
+# Relax-NG Schema
+# Source: http://docs.oasis-open.org/office/v1.2/os/
+# Copyright (c) OASIS Open 2002-2011, 2013. All Rights Reserved.
+#
+# All capitalized terms in the following text have the meanings assigned to them
+# in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The
+# full Policy may be found at the OASIS website.
+#
+# This document and translations of it may be copied and furnished to others, and
+# derivative works that comment on or otherwise explain it or assist in its
+# implementation may be prepared, copied, published, and distributed, in whole or
+# in part, without restriction of any kind, provided that the above copyright
+# notice and this section are included on all such copies and derivative works.
+# However, this document itself may not be modified in any way, including by
+# removing the copyright notice or references to OASIS, except as needed for the
+# purpose of developing any document or deliverable produced by an OASIS
+# Technical Committee (in which case the rules applicable to copyrights, as set
+# forth in the OASIS IPR Policy, must be followed) or as required to translate it
+# into languages other than English.
+#
+# The limited permissions granted above are perpetual and will not be revoked by
+# OASIS or its successors or assigns.
+#
+# This document and the information contained herein is provided on an "AS IS"
+# basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+# LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT
+# INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
+# FITNESS FOR A PARTICULAR PURPOSE.
+
+namespace anim = "urn:oasis:names:tc:opendocument:xmlns:animation:1.0"
+namespace chart = "urn:oasis:names:tc:opendocument:xmlns:chart:1.0"
+namespace config = "urn:oasis:names:tc:opendocument:xmlns:config:1.0"
+namespace db = "urn:oasis:names:tc:opendocument:xmlns:database:1.0"
+namespace dc = "http://purl.org/dc/elements/1.1/"
+namespace dr3d = "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0"
+namespace draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
+namespace fo =
+ "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
+namespace form = "urn:oasis:names:tc:opendocument:xmlns:form:1.0"
+namespace grddl = "http://www.w3.org/2003/g/data-view#"
+namespace math = "http://www.w3.org/1998/Math/MathML"
+namespace meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
+namespace number = "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"
+namespace office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+namespace presentation =
+ "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"
+namespace script = "urn:oasis:names:tc:opendocument:xmlns:script:1.0"
+namespace smil =
+ "urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0"
+namespace style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+namespace svg =
+ "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
+namespace table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+namespace text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+namespace xforms = "http://www.w3.org/2002/xforms"
+namespace xhtml = "http://www.w3.org/1999/xhtml"
+namespace xlink = "http://www.w3.org/1999/xlink"
+
+office-process-content = attribute office:process-content { boolean }?
+start =
+ office-document
+ | office-document-content
+ | office-document-styles
+ | office-document-meta
+ | office-document-settings
+office-document =
+ element office:document {
+ office-document-attrs,
+ office-document-common-attrs,
+ office-meta,
+ office-settings,
+ office-scripts,
+ office-font-face-decls,
+ office-styles,
+ office-automatic-styles,
+ office-master-styles,
+ office-body
+ }
+office-document-content =
+ element office:document-content {
+ office-document-common-attrs,
+ office-scripts,
+ office-font-face-decls,
+ office-automatic-styles,
+ office-body
+ }
+office-document-styles =
+ element office:document-styles {
+ office-document-common-attrs,
+ office-font-face-decls,
+ office-styles,
+ office-automatic-styles,
+ office-master-styles
+ }
+office-document-meta =
+ element office:document-meta {
+ office-document-common-attrs, office-meta
+ }
+office-document-settings =
+ element office:document-settings {
+ office-document-common-attrs, office-settings
+ }
+office-document-common-attrs =
+ attribute office:version { "1.2" }
+ & attribute grddl:transformation {
+ list { anyIRI* }
+ }?
+office-document-attrs = attribute office:mimetype { \string }
+office-meta = element office:meta { office-meta-content-strict }?
+office-meta-content-strict = office-meta-data*
+office-body = element office:body { office-body-content }
+office-body-content =
+ element office:text {
+ office-text-attlist,
+ office-text-content-prelude,
+ office-text-content-main,
+ office-text-content-epilogue
+ }
+ | element office:drawing {
+ office-drawing-attlist,
+ office-drawing-content-prelude,
+ office-drawing-content-main,
+ office-drawing-content-epilogue
+ }
+ | element office:presentation {
+ office-presentation-attlist,
+ office-presentation-content-prelude,
+ office-presentation-content-main,
+ office-presentation-content-epilogue
+ }
+ | element office:spreadsheet {
+ office-spreadsheet-attlist,
+ office-spreadsheet-content-prelude,
+ office-spreadsheet-content-main,
+ office-spreadsheet-content-epilogue
+ }
+ | element office:chart {
+ office-chart-attlist,
+ office-chart-content-prelude,
+ office-chart-content-main,
+ office-chart-content-epilogue
+ }
+ | element office:image {
+ office-image-attlist,
+ office-image-content-prelude,
+ office-image-content-main,
+ office-image-content-epilogue
+ }
+ | office-database
+office-text-content-prelude =
+ office-forms, text-tracked-changes, text-decls, table-decls
+office-text-content-main =
+ text-content*
+ | (text-page-sequence, (shape)*)
+text-content =
+ text-h
+ | text-p
+ | text-list
+ | text-numbered-paragraph
+ | table-table
+ | text-section
+ | text-soft-page-break
+ | text-table-of-content
+ | text-illustration-index
+ | text-table-index
+ | text-object-index
+ | text-user-index
+ | text-alphabetical-index
+ | text-bibliography
+ | shape
+ | change-marks
+office-text-content-epilogue = table-functions
+office-text-attlist =
+ attribute text:global { boolean }?
+ & attribute text:use-soft-page-breaks { boolean }?
+office-drawing-attlist = empty
+office-drawing-content-prelude = text-decls, table-decls
+office-drawing-content-main = draw-page*
+office-drawing-content-epilogue = table-functions
+office-presentation-attlist = empty
+office-presentation-content-prelude =
+ text-decls, table-decls, presentation-decls
+office-presentation-content-main = draw-page*
+office-presentation-content-epilogue =
+ presentation-settings, table-functions
+office-spreadsheet-content-prelude =
+ table-tracked-changes?, text-decls, table-decls
+table-decls =
+ table-calculation-settings?,
+ table-content-validations?,
+ table-label-ranges?
+office-spreadsheet-content-main = table-table*
+office-spreadsheet-content-epilogue = table-functions
+table-functions =
+ table-named-expressions?,
+ table-database-ranges?,
+ table-data-pilot-tables?,
+ table-consolidation?,
+ table-dde-links?
+office-chart-attlist = empty
+office-chart-content-prelude = text-decls, table-decls
+office-chart-content-main = chart-chart
+office-chart-content-epilogue = table-functions
+office-image-attlist = empty
+office-image-content-prelude = empty
+office-image-content-main = draw-frame
+office-image-content-epilogue = empty
+office-settings = element office:settings { config-config-item-set+ }?
+config-config-item-set =
+ element config:config-item-set {
+ config-config-item-set-attlist, config-items
+ }
+config-items =
+ (config-config-item
+ | config-config-item-set
+ | config-config-item-map-named
+ | config-config-item-map-indexed)+
+config-config-item-set-attlist = attribute config:name { \string }
+config-config-item =
+ element config:config-item { config-config-item-attlist, text }
+config-config-item-attlist =
+ attribute config:name { \string }
+ & attribute config:type {
+ "boolean"
+ | "short"
+ | "int"
+ | "long"
+ | "double"
+ | "string"
+ | "datetime"
+ | "base64Binary"
+ }
+config-config-item-map-indexed =
+ element config:config-item-map-indexed {
+ config-config-item-map-indexed-attlist,
+ config-config-item-map-entry+
+ }
+config-config-item-map-indexed-attlist =
+ attribute config:name { \string }
+config-config-item-map-entry =
+ element config:config-item-map-entry {
+ config-config-item-map-entry-attlist, config-items
+ }
+config-config-item-map-entry-attlist =
+ attribute config:name { \string }?
+config-config-item-map-named =
+ element config:config-item-map-named {
+ config-config-item-map-named-attlist, config-config-item-map-entry+
+ }
+config-config-item-map-named-attlist = attribute config:name { \string }
+office-scripts =
+ element office:scripts { office-script*, office-event-listeners? }?
+office-script =
+ element office:script {
+ office-script-attlist,
+ mixed { anyElements }
+ }
+office-script-attlist = attribute script:language { \string }
+office-font-face-decls =
+ element office:font-face-decls { style-font-face* }?
+office-styles =
+ element office:styles {
+ styles
+ & style-default-style*
+ & style-default-page-layout?
+ & text-outline-style?
+ & text-notes-configuration*
+ & text-bibliography-configuration?
+ & text-linenumbering-configuration?
+ & draw-gradient*
+ & svg-linearGradient*
+ & svg-radialGradient*
+ & draw-hatch*
+ & draw-fill-image*
+ & draw-marker*
+ & draw-stroke-dash*
+ & draw-opacity*
+ & style-presentation-page-layout*
+ & table-table-template*
+ }?
+office-automatic-styles =
+ element office:automatic-styles { styles & style-page-layout* }?
+office-master-styles =
+ element office:master-styles {
+ style-master-page* & style-handout-master? & draw-layer-set?
+ }?
+styles =
+ style-style*
+ & text-list-style*
+ & number-number-style*
+ & number-currency-style*
+ & number-percentage-style*
+ & number-date-style*
+ & number-time-style*
+ & number-boolean-style*
+ & number-text-style*
+office-meta-data =
+ element meta:generator { \string }
+ | element dc:title { \string }
+ | element dc:description { \string }
+ | element dc:subject { \string }
+ | element meta:keyword { \string }
+ | element meta:initial-creator { \string }
+ | dc-creator
+ | element meta:printed-by { \string }
+ | element meta:creation-date { dateTime }
+ | dc-date
+ | element meta:print-date { dateTime }
+ | element meta:template {
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:actuate { "onRequest" }?,
+ attribute xlink:title { \string }?,
+ attribute meta:date { dateTime }?
+ }
+ | element meta:auto-reload {
+ (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "replace" }?,
+ attribute xlink:actuate { "onLoad" }?)?,
+ attribute meta:delay { duration }?
+ }
+ | element meta:hyperlink-behaviour {
+ attribute office:target-frame-name { targetFrameName }?,
+ attribute xlink:show { "new" | "replace" }?
+ }
+ | element dc:language { language }
+ | element meta:editing-cycles { nonNegativeInteger }
+ | element meta:editing-duration { duration }
+ | element meta:document-statistic {
+ attribute meta:page-count { nonNegativeInteger }?,
+ attribute meta:table-count { nonNegativeInteger }?,
+ attribute meta:draw-count { nonNegativeInteger }?,
+ attribute meta:image-count { nonNegativeInteger }?,
+ attribute meta:ole-object-count { nonNegativeInteger }?,
+ attribute meta:object-count { nonNegativeInteger }?,
+ attribute meta:paragraph-count { nonNegativeInteger }?,
+ attribute meta:word-count { nonNegativeInteger }?,
+ attribute meta:character-count { nonNegativeInteger }?,
+ attribute meta:frame-count { nonNegativeInteger }?,
+ attribute meta:sentence-count { nonNegativeInteger }?,
+ attribute meta:syllable-count { nonNegativeInteger }?,
+ attribute meta:non-whitespace-character-count {
+ nonNegativeInteger
+ }?,
+ attribute meta:row-count { nonNegativeInteger }?,
+ attribute meta:cell-count { nonNegativeInteger }?
+ }
+ | element meta:user-defined {
+ attribute meta:name { \string },
+ ((attribute meta:value-type { "float" },
+ double)
+ | (attribute meta:value-type { "date" },
+ dateOrDateTime)
+ | (attribute meta:value-type { "time" },
+ duration)
+ | (attribute meta:value-type { "boolean" },
+ boolean)
+ | (attribute meta:value-type { "string" },
+ \string)
+ | text)
+ }
+dc-creator = element dc:creator { \string }
+dc-date = element dc:date { dateTime }
+text-h =
+ element text:h {
+ heading-attrs,
+ paragraph-attrs,
+ text-number?,
+ paragraph-content-or-hyperlink*
+ }
+heading-attrs =
+ attribute text:outline-level { positiveInteger }
+ & attribute text:restart-numbering { boolean }?
+ & attribute text:start-value { nonNegativeInteger }?
+ & attribute text:is-list-header { boolean }?
+text-number = element text:number { \string }
+text-p =
+ element text:p { paragraph-attrs, paragraph-content-or-hyperlink* }
+paragraph-attrs =
+ attribute text:style-name { styleNameRef }?
+ & attribute text:class-names { styleNameRefs }?
+ & attribute text:cond-style-name { styleNameRef }?
+ & (xml-id,
+ attribute text:id { NCName }?)?
+ & common-in-content-meta-attlist?
+text-page-sequence = element text:page-sequence { text-page+ }
+text-page = element text:page { text-page-attlist, empty }
+text-page-attlist = attribute text:master-page-name { styleNameRef }
+text-list =
+ element text:list {
+ text-list-attr, text-list-header?, text-list-item*
+ }
+text-list-attr =
+ attribute text:style-name { styleNameRef }?
+ & attribute text:continue-numbering { boolean }?
+ & attribute text:continue-list { IDREF }?
+ & xml-id?
+text-list-item =
+ element text:list-item { text-list-item-attr, text-list-item-content }
+text-list-item-content =
+ text-number?, (text-p | text-h | text-list | text-soft-page-break)*
+text-list-item-attr =
+ attribute text:start-value { nonNegativeInteger }?
+ & attribute text:style-override { styleNameRef }?
+ & xml-id?
+text-list-header =
+ element text:list-header {
+ text-list-header-attr, text-list-item-content
+ }
+text-list-header-attr = xml-id?
+text-numbered-paragraph =
+ element text:numbered-paragraph {
+ text-numbered-paragraph-attr, text-number?, (text-p | text-h)
+ }
+text-numbered-paragraph-attr =
+ attribute text:list-id { NCName }
+ & attribute text:level { positiveInteger }?
+ & (attribute text:style-name { styleNameRef },
+ attribute text:continue-numbering { boolean },
+ attribute text:start-value { nonNegativeInteger })?
+ & xml-id?
+text-section =
+ element text:section {
+ text-section-attlist,
+ (text-section-source | text-section-source-dde | empty),
+ text-content*
+ }
+text-section-attlist =
+ common-section-attlist
+ & (attribute text:display { "true" | "none" }
+ | (attribute text:display { "condition" },
+ attribute text:condition { \string })
+ | empty)
+common-section-attlist =
+ attribute text:style-name { styleNameRef }?
+ & attribute text:name { \string }
+ & attribute text:protected { boolean }?
+ & attribute text:protection-key { \string }?
+ & attribute text:protection-key-digest-algorithm { anyIRI }?
+ & xml-id?
+text-section-source =
+ element text:section-source { text-section-source-attr }
+text-section-source-attr =
+ (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "embed" }?)?
+ & attribute text:section-name { \string }?
+ & attribute text:filter-name { \string }?
+text-section-source-dde = office-dde-source
+text-tracked-changes =
+ element text:tracked-changes {
+ text-tracked-changes-attr, text-changed-region*
+ }?
+text-tracked-changes-attr = attribute text:track-changes { boolean }?
+text-changed-region =
+ element text:changed-region {
+ text-changed-region-attr, text-changed-region-content
+ }
+text-changed-region-attr =
+ xml-id,
+ attribute text:id { NCName }?
+text-changed-region-content =
+ element text:insertion { office-change-info }
+ | element text:deletion { office-change-info, text-content* }
+ | element text:format-change { office-change-info }
+change-marks =
+ element text:change { change-mark-attr }
+ | element text:change-start { change-mark-attr }
+ | element text:change-end { change-mark-attr }
+change-mark-attr = attribute text:change-id { IDREF }
+text-soft-page-break = element text:soft-page-break { empty }
+text-decls =
+ element text:variable-decls { text-variable-decl* }?,
+ element text:sequence-decls { text-sequence-decl* }?,
+ element text:user-field-decls { text-user-field-decl* }?,
+ element text:dde-connection-decls { text-dde-connection-decl* }?,
+ text-alphabetical-index-auto-mark-file?
+paragraph-content-or-hyperlink = paragraph-content | text-a
+paragraph-content =
+ text
+ | element text:s {
+ attribute text:c { nonNegativeInteger }?
+ }
+ | element text:tab { text-tab-attr }
+ | element text:line-break { empty }
+ | text-soft-page-break
+ | element text:span {
+ attribute text:style-name { styleNameRef }?,
+ attribute text:class-names { styleNameRefs }?,
+ paragraph-content-or-hyperlink*
+ }
+ | element text:meta {
+ text-meta-attlist, paragraph-content-or-hyperlink*
+ }
+ | (text-bookmark | text-bookmark-start | text-bookmark-end)
+ | element text:reference-mark {
+ attribute text:name { \string }
+ }
+ | (element text:reference-mark-start {
+ attribute text:name { \string }
+ }
+ | element text:reference-mark-end {
+ attribute text:name { \string }
+ })
+ | element text:note {
+ text-note-class,
+ attribute text:id { \string }?,
+ element text:note-citation {
+ attribute text:label { \string }?,
+ text
+ },
+ element text:note-body { text-content* }
+ }
+ | element text:ruby {
+ attribute text:style-name { styleNameRef }?,
+ element text:ruby-base { paragraph-content-or-hyperlink* },
+ element text:ruby-text {
+ attribute text:style-name { styleNameRef }?,
+ text
+ }
+ }
+ | (office-annotation | office-annotation-end)
+ | change-marks
+ | shape
+ | element text:date { text-date-attlist, text }
+ | element text:time { text-time-attlist, text }
+ | element text:page-number { text-page-number-attlist, text }
+ | element text:page-continuation {
+ text-page-continuation-attlist, text
+ }
+ | element text:sender-firstname { common-field-fixed-attlist, text }
+ | element text:sender-lastname { common-field-fixed-attlist, text }
+ | element text:sender-initials { common-field-fixed-attlist, text }
+ | element text:sender-title { common-field-fixed-attlist, text }
+ | element text:sender-position { common-field-fixed-attlist, text }
+ | element text:sender-email { common-field-fixed-attlist, text }
+ | element text:sender-phone-private {
+ common-field-fixed-attlist, text
+ }
+ | element text:sender-fax { common-field-fixed-attlist, text }
+ | element text:sender-company { common-field-fixed-attlist, text }
+ | element text:sender-phone-work { common-field-fixed-attlist, text }
+ | element text:sender-street { common-field-fixed-attlist, text }
+ | element text:sender-city { common-field-fixed-attlist, text }
+ | element text:sender-postal-code { common-field-fixed-attlist, text }
+ | element text:sender-country { common-field-fixed-attlist, text }
+ | element text:sender-state-or-province {
+ common-field-fixed-attlist, text
+ }
+ | element text:author-name { common-field-fixed-attlist, text }
+ | element text:author-initials { common-field-fixed-attlist, text }
+ | element text:chapter { text-chapter-attlist, text }
+ | element text:file-name { text-file-name-attlist, text }
+ | element text:template-name { text-template-name-attlist, text }
+ | element text:sheet-name { text }
+ | element text:variable-set {
+ (common-field-name-attlist
+ & common-field-formula-attlist
+ & common-value-and-type-attlist
+ & common-field-display-value-none-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:variable-get {
+ (common-field-name-attlist
+ & common-field-display-value-formula-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:variable-input {
+ (common-field-name-attlist
+ & common-field-description-attlist
+ & common-value-type-attlist
+ & common-field-display-value-none-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:user-field-get {
+ (common-field-name-attlist
+ & common-field-display-value-formula-none-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:user-field-input {
+ (common-field-name-attlist
+ & common-field-description-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:sequence {
+ (common-field-name-attlist
+ & common-field-formula-attlist
+ & common-field-num-format-attlist
+ & text-sequence-ref-name),
+ text
+ }
+ | element text:expression {
+ (common-field-formula-attlist
+ & common-value-and-type-attlist?
+ & common-field-display-value-formula-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:text-input { common-field-description-attlist, text }
+ | element text:initial-creator { common-field-fixed-attlist, text }
+ | element text:creation-date {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:date-value { dateOrDateTime }?),
+ text
+ }
+ | element text:creation-time {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:time-value { timeOrDateTime }?),
+ text
+ }
+ | element text:description { common-field-fixed-attlist, text }
+ | element text:user-defined {
+ (common-field-fixed-attlist
+ & attribute text:name { \string }
+ & common-field-data-style-name-attlist
+ & attribute office:value { double }?
+ & attribute office:date-value { dateOrDateTime }?
+ & attribute office:time-value { duration }?
+ & attribute office:boolean-value { boolean }?
+ & attribute office:string-value { \string }?),
+ text
+ }
+ | element text:print-time {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:time-value { time }?),
+ text
+ }
+ | element text:print-date {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:date-value { date }?),
+ text
+ }
+ | element text:printed-by { common-field-fixed-attlist, text }
+ | element text:title { common-field-fixed-attlist, text }
+ | element text:subject { common-field-fixed-attlist, text }
+ | element text:keywords { common-field-fixed-attlist, text }
+ | element text:editing-cycles { common-field-fixed-attlist, text }
+ | element text:editing-duration {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:duration { duration }?),
+ text
+ }
+ | element text:modification-time {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:time-value { time }?),
+ text
+ }
+ | element text:modification-date {
+ (common-field-fixed-attlist
+ & common-field-data-style-name-attlist
+ & attribute text:date-value { date }?),
+ text
+ }
+ | element text:creator { common-field-fixed-attlist, text }
+ | element text:page-count
+ | text:paragraph-count
+ | text:word-count
+ | text:character-count
+ | text:table-count
+ | text:image-count
+ | text:object-count {
+ common-field-num-format-attlist, text
+ }
+ | element text:database-display {
+ text-database-display-attlist, text
+ }
+ | element text:database-next { text-database-next-attlist }
+ | element text:database-row-select {
+ text-database-row-select-attlist
+ }
+ | element text:database-row-number {
+ (common-field-database-table
+ & common-field-num-format-attlist
+ & attribute text:value { nonNegativeInteger }?),
+ text
+ }
+ | element text:database-name { common-field-database-table, text }
+ | element text:page-variable-set {
+ text-set-page-variable-attlist, text
+ }
+ | element text:page-variable-get {
+ text-get-page-variable-attlist, text
+ }
+ | element text:placeholder { text-placeholder-attlist, text }
+ | element text:conditional-text {
+ text-conditional-text-attlist, text
+ }
+ | element text:hidden-text { text-hidden-text-attlist, text }
+ | element text:reference-ref | text:bookmark-ref {
+ text-common-ref-content & text-bookmark-ref-content
+ }
+ | element text:note-ref {
+ text-common-ref-content & text-note-ref-content
+ }
+ | element text:sequence-ref {
+ text-common-ref-content & text-sequence-ref-content
+ }
+ | element text:script {
+ ((attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI })
+ | text)
+ & attribute script:language { \string }?
+ }
+ | element text:execute-macro {
+ attribute text:name { \string }?,
+ office-event-listeners?,
+ text
+ }
+ | element text:hidden-paragraph {
+ text-hidden-paragraph-attlist, text
+ }
+ | element text:dde-connection {
+ attribute text:connection-name { \string },
+ text
+ }
+ | element text:measure {
+ attribute text:kind { "value" | "unit" | "gap" },
+ text
+ }
+ | element text:table-formula {
+ (common-field-formula-attlist
+ & common-field-display-value-formula-attlist
+ & common-field-data-style-name-attlist),
+ text
+ }
+ | element text:meta-field {
+ text-meta-field-attlist, paragraph-content-or-hyperlink*
+ }
+ | element text:toc-mark-start { text-toc-mark-start-attrs }
+ | element text:toc-mark-end { text-id }
+ | element text:toc-mark {
+ attribute text:string-value { \string },
+ text-outline-level
+ }
+ | element text:user-index-mark-start {
+ text-id, text-outline-level, text-index-name
+ }
+ | element text:user-index-mark-end { text-id }
+ | element text:user-index-mark {
+ attribute text:string-value { \string },
+ text-outline-level,
+ text-index-name
+ }
+ | element text:alphabetical-index-mark-start {
+ text-id, text-alphabetical-index-mark-attrs
+ }
+ | element text:alphabetical-index-mark-end { text-id }
+ | element text:alphabetical-index-mark {
+ attribute text:string-value { \string },
+ text-alphabetical-index-mark-attrs
+ }
+ | element text:bibliography-mark {
+ attribute text:bibliography-type { text-bibliography-types },
+ attribute text:identifier
+ | text:address
+ | text:annote
+ | text:author
+ | text:booktitle
+ | text:chapter
+ | text:edition
+ | text:editor
+ | text:howpublished
+ | text:institution
+ | text:journal
+ | text:month
+ | text:note
+ | text:number
+ | text:organizations
+ | text:pages
+ | text:publisher
+ | text:school
+ | text:series
+ | text:title
+ | text:report-type
+ | text:volume
+ | text:year
+ | text:url
+ | text:custom1
+ | text:custom2
+ | text:custom3
+ | text:custom4
+ | text:custom5
+ | text:isbn
+ | text:issn { \string }*,
+ text
+ }
+ | element presentation:header { empty }
+ | element presentation:footer { empty }
+ | element presentation:date-time { empty }
+text-tab-attr = attribute text:tab-ref { nonNegativeInteger }?
+text-a =
+ element text:a {
+ text-a-attlist, office-event-listeners?, paragraph-content*
+ }
+text-a-attlist =
+ attribute office:name { \string }?
+ & attribute office:title { \string }?
+ & attribute xlink:type { "simple" }
+ & attribute xlink:href { anyIRI }
+ & attribute xlink:actuate { "onRequest" }?
+ & attribute office:target-frame-name { targetFrameName }?
+ & attribute xlink:show { "new" | "replace" }?
+ & attribute text:style-name { styleNameRef }?
+ & attribute text:visited-style-name { styleNameRef }?
+text-meta-attlist = common-in-content-meta-attlist? & xml-id?
+text-bookmark = element text:bookmark { text-bookmark-attlist, empty }
+text-bookmark-start =
+ element text:bookmark-start { text-bookmark-start-attlist, empty }
+text-bookmark-end =
+ element text:bookmark-end { text-bookmark-end-attlist, empty }
+text-bookmark-attlist =
+ attribute text:name { \string }
+ & xml-id?
+text-bookmark-start-attlist =
+ attribute text:name { \string }
+ & xml-id?
+ & common-in-content-meta-attlist?
+text-bookmark-end-attlist = attribute text:name { \string }
+text-note-class = attribute text:note-class { "footnote" | "endnote" }
+text-date-attlist =
+ (common-field-fixed-attlist & common-field-data-style-name-attlist)
+ & attribute text:date-value { dateOrDateTime }?
+ & attribute text:date-adjust { duration }?
+text-time-attlist =
+ (common-field-fixed-attlist & common-field-data-style-name-attlist)
+ & attribute text:time-value { timeOrDateTime }?
+ & attribute text:time-adjust { duration }?
+text-page-number-attlist =
+ (common-field-num-format-attlist & common-field-fixed-attlist)
+ & attribute text:page-adjust { integer }?
+ & attribute text:select-page { "previous" | "current" | "next" }?
+text-page-continuation-attlist =
+ attribute text:select-page { "previous" | "next" }
+ & attribute text:string-value { \string }?
+text-chapter-attlist =
+ attribute text:display {
+ "name"
+ | "number"
+ | "number-and-name"
+ | "plain-number-and-name"
+ | "plain-number"
+ }
+ & attribute text:outline-level { nonNegativeInteger }
+text-file-name-attlist =
+ attribute text:display {
+ "full" | "path" | "name" | "name-and-extension"
+ }?
+ & common-field-fixed-attlist
+text-template-name-attlist =
+ attribute text:display {
+ "full" | "path" | "name" | "name-and-extension" | "area" | "title"
+ }?
+text-variable-decl =
+ element text:variable-decl {
+ common-field-name-attlist, common-value-type-attlist
+ }
+text-user-field-decl =
+ element text:user-field-decl {
+ common-field-name-attlist,
+ common-field-formula-attlist?,
+ common-value-and-type-attlist
+ }
+text-sequence-decl =
+ element text:sequence-decl { text-sequence-decl-attlist }
+text-sequence-decl-attlist =
+ common-field-name-attlist
+ & attribute text:display-outline-level { nonNegativeInteger }
+ & attribute text:separation-character { character }?
+text-sequence-ref-name = attribute text:ref-name { \string }?
+common-field-database-table =
+ common-field-database-table-attlist, common-field-database-name
+common-field-database-name =
+ attribute text:database-name { \string }?
+ | form-connection-resource
+common-field-database-table-attlist =
+ attribute text:table-name { \string }
+ & attribute text:table-type { "table" | "query" | "command" }?
+text-database-display-attlist =
+ common-field-database-table
+ & common-field-data-style-name-attlist
+ & attribute text:column-name { \string }
+text-database-next-attlist =
+ common-field-database-table
+ & attribute text:condition { \string }?
+text-database-row-select-attlist =
+ common-field-database-table
+ & attribute text:condition { \string }?
+ & attribute text:row-number { nonNegativeInteger }?
+text-set-page-variable-attlist =
+ attribute text:active { boolean }?
+ & attribute text:page-adjust { integer }?
+text-get-page-variable-attlist = common-field-num-format-attlist
+text-placeholder-attlist =
+ attribute text:placeholder-type {
+ "text" | "table" | "text-box" | "image" | "object"
+ }
+ & common-field-description-attlist
+text-conditional-text-attlist =
+ attribute text:condition { \string }
+ & attribute text:string-value-if-true { \string }
+ & attribute text:string-value-if-false { \string }
+ & attribute text:current-value { boolean }?
+text-hidden-text-attlist =
+ attribute text:condition { \string }
+ & attribute text:string-value { \string }
+ & attribute text:is-hidden { boolean }?
+text-common-ref-content =
+ text
+ & attribute text:ref-name { \string }?
+text-bookmark-ref-content =
+ attribute text:reference-format {
+ common-ref-format-values
+ | "number-no-superior"
+ | "number-all-superior"
+ | "number"
+ }?
+text-note-ref-content =
+ attribute text:reference-format { common-ref-format-values }?
+ & text-note-class
+text-sequence-ref-content =
+ attribute text:reference-format {
+ common-ref-format-values
+ | "category-and-value"
+ | "caption"
+ | "value"
+ }?
+common-ref-format-values = "page" | "chapter" | "direction" | "text"
+text-hidden-paragraph-attlist =
+ attribute text:condition { \string }
+ & attribute text:is-hidden { boolean }?
+text-meta-field-attlist = xml-id & common-field-data-style-name-attlist
+common-value-type-attlist = attribute office:value-type { valueType }
+common-value-and-type-attlist =
+ (attribute office:value-type { "float" },
+ attribute office:value { double })
+ | (attribute office:value-type { "percentage" },
+ attribute office:value { double })
+ | (attribute office:value-type { "currency" },
+ attribute office:value { double },
+ attribute office:currency { \string }?)
+ | (attribute office:value-type { "date" },
+ attribute office:date-value { dateOrDateTime })
+ | (attribute office:value-type { "time" },
+ attribute office:time-value { duration })
+ | (attribute office:value-type { "boolean" },
+ attribute office:boolean-value { boolean })
+ | (attribute office:value-type { "string" },
+ attribute office:string-value { \string }?)
+common-field-fixed-attlist = attribute text:fixed { boolean }?
+common-field-name-attlist = attribute text:name { variableName }
+common-field-description-attlist =
+ attribute text:description { \string }?
+common-field-display-value-none-attlist =
+ attribute text:display { "value" | "none" }?
+common-field-display-value-formula-none-attlist =
+ attribute text:display { "value" | "formula" | "none" }?
+common-field-display-value-formula-attlist =
+ attribute text:display { "value" | "formula" }?
+common-field-formula-attlist = attribute text:formula { \string }?
+common-field-data-style-name-attlist =
+ attribute style:data-style-name { styleNameRef }?
+common-field-num-format-attlist = common-num-format-attlist?
+text-toc-mark-start-attrs = text-id, text-outline-level
+text-outline-level = attribute text:outline-level { positiveInteger }?
+text-id = attribute text:id { \string }
+text-index-name = attribute text:index-name { \string }
+text-alphabetical-index-mark-attrs =
+ attribute text:key1 { \string }?
+ & attribute text:key2 { \string }?
+ & attribute text:string-value-phonetic { \string }?
+ & attribute text:key1-phonetic { \string }?
+ & attribute text:key2-phonetic { \string }?
+ & attribute text:main-entry { boolean }?
+text-bibliography-types =
+ "article"
+ | "book"
+ | "booklet"
+ | "conference"
+ | "custom1"
+ | "custom2"
+ | "custom3"
+ | "custom4"
+ | "custom5"
+ | "email"
+ | "inbook"
+ | "incollection"
+ | "inproceedings"
+ | "journal"
+ | "manual"
+ | "mastersthesis"
+ | "misc"
+ | "phdthesis"
+ | "proceedings"
+ | "techreport"
+ | "unpublished"
+ | "www"
+text-index-body = element text:index-body { index-content-main* }
+index-content-main = text-content | text-index-title
+text-index-title =
+ element text:index-title {
+ common-section-attlist, index-content-main*
+ }
+text-table-of-content =
+ element text:table-of-content {
+ common-section-attlist,
+ text-table-of-content-source,
+ text-index-body
+ }
+text-table-of-content-source =
+ element text:table-of-content-source {
+ text-table-of-content-source-attlist,
+ text-index-title-template?,
+ text-table-of-content-entry-template*,
+ text-index-source-styles*
+ }
+text-table-of-content-source-attlist =
+ attribute text:outline-level { positiveInteger }?
+ & attribute text:use-outline-level { boolean }?
+ & attribute text:use-index-marks { boolean }?
+ & attribute text:use-index-source-styles { boolean }?
+ & attribute text:index-scope { "document" | "chapter" }?
+ & attribute text:relative-tab-stop-position { boolean }?
+text-table-of-content-entry-template =
+ element text:table-of-content-entry-template {
+ text-table-of-content-entry-template-attlist,
+ text-table-of-content-children*
+ }
+text-table-of-content-children =
+ text-index-entry-chapter
+ | text-index-entry-page-number
+ | text-index-entry-text
+ | text-index-entry-span
+ | text-index-entry-tab-stop
+ | text-index-entry-link-start
+ | text-index-entry-link-end
+text-table-of-content-entry-template-attlist =
+ attribute text:outline-level { positiveInteger }
+ & attribute text:style-name { styleNameRef }
+text-illustration-index =
+ element text:illustration-index {
+ common-section-attlist,
+ text-illustration-index-source,
+ text-index-body
+ }
+text-illustration-index-source =
+ element text:illustration-index-source {
+ text-illustration-index-source-attrs,
+ text-index-title-template?,
+ text-illustration-index-entry-template?
+ }
+text-illustration-index-source-attrs =
+ text-index-scope-attr
+ & text-relative-tab-stop-position-attr
+ & attribute text:use-caption { boolean }?
+ & attribute text:caption-sequence-name { \string }?
+ & attribute text:caption-sequence-format {
+ "text" | "category-and-value" | "caption"
+ }?
+text-index-scope-attr =
+ attribute text:index-scope { "document" | "chapter" }?
+text-relative-tab-stop-position-attr =
+ attribute text:relative-tab-stop-position { boolean }?
+text-illustration-index-entry-template =
+ element text:illustration-index-entry-template {
+ text-illustration-index-entry-content
+ }
+text-illustration-index-entry-content =
+ text-illustration-index-entry-template-attrs,
+ (text-index-entry-chapter
+ | text-index-entry-page-number
+ | text-index-entry-text
+ | text-index-entry-span
+ | text-index-entry-tab-stop)*
+text-illustration-index-entry-template-attrs =
+ attribute text:style-name { styleNameRef }
+text-table-index =
+ element text:table-index {
+ common-section-attlist, text-table-index-source, text-index-body
+ }
+text-table-index-source =
+ element text:table-index-source {
+ text-illustration-index-source-attrs,
+ text-index-title-template?,
+ text-table-index-entry-template?
+ }
+text-table-index-entry-template =
+ element text:table-index-entry-template {
+ text-illustration-index-entry-content
+ }
+text-object-index =
+ element text:object-index {
+ common-section-attlist, text-object-index-source, text-index-body
+ }
+text-object-index-source =
+ element text:object-index-source {
+ text-object-index-source-attrs,
+ text-index-title-template?,
+ text-object-index-entry-template?
+ }
+text-object-index-source-attrs =
+ text-index-scope-attr
+ & text-relative-tab-stop-position-attr
+ & attribute text:use-spreadsheet-objects { boolean }?
+ & attribute text:use-math-objects { boolean }?
+ & attribute text:use-draw-objects { boolean }?
+ & attribute text:use-chart-objects { boolean }?
+ & attribute text:use-other-objects { boolean }?
+text-object-index-entry-template =
+ element text:object-index-entry-template {
+ text-illustration-index-entry-content
+ }
+text-user-index =
+ element text:user-index {
+ common-section-attlist, text-user-index-source, text-index-body
+ }
+text-user-index-source =
+ element text:user-index-source {
+ text-user-index-source-attr,
+ text-index-title-template?,
+ text-user-index-entry-template*,
+ text-index-source-styles*
+ }
+text-user-index-source-attr =
+ text-index-scope-attr
+ & text-relative-tab-stop-position-attr
+ & attribute text:use-index-marks { boolean }?
+ & attribute text:use-index-source-styles { boolean }?
+ & attribute text:use-graphics { boolean }?
+ & attribute text:use-tables { boolean }?
+ & attribute text:use-floating-frames { boolean }?
+ & attribute text:use-objects { boolean }?
+ & attribute text:copy-outline-levels { boolean }?
+ & attribute text:index-name { \string }
+text-user-index-entry-template =
+ element text:user-index-entry-template {
+ text-user-index-entry-template-attrs,
+ (text-index-entry-chapter
+ | text-index-entry-page-number
+ | text-index-entry-text
+ | text-index-entry-span
+ | text-index-entry-tab-stop)*
+ }
+text-user-index-entry-template-attrs =
+ attribute text:outline-level { positiveInteger }
+ & attribute text:style-name { styleNameRef }
+text-alphabetical-index =
+ element text:alphabetical-index {
+ common-section-attlist,
+ text-alphabetical-index-source,
+ text-index-body
+ }
+text-alphabetical-index-source =
+ element text:alphabetical-index-source {
+ text-alphabetical-index-source-attrs,
+ text-index-title-template?,
+ text-alphabetical-index-entry-template*
+ }
+text-alphabetical-index-source-attrs =
+ text-index-scope-attr
+ & text-relative-tab-stop-position-attr
+ & attribute text:ignore-case { boolean }?
+ & attribute text:main-entry-style-name { styleNameRef }?
+ & attribute text:alphabetical-separators { boolean }?
+ & attribute text:combine-entries { boolean }?
+ & attribute text:combine-entries-with-dash { boolean }?
+ & attribute text:combine-entries-with-pp { boolean }?
+ & attribute text:use-keys-as-entries { boolean }?
+ & attribute text:capitalize-entries { boolean }?
+ & attribute text:comma-separated { boolean }?
+ & attribute fo:language { languageCode }?
+ & attribute fo:country { countryCode }?
+ & attribute fo:script { scriptCode }?
+ & attribute style:rfc-language-tag { language }?
+ & attribute text:sort-algorithm { \string }?
+text-alphabetical-index-auto-mark-file =
+ element text:alphabetical-index-auto-mark-file {
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI }
+ }
+text-alphabetical-index-entry-template =
+ element text:alphabetical-index-entry-template {
+ text-alphabetical-index-entry-template-attrs,
+ (text-index-entry-chapter
+ | text-index-entry-page-number
+ | text-index-entry-text
+ | text-index-entry-span
+ | text-index-entry-tab-stop)*
+ }
+text-alphabetical-index-entry-template-attrs =
+ attribute text:outline-level { "1" | "2" | "3" | "separator" }
+ & attribute text:style-name { styleNameRef }
+text-bibliography =
+ element text:bibliography {
+ common-section-attlist, text-bibliography-source, text-index-body
+ }
+text-bibliography-source =
+ element text:bibliography-source {
+ text-index-title-template?, text-bibliography-entry-template*
+ }
+text-bibliography-entry-template =
+ element text:bibliography-entry-template {
+ text-bibliography-entry-template-attrs,
+ (text-index-entry-span
+ | text-index-entry-tab-stop
+ | text-index-entry-bibliography)*
+ }
+text-bibliography-entry-template-attrs =
+ attribute text:bibliography-type { text-bibliography-types }
+ & attribute text:style-name { styleNameRef }
+text-index-source-styles =
+ element text:index-source-styles {
+ attribute text:outline-level { positiveInteger },
+ text-index-source-style*
+ }
+text-index-source-style =
+ element text:index-source-style {
+ attribute text:style-name { styleName },
+ empty
+ }
+text-index-title-template =
+ element text:index-title-template {
+ attribute text:style-name { styleNameRef }?,
+ text
+ }
+text-index-entry-chapter =
+ element text:index-entry-chapter {
+ attribute text:style-name { styleNameRef }?,
+ text-index-entry-chapter-attrs
+ }
+text-index-entry-chapter-attrs =
+ attribute text:display {
+ "name"
+ | "number"
+ | "number-and-name"
+ | "plain-number"
+ | "plain-number-and-name"
+ }?
+ & attribute text:outline-level { positiveInteger }?
+text-index-entry-text =
+ element text:index-entry-text {
+ attribute text:style-name { styleNameRef }?
+ }
+text-index-entry-page-number =
+ element text:index-entry-page-number {
+ attribute text:style-name { styleNameRef }?
+ }
+text-index-entry-span =
+ element text:index-entry-span {
+ attribute text:style-name { styleNameRef }?,
+ text
+ }
+text-index-entry-bibliography =
+ element text:index-entry-bibliography {
+ text-index-entry-bibliography-attrs
+ }
+text-index-entry-bibliography-attrs =
+ attribute text:style-name { styleNameRef }?
+ & attribute text:bibliography-data-field {
+ "address"
+ | "annote"
+ | "author"
+ | "bibliography-type"
+ | "booktitle"
+ | "chapter"
+ | "custom1"
+ | "custom2"
+ | "custom3"
+ | "custom4"
+ | "custom5"
+ | "edition"
+ | "editor"
+ | "howpublished"
+ | "identifier"
+ | "institution"
+ | "isbn"
+ | "issn"
+ | "journal"
+ | "month"
+ | "note"
+ | "number"
+ | "organizations"
+ | "pages"
+ | "publisher"
+ | "report-type"
+ | "school"
+ | "series"
+ | "title"
+ | "url"
+ | "volume"
+ | "year"
+ }
+text-index-entry-tab-stop =
+ element text:index-entry-tab-stop {
+ attribute text:style-name { styleNameRef }?,
+ text-index-entry-tab-stop-attrs
+ }
+text-index-entry-tab-stop-attrs =
+ attribute style:leader-char { character }?
+ & (attribute style:type { "right" }
+ | (attribute style:type { "left" },
+ attribute style:position { length }))
+text-index-entry-link-start =
+ element text:index-entry-link-start {
+ attribute text:style-name { styleNameRef }?
+ }
+text-index-entry-link-end =
+ element text:index-entry-link-end {
+ attribute text:style-name { styleNameRef }?
+ }
+table-table =
+ element table:table {
+ table-table-attlist,
+ table-title?,
+ table-desc?,
+ table-table-source?,
+ office-dde-source?,
+ table-scenario?,
+ office-forms?,
+ table-shapes?,
+ table-columns-and-groups,
+ table-rows-and-groups,
+ table-named-expressions?
+ }
+table-columns-and-groups =
+ (table-table-column-group | table-columns-no-group)+
+table-columns-no-group =
+ (table-columns, (table-table-header-columns, table-columns?)?)
+ | (table-table-header-columns, table-columns?)
+table-columns = table-table-columns | table-table-column+
+table-rows-and-groups = (table-table-row-group | table-rows-no-group)+
+table-rows-no-group =
+ (table-rows, (table-table-header-rows, table-rows?)?)
+ | (table-table-header-rows, table-rows?)
+table-rows =
+ table-table-rows | (text-soft-page-break?, table-table-row)+
+table-table-attlist =
+ attribute table:name { \string }?
+ & attribute table:style-name { styleNameRef }?
+ & attribute table:template-name { \string }?
+ & attribute table:use-first-row-styles { boolean }?
+ & attribute table:use-last-row-styles { boolean }?
+ & attribute table:use-first-column-styles { boolean }?
+ & attribute table:use-last-column-styles { boolean }?
+ & attribute table:use-banding-rows-styles { boolean }?
+ & attribute table:use-banding-columns-styles { boolean }?
+ & attribute table:protected { boolean }?
+ & attribute table:protection-key { \string }?
+ & attribute table:protection-key-digest-algorithm { anyIRI }?
+ & attribute table:print { boolean }?
+ & attribute table:print-ranges { cellRangeAddressList }?
+ & xml-id?
+ & attribute table:is-sub-table { boolean }?
+table-title = element table:title { text }
+table-desc = element table:desc { text }
+table-table-row =
+ element table:table-row {
+ table-table-row-attlist,
+ (table-table-cell | table-covered-table-cell)+
+ }
+table-table-row-attlist =
+ attribute table:number-rows-repeated { positiveInteger }?
+ & attribute table:style-name { styleNameRef }?
+ & attribute table:default-cell-style-name { styleNameRef }?
+ & attribute table:visibility { table-visibility-value }?
+ & xml-id?
+table-visibility-value = "visible" | "collapse" | "filter"
+table-table-cell =
+ element table:table-cell {
+ table-table-cell-attlist,
+ table-table-cell-attlist-extra,
+ table-table-cell-content
+ }
+table-covered-table-cell =
+ element table:covered-table-cell {
+ table-table-cell-attlist, table-table-cell-content
+ }
+table-table-cell-content =
+ table-cell-range-source?,
+ office-annotation?,
+ table-detective?,
+ text-content*
+table-table-cell-attlist =
+ attribute table:number-columns-repeated { positiveInteger }?
+ & attribute table:style-name { styleNameRef }?
+ & attribute table:content-validation-name { \string }?
+ & attribute table:formula { \string }?
+ & common-value-and-type-attlist?
+ & attribute table:protect { boolean }?
+ & attribute table:protected { boolean }?
+ & xml-id?
+ & common-in-content-meta-attlist?
+table-table-cell-attlist-extra =
+ attribute table:number-columns-spanned { positiveInteger }?
+ & attribute table:number-rows-spanned { positiveInteger }?
+ & attribute table:number-matrix-columns-spanned { positiveInteger }?
+ & attribute table:number-matrix-rows-spanned { positiveInteger }?
+table-table-column =
+ element table:table-column { table-table-column-attlist, empty }
+table-table-column-attlist =
+ attribute table:number-columns-repeated { positiveInteger }?
+ & attribute table:style-name { styleNameRef }?
+ & attribute table:visibility { table-visibility-value }?
+ & attribute table:default-cell-style-name { styleNameRef }?
+ & xml-id?
+table-table-header-columns =
+ element table:table-header-columns { table-table-column+ }
+table-table-columns =
+ element table:table-columns { table-table-column+ }
+table-table-column-group =
+ element table:table-column-group {
+ table-table-column-group-attlist, table-columns-and-groups
+ }
+table-table-column-group-attlist = attribute table:display { boolean }?
+table-table-header-rows =
+ element table:table-header-rows {
+ (text-soft-page-break?, table-table-row)+
+ }
+table-table-rows =
+ element table:table-rows { (text-soft-page-break?, table-table-row)+ }
+table-table-row-group =
+ element table:table-row-group {
+ table-table-row-group-attlist, table-rows-and-groups
+ }
+table-table-row-group-attlist = attribute table:display { boolean }?
+cellAddress =
+ xsd:string {
+ pattern = "($?([^\. ']+|'([^']|'')+'))?\.$?[A-Z]+$?[0-9]+"
+ }
+cellRangeAddress =
+ xsd:string {
+ pattern =
+ "($?([^\. ']+|'([^']|'')+'))?\.$?[A-Z]+$?[0-9]+(:($?([^\. ']+|'([^']|'')+'))?\.$?[A-Z]+$?[0-9]+)?"
+ }
+ | xsd:string {
+ pattern =
+ "($?([^\. ']+|'([^']|'')+'))?\.$?[0-9]+:($?([^\. ']+|'([^']|'')+'))?\.$?[0-9]+"
+ }
+ | xsd:string {
+ pattern =
+ "($?([^\. ']+|'([^']|'')+'))?\.$?[A-Z]+:($?([^\. ']+|'([^']|'')+'))?\.$?[A-Z]+"
+ }
+cellRangeAddressList =
+ xsd:string
+ >> dc:description [
+ 'Value is a space separated list of "cellRangeAddress" patterns'
+ ]
+table-table-source =
+ element table:table-source {
+ table-table-source-attlist, table-linked-source-attlist, empty
+ }
+table-table-source-attlist =
+ attribute table:mode { "copy-all" | "copy-results-only" }?
+ & attribute table:table-name { \string }?
+table-linked-source-attlist =
+ attribute xlink:type { "simple" }
+ & attribute xlink:href { anyIRI }
+ & attribute xlink:actuate { "onRequest" }?
+ & attribute table:filter-name { \string }?
+ & attribute table:filter-options { \string }?
+ & attribute table:refresh-delay { duration }?
+table-scenario =
+ element table:scenario { table-scenario-attlist, empty }
+table-scenario-attlist =
+ attribute table:scenario-ranges { cellRangeAddressList }
+ & attribute table:is-active { boolean }
+ & attribute table:display-border { boolean }?
+ & attribute table:border-color { color }?
+ & attribute table:copy-back { boolean }?
+ & attribute table:copy-styles { boolean }?
+ & attribute table:copy-formulas { boolean }?
+ & attribute table:comment { \string }?
+ & attribute table:protected { boolean }?
+table-shapes = element table:shapes { shape+ }
+table-cell-range-source =
+ element table:cell-range-source {
+ table-table-cell-range-source-attlist,
+ table-linked-source-attlist,
+ empty
+ }
+table-table-cell-range-source-attlist =
+ attribute table:name { \string }
+ & attribute table:last-column-spanned { positiveInteger }
+ & attribute table:last-row-spanned { positiveInteger }
+table-detective =
+ element table:detective { table-highlighted-range*, table-operation* }
+table-operation =
+ element table:operation { table-operation-attlist, empty }
+table-operation-attlist =
+ attribute table:name {
+ "trace-dependents"
+ | "remove-dependents"
+ | "trace-precedents"
+ | "remove-precedents"
+ | "trace-errors"
+ }
+ & attribute table:index { nonNegativeInteger }
+table-highlighted-range =
+ element table:highlighted-range {
+ (table-highlighted-range-attlist
+ | table-highlighted-range-attlist-invalid),
+ empty
+ }
+table-highlighted-range-attlist =
+ attribute table:cell-range-address { cellRangeAddress }?
+ & attribute table:direction {
+ "from-another-table" | "to-another-table" | "from-same-table"
+ }
+ & attribute table:contains-error { boolean }?
+table-highlighted-range-attlist-invalid =
+ attribute table:marked-invalid { boolean }
+office-spreadsheet-attlist =
+ attribute table:structure-protected { boolean }?,
+ attribute table:protection-key { \string }?,
+ attribute table:protection-key-digest-algorithm { anyIRI }?
+table-calculation-settings =
+ element table:calculation-settings {
+ table-calculation-setting-attlist,
+ table-null-date?,
+ table-iteration?
+ }
+table-calculation-setting-attlist =
+ attribute table:case-sensitive { boolean }?
+ & attribute table:precision-as-shown { boolean }?
+ & attribute table:search-criteria-must-apply-to-whole-cell {
+ boolean
+ }?
+ & attribute table:automatic-find-labels { boolean }?
+ & attribute table:use-regular-expressions { boolean }?
+ & attribute table:use-wildcards { boolean }?
+ & attribute table:null-year { positiveInteger }?
+table-null-date =
+ element table:null-date {
+ attribute table:value-type { "date" }?,
+ attribute table:date-value { date }?,
+ empty
+ }
+table-iteration =
+ element table:iteration {
+ attribute table:status { "enable" | "disable" }?,
+ attribute table:steps { positiveInteger }?,
+ attribute table:maximum-difference { double }?,
+ empty
+ }
+table-content-validations =
+ element table:content-validations { table-content-validation+ }
+table-content-validation =
+ element table:content-validation {
+ table-validation-attlist,
+ table-help-message?,
+ (table-error-message | (table-error-macro, office-event-listeners))?
+ }
+table-validation-attlist =
+ attribute table:name { \string }
+ & attribute table:condition { \string }?
+ & attribute table:base-cell-address { cellAddress }?
+ & attribute table:allow-empty-cell { boolean }?
+ & attribute table:display-list {
+ "none" | "unsorted" | "sort-ascending"
+ }?
+table-help-message =
+ element table:help-message {
+ attribute table:title { \string }?,
+ attribute table:display { boolean }?,
+ text-p*
+ }
+table-error-message =
+ element table:error-message {
+ attribute table:title { \string }?,
+ attribute table:display { boolean }?,
+ attribute table:message-type {
+ "stop" | "warning" | "information"
+ }?,
+ text-p*
+ }
+table-error-macro =
+ element table:error-macro {
+ attribute table:execute { boolean }?
+ }
+table-label-ranges = element table:label-ranges { table-label-range* }
+table-label-range =
+ element table:label-range { table-label-range-attlist, empty }
+table-label-range-attlist =
+ attribute table:label-cell-range-address { cellRangeAddress }
+ & attribute table:data-cell-range-address { cellRangeAddress }
+ & attribute table:orientation { "column" | "row" }
+table-named-expressions =
+ element table:named-expressions {
+ (table-named-range | table-named-expression)*
+ }
+table-named-range =
+ element table:named-range { table-named-range-attlist, empty }
+table-named-range-attlist =
+ attribute table:name { \string },
+ attribute table:cell-range-address { cellRangeAddress },
+ attribute table:base-cell-address { cellAddress }?,
+ attribute table:range-usable-as {
+ "none"
+ | list {
+ ("print-range" | "filter" | "repeat-row" | "repeat-column")+
+ }
+ }?
+table-named-expression =
+ element table:named-expression {
+ table-named-expression-attlist, empty
+ }
+table-named-expression-attlist =
+ attribute table:name { \string },
+ attribute table:expression { \string },
+ attribute table:base-cell-address { cellAddress }?
+table-database-ranges =
+ element table:database-ranges { table-database-range* }
+table-database-range =
+ element table:database-range {
+ table-database-range-attlist,
+ (table-database-source-sql
+ | table-database-source-table
+ | table-database-source-query)?,
+ table-filter?,
+ table-sort?,
+ table-subtotal-rules?
+ }
+table-database-range-attlist =
+ attribute table:name { \string }?
+ & attribute table:is-selection { boolean }?
+ & attribute table:on-update-keep-styles { boolean }?
+ & attribute table:on-update-keep-size { boolean }?
+ & attribute table:has-persistent-data { boolean }?
+ & attribute table:orientation { "column" | "row" }?
+ & attribute table:contains-header { boolean }?
+ & attribute table:display-filter-buttons { boolean }?
+ & attribute table:target-range-address { cellRangeAddress }
+ & attribute table:refresh-delay { boolean }?
+table-database-source-sql =
+ element table:database-source-sql {
+ table-database-source-sql-attlist, empty
+ }
+table-database-source-sql-attlist =
+ attribute table:database-name { \string }
+ & attribute table:sql-statement { \string }
+ & attribute table:parse-sql-statement { boolean }?
+table-database-source-query =
+ element table:database-source-table {
+ table-database-source-table-attlist, empty
+ }
+table-database-source-table-attlist =
+ attribute table:database-name { \string }
+ & attribute table:database-table-name { \string }
+table-database-source-table =
+ element table:database-source-query {
+ table-database-source-query-attlist, empty
+ }
+table-database-source-query-attlist =
+ attribute table:database-name { \string }
+ & attribute table:query-name { \string }
+table-sort = element table:sort { table-sort-attlist, table-sort-by+ }
+table-sort-attlist =
+ attribute table:bind-styles-to-content { boolean }?
+ & attribute table:target-range-address { cellRangeAddress }?
+ & attribute table:case-sensitive { boolean }?
+ & attribute table:language { languageCode }?
+ & attribute table:country { countryCode }?
+ & attribute table:script { scriptCode }?
+ & attribute table:rfc-language-tag { language }?
+ & attribute table:algorithm { \string }?
+ & attribute table:embedded-number-behavior {
+ "alpha-numeric" | "integer" | "double"
+ }?
+table-sort-by = element table:sort-by { table-sort-by-attlist, empty }
+table-sort-by-attlist =
+ attribute table:field-number { nonNegativeInteger }
+ & attribute table:data-type {
+ "text" | "number" | "automatic" | \string
+ }?
+ & attribute table:order { "ascending" | "descending" }?
+table-subtotal-rules =
+ element table:subtotal-rules {
+ table-subtotal-rules-attlist,
+ table-sort-groups?,
+ table-subtotal-rule*
+ }
+table-subtotal-rules-attlist =
+ attribute table:bind-styles-to-content { boolean }?
+ & attribute table:case-sensitive { boolean }?
+ & attribute table:page-breaks-on-group-change { boolean }?
+table-sort-groups =
+ element table:sort-groups { table-sort-groups-attlist, empty }
+table-sort-groups-attlist =
+ attribute table:data-type {
+ "text" | "number" | "automatic" | \string
+ }?
+ & attribute table:order { "ascending" | "descending" }?
+table-subtotal-rule =
+ element table:subtotal-rule {
+ table-subtotal-rule-attlist, table-subtotal-field*
+ }
+table-subtotal-rule-attlist =
+ attribute table:group-by-field-number { nonNegativeInteger }
+table-subtotal-field =
+ element table:subtotal-field { table-subtotal-field-attlist, empty }
+table-subtotal-field-attlist =
+ attribute table:field-number { nonNegativeInteger }
+ & attribute table:function {
+ "average"
+ | "count"
+ | "countnums"
+ | "max"
+ | "min"
+ | "product"
+ | "stdev"
+ | "stdevp"
+ | "sum"
+ | "var"
+ | "varp"
+ | \string
+ }
+table-filter =
+ element table:filter {
+ table-filter-attlist,
+ (table-filter-condition | table-filter-and | table-filter-or)
+ }
+table-filter-attlist =
+ attribute table:target-range-address { cellRangeAddress }?
+ & attribute table:condition-source { "self" | "cell-range" }?
+ & attribute table:condition-source-range-address { cellRangeAddress }?
+ & attribute table:display-duplicates { boolean }?
+table-filter-and =
+ element table:filter-and {
+ (table-filter-or | table-filter-condition)+
+ }
+table-filter-or =
+ element table:filter-or {
+ (table-filter-and | table-filter-condition)+
+ }
+table-filter-condition =
+ element table:filter-condition {
+ table-filter-condition-attlist, table-filter-set-item*
+ }
+table-filter-condition-attlist =
+ attribute table:field-number { nonNegativeInteger }
+ & attribute table:value { \string | double }
+ & attribute table:operator { \string }
+ & attribute table:case-sensitive { \string }?
+ & attribute table:data-type { "text" | "number" }?
+table-filter-set-item =
+ element table:filter-set-item {
+ attribute table:value { \string },
+ empty
+ }
+table-data-pilot-tables =
+ element table:data-pilot-tables { table-data-pilot-table* }
+table-data-pilot-table =
+ element table:data-pilot-table {
+ table-data-pilot-table-attlist,
+ (table-database-source-sql
+ | table-database-source-table
+ | table-database-source-query
+ | table-source-service
+ | table-source-cell-range)?,
+ table-data-pilot-field+
+ }
+table-data-pilot-table-attlist =
+ attribute table:name { \string }
+ & attribute table:application-data { \string }?
+ & attribute table:grand-total { "none" | "row" | "column" | "both" }?
+ & attribute table:ignore-empty-rows { boolean }?
+ & attribute table:identify-categories { boolean }?
+ & attribute table:target-range-address { cellRangeAddress }
+ & attribute table:buttons { cellRangeAddressList }?
+ & attribute table:show-filter-button { boolean }?
+ & attribute table:drill-down-on-double-click { boolean }?
+table-source-cell-range =
+ element table:source-cell-range {
+ table-source-cell-range-attlist, table-filter?
+ }
+table-source-cell-range-attlist =
+ attribute table:cell-range-address { cellRangeAddress }
+table-source-service =
+ element table:source-service { table-source-service-attlist, empty }
+table-source-service-attlist =
+ attribute table:name { \string }
+ & attribute table:source-name { \string }
+ & attribute table:object-name { \string }
+ & attribute table:user-name { \string }?
+ & attribute table:password { \string }?
+table-data-pilot-field =
+ element table:data-pilot-field {
+ table-data-pilot-field-attlist,
+ table-data-pilot-level?,
+ table-data-pilot-field-reference?,
+ table-data-pilot-groups?
+ }
+table-data-pilot-field-attlist =
+ attribute table:source-field-name { \string }
+ & (attribute table:orientation {
+ "row" | "column" | "data" | "hidden"
+ }
+ | (attribute table:orientation { "page" },
+ attribute table:selected-page { \string }))
+ & attribute table:is-data-layout-field { \string }?
+ & attribute table:function {
+ "auto"
+ | "average"
+ | "count"
+ | "countnums"
+ | "max"
+ | "min"
+ | "product"
+ | "stdev"
+ | "stdevp"
+ | "sum"
+ | "var"
+ | "varp"
+ | \string
+ }?
+ & attribute table:used-hierarchy { integer }?
+table-data-pilot-level =
+ element table:data-pilot-level {
+ table-data-pilot-level-attlist,
+ table-data-pilot-subtotals?,
+ table-data-pilot-members?,
+ table-data-pilot-display-info?,
+ table-data-pilot-sort-info?,
+ table-data-pilot-layout-info?
+ }
+table-data-pilot-level-attlist = attribute table:show-empty { boolean }?
+table-data-pilot-subtotals =
+ element table:data-pilot-subtotals { table-data-pilot-subtotal* }
+table-data-pilot-subtotal =
+ element table:data-pilot-subtotal {
+ table-data-pilot-subtotal-attlist, empty
+ }
+table-data-pilot-subtotal-attlist =
+ attribute table:function {
+ "auto"
+ | "average"
+ | "count"
+ | "countnums"
+ | "max"
+ | "min"
+ | "product"
+ | "stdev"
+ | "stdevp"
+ | "sum"
+ | "var"
+ | "varp"
+ | \string
+ }
+table-data-pilot-members =
+ element table:data-pilot-members { table-data-pilot-member* }
+table-data-pilot-member =
+ element table:data-pilot-member {
+ table-data-pilot-member-attlist, empty
+ }
+table-data-pilot-member-attlist =
+ attribute table:name { \string }
+ & attribute table:display { boolean }?
+ & attribute table:show-details { boolean }?
+table-data-pilot-display-info =
+ element table:data-pilot-display-info {
+ table-data-pilot-display-info-attlist, empty
+ }
+table-data-pilot-display-info-attlist =
+ attribute table:enabled { boolean }
+ & attribute table:data-field { \string }
+ & attribute table:member-count { nonNegativeInteger }
+ & attribute table:display-member-mode { "from-top" | "from-bottom" }
+table-data-pilot-sort-info =
+ element table:data-pilot-sort-info {
+ table-data-pilot-sort-info-attlist, empty
+ }
+table-data-pilot-sort-info-attlist =
+ ((attribute table:sort-mode { "data" },
+ attribute table:data-field { \string })
+ | attribute table:sort-mode { "none" | "manual" | "name" })
+ & attribute table:order { "ascending" | "descending" }
+table-data-pilot-layout-info =
+ element table:data-pilot-layout-info {
+ table-data-pilot-layout-info-attlist, empty
+ }
+table-data-pilot-layout-info-attlist =
+ attribute table:layout-mode {
+ "tabular-layout"
+ | "outline-subtotals-top"
+ | "outline-subtotals-bottom"
+ }
+ & attribute table:add-empty-lines { boolean }
+table-data-pilot-field-reference =
+ element table:data-pilot-field-reference {
+ table-data-pilot-field-reference-attlist
+ }
+table-data-pilot-field-reference-attlist =
+ attribute table:field-name { \string }
+ & ((attribute table:member-type { "named" },
+ attribute table:member-name { \string })
+ | attribute table:member-type { "previous" | "next" })
+ & attribute table:type {
+ "none"
+ | "member-difference"
+ | "member-percentage"
+ | "member-percentage-difference"
+ | "running-total"
+ | "row-percentage"
+ | "column-percentage"
+ | "total-percentage"
+ | "index"
+ }
+table-data-pilot-groups =
+ element table:data-pilot-groups {
+ table-data-pilot-groups-attlist, table-data-pilot-group+
+ }
+table-data-pilot-groups-attlist =
+ attribute table:source-field-name { \string }
+ & (attribute table:date-start { dateOrDateTime | "auto" }
+ | attribute table:start { double | "auto" })
+ & (attribute table:date-end { dateOrDateTime | "auto" }
+ | attribute table:end { double | "auto" })
+ & attribute table:step { double }
+ & attribute table:grouped-by {
+ "seconds"
+ | "minutes"
+ | "hours"
+ | "days"
+ | "months"
+ | "quarters"
+ | "years"
+ }
+table-data-pilot-group =
+ element table:data-pilot-group {
+ table-data-pilot-group-attlist, table-data-pilot-group-member+
+ }
+table-data-pilot-group-attlist = attribute table:name { \string }
+table-data-pilot-group-member =
+ element table:data-pilot-group-member {
+ table-data-pilot-group-member-attlist
+ }
+table-data-pilot-group-member-attlist = attribute table:name { \string }
+table-consolidation =
+ element table:consolidation { table-consolidation-attlist, empty }
+table-consolidation-attlist =
+ attribute table:function {
+ "average"
+ | "count"
+ | "countnums"
+ | "max"
+ | "min"
+ | "product"
+ | "stdev"
+ | "stdevp"
+ | "sum"
+ | "var"
+ | "varp"
+ | \string
+ }
+ & attribute table:source-cell-range-addresses { cellRangeAddressList }
+ & attribute table:target-cell-address { cellAddress }
+ & attribute table:use-labels { "none" | "row" | "column" | "both" }?
+ & attribute table:link-to-source-data { boolean }?
+table-dde-links = element table:dde-links { table-dde-link+ }
+table-tracked-changes =
+ element table:tracked-changes {
+ table-tracked-changes-attlist,
+ (table-cell-content-change
+ | table-insertion
+ | table-deletion
+ | table-movement)*
+ }
+table-tracked-changes-attlist =
+ attribute table:track-changes { boolean }?
+table-insertion =
+ element table:insertion {
+ table-insertion-attlist,
+ common-table-change-attlist,
+ office-change-info,
+ table-dependencies?,
+ table-deletions?
+ }
+table-insertion-attlist =
+ attribute table:type { "row" | "column" | "table" }
+ & attribute table:position { integer }
+ & attribute table:count { positiveInteger }?
+ & attribute table:table { integer }?
+table-dependencies = element table:dependencies { table-dependency+ }
+table-dependency =
+ element table:dependency {
+ attribute table:id { \string },
+ empty
+ }
+table-deletions =
+ element table:deletions {
+ (table-cell-content-deletion | table-change-deletion)+
+ }
+table-cell-content-deletion =
+ element table:cell-content-deletion {
+ attribute table:id { \string }?,
+ table-cell-address?,
+ table-change-track-table-cell?
+ }
+table-change-deletion =
+ element table:change-deletion {
+ attribute table:id { \string }?,
+ empty
+ }
+table-deletion =
+ element table:deletion {
+ table-deletion-attlist,
+ common-table-change-attlist,
+ office-change-info,
+ table-dependencies?,
+ table-deletions?,
+ table-cut-offs?
+ }
+table-deletion-attlist =
+ attribute table:type { "row" | "column" | "table" }
+ & attribute table:position { integer }
+ & attribute table:table { integer }?
+ & attribute table:multi-deletion-spanned { integer }?
+table-cut-offs =
+ element table:cut-offs {
+ table-movement-cut-off+
+ | (table-insertion-cut-off, table-movement-cut-off*)
+ }
+table-insertion-cut-off =
+ element table:insertion-cut-off {
+ table-insertion-cut-off-attlist, empty
+ }
+table-insertion-cut-off-attlist =
+ attribute table:id { \string }
+ & attribute table:position { integer }
+table-movement-cut-off =
+ element table:movement-cut-off {
+ table-movement-cut-off-attlist, empty
+ }
+table-movement-cut-off-attlist =
+ attribute table:position { integer }
+ | (attribute table:start-position { integer },
+ attribute table:end-position { integer })
+table-movement =
+ element table:movement {
+ common-table-change-attlist,
+ table-source-range-address,
+ table-target-range-address,
+ office-change-info,
+ table-dependencies?,
+ table-deletions?
+ }
+table-source-range-address =
+ element table:source-range-address {
+ common-table-range-attlist, empty
+ }
+table-target-range-address =
+ element table:target-range-address {
+ common-table-range-attlist, empty
+ }
+common-table-range-attlist =
+ common-table-cell-address-attlist
+ | common-table-cell-range-address-attlist
+common-table-cell-address-attlist =
+ attribute table:column { integer },
+ attribute table:row { integer },
+ attribute table:table { integer }
+common-table-cell-range-address-attlist =
+ attribute table:start-column { integer },
+ attribute table:start-row { integer },
+ attribute table:start-table { integer },
+ attribute table:end-column { integer },
+ attribute table:end-row { integer },
+ attribute table:end-table { integer }
+table-change-track-table-cell =
+ element table:change-track-table-cell {
+ table-change-track-table-cell-attlist, text-p*
+ }
+table-change-track-table-cell-attlist =
+ attribute table:cell-address { cellAddress }?
+ & attribute table:matrix-covered { boolean }?
+ & attribute table:formula { \string }?
+ & attribute table:number-matrix-columns-spanned { positiveInteger }?
+ & attribute table:number-matrix-rows-spanned { positiveInteger }?
+ & common-value-and-type-attlist?
+table-cell-content-change =
+ element table:cell-content-change {
+ common-table-change-attlist,
+ table-cell-address,
+ office-change-info,
+ table-dependencies?,
+ table-deletions?,
+ table-previous
+ }
+table-cell-address =
+ element table:cell-address {
+ common-table-cell-address-attlist, empty
+ }
+table-previous =
+ element table:previous {
+ attribute table:id { \string }?,
+ table-change-track-table-cell
+ }
+common-table-change-attlist =
+ attribute table:id { \string }
+ & attribute table:acceptance-state {
+ "accepted" | "rejected" | "pending"
+ }?
+ & attribute table:rejecting-change-id { \string }?
+style-handout-master =
+ element style:handout-master {
+ common-presentation-header-footer-attlist,
+ style-handout-master-attlist,
+ shape*
+ }
+style-handout-master-attlist =
+ attribute presentation:presentation-page-layout-name { styleNameRef }?
+ & attribute style:page-layout-name { styleNameRef }
+ & attribute draw:style-name { styleNameRef }?
+draw-layer-set = element draw:layer-set { draw-layer* }
+draw-layer =
+ element draw:layer { draw-layer-attlist, svg-title?, svg-desc? }
+draw-layer-attlist =
+ attribute draw:name { \string }
+ & attribute draw:protected { boolean }?
+ & attribute draw:display { "always" | "screen" | "printer" | "none" }?
+draw-page =
+ element draw:page {
+ common-presentation-header-footer-attlist,
+ draw-page-attlist,
+ svg-title?,
+ svg-desc?,
+ draw-layer-set?,
+ office-forms?,
+ shape*,
+ (presentation-animations | animation-element)?,
+ presentation-notes?
+ }
+draw-page-attlist =
+ attribute draw:name { \string }?
+ & attribute draw:style-name { styleNameRef }?
+ & attribute draw:master-page-name { styleNameRef }
+ & attribute presentation:presentation-page-layout-name {
+ styleNameRef
+ }?
+ & (xml-id,
+ attribute draw:id { NCName }?)?
+ & attribute draw:nav-order { IDREFS }?
+common-presentation-header-footer-attlist =
+ attribute presentation:use-header-name { \string }?
+ & attribute presentation:use-footer-name { \string }?
+ & attribute presentation:use-date-time-name { \string }?
+shape = shape-instance | draw-a
+shape-instance =
+ draw-rect
+ | draw-line
+ | draw-polyline
+ | draw-polygon
+ | draw-regular-polygon
+ | draw-path
+ | draw-circle
+ | draw-ellipse
+ | draw-g
+ | draw-page-thumbnail
+ | draw-frame
+ | draw-measure
+ | draw-caption
+ | draw-connector
+ | draw-control
+ | dr3d-scene
+ | draw-custom-shape
+draw-rect =
+ element draw:rect {
+ draw-rect-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-rect-attlist =
+ attribute draw:corner-radius { nonNegativeLength }?
+ | (attribute svg:rx { nonNegativeLength }?,
+ attribute svg:ry { nonNegativeLength }?)
+draw-line =
+ element draw:line {
+ draw-line-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-line-attlist =
+ attribute svg:x1 { coordinate }
+ & attribute svg:y1 { coordinate }
+ & attribute svg:x2 { coordinate }
+ & attribute svg:y2 { coordinate }
+draw-polyline =
+ element draw:polyline {
+ common-draw-points-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+common-draw-points-attlist = attribute draw:points { points }
+draw-polygon =
+ element draw:polygon {
+ common-draw-points-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-regular-polygon =
+ element draw:regular-polygon {
+ draw-regular-polygon-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-regular-polygon-attlist =
+ (attribute draw:concave { "false" }
+ | (attribute draw:concave { "true" },
+ draw-regular-polygon-sharpness-attlist))
+ & attribute draw:corners { positiveInteger }
+draw-regular-polygon-sharpness-attlist =
+ attribute draw:sharpness { percent }
+draw-path =
+ element draw:path {
+ common-draw-path-data-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+common-draw-path-data-attlist = attribute svg:d { pathData }
+draw-circle =
+ element draw:circle {
+ ((draw-circle-attlist, common-draw-circle-ellipse-pos-attlist)
+ | (common-draw-position-attlist, common-draw-size-attlist)),
+ common-draw-circle-ellipse-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+common-draw-circle-ellipse-pos-attlist =
+ attribute svg:cx { coordinate },
+ attribute svg:cy { coordinate }
+draw-circle-attlist = attribute svg:r { length }
+common-draw-circle-ellipse-attlist =
+ attribute draw:kind { "full" | "section" | "cut" | "arc" }?
+ & attribute draw:start-angle { angle }?
+ & attribute draw:end-angle { angle }?
+draw-ellipse =
+ element draw:ellipse {
+ ((draw-ellipse-attlist, common-draw-circle-ellipse-pos-attlist)
+ | (common-draw-position-attlist, common-draw-size-attlist)),
+ common-draw-circle-ellipse-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-ellipse-attlist =
+ attribute svg:rx { length },
+ attribute svg:ry { length }
+draw-connector =
+ element draw:connector {
+ draw-connector-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ common-draw-viewbox-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-connector-attlist =
+ attribute draw:type { "standard" | "lines" | "line" | "curve" }?
+ & (attribute svg:x1 { coordinate },
+ attribute svg:y1 { coordinate })?
+ & attribute draw:start-shape { IDREF }?
+ & attribute draw:start-glue-point { nonNegativeInteger }?
+ & (attribute svg:x2 { coordinate },
+ attribute svg:y2 { coordinate })?
+ & attribute draw:end-shape { IDREF }?
+ & attribute draw:end-glue-point { nonNegativeInteger }?
+ & attribute draw:line-skew {
+ list { length, (length, length?)? }
+ }?
+ & attribute svg:d { pathData }?
+draw-caption =
+ element draw:caption {
+ draw-caption-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-caption-attlist =
+ (attribute draw:caption-point-x { coordinate },
+ attribute draw:caption-point-y { coordinate })?
+ & attribute draw:corner-radius { nonNegativeLength }?
+draw-measure =
+ element draw:measure {
+ draw-measure-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text
+ }
+draw-measure-attlist =
+ attribute svg:x1 { coordinate }
+ & attribute svg:y1 { coordinate }
+ & attribute svg:x2 { coordinate }
+ & attribute svg:y2 { coordinate }
+draw-control =
+ element draw:control {
+ draw-control-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ draw-glue-point*
+ }
+draw-control-attlist = attribute draw:control { IDREF }
+draw-page-thumbnail =
+ element draw:page-thumbnail {
+ draw-page-thumbnail-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ presentation-shape-attlist,
+ common-draw-shape-with-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?
+ }
+draw-page-thumbnail-attlist =
+ attribute draw:page-number { positiveInteger }?
+draw-g =
+ element draw:g {
+ draw-g-attlist,
+ common-draw-z-index-attlist,
+ common-draw-name-attlist,
+ common-draw-id-attlist,
+ common-draw-style-name-attlist,
+ common-text-spreadsheet-shape-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ shape*
+ }
+draw-g-attlist = attribute svg:y { coordinate }?
+common-draw-name-attlist = attribute draw:name { \string }?
+common-draw-caption-id-attlist = attribute draw:caption-id { IDREF }?
+common-draw-position-attlist =
+ attribute svg:x { coordinate }?,
+ attribute svg:y { coordinate }?
+common-draw-size-attlist =
+ attribute svg:width { length }?,
+ attribute svg:height { length }?
+common-draw-transform-attlist = attribute draw:transform { \string }?
+common-draw-viewbox-attlist =
+ attribute svg:viewBox {
+ list { integer, integer, integer, integer }
+ }
+common-draw-style-name-attlist =
+ (attribute draw:style-name { styleNameRef }?,
+ attribute draw:class-names { styleNameRefs }?)
+ | (attribute presentation:style-name { styleNameRef }?,
+ attribute presentation:class-names { styleNameRefs }?)
+common-draw-text-style-name-attlist =
+ attribute draw:text-style-name { styleNameRef }?
+common-draw-layer-name-attlist = attribute draw:layer { \string }?
+common-draw-id-attlist =
+ (xml-id,
+ attribute draw:id { NCName }?)?
+common-draw-z-index-attlist =
+ attribute draw:z-index { nonNegativeInteger }?
+common-text-spreadsheet-shape-attlist =
+ attribute table:end-cell-address { cellAddress }?
+ & attribute table:end-x { coordinate }?
+ & attribute table:end-y { coordinate }?
+ & attribute table:table-background { boolean }?
+ & common-text-anchor-attlist
+common-text-anchor-attlist =
+ attribute text:anchor-type {
+ "page" | "frame" | "paragraph" | "char" | "as-char"
+ }?
+ & attribute text:anchor-page-number { positiveInteger }?
+draw-text = (text-p | text-list)*
+common-draw-shape-with-styles-attlist =
+ common-draw-z-index-attlist,
+ common-draw-id-attlist,
+ common-draw-layer-name-attlist,
+ common-draw-style-name-attlist,
+ common-draw-transform-attlist,
+ common-draw-name-attlist,
+ common-text-spreadsheet-shape-attlist
+common-draw-shape-with-text-and-styles-attlist =
+ common-draw-shape-with-styles-attlist,
+ common-draw-text-style-name-attlist
+draw-glue-point =
+ element draw:glue-point { draw-glue-point-attlist, empty }
+draw-glue-point-attlist =
+ attribute draw:id { nonNegativeInteger }
+ & attribute svg:x { distance | percent }
+ & attribute svg:y { distance | percent }
+ & attribute draw:align {
+ "top-left"
+ | "top"
+ | "top-right"
+ | "left"
+ | "center"
+ | "right"
+ | "bottom-left"
+ | "bottom-right"
+ }?
+ & attribute draw:escape-direction {
+ "auto"
+ | "left"
+ | "right"
+ | "up"
+ | "down"
+ | "horizontal"
+ | "vertical"
+ }
+svg-title = element svg:title { text }
+svg-desc = element svg:desc { text }
+draw-frame =
+ element draw:frame {
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-position-attlist,
+ common-draw-rel-size-attlist,
+ common-draw-caption-id-attlist,
+ presentation-shape-attlist,
+ draw-frame-attlist,
+ (draw-text-box
+ | draw-image
+ | draw-object
+ | draw-object-ole
+ | draw-applet
+ | draw-floating-frame
+ | draw-plugin
+ | table-table)*,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-image-map?,
+ svg-title?,
+ svg-desc?,
+ (draw-contour-polygon | draw-contour-path)?
+ }
+common-draw-rel-size-attlist =
+ common-draw-size-attlist,
+ attribute style:rel-width { percent | "scale" | "scale-min" }?,
+ attribute style:rel-height { percent | "scale" | "scale-min" }?
+draw-frame-attlist = attribute draw:copy-of { \string }?
+draw-text-box =
+ element draw:text-box { draw-text-box-attlist, text-content* }
+draw-text-box-attlist =
+ attribute draw:chain-next-name { \string }?
+ & attribute draw:corner-radius { nonNegativeLength }?
+ & attribute fo:min-height { length | percent }?
+ & attribute fo:min-width { length | percent }?
+ & attribute fo:max-height { length | percent }?
+ & attribute fo:max-width { length | percent }?
+ & (xml-id,
+ attribute text:id { NCName }?)?
+draw-image =
+ element draw:image {
+ draw-image-attlist,
+ (common-draw-data-attlist | office-binary-data),
+ draw-text
+ }
+common-draw-data-attlist =
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "embed" }?,
+ attribute xlink:actuate { "onLoad" }?
+office-binary-data = element office:binary-data { base64Binary }
+draw-image-attlist =
+ attribute draw:filter-name { \string }?
+ & xml-id?
+draw-object =
+ element draw:object {
+ draw-object-attlist,
+ (common-draw-data-attlist | office-document | math-math)
+ }
+draw-object-ole =
+ element draw:object-ole {
+ draw-object-ole-attlist,
+ (common-draw-data-attlist | office-binary-data)
+ }
+draw-object-attlist =
+ attribute draw:notify-on-update-of-ranges {
+ cellRangeAddressList | \string
+ }?
+ & xml-id?
+draw-object-ole-attlist =
+ attribute draw:class-id { \string }?
+ & xml-id?
+draw-applet =
+ element draw:applet {
+ draw-applet-attlist, common-draw-data-attlist?, draw-param*
+ }
+draw-applet-attlist =
+ attribute draw:code { \string }?
+ & attribute draw:object { \string }?
+ & attribute draw:archive { \string }?
+ & attribute draw:may-script { boolean }?
+ & xml-id?
+draw-plugin =
+ element draw:plugin {
+ draw-plugin-attlist, common-draw-data-attlist, draw-param*
+ }
+draw-plugin-attlist =
+ attribute draw:mime-type { \string }?
+ & xml-id?
+draw-param = element draw:param { draw-param-attlist, empty }
+draw-param-attlist =
+ attribute draw:name { \string }?
+ & attribute draw:value { \string }?
+draw-floating-frame =
+ element draw:floating-frame {
+ draw-floating-frame-attlist, common-draw-data-attlist
+ }
+draw-floating-frame-attlist =
+ attribute draw:frame-name { \string }?
+ & xml-id?
+draw-contour-polygon =
+ element draw:contour-polygon {
+ common-contour-attlist,
+ common-draw-size-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-points-attlist,
+ empty
+ }
+draw-contour-path =
+ element draw:contour-path {
+ common-contour-attlist,
+ common-draw-size-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-path-data-attlist,
+ empty
+ }
+common-contour-attlist = attribute draw:recreate-on-edit { boolean }
+draw-a = element draw:a { draw-a-attlist, shape-instance }
+draw-a-attlist =
+ attribute xlink:type { "simple" }
+ & attribute xlink:href { anyIRI }
+ & attribute xlink:actuate { "onRequest" }?
+ & attribute office:target-frame-name { targetFrameName }?
+ & attribute xlink:show { "new" | "replace" }?
+ & attribute office:name { \string }?
+ & attribute office:title { \string }?
+ & attribute office:server-map { boolean }?
+ & xml-id?
+draw-image-map =
+ element draw:image-map {
+ (draw-area-rectangle | draw-area-circle | draw-area-polygon)*
+ }
+draw-area-rectangle =
+ element draw:area-rectangle {
+ common-draw-area-attlist,
+ attribute svg:x { coordinate },
+ attribute svg:y { coordinate },
+ attribute svg:width { length },
+ attribute svg:height { length },
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?
+ }
+draw-area-circle =
+ element draw:area-circle {
+ common-draw-area-attlist,
+ attribute svg:cx { coordinate },
+ attribute svg:cy { coordinate },
+ attribute svg:r { length },
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?
+ }
+draw-area-polygon =
+ element draw:area-polygon {
+ common-draw-area-attlist,
+ attribute svg:x { coordinate },
+ attribute svg:y { coordinate },
+ attribute svg:width { length },
+ attribute svg:height { length },
+ common-draw-viewbox-attlist,
+ common-draw-points-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?
+ }
+common-draw-area-attlist =
+ (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute office:target-frame-name { targetFrameName }?,
+ attribute xlink:show { "new" | "replace" }?)?
+ & attribute office:name { \string }?
+ & attribute draw:nohref { "nohref" }?
+dr3d-scene =
+ element dr3d:scene {
+ dr3d-scene-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-style-name-attlist,
+ common-draw-z-index-attlist,
+ common-draw-id-attlist,
+ common-draw-layer-name-attlist,
+ common-text-spreadsheet-shape-attlist,
+ common-dr3d-transform-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ dr3d-light*,
+ shapes3d*,
+ draw-glue-point*
+ }
+shapes3d =
+ dr3d-scene | dr3d-extrude | dr3d-sphere | dr3d-rotate | dr3d-cube
+dr3d-scene-attlist =
+ attribute dr3d:vrp { vector3D }?
+ & attribute dr3d:vpn { vector3D }?
+ & attribute dr3d:vup { vector3D }?
+ & attribute dr3d:projection { "parallel" | "perspective" }?
+ & attribute dr3d:distance { length }?
+ & attribute dr3d:focal-length { length }?
+ & attribute dr3d:shadow-slant { angle }?
+ & attribute dr3d:shade-mode {
+ "flat" | "phong" | "gouraud" | "draft"
+ }?
+ & attribute dr3d:ambient-color { color }?
+ & attribute dr3d:lighting-mode { boolean }?
+common-dr3d-transform-attlist = attribute dr3d:transform { \string }?
+dr3d-light = element dr3d:light { dr3d-light-attlist, empty }
+dr3d-light-attlist =
+ attribute dr3d:diffuse-color { color }?
+ & attribute dr3d:direction { vector3D }
+ & attribute dr3d:enabled { boolean }?
+ & attribute dr3d:specular { boolean }?
+dr3d-cube =
+ element dr3d:cube {
+ dr3d-cube-attlist,
+ common-draw-z-index-attlist,
+ common-draw-id-attlist,
+ common-draw-layer-name-attlist,
+ common-draw-style-name-attlist,
+ common-dr3d-transform-attlist,
+ empty
+ }
+dr3d-cube-attlist =
+ attribute dr3d:min-edge { vector3D }?,
+ attribute dr3d:max-edge { vector3D }?
+dr3d-sphere =
+ element dr3d:sphere {
+ dr3d-sphere-attlist,
+ common-draw-z-index-attlist,
+ common-draw-id-attlist,
+ common-draw-layer-name-attlist,
+ common-draw-style-name-attlist,
+ common-dr3d-transform-attlist,
+ empty
+ }
+dr3d-sphere-attlist =
+ attribute dr3d:center { vector3D }?
+ & attribute dr3d:size { vector3D }?
+dr3d-extrude =
+ element dr3d:extrude {
+ common-draw-path-data-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-id-attlist,
+ common-draw-z-index-attlist,
+ common-draw-layer-name-attlist,
+ common-draw-style-name-attlist,
+ common-dr3d-transform-attlist,
+ empty
+ }
+dr3d-rotate =
+ element dr3d:rotate {
+ common-draw-viewbox-attlist,
+ common-draw-path-data-attlist,
+ common-draw-z-index-attlist,
+ common-draw-id-attlist,
+ common-draw-layer-name-attlist,
+ common-draw-style-name-attlist,
+ common-dr3d-transform-attlist,
+ empty
+ }
+draw-custom-shape =
+ element draw:custom-shape {
+ draw-custom-shape-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ common-draw-caption-id-attlist,
+ svg-title?,
+ svg-desc?,
+ office-event-listeners?,
+ draw-glue-point*,
+ draw-text,
+ draw-enhanced-geometry?
+ }
+draw-custom-shape-attlist =
+ attribute draw:engine { namespacedToken }?
+ & attribute draw:data { \string }?
+draw-enhanced-geometry =
+ element draw:enhanced-geometry {
+ draw-enhanced-geometry-attlist, draw-equation*, draw-handle*
+ }
+draw-enhanced-geometry-attlist =
+ attribute draw:type { custom-shape-type }?
+ & attribute svg:viewBox {
+ list { integer, integer, integer, integer }
+ }?
+ & attribute draw:mirror-vertical { boolean }?
+ & attribute draw:mirror-horizontal { boolean }?
+ & attribute draw:text-rotate-angle { angle }?
+ & attribute draw:extrusion-allowed { boolean }?
+ & attribute draw:text-path-allowed { boolean }?
+ & attribute draw:concentric-gradient-fill-allowed { boolean }?
+ & attribute draw:extrusion { boolean }?
+ & attribute draw:extrusion-brightness { zeroToHundredPercent }?
+ & attribute draw:extrusion-depth {
+ list { length, double }
+ }?
+ & attribute draw:extrusion-diffusion { percent }?
+ & attribute draw:extrusion-number-of-line-segments { integer }?
+ & attribute draw:extrusion-light-face { boolean }?
+ & attribute draw:extrusion-first-light-harsh { boolean }?
+ & attribute draw:extrusion-second-light-harsh { boolean }?
+ & attribute draw:extrusion-first-light-level { zeroToHundredPercent }?
+ & attribute draw:extrusion-second-light-level {
+ zeroToHundredPercent
+ }?
+ & attribute draw:extrusion-first-light-direction { vector3D }?
+ & attribute draw:extrusion-second-light-direction { vector3D }?
+ & attribute draw:extrusion-metal { boolean }?
+ & attribute dr3d:shade-mode {
+ "flat" | "phong" | "gouraud" | "draft"
+ }?
+ & attribute draw:extrusion-rotation-angle {
+ list { angle, angle }
+ }?
+ & attribute draw:extrusion-rotation-center { vector3D }?
+ & attribute draw:extrusion-shininess { zeroToHundredPercent }?
+ & attribute draw:extrusion-skew {
+ list { double, angle }
+ }?
+ & attribute draw:extrusion-specularity { zeroToHundredPercent }?
+ & attribute dr3d:projection { "parallel" | "perspective" }?
+ & attribute draw:extrusion-viewpoint { point3D }?
+ & attribute draw:extrusion-origin {
+ list { extrusionOrigin, extrusionOrigin }
+ }?
+ & attribute draw:extrusion-color { boolean }?
+ & attribute draw:enhanced-path { \string }?
+ & attribute draw:path-stretchpoint-x { double }?
+ & attribute draw:path-stretchpoint-y { double }?
+ & attribute draw:text-areas { \string }?
+ & attribute draw:glue-points { \string }?
+ & attribute draw:glue-point-type {
+ "none" | "segments" | "rectangle"
+ }?
+ & attribute draw:glue-point-leaving-directions { \string }?
+ & attribute draw:text-path { boolean }?
+ & attribute draw:text-path-mode { "normal" | "path" | "shape" }?
+ & attribute draw:text-path-scale { "path" | "shape" }?
+ & attribute draw:text-path-same-letter-heights { boolean }?
+ & attribute draw:modifiers { \string }?
+custom-shape-type = "non-primitive" | \string
+point3D =
+ xsd:string {
+ pattern =
+ "\([ ]*-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc))([ ]+-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc))){2}[ ]*\)"
+ }
+extrusionOrigin =
+ xsd:double { minInclusive = "-0.5" maxInclusive = "0.5" }
+draw-equation = element draw:equation { draw-equation-attlist, empty }
+draw-equation-attlist =
+ attribute draw:name { \string }?
+ & attribute draw:formula { \string }?
+draw-handle = element draw:handle { draw-handle-attlist, empty }
+draw-handle-attlist =
+ attribute draw:handle-mirror-vertical { boolean }?
+ & attribute draw:handle-mirror-horizontal { boolean }?
+ & attribute draw:handle-switched { boolean }?
+ & attribute draw:handle-position { \string }
+ & attribute draw:handle-range-x-minimum { \string }?
+ & attribute draw:handle-range-x-maximum { \string }?
+ & attribute draw:handle-range-y-minimum { \string }?
+ & attribute draw:handle-range-y-maximum { \string }?
+ & attribute draw:handle-polar { \string }?
+ & attribute draw:handle-radius-range-minimum { \string }?
+ & attribute draw:handle-radius-range-maximum { \string }?
+presentation-shape-attlist =
+ attribute presentation:class { presentation-classes }?
+ & attribute presentation:placeholder { boolean }?
+ & attribute presentation:user-transformed { boolean }?
+presentation-classes =
+ "title"
+ | "outline"
+ | "subtitle"
+ | "text"
+ | "graphic"
+ | "object"
+ | "chart"
+ | "table"
+ | "orgchart"
+ | "page"
+ | "notes"
+ | "handout"
+ | "header"
+ | "footer"
+ | "date-time"
+ | "page-number"
+presentation-animations =
+ element presentation:animations {
+ (presentation-animation-elements | presentation-animation-group)*
+ }
+presentation-animation-elements =
+ presentation-show-shape
+ | presentation-show-text
+ | presentation-hide-shape
+ | presentation-hide-text
+ | presentation-dim
+ | presentation-play
+presentation-sound =
+ element presentation:sound {
+ presentation-sound-attlist,
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:actuate { "onRequest" }?,
+ attribute xlink:show { "new" | "replace" }?,
+ empty
+ }
+presentation-sound-attlist =
+ attribute presentation:play-full { boolean }?
+ & xml-id?
+presentation-show-shape =
+ element presentation:show-shape {
+ common-presentation-effect-attlist, presentation-sound?
+ }
+common-presentation-effect-attlist =
+ attribute draw:shape-id { IDREF }
+ & attribute presentation:effect { presentationEffects }?
+ & attribute presentation:direction { presentationEffectDirections }?
+ & attribute presentation:speed { presentationSpeeds }?
+ & attribute presentation:delay { duration }?
+ & attribute presentation:start-scale { percent }?
+ & attribute presentation:path-id { \string }?
+presentationEffects =
+ "none"
+ | "fade"
+ | "move"
+ | "stripes"
+ | "open"
+ | "close"
+ | "dissolve"
+ | "wavyline"
+ | "random"
+ | "lines"
+ | "laser"
+ | "appear"
+ | "hide"
+ | "move-short"
+ | "checkerboard"
+ | "rotate"
+ | "stretch"
+presentationEffectDirections =
+ "none"
+ | "from-left"
+ | "from-top"
+ | "from-right"
+ | "from-bottom"
+ | "from-center"
+ | "from-upper-left"
+ | "from-upper-right"
+ | "from-lower-left"
+ | "from-lower-right"
+ | "to-left"
+ | "to-top"
+ | "to-right"
+ | "to-bottom"
+ | "to-upper-left"
+ | "to-upper-right"
+ | "to-lower-right"
+ | "to-lower-left"
+ | "path"
+ | "spiral-inward-left"
+ | "spiral-inward-right"
+ | "spiral-outward-left"
+ | "spiral-outward-right"
+ | "vertical"
+ | "horizontal"
+ | "to-center"
+ | "clockwise"
+ | "counter-clockwise"
+presentationSpeeds = "slow" | "medium" | "fast"
+presentation-show-text =
+ element presentation:show-text {
+ common-presentation-effect-attlist, presentation-sound?
+ }
+presentation-hide-shape =
+ element presentation:hide-shape {
+ common-presentation-effect-attlist, presentation-sound?
+ }
+presentation-hide-text =
+ element presentation:hide-text {
+ common-presentation-effect-attlist, presentation-sound?
+ }
+presentation-dim =
+ element presentation:dim {
+ presentation-dim-attlist, presentation-sound?
+ }
+presentation-dim-attlist =
+ attribute draw:shape-id { IDREF }
+ & attribute draw:color { color }
+presentation-play =
+ element presentation:play { presentation-play-attlist, empty }
+presentation-play-attlist =
+ attribute draw:shape-id { IDREF },
+ attribute presentation:speed { presentationSpeeds }?
+presentation-animation-group =
+ element presentation:animation-group {
+ presentation-animation-elements*
+ }
+common-anim-attlist =
+ attribute presentation:node-type {
+ "default"
+ | "on-click"
+ | "with-previous"
+ | "after-previous"
+ | "timing-root"
+ | "main-sequence"
+ | "interactive-sequence"
+ }?
+ & attribute presentation:preset-id { \string }?
+ & attribute presentation:preset-sub-type { \string }?
+ & attribute presentation:preset-class {
+ "custom"
+ | "entrance"
+ | "exit"
+ | "emphasis"
+ | "motion-path"
+ | "ole-action"
+ | "media-call"
+ }?
+ & attribute presentation:master-element { IDREF }?
+ & attribute presentation:group-id { \string }?
+ & (xml-id,
+ attribute anim:id { NCName }?)?
+presentation-event-listener =
+ element presentation:event-listener {
+ presentation-event-listener-attlist, presentation-sound?
+ }
+presentation-event-listener-attlist =
+ attribute script:event-name { \string }
+ & attribute presentation:action {
+ "none"
+ | "previous-page"
+ | "next-page"
+ | "first-page"
+ | "last-page"
+ | "hide"
+ | "stop"
+ | "execute"
+ | "show"
+ | "verb"
+ | "fade-out"
+ | "sound"
+ | "last-visited-page"
+ }
+ & attribute presentation:effect { presentationEffects }?
+ & attribute presentation:direction { presentationEffectDirections }?
+ & attribute presentation:speed { presentationSpeeds }?
+ & attribute presentation:start-scale { percent }?
+ & (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "embed" }?,
+ attribute xlink:actuate { "onRequest" }?)?
+ & attribute presentation:verb { nonNegativeInteger }?
+presentation-decls = presentation-decl*
+presentation-decl =
+ element presentation:header-decl {
+ presentation-header-decl-attlist, text
+ }
+ | element presentation:footer-decl {
+ presentation-footer-decl-attlist, text
+ }
+ | element presentation:date-time-decl {
+ presentation-date-time-decl-attlist, text
+ }
+presentation-header-decl-attlist =
+ attribute presentation:name { \string }
+presentation-footer-decl-attlist =
+ attribute presentation:name { \string }
+presentation-date-time-decl-attlist =
+ attribute presentation:name { \string }
+ & attribute presentation:source { "fixed" | "current-date" }
+ & attribute style:data-style-name { styleNameRef }?
+presentation-settings =
+ element presentation:settings {
+ presentation-settings-attlist, presentation-show*
+ }?
+presentation-settings-attlist =
+ attribute presentation:start-page { \string }?
+ & attribute presentation:show { \string }?
+ & attribute presentation:full-screen { boolean }?
+ & attribute presentation:endless { boolean }?
+ & attribute presentation:pause { duration }?
+ & attribute presentation:show-logo { boolean }?
+ & attribute presentation:force-manual { boolean }?
+ & attribute presentation:mouse-visible { boolean }?
+ & attribute presentation:mouse-as-pen { boolean }?
+ & attribute presentation:start-with-navigator { boolean }?
+ & attribute presentation:animations { "enabled" | "disabled" }?
+ & attribute presentation:transition-on-click {
+ "enabled" | "disabled"
+ }?
+ & attribute presentation:stay-on-top { boolean }?
+ & attribute presentation:show-end-of-presentation-slide { boolean }?
+presentation-show =
+ element presentation:show { presentation-show-attlist, empty }
+presentation-show-attlist =
+ attribute presentation:name { \string }
+ & attribute presentation:pages { \string }
+chart-chart =
+ element chart:chart {
+ chart-chart-attlist,
+ chart-title?,
+ chart-subtitle?,
+ chart-footer?,
+ chart-legend?,
+ chart-plot-area,
+ table-table?
+ }
+chart-chart-attlist =
+ attribute chart:class { namespacedToken }
+ & common-draw-size-attlist
+ & attribute chart:column-mapping { \string }?
+ & attribute chart:row-mapping { \string }?
+ & attribute chart:style-name { styleNameRef }?
+ & (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI })?
+ & xml-id?
+chart-title = element chart:title { chart-title-attlist, text-p? }
+chart-title-attlist =
+ attribute table:cell-range { cellRangeAddressList }?
+ & common-draw-position-attlist
+ & attribute chart:style-name { styleNameRef }?
+chart-subtitle = element chart:subtitle { chart-title-attlist, text-p? }
+chart-footer = element chart:footer { chart-title-attlist, text-p? }
+chart-legend = element chart:legend { chart-legend-attlist, text-p? }
+chart-legend-attlist =
+ ((attribute chart:legend-position {
+ "start" | "end" | "top" | "bottom"
+ },
+ attribute chart:legend-align { "start" | "center" | "end" }?)
+ | attribute chart:legend-position {
+ "top-start" | "bottom-start" | "top-end" | "bottom-end"
+ }
+ | empty)
+ & common-draw-position-attlist
+ & (attribute style:legend-expansion { "wide" | "high" | "balanced" }
+ | (attribute style:legend-expansion { "custom" },
+ attribute style:legend-expansion-aspect-ratio { double })
+ | empty)
+ & attribute chart:style-name { styleNameRef }?
+chart-plot-area =
+ element chart:plot-area {
+ chart-plot-area-attlist,
+ dr3d-light*,
+ chart-axis*,
+ chart-series*,
+ chart-stock-gain-marker?,
+ chart-stock-loss-marker?,
+ chart-stock-range-line?,
+ chart-wall?,
+ chart-floor?
+ }
+chart-plot-area-attlist =
+ common-draw-position-attlist
+ & common-draw-size-attlist
+ & attribute chart:style-name { styleNameRef }?
+ & attribute table:cell-range-address { cellRangeAddressList }?
+ & attribute chart:data-source-has-labels {
+ "none" | "row" | "column" | "both"
+ }?
+ & dr3d-scene-attlist
+ & common-dr3d-transform-attlist
+ & xml-id?
+chart-wall = element chart:wall { chart-wall-attlist, empty }
+chart-wall-attlist =
+ attribute svg:width { length }?
+ & attribute chart:style-name { styleNameRef }?
+chart-floor = element chart:floor { chart-floor-attlist, empty }
+chart-floor-attlist =
+ attribute svg:width { length }?
+ & attribute chart:style-name { styleNameRef }?
+chart-axis =
+ element chart:axis {
+ chart-axis-attlist, chart-title?, chart-categories?, chart-grid*
+ }
+chart-axis-attlist =
+ attribute chart:dimension { chart-dimension }
+ & attribute chart:name { \string }?
+ & attribute chart:style-name { styleNameRef }?
+chart-dimension = "x" | "y" | "z"
+chart-categories =
+ element chart:categories {
+ attribute table:cell-range-address { cellRangeAddressList }?
+ }
+chart-grid = element chart:grid { chart-grid-attlist }
+chart-grid-attlist =
+ attribute chart:class { "major" | "minor" }?
+ & attribute chart:style-name { styleNameRef }?
+chart-series =
+ element chart:series {
+ chart-series-attlist,
+ chart-domain*,
+ chart-mean-value?,
+ chart-regression-curve*,
+ chart-error-indicator*,
+ chart-data-point*,
+ chart-data-label?
+ }
+chart-series-attlist =
+ attribute chart:values-cell-range-address { cellRangeAddressList }?
+ & attribute chart:label-cell-address { cellRangeAddressList }?
+ & attribute chart:class { namespacedToken }?
+ & attribute chart:attached-axis { \string }?
+ & attribute chart:style-name { styleNameRef }?
+ & xml-id?
+chart-domain =
+ element chart:domain {
+ attribute table:cell-range-address { cellRangeAddressList }?
+ }
+chart-data-point =
+ element chart:data-point {
+ chart-data-point-attlist, chart-data-label?
+ }
+chart-data-point-attlist =
+ attribute chart:repeated { positiveInteger }?
+ & attribute chart:style-name { styleNameRef }?
+ & xml-id?
+chart-data-label =
+ element chart:data-label { chart-data-label-attlist, text-p? }
+chart-data-label-attlist =
+ common-draw-position-attlist
+ & attribute chart:style-name { styleNameRef }?
+chart-mean-value =
+ element chart:mean-value { chart-mean-value-attlist, empty }
+chart-mean-value-attlist = attribute chart:style-name { styleNameRef }?
+chart-error-indicator =
+ element chart:error-indicator { chart-error-indicator-attlist, empty }
+chart-error-indicator-attlist =
+ attribute chart:style-name { styleNameRef }?
+ & attribute chart:dimension { chart-dimension }
+chart-regression-curve =
+ element chart:regression-curve {
+ chart-regression-curve-attlist, chart-equation?
+ }
+chart-regression-curve-attlist =
+ attribute chart:style-name { styleNameRef }?
+chart-equation =
+ element chart:equation { chart-equation-attlist, text-p? }
+chart-equation-attlist =
+ attribute chart:automatic-content { boolean }?
+ & attribute chart:display-r-square { boolean }?
+ & attribute chart:display-equation { boolean }?
+ & common-draw-position-attlist
+ & attribute chart:style-name { styleNameRef }?
+chart-stock-gain-marker =
+ element chart:stock-gain-marker { common-stock-marker-attlist }
+chart-stock-loss-marker =
+ element chart:stock-loss-marker { common-stock-marker-attlist }
+chart-stock-range-line =
+ element chart:stock-range-line { common-stock-marker-attlist }
+common-stock-marker-attlist =
+ attribute chart:style-name { styleNameRef }?
+office-database =
+ element office:database {
+ db-data-source,
+ db-forms?,
+ db-reports?,
+ db-queries?,
+ db-table-presentations?,
+ db-schema-definition?
+ }
+db-data-source =
+ element db:data-source {
+ db-data-source-attlist,
+ db-connection-data,
+ db-driver-settings?,
+ db-application-connection-settings?
+ }
+db-data-source-attlist = empty
+db-connection-data =
+ element db:connection-data {
+ db-connection-data-attlist,
+ (db-database-description | db-connection-resource),
+ db-login?
+ }
+db-connection-data-attlist = empty
+db-database-description =
+ element db:database-description {
+ db-database-description-attlist,
+ (db-file-based-database | db-server-database)
+ }
+db-database-description-attlist = empty
+db-file-based-database =
+ element db:file-based-database { db-file-based-database-attlist }
+db-file-based-database-attlist =
+ attribute xlink:type { "simple" }
+ & attribute xlink:href { anyIRI }
+ & attribute db:media-type { \string }
+ & attribute db:extension { \string }?
+db-server-database =
+ element db:server-database { db-server-database-attlist, empty }
+db-server-database-attlist =
+ attribute db:type { namespacedToken }
+ & (db-host-and-port | db-local-socket-name)
+ & attribute db:database-name { \string }?
+db-host-and-port =
+ attribute db:hostname { \string },
+ attribute db:port { positiveInteger }?
+db-local-socket-name = attribute db:local-socket { \string }?
+db-connection-resource =
+ element db:connection-resource {
+ db-connection-resource-attlist, empty
+ }
+db-connection-resource-attlist =
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "none" }?,
+ attribute xlink:actuate { "onRequest" }?
+db-login = element db:login { db-login-attlist, empty }
+db-login-attlist =
+ (attribute db:user-name { \string }
+ | attribute db:use-system-user { boolean })?
+ & attribute db:is-password-required { boolean }?
+ & attribute db:login-timeout { positiveInteger }?
+db-driver-settings =
+ element db:driver-settings {
+ db-driver-settings-attlist,
+ db-auto-increment?,
+ db-delimiter?,
+ db-character-set?,
+ db-table-settings?
+ }
+db-driver-settings-attlist =
+ db-show-deleted
+ & attribute db:system-driver-settings { \string }?
+ & attribute db:base-dn { \string }?
+ & db-is-first-row-header-line
+ & attribute db:parameter-name-substitution { boolean }?
+db-show-deleted = attribute db:show-deleted { boolean }?
+db-is-first-row-header-line =
+ attribute db:is-first-row-header-line { boolean }?
+db-auto-increment =
+ element db:auto-increment { db-auto-increment-attlist, empty }
+db-auto-increment-attlist =
+ attribute db:additional-column-statement { \string }?
+ & attribute db:row-retrieving-statement { \string }?
+db-delimiter = element db:delimiter { db-delimiter-attlist, empty }
+db-delimiter-attlist =
+ attribute db:field { \string }?
+ & attribute db:string { \string }?
+ & attribute db:decimal { \string }?
+ & attribute db:thousand { \string }?
+db-character-set =
+ element db:character-set { db-character-set-attlist, empty }
+db-character-set-attlist = attribute db:encoding { textEncoding }?
+db-table-settings = element db:table-settings { db-table-setting* }
+db-table-setting =
+ element db:table-setting {
+ db-table-setting-attlist, db-delimiter?, db-character-set?, empty
+ }
+db-table-setting-attlist = db-is-first-row-header-line, db-show-deleted
+db-application-connection-settings =
+ element db:application-connection-settings {
+ db-application-connection-settings-attlist,
+ db-table-filter?,
+ db-table-type-filter?,
+ db-data-source-settings?
+ }
+db-application-connection-settings-attlist =
+ attribute db:is-table-name-length-limited { boolean }?
+ & attribute db:enable-sql92-check { boolean }?
+ & attribute db:append-table-alias-name { boolean }?
+ & attribute db:ignore-driver-privileges { boolean }?
+ & attribute db:boolean-comparison-mode {
+ "equal-integer"
+ | "is-boolean"
+ | "equal-boolean"
+ | "equal-use-only-zero"
+ }?
+ & attribute db:use-catalog { boolean }?
+ & attribute db:max-row-count { integer }?
+ & attribute db:suppress-version-columns { boolean }?
+db-table-filter =
+ element db:table-filter {
+ db-table-filter-attlist,
+ db-table-include-filter?,
+ db-table-exclude-filter?
+ }
+db-table-filter-attlist = empty
+db-table-include-filter =
+ element db:table-include-filter {
+ db-table-include-filter-attlist, db-table-filter-pattern+
+ }
+db-table-include-filter-attlist = empty
+db-table-exclude-filter =
+ element db:table-exclude-filter {
+ db-table-exclude-filter-attlist, db-table-filter-pattern+
+ }
+db-table-exclude-filter-attlist = empty
+db-table-filter-pattern =
+ element db:table-filter-pattern {
+ db-table-filter-pattern-attlist, \string
+ }
+db-table-filter-pattern-attlist = empty
+db-table-type-filter =
+ element db:table-type-filter {
+ db-table-type-filter-attlist, db-table-type*
+ }
+db-table-type-filter-attlist = empty
+db-table-type = element db:table-type { db-table-type-attlist, \string }
+db-table-type-attlist = empty
+db-data-source-settings =
+ element db:data-source-settings {
+ db-data-source-settings-attlist, db-data-source-setting+
+ }
+db-data-source-settings-attlist = empty
+db-data-source-setting =
+ element db:data-source-setting {
+ db-data-source-setting-attlist, db-data-source-setting-value+
+ }
+db-data-source-setting-attlist =
+ attribute db:data-source-setting-is-list { boolean }?
+ & attribute db:data-source-setting-name { \string }
+ & attribute db:data-source-setting-type {
+ db-data-source-setting-types
+ }
+db-data-source-setting-types =
+ "boolean" | "short" | "int" | "long" | "double" | "string"
+db-data-source-setting-value =
+ element db:data-source-setting-value {
+ db-data-source-setting-value-attlist, \string
+ }
+db-data-source-setting-value-attlist = empty
+db-forms =
+ element db:forms {
+ db-forms-attlist, (db-component | db-component-collection)*
+ }
+db-forms-attlist = empty
+db-reports =
+ element db:reports {
+ db-reports-attlist, (db-component | db-component-collection)*
+ }
+db-reports-attlist = empty
+db-component-collection =
+ element db:component-collection {
+ db-component-collection-attlist,
+ common-db-object-name,
+ common-db-object-title,
+ common-db-object-description,
+ (db-component | db-component-collection)*
+ }
+db-component-collection-attlist = empty
+db-component =
+ element db:component {
+ db-component-attlist,
+ common-db-object-name,
+ common-db-object-title,
+ common-db-object-description,
+ (office-document | math-math)?
+ }
+db-component-attlist =
+ (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "none" }?,
+ attribute xlink:actuate { "onRequest" }?)?
+ & attribute db:as-template { boolean }?
+db-queries =
+ element db:queries {
+ db-queries-attlist, (db-query | db-query-collection)*
+ }
+db-queries-attlist = empty
+db-query-collection =
+ element db:query-collection {
+ db-query-collection-attlist,
+ common-db-object-name,
+ common-db-object-title,
+ common-db-object-description,
+ (db-query | db-query-collection)*
+ }
+db-query-collection-attlist = empty
+db-query =
+ element db:query {
+ db-query-attlist,
+ common-db-object-name,
+ common-db-object-title,
+ common-db-object-description,
+ common-db-table-style-name,
+ db-order-statement?,
+ db-filter-statement?,
+ db-columns?,
+ db-update-table?
+ }
+db-query-attlist =
+ attribute db:command { \string }
+ & attribute db:escape-processing { boolean }?
+db-order-statement =
+ element db:order-statement { db-command, db-apply-command, empty }
+db-filter-statement =
+ element db:filter-statement { db-command, db-apply-command, empty }
+db-update-table =
+ element db:update-table { common-db-table-name-attlist }
+db-table-presentations =
+ element db:table-representations {
+ db-table-presentations-attlist, db-table-presentation*
+ }
+db-table-presentations-attlist = empty
+db-table-presentation =
+ element db:table-representation {
+ db-table-presentation-attlist,
+ common-db-table-name-attlist,
+ common-db-object-title,
+ common-db-object-description,
+ common-db-table-style-name,
+ db-order-statement?,
+ db-filter-statement?,
+ db-columns?
+ }
+db-table-presentation-attlist = empty
+db-columns = element db:columns { db-columns-attlist, db-column+ }
+db-columns-attlist = empty
+db-column =
+ element db:column {
+ db-column-attlist,
+ common-db-object-name,
+ common-db-object-title,
+ common-db-object-description,
+ common-db-default-value
+ }
+db-column-attlist =
+ attribute db:visible { boolean }?
+ & attribute db:style-name { styleNameRef }?
+ & attribute db:default-cell-style-name { styleNameRef }?
+db-command = attribute db:command { \string }
+db-apply-command = attribute db:apply-command { boolean }?
+common-db-table-name-attlist =
+ attribute db:name { \string }
+ & attribute db:catalog-name { \string }?
+ & attribute db:schema-name { \string }?
+common-db-object-name = attribute db:name { \string }
+common-db-object-title = attribute db:title { \string }?
+common-db-object-description = attribute db:description { \string }?
+common-db-table-style-name =
+ attribute db:style-name { styleNameRef }?
+ & attribute db:default-row-style-name { styleNameRef }?
+common-db-default-value = common-value-and-type-attlist?
+db-schema-definition =
+ element db:schema-definition {
+ db-schema-definition-attlist, db-table-definitions
+ }
+db-schema-definition-attlist = empty
+db-table-definitions =
+ element db:table-definitions {
+ db-table-definitions-attlist, db-table-definition*
+ }
+db-table-definitions-attlist = empty
+db-table-definition =
+ element db:table-definition {
+ common-db-table-name-attlist,
+ db-table-definition-attlist,
+ db-column-definitions,
+ db-keys?,
+ db-indices?
+ }
+db-table-definition-attlist = attribute db:type { \string }?
+db-column-definitions =
+ element db:column-definitions {
+ db-column-definitions-attlist, db-column-definition+
+ }
+db-column-definitions-attlist = empty
+db-column-definition =
+ element db:column-definition {
+ db-column-definition-attlist, common-db-default-value
+ }
+db-column-definition-attlist =
+ attribute db:name { \string }
+ & attribute db:data-type { db-data-types }?
+ & attribute db:type-name { \string }?
+ & attribute db:precision { positiveInteger }?
+ & attribute db:scale { positiveInteger }?
+ & attribute db:is-nullable { "no-nulls" | "nullable" }?
+ & attribute db:is-empty-allowed { boolean }?
+ & attribute db:is-autoincrement { boolean }?
+db-data-types =
+ "bit"
+ | "boolean"
+ | "tinyint"
+ | "smallint"
+ | "integer"
+ | "bigint"
+ | "float"
+ | "real"
+ | "double"
+ | "numeric"
+ | "decimal"
+ | "char"
+ | "varchar"
+ | "longvarchar"
+ | "date"
+ | "time"
+ | "timestmp"
+ | "binary"
+ | "varbinary"
+ | "longvarbinary"
+ | "sqlnull"
+ | "other"
+ | "object"
+ | "distinct"
+ | "struct"
+ | "array"
+ | "blob"
+ | "clob"
+ | "ref"
+db-keys = element db:keys { db-keys-attlist, db-key+ }
+db-keys-attlist = empty
+db-key = element db:key { db-key-attlist, db-key-columns+ }
+db-key-attlist =
+ attribute db:name { \string }?
+ & attribute db:type { "primary" | "unique" | "foreign" }
+ & attribute db:referenced-table-name { \string }?
+ & attribute db:update-rule {
+ "cascade" | "restrict" | "set-null" | "no-action" | "set-default"
+ }?
+ & attribute db:delete-rule {
+ "cascade" | "restrict" | "set-null" | "no-action" | "set-default"
+ }?
+db-key-columns =
+ element db:key-columns { db-key-columns-attlist, db-key-column+ }
+db-key-columns-attlist = empty
+db-key-column = element db:key-column { db-key-column-attlist, empty }
+db-key-column-attlist =
+ attribute db:name { \string }?
+ & attribute db:related-column-name { \string }?
+db-indices = element db:indices { db-indices-attlist, db-index+ }
+db-indices-attlist = empty
+db-index = element db:index { db-index-attlist, db-index-columns+ }
+db-index-attlist =
+ attribute db:name { \string }
+ & attribute db:catalog-name { \string }?
+ & attribute db:is-unique { boolean }?
+ & attribute db:is-clustered { boolean }?
+db-index-columns = element db:index-columns { db-index-column+ }
+db-index-column =
+ element db:index-column { db-index-column-attlist, empty }
+db-index-column-attlist =
+ attribute db:name { \string }
+ & attribute db:is-ascending { boolean }?
+office-forms =
+ element office:forms {
+ office-forms-attlist, (form-form | xforms-model)*
+ }?
+office-forms-attlist =
+ attribute form:automatic-focus { boolean }?
+ & attribute form:apply-design-mode { boolean }?
+form-form =
+ element form:form {
+ common-form-control-attlist,
+ form-form-attlist,
+ form-properties?,
+ office-event-listeners?,
+ (controls | form-form)*,
+ form-connection-resource?
+ }
+form-form-attlist =
+ (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:actuate { "onRequest" }?)?
+ & attribute office:target-frame { targetFrameName }?
+ & attribute form:method { "get" | "post" | \string }?
+ & attribute form:enctype { \string }?
+ & attribute form:allow-deletes { boolean }?
+ & attribute form:allow-inserts { boolean }?
+ & attribute form:allow-updates { boolean }?
+ & attribute form:apply-filter { boolean }?
+ & attribute form:command-type { "table" | "query" | "command" }?
+ & attribute form:command { \string }?
+ & attribute form:datasource { anyIRI | \string }?
+ & attribute form:master-fields { \string }?
+ & attribute form:detail-fields { \string }?
+ & attribute form:escape-processing { boolean }?
+ & attribute form:filter { \string }?
+ & attribute form:ignore-result { boolean }?
+ & attribute form:navigation-mode { navigation }?
+ & attribute form:order { \string }?
+ & attribute form:tab-cycle { tab-cycles }?
+navigation = "none" | "current" | "parent"
+tab-cycles = "records" | "current" | "page"
+form-connection-resource =
+ element form:connection-resource {
+ attribute xlink:href { anyIRI },
+ empty
+ }
+xforms-model = element xforms:model { anyAttListOrElements }
+column-controls =
+ element form:text { form-text-attlist, common-form-control-content }
+ | element form:textarea {
+ form-textarea-attlist, common-form-control-content, text-p*
+ }
+ | element form:formatted-text {
+ form-formatted-text-attlist, common-form-control-content
+ }
+ | element form:number {
+ form-number-attlist,
+ common-numeric-control-attlist,
+ common-form-control-content,
+ common-linked-cell,
+ common-spin-button,
+ common-repeat,
+ common-delay-for-repeat
+ }
+ | element form:date {
+ form-date-attlist,
+ common-numeric-control-attlist,
+ common-form-control-content,
+ common-linked-cell,
+ common-spin-button,
+ common-repeat,
+ common-delay-for-repeat
+ }
+ | element form:time {
+ form-time-attlist,
+ common-numeric-control-attlist,
+ common-form-control-content,
+ common-linked-cell,
+ common-spin-button,
+ common-repeat,
+ common-delay-for-repeat
+ }
+ | element form:combobox {
+ form-combobox-attlist, common-form-control-content, form-item*
+ }
+ | element form:listbox {
+ form-listbox-attlist, common-form-control-content, form-option*
+ }
+ | element form:checkbox {
+ form-checkbox-attlist, common-form-control-content
+ }
+controls =
+ column-controls
+ | element form:password {
+ form-password-attlist, common-form-control-content
+ }
+ | element form:file { form-file-attlist, common-form-control-content }
+ | element form:fixed-text {
+ form-fixed-text-attlist, common-form-control-content
+ }
+ | element form:button {
+ form-button-attlist, common-form-control-content
+ }
+ | element form:image {
+ form-image-attlist, common-form-control-content
+ }
+ | element form:radio {
+ form-radio-attlist, common-form-control-content
+ }
+ | element form:frame {
+ form-frame-attlist, common-form-control-content
+ }
+ | element form:image-frame {
+ form-image-frame-attlist, common-form-control-content
+ }
+ | element form:hidden {
+ form-hidden-attlist, common-form-control-content
+ }
+ | element form:grid {
+ form-grid-attlist, common-form-control-content, form-column*
+ }
+ | element form:value-range {
+ form-value-range-attlist, common-form-control-content
+ }
+ | element form:generic-control {
+ form-generic-control-attlist, common-form-control-content
+ }
+form-text-attlist =
+ form-control-attlist,
+ common-current-value-attlist,
+ common-disabled-attlist,
+ common-maxlength-attlist,
+ common-printable-attlist,
+ common-readonly-attlist,
+ common-tab-attlist,
+ common-title-attlist,
+ common-value-attlist,
+ common-convert-empty-attlist,
+ common-data-field-attlist,
+ common-linked-cell
+form-control-attlist =
+ common-form-control-attlist,
+ common-control-id-attlist,
+ xforms-bind-attlist
+common-form-control-content = form-properties?, office-event-listeners?
+form-textarea-attlist =
+ form-control-attlist,
+ common-current-value-attlist,
+ common-disabled-attlist,
+ common-maxlength-attlist,
+ common-printable-attlist,
+ common-readonly-attlist,
+ common-tab-attlist,
+ common-title-attlist,
+ common-value-attlist,
+ common-convert-empty-attlist,
+ common-data-field-attlist,
+ common-linked-cell
+form-password-attlist =
+ form-control-attlist
+ & common-disabled-attlist
+ & common-maxlength-attlist
+ & common-printable-attlist
+ & common-tab-attlist
+ & common-title-attlist
+ & common-value-attlist
+ & common-convert-empty-attlist
+ & common-linked-cell
+ & attribute form:echo-char { character }?
+form-file-attlist =
+ form-control-attlist,
+ common-current-value-attlist,
+ common-disabled-attlist,
+ common-maxlength-attlist,
+ common-printable-attlist,
+ common-readonly-attlist,
+ common-tab-attlist,
+ common-title-attlist,
+ common-value-attlist,
+ common-linked-cell
+form-formatted-text-attlist =
+ form-control-attlist
+ & common-current-value-attlist
+ & common-disabled-attlist
+ & common-maxlength-attlist
+ & common-printable-attlist
+ & common-readonly-attlist
+ & common-tab-attlist
+ & common-title-attlist
+ & common-value-attlist
+ & common-convert-empty-attlist
+ & common-data-field-attlist
+ & common-linked-cell
+ & common-spin-button
+ & common-repeat
+ & common-delay-for-repeat
+ & attribute form:max-value { \string }?
+ & attribute form:min-value { \string }?
+ & attribute form:validation { boolean }?
+common-numeric-control-attlist =
+ form-control-attlist,
+ common-disabled-attlist,
+ common-maxlength-attlist,
+ common-printable-attlist,
+ common-readonly-attlist,
+ common-tab-attlist,
+ common-title-attlist,
+ common-convert-empty-attlist,
+ common-data-field-attlist
+form-number-attlist =
+ attribute form:value { double }?
+ & attribute form:current-value { double }?
+ & attribute form:min-value { double }?
+ & attribute form:max-value { double }?
+form-date-attlist =
+ attribute form:value { date }?
+ & attribute form:current-value { date }?
+ & attribute form:min-value { date }?
+ & attribute form:max-value { date }?
+form-time-attlist =
+ attribute form:value { time }?
+ & attribute form:current-value { time }?
+ & attribute form:min-value { time }?
+ & attribute form:max-value { time }?
+form-fixed-text-attlist =
+ form-control-attlist
+ & for
+ & common-disabled-attlist
+ & label
+ & common-printable-attlist
+ & common-title-attlist
+ & attribute form:multi-line { boolean }?
+form-combobox-attlist =
+ form-control-attlist
+ & common-current-value-attlist
+ & common-disabled-attlist
+ & dropdown
+ & common-maxlength-attlist
+ & common-printable-attlist
+ & common-readonly-attlist
+ & size
+ & common-tab-attlist
+ & common-title-attlist
+ & common-value-attlist
+ & common-convert-empty-attlist
+ & common-data-field-attlist
+ & list-source
+ & list-source-type
+ & common-linked-cell
+ & common-source-cell-range
+ & attribute form:auto-complete { boolean }?
+form-item = element form:item { form-item-attlist, text }
+form-item-attlist = label
+form-listbox-attlist =
+ form-control-attlist
+ & common-disabled-attlist
+ & dropdown
+ & common-printable-attlist
+ & size
+ & common-tab-attlist
+ & common-title-attlist
+ & bound-column
+ & common-data-field-attlist
+ & list-source
+ & list-source-type
+ & common-linked-cell
+ & list-linkage-type
+ & common-source-cell-range
+ & attribute form:multiple { boolean }?
+ & attribute form:xforms-list-source { \string }?
+list-linkage-type =
+ attribute form:list-linkage-type {
+ "selection" | "selection-indices"
+ }?
+form-option = element form:option { form-option-attlist, text }
+form-option-attlist =
+ current-selected, selected, label, common-value-attlist
+form-button-attlist =
+ form-control-attlist
+ & button-type
+ & common-disabled-attlist
+ & label
+ & image-data
+ & common-printable-attlist
+ & common-tab-attlist
+ & target-frame
+ & target-location
+ & common-title-attlist
+ & common-value-attlist
+ & common-form-relative-image-position-attlist
+ & common-repeat
+ & common-delay-for-repeat
+ & attribute form:default-button { boolean }?
+ & attribute form:toggle { boolean }?
+ & attribute form:focus-on-click { boolean }?
+ & attribute form:xforms-submission { \string }?
+form-image-attlist =
+ form-control-attlist,
+ button-type,
+ common-disabled-attlist,
+ image-data,
+ common-printable-attlist,
+ common-tab-attlist,
+ target-frame,
+ target-location,
+ common-title-attlist,
+ common-value-attlist
+form-checkbox-attlist =
+ form-control-attlist
+ & common-disabled-attlist
+ & label
+ & common-printable-attlist
+ & common-tab-attlist
+ & common-title-attlist
+ & common-value-attlist
+ & common-data-field-attlist
+ & common-form-visual-effect-attlist
+ & common-form-relative-image-position-attlist
+ & common-linked-cell
+ & attribute form:current-state { states }?
+ & attribute form:is-tristate { boolean }?
+ & attribute form:state { states }?
+states = "unchecked" | "checked" | "unknown"
+form-radio-attlist =
+ form-control-attlist,
+ current-selected,
+ common-disabled-attlist,
+ label,
+ common-printable-attlist,
+ selected,
+ common-tab-attlist,
+ common-title-attlist,
+ common-value-attlist,
+ common-data-field-attlist,
+ common-form-visual-effect-attlist,
+ common-form-relative-image-position-attlist,
+ common-linked-cell
+form-frame-attlist =
+ form-control-attlist,
+ common-disabled-attlist,
+ for,
+ label,
+ common-printable-attlist,
+ common-title-attlist
+form-image-frame-attlist =
+ form-control-attlist,
+ common-disabled-attlist,
+ image-data,
+ common-printable-attlist,
+ common-readonly-attlist,
+ common-title-attlist,
+ common-data-field-attlist
+form-hidden-attlist = form-control-attlist, common-value-attlist
+form-grid-attlist =
+ form-control-attlist,
+ common-disabled-attlist,
+ common-printable-attlist,
+ common-tab-attlist,
+ common-title-attlist
+form-column =
+ element form:column { form-column-attlist, column-controls+ }
+form-column-attlist =
+ common-form-control-attlist, label, text-style-name
+text-style-name = attribute form:text-style-name { styleNameRef }?
+form-value-range-attlist =
+ form-control-attlist
+ & common-disabled-attlist
+ & common-printable-attlist
+ & common-tab-attlist
+ & common-title-attlist
+ & common-value-attlist
+ & common-linked-cell
+ & common-repeat
+ & common-delay-for-repeat
+ & attribute form:max-value { integer }?
+ & attribute form:min-value { integer }?
+ & attribute form:step-size { positiveInteger }?
+ & attribute form:page-step-size { positiveInteger }?
+ & attribute form:orientation { "horizontal" | "vertical" }?
+form-generic-control-attlist = form-control-attlist
+common-form-control-attlist =
+ attribute form:name { \string }?
+ & attribute form:control-implementation { namespacedToken }?
+xforms-bind-attlist = attribute xforms:bind { \string }?
+types = "submit" | "reset" | "push" | "url"
+button-type = attribute form:button-type { types }?
+common-control-id-attlist =
+ xml-id,
+ attribute form:id { NCName }?
+current-selected = attribute form:current-selected { boolean }?
+common-value-attlist = attribute form:value { \string }?
+common-current-value-attlist = attribute form:current-value { \string }?
+common-disabled-attlist = attribute form:disabled { boolean }?
+dropdown = attribute form:dropdown { boolean }?
+for = attribute form:for { \string }?
+image-data = attribute form:image-data { anyIRI }?
+label = attribute form:label { \string }?
+common-maxlength-attlist =
+ attribute form:max-length { nonNegativeInteger }?
+common-printable-attlist = attribute form:printable { boolean }?
+common-readonly-attlist = attribute form:readonly { boolean }?
+selected = attribute form:selected { boolean }?
+size = attribute form:size { nonNegativeInteger }?
+common-tab-attlist =
+ attribute form:tab-index { nonNegativeInteger }?
+ & attribute form:tab-stop { boolean }?
+target-frame = attribute office:target-frame { targetFrameName }?
+target-location = attribute xlink:href { anyIRI }?
+common-title-attlist = attribute form:title { \string }?
+common-form-visual-effect-attlist =
+ attribute form:visual-effect { "flat" | "3d" }?
+common-form-relative-image-position-attlist =
+ attribute form:image-position { "center" }?
+ | (attribute form:image-position {
+ "start" | "end" | "top" | "bottom"
+ },
+ attribute form:image-align { "start" | "center" | "end" }?)
+bound-column = attribute form:bound-column { \string }?
+common-convert-empty-attlist =
+ attribute form:convert-empty-to-null { boolean }?
+common-data-field-attlist = attribute form:data-field { \string }?
+list-source = attribute form:list-source { \string }?
+list-source-type =
+ attribute form:list-source-type {
+ "table"
+ | "query"
+ | "sql"
+ | "sql-pass-through"
+ | "value-list"
+ | "table-fields"
+ }?
+common-linked-cell =
+ attribute form:linked-cell { cellAddress | \string }?
+common-source-cell-range =
+ attribute form:source-cell-range { cellRangeAddress | \string }?
+common-spin-button = attribute form:spin-button { boolean }?
+common-repeat = attribute form:repeat { boolean }?
+common-delay-for-repeat = attribute form:delay-for-repeat { duration }?
+form-properties = element form:properties { form-property+ }
+form-property =
+ element form:property {
+ form-property-name, form-property-value-and-type-attlist
+ }
+ | element form:list-property {
+ form-property-name, form-property-type-and-value-list
+ }
+form-property-name = attribute form:property-name { \string }
+form-property-value-and-type-attlist =
+ common-value-and-type-attlist
+ | attribute office:value-type { "void" }
+form-property-type-and-value-list =
+ (attribute office:value-type { "float" },
+ element form:list-value {
+ attribute office:value { double }
+ }*)
+ | (attribute office:value-type { "percentage" },
+ element form:list-value {
+ attribute office:value { double }
+ }*)
+ | (attribute office:value-type { "currency" },
+ element form:list-value {
+ attribute office:value { double },
+ attribute office:currency { \string }?
+ }*)
+ | (attribute office:value-type { "date" },
+ element form:list-value {
+ attribute office:date-value { dateOrDateTime }
+ }*)
+ | (attribute office:value-type { "time" },
+ element form:list-value {
+ attribute office:time-value { duration }
+ }*)
+ | (attribute office:value-type { "boolean" },
+ element form:list-value {
+ attribute office:boolean-value { boolean }
+ }*)
+ | (attribute office:value-type { "string" },
+ element form:list-value {
+ attribute office:string-value { \string }
+ }*)
+ | attribute office:value-type { "void" }
+office-annotation =
+ element office:annotation {
+ office-annotation-attlist,
+ draw-caption-attlist,
+ common-draw-position-attlist,
+ common-draw-size-attlist,
+ common-draw-shape-with-text-and-styles-attlist,
+ dc-creator?,
+ dc-date?,
+ meta-date-string?,
+ (text-p | text-list)*
+ }
+office-annotation-end =
+ element office:annotation-end { office-annotation-end-attlist }
+office-annotation-attlist =
+ attribute office:display { boolean }?
+ & common-office-annotation-name-attlist?
+office-annotation-end-attlist = common-office-annotation-name-attlist
+common-office-annotation-name-attlist =
+ attribute office:name { \string }
+meta-date-string = element meta:date-string { \string }
+common-num-format-prefix-suffix-attlist =
+ attribute style:num-prefix { \string }?,
+ attribute style:num-suffix { \string }?
+common-num-format-attlist =
+ attribute style:num-format { "1" | "i" | "I" | \string | empty }
+ | (attribute style:num-format { "a" | "A" },
+ style-num-letter-sync-attlist)
+ | empty
+style-num-letter-sync-attlist =
+ attribute style:num-letter-sync { boolean }?
+office-change-info =
+ element office:change-info { dc-creator, dc-date, text-p* }
+office-event-listeners =
+ element office:event-listeners {
+ (script-event-listener | presentation-event-listener)*
+ }
+script-event-listener =
+ element script:event-listener { script-event-listener-attlist, empty }
+script-event-listener-attlist =
+ attribute script:event-name { \string }
+ & attribute script:language { \string }
+ & (attribute script:macro-name { \string }
+ | (attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:actuate { "onRequest" }?))
+math-math = element math:math { mathMarkup }
+[
+ dc:description [
+ "To avoid inclusion of the complete MathML schema, anything is allowed within a math:math top-level element"
+ ]
+]
+mathMarkup =
+ (attribute * { text }
+ | text
+ | element * { mathMarkup })*
+text-dde-connection-decl =
+ element text:dde-connection-decl {
+ text-dde-connection-decl-attlist, common-dde-connection-decl-attlist
+ }
+text-dde-connection-decl-attlist = attribute office:name { \string }
+common-dde-connection-decl-attlist =
+ attribute office:dde-application { \string }
+ & attribute office:dde-topic { \string }
+ & attribute office:dde-item { \string }
+ & attribute office:automatic-update { boolean }?
+table-dde-link =
+ element table:dde-link { office-dde-source, table-table }
+office-dde-source =
+ element office:dde-source {
+ office-dde-source-attlist, common-dde-connection-decl-attlist
+ }
+office-dde-source-attlist =
+ attribute office:name { \string }?
+ & attribute office:conversion-mode {
+ "into-default-style-data-style"
+ | "into-english-number"
+ | "keep-text"
+ }?
+animation-element =
+ element anim:animate {
+ common-anim-target-attlist,
+ common-anim-named-target-attlist,
+ common-anim-values-attlist,
+ common-anim-spline-mode-attlist,
+ common-spline-anim-value-attlist,
+ common-timing-attlist,
+ common-anim-add-accum-attlist
+ }
+ | element anim:set {
+ common-anim-target-attlist,
+ common-anim-named-target-attlist,
+ common-anim-set-values-attlist,
+ common-timing-attlist,
+ common-anim-add-accum-attlist
+ }
+ | element anim:animateMotion {
+ anim-animate-motion-attlist,
+ common-anim-target-attlist,
+ common-anim-named-target-attlist,
+ common-anim-add-accum-attlist,
+ common-anim-values-attlist,
+ common-timing-attlist,
+ common-spline-anim-value-attlist
+ }
+ | element anim:animateColor {
+ common-anim-target-attlist,
+ common-anim-named-target-attlist,
+ common-anim-add-accum-attlist,
+ common-anim-values-attlist,
+ common-anim-spline-mode-attlist,
+ common-spline-anim-value-attlist,
+ anim-animate-color-attlist,
+ common-timing-attlist
+ }
+ | element anim:animateTransform {
+ common-anim-target-attlist,
+ common-anim-named-target-attlist,
+ common-anim-add-accum-attlist,
+ common-anim-values-attlist,
+ anim-animate-transform-attlist,
+ common-timing-attlist
+ }
+ | element anim:transitionFilter {
+ common-anim-target-attlist,
+ common-anim-add-accum-attlist,
+ common-anim-values-attlist,
+ common-anim-spline-mode-attlist,
+ anim-transition-filter-attlist,
+ common-timing-attlist
+ }
+ | element anim:par {
+ common-anim-attlist,
+ common-timing-attlist,
+ common-endsync-timing-attlist,
+ animation-element*
+ }
+ | element anim:seq {
+ common-anim-attlist,
+ common-endsync-timing-attlist,
+ common-timing-attlist,
+ animation-element*
+ }
+ | element anim:iterate {
+ common-anim-attlist,
+ anim-iterate-attlist,
+ common-timing-attlist,
+ common-endsync-timing-attlist,
+ animation-element*
+ }
+ | element anim:audio {
+ common-anim-attlist,
+ anim-audio-attlist,
+ common-basic-timing-attlist
+ }
+ | element anim:command {
+ common-anim-attlist,
+ anim-command-attlist,
+ common-begin-end-timing-attlist,
+ common-anim-target-attlist,
+ element anim:param {
+ attribute anim:name { \string },
+ attribute anim:value { \string }
+ }*
+ }
+anim-animate-motion-attlist =
+ attribute svg:path { pathData }?
+ & attribute svg:origin { \string }?
+ & attribute smil:calcMode {
+ "discrete" | "linear" | "paced" | "spline"
+ }?
+anim-animate-color-attlist =
+ attribute anim:color-interpolation { "rgb" | "hsl" }?
+ & attribute anim:color-interpolation-direction {
+ "clockwise" | "counter-clockwise"
+ }?
+anim-animate-transform-attlist =
+ attribute svg:type {
+ "translate" | "scale" | "rotate" | "skewX" | "skewY"
+ }
+anim-transition-filter-attlist =
+ attribute smil:type { \string }
+ & attribute smil:subtype { \string }?
+ & attribute smil:direction { "forward" | "reverse" }?
+ & attribute smil:fadeColor { color }?
+ & attribute smil:mode { "in" | "out" }?
+common-anim-target-attlist =
+ attribute smil:targetElement { IDREF }?
+ & attribute anim:sub-item { \string }?
+common-anim-named-target-attlist =
+ attribute smil:attributeName { \string }
+common-anim-values-attlist =
+ attribute smil:values { \string }?
+ & attribute anim:formula { \string }?
+ & common-anim-set-values-attlist
+ & attribute smil:from { \string }?
+ & attribute smil:by { \string }?
+common-anim-spline-mode-attlist =
+ attribute smil:calcMode {
+ "discrete" | "linear" | "paced" | "spline"
+ }?
+common-spline-anim-value-attlist =
+ attribute smil:keyTimes { \string }?
+ & attribute smil:keySplines { \string }?
+common-anim-add-accum-attlist =
+ attribute smil:accumulate { "none" | "sum" }?
+ & attribute smil:additive { "replace" | "sum" }?
+common-anim-set-values-attlist = attribute smil:to { \string }?
+common-begin-end-timing-attlist =
+ attribute smil:begin { \string }?
+ & attribute smil:end { \string }?
+common-dur-timing-attlist = attribute smil:dur { \string }?
+common-endsync-timing-attlist =
+ attribute smil:endsync { "first" | "last" | "all" | "media" | IDREF }?
+common-repeat-timing-attlist =
+ attribute smil:repeatDur { \string }?,
+ attribute smil:repeatCount { nonNegativeDecimal | "indefinite" }?
+nonNegativeDecimal = xsd:decimal { minInclusive = "0.0" }
+common-fill-timing-attlist =
+ attribute smil:fill {
+ "remove" | "freeze" | "hold" | "auto" | "default" | "transition"
+ }?
+common-fill-default-attlist =
+ attribute smil:fillDefault {
+ "remove" | "freeze" | "hold" | "transition" | "auto" | "inherit"
+ }?
+common-restart-timing-attlist =
+ attribute smil:restart {
+ "never" | "always" | "whenNotActive" | "default"
+ }?
+common-restart-default-attlist =
+ attribute smil:restartDefault {
+ "never" | "always" | "whenNotActive" | "inherit"
+ }?
+common-time-manip-attlist =
+ attribute smil:accelerate { zeroToOneDecimal }?
+ & attribute smil:decelerate { zeroToOneDecimal }?
+ & attribute smil:autoReverse { boolean }?
+zeroToOneDecimal = xsd:decimal { minInclusive = "0" maxInclusive = "1" }
+common-basic-timing-attlist =
+ common-begin-end-timing-attlist,
+ common-dur-timing-attlist,
+ common-repeat-timing-attlist,
+ common-restart-timing-attlist,
+ common-restart-default-attlist,
+ common-fill-timing-attlist,
+ common-fill-default-attlist
+common-timing-attlist =
+ common-basic-timing-attlist, common-time-manip-attlist
+anim-iterate-attlist =
+ common-anim-target-attlist
+ & attribute anim:iterate-type { \string }?
+ & attribute anim:iterate-interval { duration }?
+anim-audio-attlist =
+ attribute xlink:href { anyIRI }?
+ & attribute anim:audio-level { double }?
+anim-command-attlist = attribute anim:command { \string }
+style-style =
+ element style:style {
+ style-style-attlist, style-style-content, style-map*
+ }
+common-in-content-meta-attlist =
+ attribute xhtml:about { URIorSafeCURIE },
+ attribute xhtml:property { CURIEs },
+ common-meta-literal-attlist
+common-meta-literal-attlist =
+ attribute xhtml:datatype { CURIE }?,
+ attribute xhtml:content { \string }?
+xml-id = attribute xml:id { ID }
+style-style-attlist =
+ attribute style:name { styleName }
+ & attribute style:display-name { \string }?
+ & attribute style:parent-style-name { styleNameRef }?
+ & attribute style:next-style-name { styleNameRef }?
+ & attribute style:list-level { positiveInteger | empty }?
+ & attribute style:list-style-name { styleName | empty }?
+ & attribute style:master-page-name { styleNameRef }?
+ & attribute style:auto-update { boolean }?
+ & attribute style:data-style-name { styleNameRef }?
+ & attribute style:percentage-data-style-name { styleNameRef }?
+ & attribute style:class { \string }?
+ & attribute style:default-outline-level { positiveInteger | empty }?
+style-map = element style:map { style-map-attlist, empty }
+style-map-attlist =
+ attribute style:condition { \string }
+ & attribute style:apply-style-name { styleNameRef }
+ & attribute style:base-cell-address { cellAddress }?
+style-default-style =
+ element style:default-style { style-style-content }
+style-page-layout =
+ element style:page-layout {
+ style-page-layout-attlist, style-page-layout-content
+ }
+style-page-layout-content =
+ style-page-layout-properties?,
+ style-header-style?,
+ style-footer-style?
+style-page-layout-attlist =
+ attribute style:name { styleName }
+ & attribute style:page-usage {
+ "all" | "left" | "right" | "mirrored"
+ }?
+style-header-style =
+ element style:header-style { style-header-footer-properties? }
+style-footer-style =
+ element style:footer-style { style-header-footer-properties? }
+style-default-page-layout =
+ element style:default-page-layout { style-page-layout-content }
+style-master-page =
+ element style:master-page {
+ style-master-page-attlist,
+ (style-header, style-header-left?)?,
+ (style-footer, style-footer-left?)?,
+ draw-layer-set?,
+ office-forms?,
+ shape*,
+ animation-element?,
+ presentation-notes?
+ }
+style-master-page-attlist =
+ attribute style:name { styleName }
+ & attribute style:display-name { \string }?
+ & attribute style:page-layout-name { styleNameRef }
+ & attribute draw:style-name { styleNameRef }?
+ & attribute style:next-style-name { styleNameRef }?
+style-header =
+ element style:header {
+ common-style-header-footer-attlist, header-footer-content
+ }
+style-footer =
+ element style:footer {
+ common-style-header-footer-attlist, header-footer-content
+ }
+style-header-left =
+ element style:header-left {
+ common-style-header-footer-attlist, header-footer-content
+ }
+style-footer-left =
+ element style:footer-left {
+ common-style-header-footer-attlist, header-footer-content
+ }
+header-footer-content =
+ (text-tracked-changes,
+ text-decls,
+ (text-h
+ | text-p
+ | text-list
+ | table-table
+ | text-section
+ | text-table-of-content
+ | text-illustration-index
+ | text-table-index
+ | text-object-index
+ | text-user-index
+ | text-alphabetical-index
+ | text-bibliography
+ | text-index-title
+ | change-marks)*)
+ | (style-region-left?, style-region-center?, style-region-right?)
+common-style-header-footer-attlist =
+ attribute style:display { boolean }?
+style-region-left = element style:region-left { region-content }
+style-region-center = element style:region-center { region-content }
+style-region-right = element style:region-right { region-content }
+region-content = text-p*
+presentation-notes =
+ element presentation:notes {
+ common-presentation-header-footer-attlist,
+ presentation-notes-attlist,
+ office-forms,
+ shape*
+ }
+presentation-notes-attlist =
+ attribute style:page-layout-name { styleNameRef }?
+ & attribute draw:style-name { styleNameRef }?
+table-table-template =
+ element table:table-template {
+ table-table-template-attlist,
+ table-first-row?,
+ table-last-row?,
+ table-first-column?,
+ table-last-column?,
+ table-body,
+ table-even-rows?,
+ table-odd-rows?,
+ table-even-columns?,
+ table-odd-columns?,
+ table-background?
+ }
+table-table-template-attlist =
+ attribute table:name { \string }
+ & attribute table:first-row-start-column { rowOrCol }
+ & attribute table:first-row-end-column { rowOrCol }
+ & attribute table:last-row-start-column { rowOrCol }
+ & attribute table:last-row-end-column { rowOrCol }
+rowOrCol = "row" | "column"
+table-first-row =
+ element table:first-row { common-table-template-attlist, empty }
+table-last-row =
+ element table:last-row { common-table-template-attlist, empty }
+table-first-column =
+ element table:first-column { common-table-template-attlist, empty }
+table-last-column =
+ element table:last-column { common-table-template-attlist, empty }
+table-body = element table:body { common-table-template-attlist, empty }
+table-even-rows =
+ element table:even-rows { common-table-template-attlist, empty }
+table-odd-rows =
+ element table:odd-rows { common-table-template-attlist, empty }
+table-even-columns =
+ element table:even-columns { common-table-template-attlist, empty }
+table-odd-columns =
+ element table:odd-columns { common-table-template-attlist, empty }
+common-table-template-attlist =
+ attribute table:style-name { styleNameRef },
+ attribute table:paragraph-style-name { styleNameRef }?
+table-background =
+ element table:background { table-background-attlist, empty }
+table-background-attlist = attribute table:style-name { styleNameRef }
+style-font-face =
+ element style:font-face {
+ style-font-face-attlist, svg-font-face-src?, svg-definition-src?
+ }
+style-font-face-attlist =
+ attribute svg:font-family { \string }?
+ & attribute svg:font-style { fontStyle }?
+ & attribute svg:font-variant { fontVariant }?
+ & attribute svg:font-weight { fontWeight }?
+ & attribute svg:font-stretch {
+ "normal"
+ | "ultra-condensed"
+ | "extra-condensed"
+ | "condensed"
+ | "semi-condensed"
+ | "semi-expanded"
+ | "expanded"
+ | "extra-expanded"
+ | "ultra-expanded"
+ }?
+ & attribute svg:font-size { positiveLength }?
+ & attribute svg:unicode-range { \string }?
+ & attribute svg:units-per-em { integer }?
+ & attribute svg:panose-1 { \string }?
+ & attribute svg:stemv { integer }?
+ & attribute svg:stemh { integer }?
+ & attribute svg:slope { integer }?
+ & attribute svg:cap-height { integer }?
+ & attribute svg:x-height { integer }?
+ & attribute svg:accent-height { integer }?
+ & attribute svg:ascent { integer }?
+ & attribute svg:descent { integer }?
+ & attribute svg:widths { \string }?
+ & attribute svg:bbox { \string }?
+ & attribute svg:ideographic { integer }?
+ & attribute svg:alphabetic { integer }?
+ & attribute svg:mathematical { integer }?
+ & attribute svg:hanging { integer }?
+ & attribute svg:v-ideographic { integer }?
+ & attribute svg:v-alphabetic { integer }?
+ & attribute svg:v-mathematical { integer }?
+ & attribute svg:v-hanging { integer }?
+ & attribute svg:underline-position { integer }?
+ & attribute svg:underline-thickness { integer }?
+ & attribute svg:strikethrough-position { integer }?
+ & attribute svg:strikethrough-thickness { integer }?
+ & attribute svg:overline-position { integer }?
+ & attribute svg:overline-thickness { integer }?
+ & attribute style:name { \string }
+ & attribute style:font-adornments { \string }?
+ & attribute style:font-family-generic { fontFamilyGeneric }?
+ & attribute style:font-pitch { fontPitch }?
+ & attribute style:font-charset { textEncoding }?
+svg-font-face-src =
+ element svg:font-face-src {
+ (svg-font-face-uri | svg-font-face-name)+
+ }
+svg-font-face-uri =
+ element svg:font-face-uri {
+ common-svg-font-face-xlink-attlist, svg-font-face-format*
+ }
+svg-font-face-format =
+ element svg:font-face-format {
+ attribute svg:string { \string }?,
+ empty
+ }
+svg-font-face-name =
+ element svg:font-face-name {
+ attribute svg:name { \string }?,
+ empty
+ }
+svg-definition-src =
+ element svg:definition-src {
+ common-svg-font-face-xlink-attlist, empty
+ }
+common-svg-font-face-xlink-attlist =
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:actuate { "onRequest" }?
+number-number-style =
+ element number:number-style {
+ common-data-style-attlist,
+ style-text-properties?,
+ number-text?,
+ (any-number, number-text?)?,
+ style-map*
+ }
+any-number = number-number | number-scientific-number | number-fraction
+number-number =
+ element number:number {
+ number-number-attlist,
+ common-decimal-places-attlist,
+ common-number-attlist,
+ number-embedded-text*
+ }
+number-number-attlist =
+ attribute number:decimal-replacement { \string }?
+ & attribute number:display-factor { double }?
+number-embedded-text =
+ element number:embedded-text { number-embedded-text-attlist, text }
+number-embedded-text-attlist = attribute number:position { integer }
+number-scientific-number =
+ element number:scientific-number {
+ number-scientific-number-attlist,
+ common-decimal-places-attlist,
+ common-number-attlist,
+ empty
+ }
+number-scientific-number-attlist =
+ attribute number:min-exponent-digits { integer }?
+number-fraction =
+ element number:fraction {
+ number-fraction-attlist, common-number-attlist, empty
+ }
+number-fraction-attlist =
+ attribute number:min-numerator-digits { integer }?
+ & attribute number:min-denominator-digits { integer }?
+ & attribute number:denominator-value { integer }?
+number-currency-style =
+ element number:currency-style {
+ common-data-style-attlist,
+ common-auto-reorder-attlist,
+ style-text-properties?,
+ number-text?,
+ ((number-and-text, currency-symbol-and-text?)
+ | (currency-symbol-and-text, number-and-text?))?,
+ style-map*
+ }
+currency-symbol-and-text = number-currency-symbol, number-text?
+number-and-text = number-number, number-text?
+number-currency-symbol =
+ element number:currency-symbol {
+ number-currency-symbol-attlist, text
+ }
+number-currency-symbol-attlist =
+ attribute number:language { languageCode }?,
+ attribute number:country { countryCode }?,
+ attribute number:script { scriptCode }?,
+ attribute number:rfc-language-tag { language }?
+number-percentage-style =
+ element number:percentage-style {
+ common-data-style-attlist,
+ style-text-properties?,
+ number-text?,
+ number-and-text?,
+ style-map*
+ }
+number-date-style =
+ element number:date-style {
+ common-data-style-attlist,
+ common-auto-reorder-attlist,
+ common-format-source-attlist,
+ style-text-properties?,
+ number-text?,
+ (any-date, number-text?)+,
+ style-map*
+ }
+any-date =
+ number-day
+ | number-month
+ | number-year
+ | number-era
+ | number-day-of-week
+ | number-week-of-year
+ | number-quarter
+ | number-hours
+ | number-am-pm
+ | number-minutes
+ | number-seconds
+number-day =
+ element number:day {
+ number-day-attlist, common-calendar-attlist, empty
+ }
+number-day-attlist = attribute number:style { "short" | "long" }?
+number-month =
+ element number:month {
+ number-month-attlist, common-calendar-attlist, empty
+ }
+number-month-attlist =
+ attribute number:textual { boolean }?
+ & attribute number:possessive-form { boolean }?
+ & attribute number:style { "short" | "long" }?
+number-year =
+ element number:year {
+ number-year-attlist, common-calendar-attlist, empty
+ }
+number-year-attlist = attribute number:style { "short" | "long" }?
+number-era =
+ element number:era {
+ number-era-attlist, common-calendar-attlist, empty
+ }
+number-era-attlist = attribute number:style { "short" | "long" }?
+number-day-of-week =
+ element number:day-of-week {
+ number-day-of-week-attlist, common-calendar-attlist, empty
+ }
+number-day-of-week-attlist =
+ attribute number:style { "short" | "long" }?
+number-week-of-year =
+ element number:week-of-year { common-calendar-attlist, empty }
+number-quarter =
+ element number:quarter {
+ number-quarter-attlist, common-calendar-attlist, empty
+ }
+number-quarter-attlist = attribute number:style { "short" | "long" }?
+number-time-style =
+ element number:time-style {
+ number-time-style-attlist,
+ common-data-style-attlist,
+ common-format-source-attlist,
+ style-text-properties?,
+ number-text?,
+ (any-time, number-text?)+,
+ style-map*
+ }
+any-time = number-hours | number-am-pm | number-minutes | number-seconds
+number-time-style-attlist =
+ attribute number:truncate-on-overflow { boolean }?
+number-hours = element number:hours { number-hours-attlist, empty }
+number-hours-attlist = attribute number:style { "short" | "long" }?
+number-minutes =
+ element number:minutes { number-minutes-attlist, empty }
+number-minutes-attlist = attribute number:style { "short" | "long" }?
+number-seconds =
+ element number:seconds { number-seconds-attlist, empty }
+number-seconds-attlist =
+ attribute number:style { "short" | "long" }?
+ & attribute number:decimal-places { integer }?
+number-am-pm = element number:am-pm { empty }
+number-boolean-style =
+ element number:boolean-style {
+ common-data-style-attlist,
+ style-text-properties?,
+ number-text?,
+ (number-boolean, number-text?)?,
+ style-map*
+ }
+number-boolean = element number:boolean { empty }
+number-text-style =
+ element number:text-style {
+ common-data-style-attlist,
+ style-text-properties?,
+ number-text?,
+ (number-text-content, number-text?)*,
+ style-map*
+ }
+number-text = element number:text { text }
+number-text-content = element number:text-content { empty }
+common-data-style-attlist =
+ attribute style:name { styleName }
+ & attribute style:display-name { \string }?
+ & attribute number:language { languageCode }?
+ & attribute number:country { countryCode }?
+ & attribute number:script { scriptCode }?
+ & attribute number:rfc-language-tag { language }?
+ & attribute number:title { \string }?
+ & attribute style:volatile { boolean }?
+ & attribute number:transliteration-format { \string }?
+ & attribute number:transliteration-language { countryCode }?
+ & attribute number:transliteration-country { countryCode }?
+ & attribute number:transliteration-style {
+ "short" | "medium" | "long"
+ }?
+common-auto-reorder-attlist =
+ attribute number:automatic-order { boolean }?
+common-format-source-attlist =
+ attribute number:format-source { "fixed" | "language" }?
+common-decimal-places-attlist =
+ attribute number:decimal-places { integer }?
+common-number-attlist =
+ attribute number:min-integer-digits { integer }?
+ & attribute number:grouping { boolean }?
+common-calendar-attlist =
+ attribute number:calendar {
+ "gregorian"
+ | "gengou"
+ | "ROC"
+ | "hanja_yoil"
+ | "hanja"
+ | "hijri"
+ | "jewish"
+ | "buddhist"
+ | \string
+ }?
+style-style-content =
+ (attribute style:family { "text" },
+ style-text-properties?)
+ | (attribute style:family { "paragraph" },
+ style-paragraph-properties?,
+ style-text-properties?)
+ | (attribute style:family { "section" },
+ style-section-properties?)
+ | (attribute style:family { "ruby" },
+ style-ruby-properties?)
+ | (attribute style:family { "table" },
+ style-table-properties?)
+ | (attribute style:family { "table-column" },
+ style-table-column-properties?)
+ | (attribute style:family { "table-row" },
+ style-table-row-properties?)
+ | (attribute style:family { "table-cell" },
+ style-table-cell-properties?,
+ style-paragraph-properties?,
+ style-text-properties?)
+ | (attribute style:family { "graphic" | "presentation" },
+ style-graphic-properties?,
+ style-paragraph-properties?,
+ style-text-properties?)
+ | (attribute style:family { "drawing-page" },
+ style-drawing-page-properties?)
+ | (attribute style:family { "chart" },
+ style-chart-properties?,
+ style-graphic-properties?,
+ style-paragraph-properties?,
+ style-text-properties?)
+text-linenumbering-configuration =
+ element text:linenumbering-configuration {
+ text-linenumbering-configuration-attlist,
+ text-linenumbering-separator?
+ }
+text-linenumbering-configuration-attlist =
+ attribute text:number-lines { boolean }?
+ & common-num-format-attlist?
+ & attribute text:style-name { styleNameRef }?
+ & attribute text:increment { nonNegativeInteger }?
+ & attribute text:number-position {
+ "left" | "right" | "inner" | "outer"
+ }?
+ & attribute text:offset { nonNegativeLength }?
+ & attribute text:count-empty-lines { boolean }?
+ & attribute text:count-in-text-boxes { boolean }?
+ & attribute text:restart-on-page { boolean }?
+text-linenumbering-separator =
+ element text:linenumbering-separator {
+ attribute text:increment { nonNegativeInteger }?,
+ text
+ }
+text-notes-configuration =
+ element text:notes-configuration { text-notes-configuration-content }
+text-notes-configuration-content =
+ text-note-class
+ & attribute text:citation-style-name { styleNameRef }?
+ & attribute text:citation-body-style-name { styleNameRef }?
+ & attribute text:default-style-name { styleNameRef }?
+ & attribute text:master-page-name { styleNameRef }?
+ & attribute text:start-value { nonNegativeInteger }?
+ & common-num-format-prefix-suffix-attlist
+ & common-num-format-attlist?
+ & attribute text:start-numbering-at {
+ "document" | "chapter" | "page"
+ }?
+ & attribute text:footnotes-position {
+ "text" | "page" | "section" | "document"
+ }?
+ & element text:note-continuation-notice-forward { text }?
+ & element text:note-continuation-notice-backward { text }?
+text-bibliography-configuration =
+ element text:bibliography-configuration {
+ text-bibliography-configuration-attlist, text-sort-key*
+ }
+text-bibliography-configuration-attlist =
+ attribute text:prefix { \string }?
+ & attribute text:suffix { \string }?
+ & attribute text:numbered-entries { boolean }?
+ & attribute text:sort-by-position { boolean }?
+ & attribute fo:language { languageCode }?
+ & attribute fo:country { countryCode }?
+ & attribute fo:script { scriptCode }?
+ & attribute style:rfc-language-tag { language }?
+ & attribute text:sort-algorithm { \string }?
+text-sort-key = element text:sort-key { text-sort-key-attlist, empty }
+text-sort-key-attlist =
+ attribute text:key {
+ "address"
+ | "annote"
+ | "author"
+ | "bibliography-type"
+ | "booktitle"
+ | "chapter"
+ | "custom1"
+ | "custom2"
+ | "custom3"
+ | "custom4"
+ | "custom5"
+ | "edition"
+ | "editor"
+ | "howpublished"
+ | "identifier"
+ | "institution"
+ | "isbn"
+ | "issn"
+ | "journal"
+ | "month"
+ | "note"
+ | "number"
+ | "organizations"
+ | "pages"
+ | "publisher"
+ | "report-type"
+ | "school"
+ | "series"
+ | "title"
+ | "url"
+ | "volume"
+ | "year"
+ },
+ attribute text:sort-ascending { boolean }?
+text-list-style =
+ element text:list-style {
+ text-list-style-attr, text-list-style-content*
+ }
+text-list-style-attr =
+ attribute style:name { styleName }
+ & attribute style:display-name { \string }?
+ & attribute text:consecutive-numbering { boolean }?
+text-list-style-content =
+ element text:list-level-style-number {
+ text-list-level-style-attr,
+ text-list-level-style-number-attr,
+ style-list-level-properties?,
+ style-text-properties?
+ }
+ | element text:list-level-style-bullet {
+ text-list-level-style-attr,
+ text-list-level-style-bullet-attr,
+ style-list-level-properties?,
+ style-text-properties?
+ }
+ | element text:list-level-style-image {
+ text-list-level-style-attr,
+ text-list-level-style-image-attr,
+ style-list-level-properties?
+ }
+text-list-level-style-number-attr =
+ attribute text:style-name { styleNameRef }?
+ & common-num-format-attlist
+ & common-num-format-prefix-suffix-attlist
+ & attribute text:display-levels { positiveInteger }?
+ & attribute text:start-value { positiveInteger }?
+text-list-level-style-bullet-attr =
+ attribute text:style-name { styleNameRef }?
+ & attribute text:bullet-char { character }
+ & common-num-format-prefix-suffix-attlist
+ & attribute text:bullet-relative-size { percent }?
+text-list-level-style-image-attr =
+ common-draw-data-attlist | office-binary-data
+text-list-level-style-attr = attribute text:level { positiveInteger }
+text-outline-style =
+ element text:outline-style {
+ text-outline-style-attr, text-outline-level-style+
+ }
+text-outline-style-attr = attribute style:name { styleName }
+text-outline-level-style =
+ element text:outline-level-style {
+ text-outline-level-style-attlist,
+ style-list-level-properties?,
+ style-text-properties?
+ }
+text-outline-level-style-attlist =
+ attribute text:level { positiveInteger }
+ & attribute text:style-name { styleNameRef }?
+ & common-num-format-attlist
+ & common-num-format-prefix-suffix-attlist
+ & attribute text:display-levels { positiveInteger }?
+ & attribute text:start-value { positiveInteger }?
+style-graphic-properties =
+ element style:graphic-properties {
+ style-graphic-properties-content-strict
+ }
+style-graphic-properties-content-strict =
+ style-graphic-properties-attlist,
+ style-graphic-fill-properties-attlist,
+ style-graphic-properties-elements
+style-drawing-page-properties =
+ element style:drawing-page-properties {
+ style-drawing-page-properties-content-strict
+ }
+style-drawing-page-properties-content-strict =
+ style-graphic-fill-properties-attlist,
+ style-drawing-page-properties-attlist,
+ style-drawing-page-properties-elements
+draw-gradient =
+ element draw:gradient {
+ common-draw-gradient-attlist, draw-gradient-attlist, empty
+ }
+common-draw-gradient-attlist =
+ attribute draw:name { styleName }?
+ & attribute draw:display-name { \string }?
+ & attribute draw:style { gradient-style }
+ & attribute draw:cx { percent }?
+ & attribute draw:cy { percent }?
+ & attribute draw:angle { angle }?
+ & attribute draw:border { percent }?
+gradient-style =
+ "linear" | "axial" | "radial" | "ellipsoid" | "square" | "rectangular"
+draw-gradient-attlist =
+ attribute draw:start-color { color }?
+ & attribute draw:end-color { color }?
+ & attribute draw:start-intensity { zeroToHundredPercent }?
+ & attribute draw:end-intensity { zeroToHundredPercent }?
+svg-linearGradient =
+ element svg:linearGradient {
+ common-svg-gradient-attlist,
+ attribute svg:x1 { coordinate | percent }?,
+ attribute svg:y1 { coordinate | percent }?,
+ attribute svg:x2 { coordinate | percent }?,
+ attribute svg:y2 { coordinate | percent }?,
+ svg-stop*
+ }
+svg-radialGradient =
+ element svg:radialGradient {
+ common-svg-gradient-attlist,
+ attribute svg:cx { coordinate | percent }?,
+ attribute svg:cy { coordinate | percent }?,
+ attribute svg:r { coordinate | percent }?,
+ attribute svg:fx { coordinate | percent }?,
+ attribute svg:fy { coordinate | percent }?,
+ svg-stop*
+ }
+svg-stop =
+ element svg:stop {
+ attribute svg:offset { double | percent },
+ attribute svg:stop-color { color }?,
+ attribute svg:stop-opacity { double }?
+ }
+common-svg-gradient-attlist =
+ attribute svg:gradientUnits { "objectBoundingBox" }?
+ & attribute svg:gradientTransform { \string }?
+ & attribute svg:spreadMethod { "pad" | "reflect" | "repeat" }?
+ & attribute draw:name { styleName }
+ & attribute draw:display-name { \string }?
+draw-hatch = element draw:hatch { draw-hatch-attlist, empty }
+draw-hatch-attlist =
+ attribute draw:name { styleName }
+ & attribute draw:display-name { \string }?
+ & attribute draw:style { "single" | "double" | "triple" }
+ & attribute draw:color { color }?
+ & attribute draw:distance { length }?
+ & attribute draw:rotation { angle }?
+draw-fill-image =
+ element draw:fill-image {
+ draw-fill-image-attlist,
+ attribute xlink:type { "simple" },
+ attribute xlink:href { anyIRI },
+ attribute xlink:show { "embed" }?,
+ attribute xlink:actuate { "onLoad" }?,
+ empty
+ }
+draw-fill-image-attlist =
+ attribute draw:name { styleName }
+ & attribute draw:display-name { \string }?
+ & attribute svg:width { length }?
+ & attribute svg:height { length }?
+draw-opacity =
+ element draw:opacity {
+ common-draw-gradient-attlist, draw-opacity-attlist, empty
+ }
+draw-opacity-attlist =
+ attribute draw:start { zeroToHundredPercent }?,
+ attribute draw:end { zeroToHundredPercent }?
+draw-marker =
+ element draw:marker {
+ draw-marker-attlist,
+ common-draw-viewbox-attlist,
+ common-draw-path-data-attlist,
+ empty
+ }
+draw-marker-attlist =
+ attribute draw:name { styleName }
+ & attribute draw:display-name { \string }?
+draw-stroke-dash =
+ element draw:stroke-dash { draw-stroke-dash-attlist, empty }
+draw-stroke-dash-attlist =
+ attribute draw:name { styleName }
+ & attribute draw:display-name { \string }?
+ & attribute draw:style { "rect" | "round" }?
+ & attribute draw:dots1 { integer }?
+ & attribute draw:dots1-length { length | percent }?
+ & attribute draw:dots2 { integer }?
+ & attribute draw:dots2-length { length | percent }?
+ & attribute draw:distance { length | percent }?
+style-presentation-page-layout =
+ element style:presentation-page-layout {
+ attribute style:name { styleName },
+ attribute style:display-name { \string }?,
+ presentation-placeholder*
+ }
+presentation-placeholder =
+ element presentation:placeholder {
+ attribute presentation:object { presentation-classes },
+ attribute svg:x { coordinate | percent },
+ attribute svg:y { coordinate | percent },
+ attribute svg:width { length | percent },
+ attribute svg:height { length | percent },
+ empty
+ }
+style-page-layout-properties =
+ element style:page-layout-properties {
+ style-page-layout-properties-content-strict
+ }
+style-page-layout-properties-content-strict =
+ style-page-layout-properties-attlist,
+ style-page-layout-properties-elements
+style-page-layout-properties-attlist =
+ attribute fo:page-width { length }?
+ & attribute fo:page-height { length }?
+ & common-num-format-attlist?
+ & common-num-format-prefix-suffix-attlist
+ & attribute style:paper-tray-name { "default" | \string }?
+ & attribute style:print-orientation { "portrait" | "landscape" }?
+ & common-horizontal-margin-attlist
+ & common-vertical-margin-attlist
+ & common-margin-attlist
+ & common-border-attlist
+ & common-border-line-width-attlist
+ & common-padding-attlist
+ & common-shadow-attlist
+ & common-background-color-attlist
+ & attribute style:register-truth-ref-style-name { styleNameRef }?
+ & attribute style:print {
+ list {
+ ("headers"
+ | "grid"
+ | "annotations"
+ | "objects"
+ | "charts"
+ | "drawings"
+ | "formulas"
+ | "zero-values")*
+ }
+ }?
+ & attribute style:print-page-order { "ttb" | "ltr" }?
+ & attribute style:first-page-number { positiveInteger | "continue" }?
+ & attribute style:scale-to { percent }?
+ & attribute style:scale-to-pages { positiveInteger }?
+ & attribute style:table-centering {
+ "horizontal" | "vertical" | "both" | "none"
+ }?
+ & attribute style:footnote-max-height { length }?
+ & common-writing-mode-attlist
+ & attribute style:layout-grid-mode { "none" | "line" | "both" }?
+ & attribute style:layout-grid-standard-mode { boolean }?
+ & attribute style:layout-grid-base-height { length }?
+ & attribute style:layout-grid-ruby-height { length }?
+ & attribute style:layout-grid-lines { positiveInteger }?
+ & attribute style:layout-grid-base-width { length }?
+ & attribute style:layout-grid-color { color }?
+ & attribute style:layout-grid-ruby-below { boolean }?
+ & attribute style:layout-grid-print { boolean }?
+ & attribute style:layout-grid-display { boolean }?
+ & attribute style:layout-grid-snap-to { boolean }?
+style-page-layout-properties-elements =
+ style-background-image & style-columns & style-footnote-sep
+style-footnote-sep =
+ element style:footnote-sep { style-footnote-sep-attlist, empty }?
+style-footnote-sep-attlist =
+ attribute style:width { length }?,
+ attribute style:rel-width { percent }?,
+ attribute style:color { color }?,
+ attribute style:line-style { lineStyle }?,
+ attribute style:adjustment { "left" | "center" | "right" }?,
+ attribute style:distance-before-sep { length }?,
+ attribute style:distance-after-sep { length }?
+style-header-footer-properties =
+ element style:header-footer-properties {
+ style-header-footer-properties-content-strict
+ }
+style-header-footer-properties-content-strict =
+ style-header-footer-properties-attlist,
+ style-header-footer-properties-elements
+style-header-footer-properties-attlist =
+ attribute svg:height { length }?
+ & attribute fo:min-height { length }?
+ & common-horizontal-margin-attlist
+ & common-vertical-margin-attlist
+ & common-margin-attlist
+ & common-border-attlist
+ & common-border-line-width-attlist
+ & common-padding-attlist
+ & common-background-color-attlist
+ & common-shadow-attlist
+ & attribute style:dynamic-spacing { boolean }?
+style-header-footer-properties-elements = style-background-image
+style-text-properties =
+ element style:text-properties { style-text-properties-content-strict }
+style-text-properties-content-strict =
+ style-text-properties-attlist, style-text-properties-elements
+style-text-properties-elements = empty
+style-text-properties-attlist =
+ attribute fo:font-variant { fontVariant }?
+ & attribute fo:text-transform {
+ "none" | "lowercase" | "uppercase" | "capitalize"
+ }?
+ & attribute fo:color { color }?
+ & attribute style:use-window-font-color { boolean }?
+ & attribute style:text-outline { boolean }?
+ & attribute style:text-line-through-type { lineType }?
+ & attribute style:text-line-through-style { lineStyle }?
+ & attribute style:text-line-through-width { lineWidth }?
+ & attribute style:text-line-through-color { "font-color" | color }?
+ & attribute style:text-line-through-text { \string }?
+ & attribute style:text-line-through-text-style { styleNameRef }?
+ & attribute style:text-position {
+ list { (percent | "super" | "sub"), percent? }
+ }?
+ & attribute style:font-name { \string }?
+ & attribute style:font-name-asian { \string }?
+ & attribute style:font-name-complex { \string }?
+ & attribute fo:font-family { \string }?
+ & attribute style:font-family-asian { \string }?
+ & attribute style:font-family-complex { \string }?
+ & attribute style:font-family-generic { fontFamilyGeneric }?
+ & attribute style:font-family-generic-asian { fontFamilyGeneric }?
+ & attribute style:font-family-generic-complex { fontFamilyGeneric }?
+ & attribute style:font-style-name { \string }?
+ & attribute style:font-style-name-asian { \string }?
+ & attribute style:font-style-name-complex { \string }?
+ & attribute style:font-pitch { fontPitch }?
+ & attribute style:font-pitch-asian { fontPitch }?
+ & attribute style:font-pitch-complex { fontPitch }?
+ & attribute style:font-charset { textEncoding }?
+ & attribute style:font-charset-asian { textEncoding }?
+ & attribute style:font-charset-complex { textEncoding }?
+ & attribute fo:font-size { positiveLength | percent }?
+ & attribute style:font-size-asian { positiveLength | percent }?
+ & attribute style:font-size-complex { positiveLength | percent }?
+ & attribute style:font-size-rel { length }?
+ & attribute style:font-size-rel-asian { length }?
+ & attribute style:font-size-rel-complex { length }?
+ & attribute style:script-type {
+ "latin" | "asian" | "complex" | "ignore"
+ }?
+ & attribute fo:letter-spacing { length | "normal" }?
+ & attribute fo:language { languageCode }?
+ & attribute style:language-asian { languageCode }?
+ & attribute style:language-complex { languageCode }?
+ & attribute fo:country { countryCode }?
+ & attribute style:country-asian { countryCode }?
+ & attribute style:country-complex { countryCode }?
+ & attribute fo:script { scriptCode }?
+ & attribute style:script-asian { scriptCode }?
+ & attribute style:script-complex { scriptCode }?
+ & attribute style:rfc-language-tag { language }?
+ & attribute style:rfc-language-tag-asian { language }?
+ & attribute style:rfc-language-tag-complex { language }?
+ & attribute fo:font-style { fontStyle }?
+ & attribute style:font-style-asian { fontStyle }?
+ & attribute style:font-style-complex { fontStyle }?
+ & attribute style:font-relief { "none" | "embossed" | "engraved" }?
+ & attribute fo:text-shadow { shadowType }?
+ & attribute style:text-underline-type { lineType }?
+ & attribute style:text-underline-style { lineStyle }?
+ & attribute style:text-underline-width { lineWidth }?
+ & attribute style:text-underline-color { "font-color" | color }?
+ & attribute style:text-overline-type { lineType }?
+ & attribute style:text-overline-style { lineStyle }?
+ & attribute style:text-overline-width { lineWidth }?
+ & attribute style:text-overline-color { "font-color" | color }?
+ & attribute style:text-overline-mode { lineMode }?
+ & attribute fo:font-weight { fontWeight }?
+ & attribute style:font-weight-asian { fontWeight }?
+ & attribute style:font-weight-complex { fontWeight }?
+ & attribute style:text-underline-mode { lineMode }?
+ & attribute style:text-line-through-mode { lineMode }?
+ & attribute style:letter-kerning { boolean }?
+ & attribute style:text-blinking { boolean }?
+ & common-background-color-attlist
+ & attribute style:text-combine { "none" | "letters" | "lines" }?
+ & attribute style:text-combine-start-char { character }?
+ & attribute style:text-combine-end-char { character }?
+ & attribute style:text-emphasize {
+ "none"
+ | list {
+ ("none" | "accent" | "dot" | "circle" | "disc"),
+ ("above" | "below")
+ }
+ }?
+ & attribute style:text-scale { percent }?
+ & attribute style:text-rotation-angle { angle }?
+ & attribute style:text-rotation-scale { "fixed" | "line-height" }?
+ & attribute fo:hyphenate { boolean }?
+ & attribute fo:hyphenation-remain-char-count { positiveInteger }?
+ & attribute fo:hyphenation-push-char-count { positiveInteger }?
+ & (attribute text:display { "true" }
+ | attribute text:display { "none" }
+ | (attribute text:display { "condition" },
+ attribute text:condition { "none" })
+ | empty)
+fontVariant = "normal" | "small-caps"
+fontFamilyGeneric =
+ "roman" | "swiss" | "modern" | "decorative" | "script" | "system"
+fontPitch = "fixed" | "variable"
+textEncoding = xsd:string { pattern = "[A-Za-z][A-Za-z0-9._\-]*" }
+fontStyle = "normal" | "italic" | "oblique"
+shadowType = "none" | \string
+lineType = "none" | "single" | "double"
+lineStyle =
+ "none"
+ | "solid"
+ | "dotted"
+ | "dash"
+ | "long-dash"
+ | "dot-dash"
+ | "dot-dot-dash"
+ | "wave"
+lineWidth =
+ "auto"
+ | "normal"
+ | "bold"
+ | "thin"
+ | "medium"
+ | "thick"
+ | positiveInteger
+ | percent
+ | positiveLength
+fontWeight =
+ "normal"
+ | "bold"
+ | "100"
+ | "200"
+ | "300"
+ | "400"
+ | "500"
+ | "600"
+ | "700"
+ | "800"
+ | "900"
+lineMode = "continuous" | "skip-white-space"
+style-paragraph-properties =
+ element style:paragraph-properties {
+ style-paragraph-properties-content-strict
+ }
+style-paragraph-properties-content-strict =
+ style-paragraph-properties-attlist,
+ style-paragraph-properties-elements
+style-paragraph-properties-attlist =
+ attribute fo:line-height { "normal" | nonNegativeLength | percent }?
+ & attribute style:line-height-at-least { nonNegativeLength }?
+ & attribute style:line-spacing { length }?
+ & attribute style:font-independent-line-spacing { boolean }?
+ & common-text-align
+ & attribute fo:text-align-last { "start" | "center" | "justify" }?
+ & attribute style:justify-single-word { boolean }?
+ & attribute fo:keep-together { "auto" | "always" }?
+ & attribute fo:widows { nonNegativeInteger }?
+ & attribute fo:orphans { nonNegativeInteger }?
+ & attribute style:tab-stop-distance { nonNegativeLength }?
+ & attribute fo:hyphenation-keep { "auto" | "page" }?
+ & attribute fo:hyphenation-ladder-count {
+ "no-limit" | positiveInteger
+ }?
+ & attribute style:register-true { boolean }?
+ & common-horizontal-margin-attlist
+ & attribute fo:text-indent { length | percent }?
+ & attribute style:auto-text-indent { boolean }?
+ & common-vertical-margin-attlist
+ & common-margin-attlist
+ & common-break-attlist
+ & common-background-color-attlist
+ & common-border-attlist
+ & common-border-line-width-attlist
+ & attribute style:join-border { boolean }?
+ & common-padding-attlist
+ & common-shadow-attlist
+ & common-keep-with-next-attlist
+ & attribute text:number-lines { boolean }?
+ & attribute text:line-number { nonNegativeInteger }?
+ & attribute style:text-autospace { "none" | "ideograph-alpha" }?
+ & attribute style:punctuation-wrap { "simple" | "hanging" }?
+ & attribute style:line-break { "normal" | "strict" }?
+ & attribute style:vertical-align {
+ "top" | "middle" | "bottom" | "auto" | "baseline"
+ }?
+ & common-writing-mode-attlist
+ & attribute style:writing-mode-automatic { boolean }?
+ & attribute style:snap-to-layout-grid { boolean }?
+ & common-page-number-attlist
+ & common-background-transparency-attlist
+common-text-align =
+ attribute fo:text-align {
+ "start" | "end" | "left" | "right" | "center" | "justify"
+ }?
+style-paragraph-properties-elements =
+ style-tab-stops & style-drop-cap & style-background-image
+style-tab-stops = element style:tab-stops { style-tab-stop* }?
+style-tab-stop =
+ element style:tab-stop { style-tab-stop-attlist, empty }
+style-tab-stop-attlist =
+ attribute style:position { length }
+ & (attribute style:type { "left" | "center" | "right" }?
+ | (attribute style:type { "char" },
+ style-tab-stop-char-attlist))
+ & attribute style:leader-type { lineType }?
+ & attribute style:leader-style { lineStyle }?
+ & attribute style:leader-width { lineWidth }?
+ & attribute style:leader-color { "font-color" | color }?
+ & attribute style:leader-text { character }?
+ & attribute style:leader-text-style { styleNameRef }?
+style-tab-stop-char-attlist = attribute style:char { character }
+style-drop-cap =
+ element style:drop-cap { style-drop-cap-attlist, empty }?
+style-drop-cap-attlist =
+ attribute style:length { "word" | positiveInteger }?
+ & attribute style:lines { positiveInteger }?
+ & attribute style:distance { length }?
+ & attribute style:style-name { styleNameRef }?
+common-horizontal-margin-attlist =
+ attribute fo:margin-left { length | percent }?,
+ attribute fo:margin-right { length | percent }?
+common-vertical-margin-attlist =
+ attribute fo:margin-top { nonNegativeLength | percent }?,
+ attribute fo:margin-bottom { nonNegativeLength | percent }?
+common-margin-attlist =
+ attribute fo:margin { nonNegativeLength | percent }?
+common-break-attlist =
+ attribute fo:break-before { "auto" | "column" | "page" }?,
+ attribute fo:break-after { "auto" | "column" | "page" }?
+common-background-color-attlist =
+ attribute fo:background-color { "transparent" | color }?
+style-background-image =
+ element style:background-image {
+ style-background-image-attlist,
+ (common-draw-data-attlist | office-binary-data | empty)
+ }?
+style-background-image-attlist =
+ attribute style:repeat { "no-repeat" | "repeat" | "stretch" }?
+ & attribute style:position {
+ "left"
+ | "center"
+ | "right"
+ | "top"
+ | "bottom"
+ | list { horiBackPos, vertBackPos }
+ | list { vertBackPos, horiBackPos }
+ }?
+ & attribute style:filter-name { \string }?
+ & attribute draw:opacity { zeroToHundredPercent }?
+horiBackPos = "left" | "center" | "right"
+vertBackPos = "top" | "center" | "bottom"
+common-border-attlist =
+ attribute fo:border { \string }?,
+ attribute fo:border-top { \string }?,
+ attribute fo:border-bottom { \string }?,
+ attribute fo:border-left { \string }?,
+ attribute fo:border-right { \string }?
+common-border-line-width-attlist =
+ attribute style:border-line-width { borderWidths }?,
+ attribute style:border-line-width-top { borderWidths }?,
+ attribute style:border-line-width-bottom { borderWidths }?,
+ attribute style:border-line-width-left { borderWidths }?,
+ attribute style:border-line-width-right { borderWidths }?
+borderWidths = list { positiveLength, positiveLength, positiveLength }
+common-padding-attlist =
+ attribute fo:padding { nonNegativeLength }?,
+ attribute fo:padding-top { nonNegativeLength }?,
+ attribute fo:padding-bottom { nonNegativeLength }?,
+ attribute fo:padding-left { nonNegativeLength }?,
+ attribute fo:padding-right { nonNegativeLength }?
+common-shadow-attlist = attribute style:shadow { shadowType }?
+common-keep-with-next-attlist =
+ attribute fo:keep-with-next { "auto" | "always" }?
+common-writing-mode-attlist =
+ attribute style:writing-mode {
+ "lr-tb" | "rl-tb" | "tb-rl" | "tb-lr" | "lr" | "rl" | "tb" | "page"
+ }?
+common-page-number-attlist =
+ attribute style:page-number { positiveInteger | "auto" }?
+common-background-transparency-attlist =
+ attribute style:background-transparency { zeroToHundredPercent }?
+style-ruby-properties =
+ element style:ruby-properties { style-ruby-properties-content-strict }
+style-ruby-properties-content-strict =
+ style-ruby-properties-attlist, style-ruby-properties-elements
+style-ruby-properties-elements = empty
+style-ruby-properties-attlist =
+ attribute style:ruby-position { "above" | "below" }?
+ & attribute style:ruby-align {
+ "left"
+ | "center"
+ | "right"
+ | "distribute-letter"
+ | "distribute-space"
+ }?
+style-section-properties =
+ element style:section-properties {
+ style-section-properties-content-strict
+ }
+style-section-properties-content-strict =
+ style-section-properties-attlist, style-section-properties-elements
+style-section-properties-attlist =
+ common-background-color-attlist
+ & common-horizontal-margin-attlist
+ & attribute style:protect { boolean }?
+ & common-editable-attlist
+ & attribute text:dont-balance-text-columns { boolean }?
+ & common-writing-mode-attlist
+style-section-properties-elements =
+ style-background-image & style-columns & text-notes-configuration*
+style-columns =
+ element style:columns {
+ style-columns-attlist, style-column-sep?, style-column*
+ }?
+style-columns-attlist =
+ attribute fo:column-count { positiveInteger }
+ & attribute fo:column-gap { length }?
+style-column = element style:column { style-column-attlist }
+style-column-attlist =
+ attribute style:rel-width { relativeLength }
+ & attribute fo:start-indent { length }?
+ & attribute fo:end-indent { length }?
+ & attribute fo:space-before { length }?
+ & attribute fo:space-after { length }?
+style-column-sep = element style:column-sep { style-column-sep-attlist }
+style-column-sep-attlist =
+ attribute style:style {
+ "none" | "solid" | "dotted" | "dashed" | "dot-dashed"
+ }?
+ & attribute style:width { length }
+ & attribute style:height { zeroToHundredPercent }?
+ & attribute style:vertical-align { "top" | "middle" | "bottom" }?
+ & attribute style:color { color }?
+style-table-properties =
+ element style:table-properties {
+ style-table-properties-content-strict
+ }
+style-table-properties-content-strict =
+ style-table-properties-attlist, style-table-properties-elements
+style-table-properties-attlist =
+ attribute style:width { positiveLength }?
+ & attribute style:rel-width { percent }?
+ & attribute table:align { "left" | "center" | "right" | "margins" }?
+ & common-horizontal-margin-attlist
+ & common-vertical-margin-attlist
+ & common-margin-attlist
+ & common-page-number-attlist
+ & common-break-attlist
+ & common-background-color-attlist
+ & common-shadow-attlist
+ & common-keep-with-next-attlist
+ & attribute style:may-break-between-rows { boolean }?
+ & attribute table:border-model { "collapsing" | "separating" }?
+ & common-writing-mode-attlist
+ & attribute table:display { boolean }?
+style-table-properties-elements = style-background-image
+style-table-column-properties =
+ element style:table-column-properties {
+ style-table-column-properties-content-strict
+ }
+style-table-column-properties-content-strict =
+ style-table-column-properties-attlist,
+ style-table-column-properties-elements
+style-table-column-properties-elements = empty
+style-table-column-properties-attlist =
+ attribute style:column-width { positiveLength }?
+ & attribute style:rel-column-width { relativeLength }?
+ & attribute style:use-optimal-column-width { boolean }?
+ & common-break-attlist
+style-table-row-properties =
+ element style:table-row-properties {
+ style-table-row-properties-content-strict
+ }
+style-table-row-properties-content-strict =
+ style-table-row-properties-attlist,
+ style-table-row-properties-elements
+style-table-row-properties-attlist =
+ attribute style:row-height { positiveLength }?
+ & attribute style:min-row-height { nonNegativeLength }?
+ & attribute style:use-optimal-row-height { boolean }?
+ & common-background-color-attlist
+ & common-break-attlist
+ & attribute fo:keep-together { "auto" | "always" }?
+style-table-row-properties-elements = style-background-image
+style-table-cell-properties =
+ element style:table-cell-properties {
+ style-table-cell-properties-content-strict
+ }
+style-table-cell-properties-content-strict =
+ style-table-cell-properties-attlist,
+ style-table-cell-properties-elements
+style-table-cell-properties-attlist =
+ attribute style:vertical-align {
+ "top" | "middle" | "bottom" | "automatic"
+ }?
+ & attribute style:text-align-source { "fix" | "value-type" }?
+ & common-style-direction-attlist
+ & attribute style:glyph-orientation-vertical {
+ "auto" | "0" | "0deg" | "0rad" | "0grad"
+ }?
+ & common-writing-mode-attlist
+ & common-shadow-attlist
+ & common-background-color-attlist
+ & common-border-attlist
+ & attribute style:diagonal-tl-br { \string }?
+ & attribute style:diagonal-tl-br-widths { borderWidths }?
+ & attribute style:diagonal-bl-tr { \string }?
+ & attribute style:diagonal-bl-tr-widths { borderWidths }?
+ & common-border-line-width-attlist
+ & common-padding-attlist
+ & attribute fo:wrap-option { "no-wrap" | "wrap" }?
+ & common-rotation-angle-attlist
+ & attribute style:rotation-align {
+ "none" | "bottom" | "top" | "center"
+ }?
+ & attribute style:cell-protect {
+ "none"
+ | "hidden-and-protected"
+ | list { ("protected" | "formula-hidden")+ }
+ }?
+ & attribute style:print-content { boolean }?
+ & attribute style:decimal-places { nonNegativeInteger }?
+ & attribute style:repeat-content { boolean }?
+ & attribute style:shrink-to-fit { boolean }?
+common-style-direction-attlist =
+ attribute style:direction { "ltr" | "ttb" }?
+style-table-cell-properties-elements = style-background-image
+common-rotation-angle-attlist =
+ attribute style:rotation-angle { angle }?
+style-list-level-properties =
+ element style:list-level-properties {
+ style-list-level-properties-content-strict
+ }
+style-list-level-properties-content-strict =
+ style-list-level-properties-attlist,
+ style-list-level-properties-elements
+style-list-level-properties-attlist =
+ common-text-align
+ & attribute text:space-before { length }?
+ & attribute text:min-label-width { nonNegativeLength }?
+ & attribute text:min-label-distance { nonNegativeLength }?
+ & attribute style:font-name { \string }?
+ & attribute fo:width { positiveLength }?
+ & attribute fo:height { positiveLength }?
+ & common-vertical-rel-attlist
+ & common-vertical-pos-attlist
+ & attribute text:list-level-position-and-space-mode {
+ "label-width-and-position" | "label-alignment"
+ }?
+style-list-level-properties-elements = style-list-level-label-alignment
+style-list-level-label-alignment =
+ element style:list-level-label-alignment {
+ style-list-level-label-alignment-attlist, empty
+ }?
+style-list-level-label-alignment-attlist =
+ attribute text:label-followed-by { "listtab" | "space" | "nothing" }
+ & attribute text:list-tab-stop-position { length }?
+ & attribute fo:text-indent { length }?
+ & attribute fo:margin-left { length }?
+style-graphic-properties-attlist =
+ attribute draw:stroke { "none" | "dash" | "solid" }?
+ & attribute draw:stroke-dash { styleNameRef }?
+ & attribute draw:stroke-dash-names { styleNameRefs }?
+ & attribute svg:stroke-width { length }?
+ & attribute svg:stroke-color { color }?
+ & attribute draw:marker-start { styleNameRef }?
+ & attribute draw:marker-end { styleNameRef }?
+ & attribute draw:marker-start-width { length }?
+ & attribute draw:marker-end-width { length }?
+ & attribute draw:marker-start-center { boolean }?
+ & attribute draw:marker-end-center { boolean }?
+ & attribute svg:stroke-opacity {
+ xsd:double { minInclusive = "0" maxInclusive = "1" }
+ | zeroToHundredPercent
+ }?
+ & attribute draw:stroke-linejoin {
+ "miter" | "round" | "bevel" | "middle" | "none"
+ }?
+ & attribute svg:stroke-linecap { "butt" | "square" | "round" }?
+ & attribute draw:symbol-color { color }?
+ & attribute text:animation {
+ "none" | "scroll" | "alternate" | "slide"
+ }?
+ & attribute text:animation-direction {
+ "left" | "right" | "up" | "down"
+ }?
+ & attribute text:animation-start-inside { boolean }?
+ & attribute text:animation-stop-inside { boolean }?
+ & attribute text:animation-repeat { nonNegativeInteger }?
+ & attribute text:animation-delay { duration }?
+ & attribute text:animation-steps { length }?
+ & attribute draw:auto-grow-width { boolean }?
+ & attribute draw:auto-grow-height { boolean }?
+ & attribute draw:fit-to-size { boolean }?
+ & attribute draw:fit-to-contour { boolean }?
+ & attribute draw:textarea-vertical-align {
+ "top" | "middle" | "bottom" | "justify"
+ }?
+ & attribute draw:textarea-horizontal-align {
+ "left" | "center" | "right" | "justify"
+ }?
+ & attribute fo:wrap-option { "no-wrap" | "wrap" }?
+ & attribute style:shrink-to-fit { boolean }?
+ & attribute draw:color-mode {
+ "greyscale" | "mono" | "watermark" | "standard"
+ }?
+ & attribute draw:color-inversion { boolean }?
+ & attribute draw:luminance { zeroToHundredPercent }?
+ & attribute draw:contrast { percent }?
+ & attribute draw:gamma { percent }?
+ & attribute draw:red { signedZeroToHundredPercent }?
+ & attribute draw:green { signedZeroToHundredPercent }?
+ & attribute draw:blue { signedZeroToHundredPercent }?
+ & attribute draw:image-opacity { zeroToHundredPercent }?
+ & attribute draw:shadow { "visible" | "hidden" }?
+ & attribute draw:shadow-offset-x { length }?
+ & attribute draw:shadow-offset-y { length }?
+ & attribute draw:shadow-color { color }?
+ & attribute draw:shadow-opacity { zeroToHundredPercent }?
+ & attribute draw:start-line-spacing-horizontal { distance }?
+ & attribute draw:start-line-spacing-vertical { distance }?
+ & attribute draw:end-line-spacing-horizontal { distance }?
+ & attribute draw:end-line-spacing-vertical { distance }?
+ & attribute draw:line-distance { distance }?
+ & attribute draw:guide-overhang { length }?
+ & attribute draw:guide-distance { distance }?
+ & attribute draw:start-guide { length }?
+ & attribute draw:end-guide { length }?
+ & attribute draw:placing { "below" | "above" }?
+ & attribute draw:parallel { boolean }?
+ & attribute draw:measure-align {
+ "automatic" | "left-outside" | "inside" | "right-outside"
+ }?
+ & attribute draw:measure-vertical-align {
+ "automatic" | "above" | "below" | "center"
+ }?
+ & attribute draw:unit {
+ "automatic"
+ | "mm"
+ | "cm"
+ | "m"
+ | "km"
+ | "pt"
+ | "pc"
+ | "inch"
+ | "ft"
+ | "mi"
+ }?
+ & attribute draw:show-unit { boolean }?
+ & attribute draw:decimal-places { nonNegativeInteger }?
+ & attribute draw:caption-type {
+ "straight-line" | "angled-line" | "angled-connector-line"
+ }?
+ & attribute draw:caption-angle-type { "fixed" | "free" }?
+ & attribute draw:caption-angle { angle }?
+ & attribute draw:caption-gap { distance }?
+ & attribute draw:caption-escape-direction {
+ "horizontal" | "vertical" | "auto"
+ }?
+ & attribute draw:caption-escape { length | percent }?
+ & attribute draw:caption-line-length { length }?
+ & attribute draw:caption-fit-line-length { boolean }?
+ & attribute dr3d:horizontal-segments { nonNegativeInteger }?
+ & attribute dr3d:vertical-segments { nonNegativeInteger }?
+ & attribute dr3d:edge-rounding { percent }?
+ & attribute dr3d:edge-rounding-mode { "correct" | "attractive" }?
+ & attribute dr3d:back-scale { percent }?
+ & attribute dr3d:depth { length }?
+ & attribute dr3d:backface-culling { "enabled" | "disabled" }?
+ & attribute dr3d:end-angle { angle }?
+ & attribute dr3d:close-front { boolean }?
+ & attribute dr3d:close-back { boolean }?
+ & attribute dr3d:lighting-mode { "standard" | "double-sided" }?
+ & attribute dr3d:normals-kind { "object" | "flat" | "sphere" }?
+ & attribute dr3d:normals-direction { "normal" | "inverse" }?
+ & attribute dr3d:texture-generation-mode-x {
+ "object" | "parallel" | "sphere"
+ }?
+ & attribute dr3d:texture-generation-mode-y {
+ "object" | "parallel" | "sphere"
+ }?
+ & attribute dr3d:texture-kind { "luminance" | "intensity" | "color" }?
+ & attribute dr3d:texture-filter { "enabled" | "disabled" }?
+ & attribute dr3d:texture-mode { "replace" | "modulate" | "blend" }?
+ & attribute dr3d:ambient-color { color }?
+ & attribute dr3d:emissive-color { color }?
+ & attribute dr3d:specular-color { color }?
+ & attribute dr3d:diffuse-color { color }?
+ & attribute dr3d:shininess { percent }?
+ & attribute dr3d:shadow { "visible" | "hidden" }?
+ & common-draw-rel-size-attlist
+ & attribute fo:min-width { length | percent }?
+ & attribute fo:min-height { length | percent }?
+ & attribute fo:max-height { length | percent }?
+ & attribute fo:max-width { length | percent }?
+ & common-horizontal-margin-attlist
+ & common-vertical-margin-attlist
+ & common-margin-attlist
+ & attribute style:print-content { boolean }?
+ & attribute style:protect {
+ "none"
+ | list { ("content" | "position" | "size")+ }
+ }?
+ & attribute style:horizontal-pos {
+ "left"
+ | "center"
+ | "right"
+ | "from-left"
+ | "inside"
+ | "outside"
+ | "from-inside"
+ }?
+ & attribute svg:x { coordinate }?
+ & attribute style:horizontal-rel {
+ "page"
+ | "page-content"
+ | "page-start-margin"
+ | "page-end-margin"
+ | "frame"
+ | "frame-content"
+ | "frame-start-margin"
+ | "frame-end-margin"
+ | "paragraph"
+ | "paragraph-content"
+ | "paragraph-start-margin"
+ | "paragraph-end-margin"
+ | "char"
+ }?
+ & common-vertical-pos-attlist
+ & common-vertical-rel-attlist
+ & common-text-anchor-attlist
+ & common-border-attlist
+ & common-border-line-width-attlist
+ & common-padding-attlist
+ & common-shadow-attlist
+ & common-background-color-attlist
+ & common-background-transparency-attlist
+ & common-editable-attlist
+ & attribute style:wrap {
+ "none"
+ | "left"
+ | "right"
+ | "parallel"
+ | "dynamic"
+ | "run-through"
+ | "biggest"
+ }?
+ & attribute style:wrap-dynamic-threshold { nonNegativeLength }?
+ & attribute style:number-wrapped-paragraphs {
+ "no-limit" | positiveInteger
+ }?
+ & attribute style:wrap-contour { boolean }?
+ & attribute style:wrap-contour-mode { "full" | "outside" }?
+ & attribute style:run-through { "foreground" | "background" }?
+ & attribute style:flow-with-text { boolean }?
+ & attribute style:overflow-behavior {
+ "clip" | "auto-create-new-frame"
+ }?
+ & attribute style:mirror {
+ "none"
+ | "vertical"
+ | horizontal-mirror
+ | list { "vertical", horizontal-mirror }
+ | list { horizontal-mirror, "vertical" }
+ }?
+ & attribute fo:clip { "auto" | clipShape }?
+ & attribute draw:wrap-influence-on-position {
+ "iterative" | "once-concurrent" | "once-successive"
+ }?
+ & common-writing-mode-attlist
+ & attribute draw:frame-display-scrollbar { boolean }?
+ & attribute draw:frame-display-border { boolean }?
+ & attribute draw:frame-margin-horizontal { nonNegativePixelLength }?
+ & attribute draw:frame-margin-vertical { nonNegativePixelLength }?
+ & attribute draw:visible-area-left { nonNegativeLength }?
+ & attribute draw:visible-area-top { nonNegativeLength }?
+ & attribute draw:visible-area-width { positiveLength }?
+ & attribute draw:visible-area-height { positiveLength }?
+ & attribute draw:draw-aspect {
+ "content" | "thumbnail" | "icon" | "print-view"
+ }?
+ & attribute draw:ole-draw-aspect { nonNegativeInteger }?
+style-graphic-fill-properties-attlist =
+ attribute draw:fill {
+ "none" | "solid" | "bitmap" | "gradient" | "hatch"
+ }?
+ & attribute draw:fill-color { color }?
+ & attribute draw:secondary-fill-color { color }?
+ & attribute draw:fill-gradient-name { styleNameRef }?
+ & attribute draw:gradient-step-count { nonNegativeInteger }?
+ & attribute draw:fill-hatch-name { styleNameRef }?
+ & attribute draw:fill-hatch-solid { boolean }?
+ & attribute draw:fill-image-name { styleNameRef }?
+ & attribute style:repeat { "no-repeat" | "repeat" | "stretch" }?
+ & attribute draw:fill-image-width { length | percent }?
+ & attribute draw:fill-image-height { length | percent }?
+ & attribute draw:fill-image-ref-point-x { percent }?
+ & attribute draw:fill-image-ref-point-y { percent }?
+ & attribute draw:fill-image-ref-point {
+ "top-left"
+ | "top"
+ | "top-right"
+ | "left"
+ | "center"
+ | "right"
+ | "bottom-left"
+ | "bottom"
+ | "bottom-right"
+ }?
+ & attribute draw:tile-repeat-offset {
+ list { zeroToHundredPercent, ("horizontal" | "vertical") }
+ }?
+ & attribute draw:opacity { zeroToHundredPercent }?
+ & attribute draw:opacity-name { styleNameRef }?
+ & attribute svg:fill-rule { "nonzero" | "evenodd" }?
+style-graphic-properties-elements =
+ text-list-style? & style-background-image & style-columns
+common-vertical-pos-attlist =
+ attribute style:vertical-pos {
+ "top" | "middle" | "bottom" | "from-top" | "below"
+ }?,
+ attribute svg:y { coordinate }?
+common-vertical-rel-attlist =
+ attribute style:vertical-rel {
+ "page"
+ | "page-content"
+ | "frame"
+ | "frame-content"
+ | "paragraph"
+ | "paragraph-content"
+ | "char"
+ | "line"
+ | "baseline"
+ | "text"
+ }?
+common-editable-attlist = attribute style:editable { boolean }?
+horizontal-mirror =
+ "horizontal" | "horizontal-on-odd" | "horizontal-on-even"
+clipShape =
+ xsd:string {
+ pattern =
+ "rect\([ ]*((-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc)))|(auto))([ ]*,[ ]*((-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc))))|(auto)){3}[ ]*\)"
+ }
+nonNegativePixelLength =
+ xsd:string { pattern = "([0-9]+(\.[0-9]*)?|\.[0-9]+)(px)" }
+style-chart-properties =
+ element style:chart-properties {
+ style-chart-properties-content-strict
+ }
+style-chart-properties-content-strict =
+ style-chart-properties-attlist, style-chart-properties-elements
+style-chart-properties-elements = empty
+style-chart-properties-attlist =
+ attribute chart:scale-text { boolean }?
+ & attribute chart:three-dimensional { boolean }?
+ & attribute chart:deep { boolean }?
+ & attribute chart:right-angled-axes { boolean }?
+ & (attribute chart:symbol-type { "none" }
+ | attribute chart:symbol-type { "automatic" }
+ | (attribute chart:symbol-type { "named-symbol" },
+ attribute chart:symbol-name {
+ "square"
+ | "diamond"
+ | "arrow-down"
+ | "arrow-up"
+ | "arrow-right"
+ | "arrow-left"
+ | "bow-tie"
+ | "hourglass"
+ | "circle"
+ | "star"
+ | "x"
+ | "plus"
+ | "asterisk"
+ | "horizontal-bar"
+ | "vertical-bar"
+ })
+ | (attribute chart:symbol-type { "image" },
+ element chart:symbol-image {
+ attribute xlink:href { anyIRI }
+ })
+ | empty)
+ & attribute chart:symbol-width { nonNegativeLength }?
+ & attribute chart:symbol-height { nonNegativeLength }?
+ & attribute chart:sort-by-x-values { boolean }?
+ & attribute chart:vertical { boolean }?
+ & attribute chart:connect-bars { boolean }?
+ & attribute chart:gap-width { integer }?
+ & attribute chart:overlap { integer }?
+ & attribute chart:group-bars-per-axis { boolean }?
+ & attribute chart:japanese-candle-stick { boolean }?
+ & attribute chart:interpolation {
+ "none" | "cubic-spline" | "b-spline"
+ }?
+ & attribute chart:spline-order { positiveInteger }?
+ & attribute chart:spline-resolution { positiveInteger }?
+ & attribute chart:pie-offset { nonNegativeInteger }?
+ & attribute chart:angle-offset { angle }?
+ & attribute chart:hole-size { percent }?
+ & attribute chart:lines { boolean }?
+ & attribute chart:solid-type {
+ "cuboid" | "cylinder" | "cone" | "pyramid"
+ }?
+ & attribute chart:stacked { boolean }?
+ & attribute chart:percentage { boolean }?
+ & attribute chart:treat-empty-cells {
+ "use-zero" | "leave-gap" | "ignore"
+ }?
+ & attribute chart:link-data-style-to-source { boolean }?
+ & attribute chart:logarithmic { boolean }?
+ & attribute chart:maximum { double }?
+ & attribute chart:minimum { double }?
+ & attribute chart:origin { double }?
+ & attribute chart:interval-major { double }?
+ & attribute chart:interval-minor-divisor { positiveInteger }?
+ & attribute chart:tick-marks-major-inner { boolean }?
+ & attribute chart:tick-marks-major-outer { boolean }?
+ & attribute chart:tick-marks-minor-inner { boolean }?
+ & attribute chart:tick-marks-minor-outer { boolean }?
+ & attribute chart:reverse-direction { boolean }?
+ & attribute chart:display-label { boolean }?
+ & attribute chart:text-overlap { boolean }?
+ & attribute text:line-break { boolean }?
+ & attribute chart:label-arrangement {
+ "side-by-side" | "stagger-even" | "stagger-odd"
+ }?
+ & common-style-direction-attlist
+ & common-rotation-angle-attlist
+ & attribute chart:data-label-number {
+ "none" | "value" | "percentage" | "value-and-percentage"
+ }?
+ & attribute chart:data-label-text { boolean }?
+ & attribute chart:data-label-symbol { boolean }?
+ & element chart:label-separator { text-p }?
+ & attribute chart:label-position { labelPositions }?
+ & attribute chart:label-position-negative { labelPositions }?
+ & attribute chart:visible { boolean }?
+ & attribute chart:auto-position { boolean }?
+ & attribute chart:auto-size { boolean }?
+ & attribute chart:mean-value { boolean }?
+ & attribute chart:error-category {
+ "none"
+ | "variance"
+ | "standard-deviation"
+ | "percentage"
+ | "error-margin"
+ | "constant"
+ | "standard-error"
+ | "cell-range"
+ }?
+ & attribute chart:error-percentage { double }?
+ & attribute chart:error-margin { double }?
+ & attribute chart:error-lower-limit { double }?
+ & attribute chart:error-upper-limit { double }?
+ & attribute chart:error-upper-indicator { boolean }?
+ & attribute chart:error-lower-indicator { boolean }?
+ & attribute chart:error-lower-range { cellRangeAddressList }?
+ & attribute chart:error-upper-range { cellRangeAddressList }?
+ & attribute chart:series-source { "columns" | "rows" }?
+ & attribute chart:regression-type {
+ "none" | "linear" | "logarithmic" | "exponential" | "power"
+ }?
+ & attribute chart:axis-position { "start" | "end" | double }?
+ & attribute chart:axis-label-position {
+ "near-axis"
+ | "near-axis-other-side"
+ | "outside-start"
+ | "outside-end"
+ }?
+ & attribute chart:tick-mark-position {
+ "at-labels" | "at-axis" | "at-labels-and-axis"
+ }?
+ & attribute chart:include-hidden-cells { boolean }?
+labelPositions =
+ "avoid-overlap"
+ | "center"
+ | "top"
+ | "top-right"
+ | "right"
+ | "bottom-right"
+ | "bottom"
+ | "bottom-left"
+ | "left"
+ | "top-left"
+ | "inside"
+ | "outside"
+ | "near-origin"
+style-drawing-page-properties-attlist =
+ attribute presentation:transition-type {
+ "manual" | "automatic" | "semi-automatic"
+ }?
+ & attribute presentation:transition-style {
+ "none"
+ | "fade-from-left"
+ | "fade-from-top"
+ | "fade-from-right"
+ | "fade-from-bottom"
+ | "fade-from-upperleft"
+ | "fade-from-upperright"
+ | "fade-from-lowerleft"
+ | "fade-from-lowerright"
+ | "move-from-left"
+ | "move-from-top"
+ | "move-from-right"
+ | "move-from-bottom"
+ | "move-from-upperleft"
+ | "move-from-upperright"
+ | "move-from-lowerleft"
+ | "move-from-lowerright"
+ | "uncover-to-left"
+ | "uncover-to-top"
+ | "uncover-to-right"
+ | "uncover-to-bottom"
+ | "uncover-to-upperleft"
+ | "uncover-to-upperright"
+ | "uncover-to-lowerleft"
+ | "uncover-to-lowerright"
+ | "fade-to-center"
+ | "fade-from-center"
+ | "vertical-stripes"
+ | "horizontal-stripes"
+ | "clockwise"
+ | "counterclockwise"
+ | "open-vertical"
+ | "open-horizontal"
+ | "close-vertical"
+ | "close-horizontal"
+ | "wavyline-from-left"
+ | "wavyline-from-top"
+ | "wavyline-from-right"
+ | "wavyline-from-bottom"
+ | "spiralin-left"
+ | "spiralin-right"
+ | "spiralout-left"
+ | "spiralout-right"
+ | "roll-from-top"
+ | "roll-from-left"
+ | "roll-from-right"
+ | "roll-from-bottom"
+ | "stretch-from-left"
+ | "stretch-from-top"
+ | "stretch-from-right"
+ | "stretch-from-bottom"
+ | "vertical-lines"
+ | "horizontal-lines"
+ | "dissolve"
+ | "random"
+ | "vertical-checkerboard"
+ | "horizontal-checkerboard"
+ | "interlocking-horizontal-left"
+ | "interlocking-horizontal-right"
+ | "interlocking-vertical-top"
+ | "interlocking-vertical-bottom"
+ | "fly-away"
+ | "open"
+ | "close"
+ | "melt"
+ }?
+ & attribute presentation:transition-speed { presentationSpeeds }?
+ & attribute smil:type { \string }?
+ & attribute smil:subtype { \string }?
+ & attribute smil:direction { "forward" | "reverse" }?
+ & attribute smil:fadeColor { color }?
+ & attribute presentation:duration { duration }?
+ & attribute presentation:visibility { "visible" | "hidden" }?
+ & attribute draw:background-size { "full" | "border" }?
+ & attribute presentation:background-objects-visible { boolean }?
+ & attribute presentation:background-visible { boolean }?
+ & attribute presentation:display-header { boolean }?
+ & attribute presentation:display-footer { boolean }?
+ & attribute presentation:display-page-number { boolean }?
+ & attribute presentation:display-date-time { boolean }?
+style-drawing-page-properties-elements = presentation-sound?
+\string = xsd:string
+date = xsd:date
+time = xsd:time
+dateTime = xsd:dateTime
+duration = xsd:duration
+integer = xsd:integer
+nonNegativeInteger = xsd:nonNegativeInteger
+positiveInteger = xsd:positiveInteger
+double = xsd:double
+anyURI = xsd:anyURI
+base64Binary = xsd:base64Binary
+ID = xsd:ID
+IDREF = xsd:IDREF
+IDREFS = xsd:IDREFS
+NCName = xsd:NCName
+boolean = "true" | "false"
+dateOrDateTime = xsd:date | xsd:dateTime
+timeOrDateTime = xsd:time | xsd:dateTime
+language = xsd:language
+countryCode = xsd:token { pattern = "[A-Za-z0-9]{1,8}" }
+languageCode = xsd:token { pattern = "[A-Za-z]{1,8}" }
+scriptCode = xsd:token { pattern = "[A-Za-z0-9]{1,8}" }
+character = xsd:string { length = "1" }
+length =
+ xsd:string {
+ pattern =
+ "-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc)|(px))"
+ }
+nonNegativeLength =
+ xsd:string {
+ pattern =
+ "([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc)|(px))"
+ }
+positiveLength =
+ xsd:string {
+ pattern =
+ "([0-9]*[1-9][0-9]*(\.[0-9]*)?|0+\.[0-9]*[1-9][0-9]*|\.[0-9]*[1-9][0-9]*)((cm)|(mm)|(in)|(pt)|(pc)|(px))"
+ }
+percent = xsd:string { pattern = "-?([0-9]+(\.[0-9]*)?|\.[0-9]+)%" }
+zeroToHundredPercent =
+ xsd:string {
+ pattern = "([0-9]?[0-9](\.[0-9]*)?|100(\.0*)?|\.[0-9]+)%"
+ }
+signedZeroToHundredPercent =
+ xsd:string {
+ pattern = "-?([0-9]?[0-9](\.[0-9]*)?|100(\.0*)?|\.[0-9]+)%"
+ }
+relativeLength = xsd:string { pattern = "[0-9]+\*" }
+coordinate = length
+distance = length
+color = xsd:string { pattern = "#[0-9a-fA-F]{6}" }
+angle = xsd:string
+CURIE =
+ xsd:string { pattern = "(([\i-[:]][\c-[:]]*)?:)?.+" minLength = "1" }
+CURIEs = list { CURIE+ }
+SafeCURIE =
+ xsd:string {
+ pattern = "\[(([\i-[:]][\c-[:]]*)?:)?.+\]"
+ minLength = "3"
+ }
+URIorSafeCURIE = anyURI | SafeCURIE
+styleName = xsd:NCName
+styleNameRef = xsd:NCName | empty
+styleNameRefs = list { xsd:NCName* }
+variableName = xsd:string
+targetFrameName = "_self" | "_blank" | "_parent" | "_top" | \string
+valueType =
+ "float"
+ | "time"
+ | "date"
+ | "percentage"
+ | "currency"
+ | "boolean"
+ | "string"
+points =
+ xsd:string { pattern = "-?[0-9]+,-?[0-9]+([ ]+-?[0-9]+,-?[0-9]+)*" }
+pathData = xsd:string
+vector3D =
+ xsd:string {
+ pattern =
+ "\([ ]*-?([0-9]+(\.[0-9]*)?|\.[0-9]+)([ ]+-?([0-9]+(\.[0-9]*)?|\.[0-9]+)){2}[ ]*\)"
+ }
+namespacedToken = xsd:QName { pattern = "[^:]+:[^:]+" }
+anyIRI =
+ xsd:anyURI
+ >> dc:description [
+ "An IRI-reference as defined in [RFC3987]. See ODF 1.2 Part 1 section 18.3."
+ ]
+anyAttListOrElements =
+ attribute * { text }*,
+ anyElements
+anyElements =
+ element * {
+ mixed { anyAttListOrElements }
+ }*
diff --git a/etc/schema/schemas.xml b/etc/schema/schemas.xml
new file mode 100644
index 0000000..f1e0ed7
--- /dev/null
+++ b/etc/schema/schemas.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<locatingRules xmlns="http://thaiopensource.com/ns/locating-rules/1.0">
+ <documentElement prefix="office" typeId="OpenDocument"/>
+ <documentElement prefix="manifest" localName="manifest" typeId="OpenDocument Manifest"/>
+ <typeId id="OpenDocument" uri="od-schema-v1.2-os.rnc"/>
+ <typeId id="OpenDocument Manifest" uri="od-manifest-schema-v1.2-os.rnc"/>
+</locatingRules>
diff --git a/etc/styles/OrgOdtContentTemplate.xml b/etc/styles/OrgOdtContentTemplate.xml
new file mode 100644
index 0000000..d0c98a3
--- /dev/null
+++ b/etc/styles/OrgOdtContentTemplate.xml
@@ -0,0 +1,275 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- See etc/org/README for copyright information -->
+<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+ xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
+ xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
+ xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"
+ xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
+ xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0"
+ xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0"
+ xmlns:math="http://www.w3.org/1998/Math/MathML"
+ xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0"
+ xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0"
+ xmlns:ooo="http://openoffice.org/2004/office"
+ xmlns:ooow="http://openoffice.org/2004/writer"
+ xmlns:oooc="http://openoffice.org/2004/calc"
+ xmlns:dom="http://www.w3.org/2001/xml-events"
+ xmlns:xforms="http://www.w3.org/2002/xforms"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:rpt="http://openoffice.org/2005/report"
+ xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2"
+ xmlns:xodt="http://www.w3.org/1999/xodt"
+ xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" office:version="1.2">
+ <!-- scripts -->
+ <office:scripts/>
+
+ <!-- font face declarations -->
+ <office:font-face-decls>
+ <style:font-face style:name="Tahoma1" svg:font-family="Tahoma"/>
+ <style:font-face style:name="courier" svg:font-family="courier, monospace"/>
+ <style:font-face style:name="Arial Unicode MS" svg:font-family="&apos;Arial Unicode MS&apos;" style:font-pitch="variable"/>
+ <style:font-face style:name="HG Mincho Light J" svg:font-family="&apos;HG Mincho Light J&apos;" style:font-pitch="variable"/>
+ <style:font-face style:name="Thorndale" svg:font-family="Thorndale" style:font-family-generic="roman" style:font-pitch="variable"/>
+ <style:font-face style:name="Times New Roman" svg:font-family="&apos;Times New Roman&apos;" style:font-family-generic="roman" style:font-pitch="variable"/>
+ <style:font-face style:name="Albany" svg:font-family="Albany" style:font-family-generic="swiss" style:font-pitch="variable"/>
+ <style:font-face style:name="SimSun" svg:font-family="SimSun" style:font-family-generic="system" style:font-pitch="variable"/>
+ <style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable"/>
+ </office:font-face-decls>
+
+ <!-- automatic styles -->
+ <office:automatic-styles>
+
+ <!-- Section styles -->
+
+ <!-- Section styles for Table Of Contents and Other Indices -->
+ <style:style style:name="OrgIndexSection" style:family="section">
+ <style:section-properties fo:background-color="#c0c0c0" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ <style:background-image/>
+ </style:section-properties>
+ </style:style>
+
+ <!-- Indented sections, used as container for tables that occur
+ within list items -->
+ <style:style style:name="OrgIndentedSection-Level-1" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="1.281cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-2" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="1.905cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-3" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="2.54cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-4" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="3.175cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-5" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="3.81cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-6" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="4.445cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-7" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="5.08cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-8" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="5.715cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-9" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="6.35cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+ <style:style style:name="OrgIndentedSection-Level-10" style:family="section">
+ <style:section-properties text:dont-balance-text-columns="false" fo:margin-left="6.985cm" fo:margin-right="0cm" style:editable="false">
+ <style:columns fo:column-count="1" fo:column-gap="0cm"/>
+ </style:section-properties>
+ </style:style>
+
+ <!-- Table styles -->
+ <style:style style:name="OrgTable" style:family="table">
+ <style:table-properties style:rel-width="96%" fo:margin-top="0cm" fo:margin-bottom="0.20cm" table:align="center"/>
+ </style:style>
+
+ <style:style style:name="OrgTableColumn" style:family="table-column">
+ <style:table-column-properties style:rel-column-width="1*"/>
+ </style:style>
+
+ <style:style style:name="OrgTblCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellL" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="0.002cm solid #000000" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="none" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellLR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellT" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="none" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTL" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="none" fo:border-left="0.002cm solid #000000" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="none" fo:border-left="none" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTLR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="none" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellB" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="0.002cm solid #000000" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellBL" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="0.002cm solid #000000" fo:border-left="0.002cm solid #000000" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellBR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="0.002cm solid #000000" fo:border-left="none" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellBLR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="0.002cm solid #000000" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTB" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTBL" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000" fo:border-left="0.002cm solid #000000" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTBR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000" fo:border-left="none" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+ <style:style style:name="OrgTblCellTBLR" style:family="table-cell" style:parent-style-name="OrgTblCell">
+ <style:table-cell-properties fo:padding="0.159cm" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000"/>
+ </style:style>
+
+ <!-- BEGIN: Table styles for numbered equations -->
+ <style:style style:name="OrgEquation" style:family="table">
+ <style:table-properties style:rel-width="100%" fo:margin-top="0cm" fo:margin-bottom="0.20cm" table:align="center"/>
+ </style:style>
+ <style:style style:name="OrgEquationTableColumn" style:family="table-column">
+ <style:table-column-properties style:rel-column-width="1*"/>
+ </style:style>
+ <style:style style:name="OrgFirstEquationFirstColumnTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="middle" fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgEquationLastColumnTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="middle" fo:padding="0.159cm" fo:border-top="none" fo:border-bottom="none" fo:border-left="none" fo:border-right="none"/>
+ </style:style>
+ <style:style style:name="OrgEquationFirstColumnTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgEquationLastColumnTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="end" style:justify-single-word="false"/>
+ </style:style>
+ <!-- END: Table styles for numbered equations -->
+
+ <!-- BEGIN: Custom Table Template -->
+ <style:style style:name="Custom" style:family="table">
+ <style:table-properties style:rel-width="80%" table:align="center"/>
+ </style:style>
+
+ <style:style style:name="CustomColumn" style:family="table-column">
+ <style:table-column-properties style:rel-column-width="1*"/>
+ </style:style>
+
+ <!-- Table Paragraph Styles -->
+ <style:style style:name="CustomTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="start" style:justify-single-word="false"/>
+ <style:text-properties fo:color="#000000" style:text-outline="false" style:text-line-through-style="none" style:font-name="Times New Roman" fo:font-size="12pt" fo:font-style="normal" fo:text-shadow="none" style:text-underline-style="none" fo:font-weight="normal" style:font-size-asian="12pt" style:font-style-asian="normal" style:font-weight-asian="normal" style:font-size-complex="12pt" style:font-style-complex="normal" style:font-weight-complex="normal" style:text-overline-style="none" style:text-overline-color="font-color"/>
+ </style:style>
+
+ <style:style style:name="CustomLastRowTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="start" style:justify-single-word="false"/>
+ <style:text-properties fo:color="#000000" style:text-outline="false" style:text-line-through-style="none" style:font-name="Times New Roman" fo:font-size="12pt" fo:font-style="normal" fo:text-shadow="none" style:text-underline-style="none" fo:font-weight="normal" style:font-size-asian="12pt" style:font-style-asian="normal" style:font-weight-asian="normal" style:font-size-complex="12pt" style:font-style-complex="normal" style:font-weight-complex="normal" style:text-overline-style="none" style:text-overline-color="font-color"/>
+ </style:style>
+
+ <style:style style:name="CustomLastColumnTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="start" style:justify-single-word="false"/>
+ <style:text-properties fo:color="#000000" style:text-outline="false" style:text-line-through-style="none" style:font-name="Times New Roman" fo:font-size="12pt" fo:font-style="normal" fo:text-shadow="none" style:text-underline-style="none" fo:font-weight="normal" style:font-size-asian="12pt" style:font-style-asian="normal" style:font-weight-asian="normal" style:font-size-complex="12pt" style:font-style-complex="normal" style:font-weight-complex="normal" style:text-overline-style="none" style:text-overline-color="font-color"/>
+ </style:style>
+
+ <style:style style:name="CustomFirstRowTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="start" style:justify-single-word="false"/>
+ <style:text-properties fo:color="#ffffff" style:text-outline="false" style:text-line-through-style="none" style:font-name="Times New Roman" fo:font-size="12pt" fo:font-style="normal" fo:text-shadow="none" style:text-underline-style="none" fo:font-weight="normal" style:font-size-asian="12pt" style:font-style-asian="normal" style:font-weight-asian="normal" style:font-size-complex="12pt" style:font-style-complex="normal" style:font-weight-complex="normal" style:text-overline-style="none" style:text-overline-color="font-color"/>
+ </style:style>
+
+ <style:style style:name="CustomFirstColumnTableParagraph" style:family="paragraph" style:parent-style-name="Table_20_Contents">
+ <style:paragraph-properties fo:text-align="start" style:justify-single-word="false"/>
+ <style:text-properties fo:color="#ffffff" style:text-outline="false" style:text-line-through-style="none" style:font-name="Times New Roman" fo:font-size="12pt" fo:font-style="normal" fo:text-shadow="none" style:text-underline-style="none" fo:font-weight="normal" style:font-size-asian="12pt" style:font-style-asian="normal" style:font-weight-asian="normal" style:font-size-complex="12pt" style:font-style-complex="normal" style:font-weight-complex="normal" style:text-overline-style="none" style:text-overline-color="font-color"/>
+ </style:style>
+
+ <!-- Table Cell Styles -->
+ <style:style style:name="CustomTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:background-color="#ffffff" fo:padding="0.097cm" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000">
+ <style:background-image/>
+ </style:table-cell-properties>
+ </style:style>
+
+ <style:style style:name="CustomFirstRowTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:background-color="#000080" fo:padding="0.097cm" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000">
+ <style:background-image/>
+ </style:table-cell-properties>
+ </style:style>
+
+ <style:style style:name="CustomLastRowTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:background-color="#cccccc" fo:padding="0.097cm" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000">
+ <style:background-image/>
+ </style:table-cell-properties>
+ </style:style>
+
+ <style:style style:name="CustomFirstColumnTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:background-color="#4d4d4d" fo:padding="0.097cm" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000">
+ <style:background-image/>
+ </style:table-cell-properties>
+ </style:style>
+
+ <style:style style:name="CustomLastColumnTableCell" style:family="table-cell">
+ <style:table-cell-properties style:vertical-align="top" fo:background-color="#cccccc" fo:padding="0.097cm" fo:border-left="0.002cm solid #000000" fo:border-right="0.002cm solid #000000" fo:border-top="0.002cm solid #000000" fo:border-bottom="0.002cm solid #000000">
+ <style:background-image/>
+ </style:table-cell-properties>
+ </style:style>
+
+ <!-- END: Custom Table Template -->
+
+ </office:automatic-styles>
+
+ <office:body>
+ <office:text>
+ <text:sequence-decls>
+ <text:sequence-decl text:display-outline-level="0" text:name="Illustration"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Table"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Text"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Drawing"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Equation"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Figure"/>
+ <text:sequence-decl text:display-outline-level="0" text:name="Listing"/>
+ </text:sequence-decls>
+ </office:text>
+ </office:body>
+</office:document-content>
diff --git a/etc/styles/OrgOdtStyles.xml b/etc/styles/OrgOdtStyles.xml
new file mode 100644
index 0000000..1a8edee
--- /dev/null
+++ b/etc/styles/OrgOdtStyles.xml
@@ -0,0 +1,861 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- See etc/org/README for copyright information -->
+<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:rpt="http://openoffice.org/2005/report" xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:grddl="http://www.w3.org/2003/g/data-view#" office:version="1.2">
+ <office:font-face-decls>
+ <style:font-face style:name="OpenSymbol" svg:font-family="OpenSymbol"/>
+ <style:font-face style:name="Tahoma1" svg:font-family="Tahoma"/>
+ <style:font-face style:name="Courier New" svg:font-family="&apos;Courier New&apos;" style:font-family-generic="modern" style:font-pitch="fixed"/>
+ <style:font-face style:name="NSimSun" svg:font-family="NSimSun" style:font-family-generic="modern" style:font-pitch="fixed"/>
+ <style:font-face style:name="Times New Roman" svg:font-family="&apos;Times New Roman&apos;" style:font-family-generic="roman" style:font-pitch="variable"/>
+ <style:font-face style:name="Arial" svg:font-family="Arial" style:font-family-generic="swiss" style:font-pitch="variable"/>
+ <style:font-face style:name="SimSun" svg:font-family="SimSun" style:font-family-generic="system" style:font-pitch="variable"/>
+ <style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable"/>
+ </office:font-face-decls>
+ <office:styles>
+ <style:default-style style:family="graphic">
+ <style:graphic-properties draw:shadow-offset-x="0.3cm" draw:shadow-offset-y="0.3cm" draw:start-line-spacing-horizontal="0.283cm" draw:start-line-spacing-vertical="0.283cm" draw:end-line-spacing-horizontal="0.283cm" draw:end-line-spacing-vertical="0.283cm" style:flow-with-text="false"/>
+ <style:paragraph-properties style:text-autospace="ideograph-alpha" style:line-break="strict" style:writing-mode="lr-tb" style:font-independent-line-spacing="false">
+ <style:tab-stops/>
+ </style:paragraph-properties>
+ <style:text-properties style:use-window-font-color="true" fo:font-size="12pt" fo:language="en" fo:country="GB" style:letter-kerning="true" style:font-size-asian="12pt" style:language-asian="zh" style:country-asian="CN" style:font-size-complex="12pt" style:language-complex="hi" style:country-complex="IN"/>
+ </style:default-style>
+ <style:default-style style:family="paragraph">
+ <style:paragraph-properties fo:hyphenation-ladder-count="no-limit" style:text-autospace="ideograph-alpha" style:punctuation-wrap="hanging" style:line-break="strict" style:tab-stop-distance="1.251cm" style:writing-mode="page"/>
+ <style:text-properties style:use-window-font-color="true" style:font-name="Times New Roman" fo:font-size="12pt" fo:language="en" fo:country="GB" style:letter-kerning="true" style:font-name-asian="SimSun" style:font-size-asian="12pt" style:language-asian="zh" style:country-asian="CN" style:font-name-complex="Tahoma" style:font-size-complex="12pt" style:language-complex="hi" style:country-complex="IN" fo:hyphenate="false" fo:hyphenation-remain-char-count="2" fo:hyphenation-push-char-count="2"/>
+ </style:default-style>
+ <style:default-style style:family="table">
+ <style:table-properties table:border-model="collapsing"/>
+ </style:default-style>
+ <style:default-style style:family="table-row">
+ <style:table-row-properties fo:keep-together="auto"/>
+ </style:default-style>
+
+ <!-- Outline numbering -->
+ <text:outline-style style:name="OrgOutline">
+ <text:outline-level-style text:level="1" style:num-suffix=". " style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-0.762cm" fo:margin-left="0.762cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="2" style:num-suffix=". " style:num-format="1" text:display-levels="2">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-1.016cm" fo:margin-left="1.016cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="3" style:num-suffix=". " style:num-format="1" text:display-levels="3">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-1.27cm" fo:margin-left="1.27cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="4" style:num-suffix=". " style:num-format="1" text:display-levels="4">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-1.524cm" fo:margin-left="1.524cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="5" style:num-suffix=". " style:num-format="1" text:display-levels="5">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-1.778cm" fo:margin-left="1.778cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="6" style:num-suffix=". " style:num-format="1" text:display-levels="6">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-2.032cm" fo:margin-left="2.032cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="7" style:num-suffix=". " style:num-format="1" text:display-levels="7">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-2.286cm" fo:margin-left="2.286cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="8" style:num-suffix=". " style:num-format="1" text:display-levels="8">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-2.54cm" fo:margin-left="2.54cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="9" style:num-suffix=". " style:num-format="1" text:display-levels="9">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-2.794cm" fo:margin-left="2.794cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ <text:outline-level-style text:level="10" style:num-suffix=". " style:num-format="1" text:display-levels="10">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="nothing" fo:text-indent="-3.048cm" fo:margin-left="3.048cm"/>
+ </style:list-level-properties>
+ </text:outline-level-style>
+ </text:outline-style>
+
+ <style:style style:name="Standard" style:family="paragraph" style:class="text"/>
+ <style:style style:name="Heading" style:family="paragraph" style:parent-style-name="Standard" style:next-style-name="Text_20_body" style:class="text">
+ <style:paragraph-properties fo:margin-top="0.423cm" fo:margin-bottom="0.212cm" fo:keep-with-next="always">
+ <style:tab-stops>
+ <style:tab-stop style:position="17cm" style:type="right"/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ <style:text-properties style:font-name="Arial" fo:font-size="14pt" style:font-name-asian="SimSun" style:font-size-asian="14pt" style:font-name-complex="Tahoma" style:font-size-complex="14pt"/>
+ </style:style>
+ <style:style style:name="Text_20_body" style:display-name="Text body" style:family="paragraph" style:parent-style-name="Standard" style:class="text">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.212cm"/>
+ </style:style>
+ <style:style style:name="List" style:family="paragraph" style:parent-style-name="Text_20_body" style:class="list">
+ <style:text-properties style:font-name-complex="Tahoma1"/>
+ </style:style>
+ <style:style style:name="Caption" style:family="paragraph" style:parent-style-name="Standard" style:class="extra">
+ <style:paragraph-properties fo:margin-top="0.212cm" fo:margin-bottom="0.212cm" text:number-lines="false" text:line-number="0"/>
+ <style:text-properties fo:font-size="12pt" fo:font-style="italic" style:font-size-asian="12pt" style:font-style-asian="italic" style:font-name-complex="Tahoma1" style:font-size-complex="12pt" style:font-style-complex="italic"/>
+ </style:style>
+ <style:style style:name="Index" style:family="paragraph" style:parent-style-name="Standard" style:class="index">
+ <style:paragraph-properties text:number-lines="false" text:line-number="0"/>
+ <style:text-properties style:font-name-complex="Tahoma1"/>
+ </style:style>
+ <style:style style:name="Heading_20_1" style:display-name="Heading 1" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="1" style:class="text">
+ <style:text-properties fo:font-size="115%" fo:font-weight="bold" style:font-size-asian="115%" style:font-weight-asian="bold" style:font-size-complex="115%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_1_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_1" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_2" style:display-name="Heading 2" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="2" style:class="text">
+ <style:text-properties fo:font-size="14pt" fo:font-style="italic" fo:font-weight="bold" style:font-size-asian="14pt" style:font-style-asian="italic" style:font-weight-asian="bold" style:font-size-complex="14pt" style:font-style-complex="italic" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_2_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_2" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_3" style:display-name="Heading 3" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="3" style:class="text">
+ <style:text-properties fo:font-size="14pt" fo:font-weight="bold" style:font-size-asian="14pt" style:font-weight-asian="bold" style:font-size-complex="14pt" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_3_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_3" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_4" style:display-name="Heading 4" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="4" style:class="text">
+ <style:text-properties fo:font-size="85%" fo:font-style="italic" fo:font-weight="bold" style:font-size-asian="85%" style:font-style-asian="italic" style:font-weight-asian="bold" style:font-size-complex="85%" style:font-style-complex="italic" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_4_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_4" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_5" style:display-name="Heading 5" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="5" style:class="text">
+ <style:text-properties fo:font-size="85%" fo:font-weight="bold" style:font-size-asian="85%" style:font-weight-asian="bold" style:font-size-complex="85%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_5_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_5" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_6" style:display-name="Heading 6" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="6" style:class="text">
+ <style:text-properties fo:font-size="75%" fo:font-weight="bold" style:font-size-asian="75%" style:font-weight-asian="bold" style:font-size-complex="75%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_6_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_6" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_7" style:display-name="Heading 7" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="7" style:class="text">
+ <style:text-properties fo:font-size="75%" fo:font-weight="bold" style:font-size-asian="75%" style:font-weight-asian="bold" style:font-size-complex="75%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_7_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_7" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_8" style:display-name="Heading 8" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="8" style:class="text">
+ <style:text-properties fo:font-size="75%" fo:font-weight="bold" style:font-size-asian="75%" style:font-weight-asian="bold" style:font-size-complex="75%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_8_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_8" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_9" style:display-name="Heading 9" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="9" style:class="text">
+ <style:text-properties fo:font-size="75%" fo:font-weight="bold" style:font-size-asian="75%" style:font-weight-asian="bold" style:font-size-complex="75%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_9_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_9" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_10" style:display-name="Heading 10" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:default-outline-level="10" style:class="text">
+ <style:text-properties fo:font-size="75%" fo:font-weight="bold" style:font-size-asian="75%" style:font-weight-asian="bold" style:font-size-complex="75%" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Heading_20_10_unnumbered" style:family="paragraph" style:parent-style-name="Heading_20_10" style:list-style-name="">
+ </style:style>
+ <style:style style:name="Heading_20_1.title" style:display-name="Heading 1.title" style:family="paragraph" style:parent-style-name="Heading_20_1">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="Title" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Subtitle" style:class="chapter">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ <style:text-properties fo:font-size="18pt" fo:font-weight="bold" style:font-size-asian="18pt" style:font-weight-asian="bold" style:font-size-complex="18pt" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="OrgTitle" style:family="paragraph" style:parent-style-name="Title">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0cm"/>
+ <style:text-properties fo:font-size="24pt"/>
+ </style:style>
+ <style:style style:name="Subtitle" style:family="paragraph" style:parent-style-name="Heading" style:next-style-name="Text_20_body" style:class="chapter">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ <style:text-properties fo:font-size="14pt" fo:font-style="italic" style:font-size-asian="14pt" style:font-style-asian="italic" style:font-size-complex="14pt" style:font-style-complex="italic"/>
+ </style:style>
+ <style:style style:name="OrgSubtitle" style:family="paragraph" style:parent-style-name="Subtitle">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0cm"/>
+ <style:text-properties fo:font-size="20pt"/>
+ </style:style>
+ <style:style style:name="Text_20_body_20_indent" style:display-name="Text body indent" style:family="paragraph" style:parent-style-name="Text_20_body" style:class="text">
+ <style:paragraph-properties fo:margin-left="0.499cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false"/>
+ </style:style>
+ <style:style style:name="List_20_Indent" style:display-name="List Indent" style:family="paragraph" style:parent-style-name="Text_20_body" style:class="text">
+ <style:paragraph-properties fo:margin-left="5.001cm" fo:margin-right="0cm" fo:text-indent="-4.5cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="0cm"/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="First_20_line_20_indent" style:display-name="First line indent" style:family="paragraph" style:parent-style-name="Text_20_body" style:class="text">
+ <style:paragraph-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:text-indent="0.499cm" style:auto-text-indent="false"/>
+ </style:style>
+ <style:style style:name="Hanging_20_indent" style:display-name="Hanging indent" style:family="paragraph" style:parent-style-name="Text_20_body" style:class="text">
+ <style:paragraph-properties fo:margin-left="1cm" fo:margin-right="0cm" fo:text-indent="-0.499cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="0cm"/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Salutation" style:family="paragraph" style:parent-style-name="Standard" style:class="text">
+ <style:paragraph-properties text:number-lines="false" text:line-number="0"/>
+ </style:style>
+ <style:style style:name="Contents_20_Heading" style:display-name="Contents Heading" style:family="paragraph" style:parent-style-name="Heading" style:class="index">
+ <style:paragraph-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false" text:number-lines="false" text:line-number="0"/>
+ <style:text-properties fo:font-size="16pt" fo:font-weight="bold" style:font-size-asian="16pt" style:font-weight-asian="bold" style:font-size-complex="16pt" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Contents_20_1" style:display-name="Contents 1" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="17cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_2" style:display-name="Contents 2" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="0.499cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="16.501cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_3" style:display-name="Contents 3" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="0.998cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="16.002cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_4" style:display-name="Contents 4" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="1.498cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="15.503cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_5" style:display-name="Contents 5" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="1.997cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="15.004cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_6" style:display-name="Contents 6" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="2.496cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="14.504cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_7" style:display-name="Contents 7" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="2.995cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="14.005cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_8" style:display-name="Contents 8" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="3.494cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="13.506cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_9" style:display-name="Contents 9" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="3.993cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="13.007cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Contents_20_10" style:display-name="Contents 10" style:family="paragraph" style:parent-style-name="Index" style:class="index">
+ <style:paragraph-properties fo:margin-left="4.493cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false">
+ <style:tab-stops>
+ <style:tab-stop style:position="12.508cm" style:type="right" style:leader-style="dotted" style:leader-text="."/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Quotations" style:family="paragraph" style:parent-style-name="Standard" style:class="html">
+ <style:paragraph-properties fo:margin-left="1cm" fo:margin-right="1cm" fo:margin-top="0cm" fo:margin-bottom="0.499cm" fo:text-indent="0cm" style:auto-text-indent="false"/>
+ </style:style>
+ <style:style style:name="OrgFootnoteQuotations" style:family="paragraph" style:parent-style-name="Footnote" style:class="html">
+ <style:paragraph-properties fo:margin-left="1cm" fo:margin-right="1cm" fo:margin-top="0cm" fo:margin-bottom="0.499cm" fo:text-indent="0cm" style:auto-text-indent="false"/>
+ </style:style>
+ <style:style style:name="Preformatted_20_Text" style:display-name="Preformatted Text" style:family="paragraph" style:parent-style-name="Standard" style:class="html">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0cm"/>
+ <style:text-properties style:font-name="Courier New" fo:font-size="10pt" style:font-name-asian="NSimSun" style:font-size-asian="10pt" style:font-name-complex="Courier New" style:font-size-complex="10pt"/>
+ </style:style>
+
+ <style:style style:name="OrgVerse" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
+ <style:paragraph-properties fo:background-color="transparent" fo:padding="0cm" fo:border="none" style:shadow="none">
+ <style:background-image/>
+ </style:paragraph-properties>
+ </style:style>
+
+ <style:style style:name="OrgClock" style:family="paragraph" style:parent-style-name="Text_20_body">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0cm"/>
+ </style:style>
+ <style:style style:name="OrgClockLastLine" style:family="paragraph" style:parent-style-name="OrgClock"/>
+ <style:style style:name="OrgPlanning" style:family="paragraph" style:parent-style-name="Text_20_body"/>
+
+ <!-- Fixed width block -->
+ <style:style style:name="OrgFixedWidthBlock" style:family="paragraph" style:parent-style-name="Preformatted_20_Text">
+ <style:paragraph-properties fo:background-color="#c0c0c0" fo:padding="0.049cm" fo:border="0.06pt solid #000000" style:shadow="none">
+ <style:background-image/>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="OrgFixedWidthBlockLastLine" style:family="paragraph" style:parent-style-name="OrgFixedWidthBlock">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.21cm"/>
+ </style:style>
+
+ <style:style style:name="OrgFormula" style:family="paragraph" style:parent-style-name="Text_20_body">
+ <style:paragraph-properties>
+ <style:tab-stops>
+ <style:tab-stop style:position="17cm" style:type="right"/>
+ </style:tab-stops>
+ </style:paragraph-properties>
+ </style:style>
+
+ <style:style style:name="OrgSrcBlockLastLine" style:family="paragraph" style:parent-style-name="OrgSrcBlock">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.21cm"/>
+ </style:style>
+
+ <style:style style:name="OrgCenter" style:family="paragraph" style:parent-style-name="Text_20_body">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgFootnoteCenter" style:family="paragraph" style:parent-style-name="Footnote">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgTableContents" style:family="paragraph" style:parent-style-name="Text_20_body"/>
+ <style:style style:name="OrgTableHeading" style:family="paragraph" style:parent-style-name="OrgTableContents" style:class="extra">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false" text:number-lines="false" text:line-number="0"/>
+ <style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
+ </style:style>
+
+ <style:style style:name="OrgTableHeadingLeft" style:family="paragraph" style:parent-style-name="OrgTableHeading">
+ <style:paragraph-properties fo:text-align="left" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgTableHeadingRight" style:family="paragraph" style:parent-style-name="OrgTableHeading">
+ <style:paragraph-properties fo:text-align="right" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgTableHeadingCenter" style:family="paragraph" style:parent-style-name="OrgTableHeading">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+
+ <style:style style:name="OrgTableContentsLeft" style:family="paragraph" style:parent-style-name="OrgTableContents">
+ <style:paragraph-properties fo:text-align="left" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgTableContentsRight" style:family="paragraph" style:parent-style-name="OrgTableContents">
+ <style:paragraph-properties fo:text-align="right" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="OrgTableContentsCenter" style:family="paragraph" style:parent-style-name="OrgTableContents">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="Text_20_body_20_bold" style:display-name="Text body bold" style:family="paragraph" style:parent-style-name="Text_20_body" style:next-style-name="Text_20_body">
+ <style:text-properties fo:font-weight="bold"/>
+ </style:style>
+ <style:style style:name="Footnote" style:family="paragraph" style:parent-style-name="Standard" style:class="extra">
+ <style:paragraph-properties fo:margin-left="0.499cm" fo:margin-right="0cm" fo:text-indent="-0.499cm" style:auto-text-indent="false" text:number-lines="false" text:line-number="0"/>
+ <style:text-properties fo:font-size="10pt" style:font-size-asian="10pt" style:font-size-complex="10pt"/>
+ </style:style>
+ <style:style style:name="Figure" style:family="paragraph" style:parent-style-name="Caption"/>
+ <style:style style:name="Illustration_20_Index_20_Heading" style:display-name="Illustration Index Heading" style:family="paragraph" style:parent-style-name="Heading" style:class="index">
+ <style:paragraph-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false" text:number-lines="false" text:line-number="0"/>
+ <style:text-properties fo:font-size="16pt" fo:font-weight="bold" style:font-size-asian="16pt" style:font-weight-asian="bold" style:font-size-complex="16pt" style:font-weight-complex="bold"/>
+ </style:style>
+ <style:style style:name="Table" style:family="paragraph" style:parent-style-name="Caption" style:class="extra">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:style style:name="Listing" style:family="paragraph" style:parent-style-name="Caption" style:class="extra">
+ <style:paragraph-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false" fo:keep-with-next="always">
+ <style:tab-stops/>
+ </style:paragraph-properties>
+ </style:style>
+ <style:style style:name="Horizontal_20_Line" style:display-name="Horizontal Line" style:family="paragraph" style:parent-style-name="Standard" style:next-style-name="Text_20_body" style:class="html">
+ <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.21cm" style:page-number="auto" fo:padding="0cm" fo:border-left="none" fo:border-right="none" fo:border-top="none" fo:border-bottom="0.06pt solid #000000" style:shadow="none" text:number-lines="false" text:line-number="0" style:join-border="false"/>
+ <style:text-properties fo:font-size="6pt" style:font-size-asian="6pt" style:font-size-complex="6pt"/>
+ </style:style>
+
+ <style:style style:name="Emphasis" style:family="text">
+ <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
+ </style:style>
+ <style:style style:name="Underline" style:family="text">
+ <style:text-properties style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color" fo:background-color="transparent"/>
+ </style:style>
+ <style:style style:name="Strikethrough" style:family="text">
+ <style:text-properties style:text-line-through-style="solid"/>
+ </style:style>
+ <style:style style:name="Source_20_Text" style:display-name="Source Text" style:family="text">
+ <style:text-properties style:font-name="Courier New" fo:background-color="transparent" style:font-name-asian="NSimSun" style:font-name-complex="Courier New"/>
+ </style:style>
+ <style:style style:name="Citation" style:family="text">
+ <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
+ </style:style>
+ <style:style style:name="Example" style:family="text">
+ <style:text-properties style:font-name="Courier New" fo:background-color="transparent" style:font-name-asian="NSimSun" style:font-name-complex="Courier New"/>
+ </style:style>
+ <style:style style:name="OrgCode" style:family="text" style:parent-style-name="Source_20_Text"/>
+
+ <!-- BEGIN: Org Agenda Styles -->
+ <style:style style:name="OrgTodo" style:family="text"/>
+ <style:style style:name="OrgDone" style:family="text"/>
+
+ <style:style style:name="OrgTag" style:family="text">
+ <style:text-properties fo:font-variant="small-caps" fo:background-color="transparent"/>
+ </style:style>
+ <style:style style:name="OrgTags" style:family="text"/>
+
+ <style:style style:name="OrgPriority" style:family="text"/>
+ <style:style style:name="OrgPriority-A" style:family="text" style:parent-style-name="OrgPriority"/>
+ <style:style style:name="OrgPriority-B" style:family="text" style:parent-style-name="OrgPriority"/>
+ <style:style style:name="OrgPriority-C" style:family="text" style:parent-style-name="OrgPriority"/>
+
+ <style:style style:name="OrgTimestamp" style:display-name="OrgTimestamp" style:family="text">
+ <style:text-properties style:font-name="Courier New" fo:background-color="transparent" style:font-name-asian="NSimSun" style:font-name-complex="Courier New"/>
+ </style:style>
+ <style:style style:name="OrgActiveTimestamp" style:family="text" style:parent-style-name="OrgTimestamp"/>
+ <style:style style:name="OrgInactiveTimestamp" style:family="text" style:parent-style-name="OrgTimestamp"/>
+ <style:style style:name="OrgTimestampKeyword" style:family="text">
+ <style:text-properties style:use-window-font-color="true" fo:font-weight="bold"/>
+ </style:style>
+ <style:style style:name="OrgScheduledKeyword" style:family="text" style:parent-style-name="OrgTimestampKeyword"/>
+ <style:style style:name="OrgDeadlineKeyword" style:family="text" style:parent-style-name="OrgTimestampKeyword"/>
+ <style:style style:name="OrgClockKeyword" style:family="text" style:parent-style-name="OrgTimestampKeyword"/>
+ <style:style style:name="OrgClosedKeyword" style:family="text" style:parent-style-name="OrgTimestampKeyword"/>
+ <style:style style:name="OrgTimestampWrapper" style:family="text"/>
+ <style:style style:name="OrgTarget" style:family="text"/>
+
+ <number:date-style style:name="OrgDate" number:automatic-order="true">
+ <number:day number:style="long"/>
+ <number:text>/</number:text>
+ <number:month number:style="long"/>
+ <number:text>/</number:text>
+ <number:year number:style="long"/>
+ </number:date-style>
+ <!-- END: Org Agenda Styles -->
+
+ <style:style style:name="Bold" style:family="text">
+ <style:text-properties fo:font-weight="bold"/>
+ </style:style>
+ <style:style style:name="Numbering_20_Symbols" style:display-name="Numbering Symbols" style:family="text"/>
+ <style:style style:name="Footnote_20_Symbol" style:display-name="Footnote Symbol" style:family="text"/>
+ <style:style style:name="Footnote_20_anchor" style:display-name="Footnote anchor" style:family="text">
+ <style:text-properties style:text-position="super 58%"/>
+ </style:style>
+ <style:style style:name="OrgSuperscript" style:family="text">
+ <style:text-properties style:text-position="super 58%"/>
+ </style:style>
+ <style:style style:name="OrgSubscript" style:family="text">
+ <style:text-properties style:text-position="sub 58%"/>
+ </style:style>
+ <style:style style:name="Internet_20_link" style:display-name="Internet link" style:family="text">
+ <style:text-properties fo:color="#000080" fo:language="zxx" fo:country="none" style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color" style:language-asian="zxx" style:country-asian="none" style:language-complex="zxx" style:country-complex="none"/>
+ </style:style>
+ <style:style style:name="Graphics" style:family="graphic">
+ <style:graphic-properties text:anchor-type="paragraph" svg:x="0cm" svg:y="0cm" style:wrap="none" style:vertical-pos="top" style:vertical-rel="paragraph" style:horizontal-pos="center" style:horizontal-rel="paragraph"/>
+ </style:style>
+ <style:style style:name="Frame" style:family="graphic">
+ <style:graphic-properties text:anchor-type="paragraph" svg:x="0cm" svg:y="0cm" fo:margin-left="0.201cm" fo:margin-right="0.201cm" fo:margin-top="0.201cm" fo:margin-bottom="0.201cm" style:wrap="parallel" style:number-wrapped-paragraphs="no-limit" style:wrap-contour="false" style:vertical-pos="top" style:vertical-rel="paragraph-content" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" fo:padding="0.15cm" fo:border="0.002cm solid #000000"/>
+ </style:style>
+
+ <!-- Simple Images -->
+ <style:style style:name="OrgDisplayImage" style:family="graphic" style:parent-style-name="Graphics">
+ <style:graphic-properties text:anchor-type="paragraph" style:wrap="none" style:vertical-pos="top" style:vertical-rel="paragraph" style:horizontal-pos="center" style:horizontal-rel="paragraph"/>
+ </style:style>
+
+ <style:style style:name="OrgPageImage" style:family="graphic" style:parent-style-name="Graphics">
+ <style:graphic-properties text:anchor-type="page" fo:margin-top="0.21cm" fo:margin-bottom="0.21cm" style:vertical-pos="middle" style:vertical-rel="page" style:horizontal-pos="center" style:horizontal-rel="page" fo:background-color="transparent" style:background-transparency="100%" style:shadow="none" style:mirror="none" fo:clip="rect(0cm, 0cm, 0cm, 0cm)" draw:luminance="0%" draw:contrast="0%" draw:red="0%" draw:green="0%" draw:blue="0%" draw:gamma="100%" draw:color-inversion="false" draw:image-opacity="100%" draw:color-mode="standard">
+ <style:background-image/>
+ </style:graphic-properties>
+ </style:style>
+
+ <!-- Captioned Images -->
+ <style:style style:name="OrgCaptionedImage" style:family="graphic" style:parent-style-name="Graphics">
+ <style:graphic-properties style:rel-width="100%" text:anchor-type="paragraph" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0cm" fo:margin-bottom="0cm" style:run-through="foreground" style:wrap="none" style:vertical-pos="from-top" style:vertical-rel="paragraph-content" style:horizontal-pos="from-left" style:horizontal-rel="paragraph-content" fo:padding="0cm" fo:border="none" style:shadow="none"/>
+ </style:style>
+
+ <style:style style:name="OrgImageCaptionFrame" style:family="graphic" style:parent-style-name="Frame">
+ <style:graphic-properties text:anchor-type="paragraph" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0cm" fo:margin-bottom="0cm" style:wrap="none" style:vertical-pos="top" style:vertical-rel="paragraph" style:horizontal-pos="center" style:horizontal-rel="paragraph" fo:padding="0cm" fo:border="none"/>
+ </style:style>
+
+ <style:style style:name="OrgPageImageCaptionFrame" style:family="graphic" style:parent-style-name="Frame">
+ <style:graphic-properties text:anchor-type="paragraph" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0.21cm" fo:margin-bottom="0.21cm" style:wrap="none" style:vertical-pos="middle" style:vertical-rel="page" style:horizontal-pos="center" style:horizontal-rel="page" fo:background-color="transparent" style:background-transparency="100%" fo:padding="0cm" fo:border="none" style:shadow="none">
+ <style:background-image/>
+ </style:graphic-properties>
+ </style:style>
+
+ <!-- Inlined Images -->
+ <style:style style:name="OrgInlineImage" style:family="graphic" style:parent-style-name="Graphics">
+ <style:graphic-properties text:anchor-type="as-char" style:vertical-pos="top" style:vertical-rel="baseline" style:horizontal-pos="center" style:horizontal-rel="paragraph"/>
+ </style:style>
+
+ <!-- Inline Formula -->
+ <style:style style:name="OrgFormula" style:family="graphic">
+ <style:graphic-properties text:anchor-type="as-char" svg:y="0cm" fo:margin-left="0.201cm" fo:margin-right="0.201cm" style:vertical-pos="middle" style:vertical-rel="text" style:shadow="none"/>
+ </style:style>
+
+ <style:style style:name="OrgInlineFormula" style:family="graphic" style:parent-style-name="Formula">
+ <style:graphic-properties text:anchor-type="as-char" fo:margin-left="0.201cm" fo:margin-right="0.201cm" style:vertical-pos="middle" style:vertical-rel="text"/>
+ </style:style>
+
+ <style:style style:name="OrgInlineFormula" style:family="graphic" style:parent-style-name="Formula">
+ <style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" draw:ole-draw-aspect="1"/>
+ </style:style>
+
+ <style:style style:name="OrgDisplayFormula" style:family="graphic" style:parent-style-name="OrgFormula">
+ <style:graphic-properties style:vertical-pos="middle" style:vertical-rel="text" style:horizontal-pos="from-left" style:horizontal-rel="paragraph-content" draw:ole-draw-aspect="1"/>
+ </style:style>
+
+ <style:style style:name="OrgFormulaCaptionFrame" style:family="graphic" style:parent-style-name="Frame">
+ <style:graphic-properties text:anchor-type="paragraph" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0cm" fo:margin-bottom="0cm" style:wrap="right" style:number-wrapped-paragraphs="1" style:wrap-contour="false" style:vertical-pos="top" style:vertical-rel="paragraph" style:horizontal-pos="center" style:horizontal-rel="paragraph" fo:padding="0cm" fo:border="none"/>
+ </style:style>
+
+ <style:style style:name="OrgCaptionedFormula" style:family="graphic" style:parent-style-name="OrgFormula">
+ <style:graphic-properties fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0cm" fo:margin-bottom="0cm" style:run-through="foreground" style:wrap="none" style:vertical-pos="from-top" style:vertical-rel="paragraph-content" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" fo:padding="0cm" fo:border="none" style:shadow="none" draw:ole-draw-aspect="1"/>
+ </style:style>
+
+ <!-- Inline Tasks -->
+ <style:style style:name="OrgInlineTaskHeading" style:family="paragraph" style:parent-style-name="Caption" style:next-style-name="Text_20_body">
+ <style:text-properties style:font-name="Arial1" fo:font-style="normal" fo:font-weight="bold"/>
+ </style:style>
+ <style:style style:name="OrgInlineTaskFrame" style:family="graphic" style:parent-style-name="Frame">
+ <style:graphic-properties svg:x="0cm" svg:y="0cm" style:wrap="none" style:vertical-pos="top" style:vertical-rel="paragraph-content" style:horizontal-pos="center" style:horizontal-rel="paragraph-content" fo:background-color="#ffffcc" style:background-transparency="0%" fo:padding="0.15cm" fo:border="0.26pt solid #000000" style:shadow="none">
+ <style:background-image/>
+ </style:graphic-properties>
+ </style:style>
+
+ <text:list-style style:name="Numbering_20_1" style:display-name="Numbering 1">
+ <text:list-level-style-number text:level="1" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="0.499cm" fo:text-indent="-0.499cm" fo:margin-left="0.499cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="2" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1cm" fo:text-indent="-0.499cm" fo:margin-left="1cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="3" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.499cm" fo:text-indent="-0.499cm" fo:margin-left="1.499cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="4" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2cm" fo:text-indent="-0.499cm" fo:margin-left="2cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="5" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.499cm" fo:text-indent="-0.499cm" fo:margin-left="2.499cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="6" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3cm" fo:text-indent="-0.499cm" fo:margin-left="3cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="7" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.5cm" fo:text-indent="-0.499cm" fo:margin-left="3.5cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="8" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.001cm" fo:text-indent="-0.499cm" fo:margin-left="4.001cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="9" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.5cm" fo:text-indent="-0.499cm" fo:margin-left="4.5cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="10" text:style-name="Numbering_20_Symbols" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="5.001cm" fo:text-indent="-0.499cm" fo:margin-left="5.001cm"/>
+ </style:list-level-properties>
+ </text:list-level-style-number>
+ </text:list-style>
+ <text:list-style style:name="List_20_1" style:display-name="List 1">
+ <text:list-level-style-bullet text:level="1" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="0.4cm" fo:text-indent="-0.4cm" fo:margin-left="0.4cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="2" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="0.801cm" fo:text-indent="-0.4cm" fo:margin-left="0.801cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="3" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.199cm" fo:text-indent="-0.4cm" fo:margin-left="1.199cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="4" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="1.6cm" fo:text-indent="-0.4cm" fo:margin-left="1.6cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="5" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2cm" fo:text-indent="-0.4cm" fo:margin-left="2cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="6" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.401cm" fo:text-indent="-0.4cm" fo:margin-left="2.401cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="7" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="2.799cm" fo:text-indent="-0.4cm" fo:margin-left="2.799cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="8" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.2cm" fo:text-indent="-0.4cm" fo:margin-left="3.2cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="9" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="3.6cm" fo:text-indent="-0.4cm" fo:margin-left="3.6cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="10" text:style-name="Numbering_20_Symbols" text:bullet-char="•">
+ <style:list-level-properties text:list-level-position-and-space-mode="label-alignment">
+ <style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="4.001cm" fo:text-indent="-0.4cm" fo:margin-left="4.001cm"/>
+ </style:list-level-properties>
+ <style:text-properties style:font-name="OpenSymbol"/>
+ </text:list-level-style-bullet>
+ </text:list-style>
+
+ <!-- Numbered List -->
+ <text:list-style style:name="OrgNumberedList">
+ <text:list-level-style-number text:level="1" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="0.635cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="2" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="1.27cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="3" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="1.905cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="4" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="2.54cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="5" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="3.175cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="6" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="3.81cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="7" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="4.445cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="8" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="5.08cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="9" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="5.715cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="10" style:num-suffix="." style:num-format="1">
+ <style:list-level-properties text:space-before="6.35cm" text:min-label-width="0.635cm"/>
+ </text:list-level-style-number>
+ </text:list-style>
+
+ <!-- Bulleted List -->
+ <text:list-style style:name="OrgBulletedList">
+ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="0.635cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="2" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="1.27cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="3" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="1.905cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="4" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="2.54cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="5" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="3.175cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="6" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="3.81cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="7" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="4.445cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="8" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="5.08cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="9" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="5.715cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ <text:list-level-style-bullet text:level="10" text:style-name="Bullet_20_Symbols" style:num-suffix="." text:bullet-char="•">
+ <style:list-level-properties text:space-before="6.35cm" text:min-label-width="0.635cm"/>
+ <style:text-properties fo:font-family="StarSymbol" style:font-charset="x-symbol"/>
+ </text:list-level-style-bullet>
+ </text:list-style>
+
+ <!-- Description List -->
+ <text:list-style style:name="OrgDescriptionList">
+ <text:list-level-style-number text:level="1" style:num-format="">
+ <style:list-level-properties text:space-before="0.635cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="2" style:num-format="">
+ <style:list-level-properties text:space-before="1.27cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="3" style:num-format="">
+ <style:list-level-properties text:space-before="1.905cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="4" style:num-format="">
+ <style:list-level-properties text:space-before="2.54cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="5" style:num-format="">
+ <style:list-level-properties text:space-before="3.175cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="6" style:num-format="">
+ <style:list-level-properties text:space-before="3.81cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="7" style:num-format="">
+ <style:list-level-properties text:space-before="4.445cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="8" style:num-format="">
+ <style:list-level-properties text:space-before="5.08cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="9" style:num-format="">
+ <style:list-level-properties text:space-before="5.715cm"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="10" style:num-format="">
+ <style:list-level-properties text:space-before="6.35cm"/>
+ </text:list-level-style-number>
+ </text:list-style>
+
+ <text:list-style style:name="OrgSrcBlockNumberedLine">
+ <text:list-level-style-number text:level="1" style:num-format="1">
+ <style:list-level-properties text:space-before="0.635cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="2" style:num-format="1">
+ <style:list-level-properties text:space-before="1.27cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="3" style:num-format="1">
+ <style:list-level-properties text:space-before="1.905cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="4" style:num-format="1">
+ <style:list-level-properties text:space-before="2.54cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="5" style:num-format="1">
+ <style:list-level-properties text:space-before="3.175cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="6" style:num-format="1">
+ <style:list-level-properties text:space-before="3.81cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="7" style:num-format="1">
+ <style:list-level-properties text:space-before="4.445cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="8" style:num-format="1">
+ <style:list-level-properties text:space-before="5.08cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="9" style:num-format="1">
+ <style:list-level-properties text:space-before="5.715cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ <text:list-level-style-number text:level="10" style:num-format="1">
+ <style:list-level-properties text:space-before="6.35cm" text:min-label-width="0.635cm" text:min-label-distance="0.101cm" fo:text-align="end"/>
+ </text:list-level-style-number>
+ </text:list-style>
+
+ <text:notes-configuration text:note-class="footnote" text:citation-style-name="Footnote_20_Symbol" text:citation-body-style-name="Footnote_20_anchor" style:num-format="1" text:start-value="0" text:footnotes-position="page" text:start-numbering-at="document"/>
+ <text:notes-configuration text:note-class="endnote" style:num-format="i" text:start-value="0"/>
+ <text:linenumbering-configuration text:number-lines="false" text:offset="0.499cm" style:num-format="1" text:number-position="left" text:increment="5"/>
+ </office:styles>
+ <office:automatic-styles>
+ <style:style style:name="MP1" style:family="paragraph" style:parent-style-name="Footer">
+ <style:paragraph-properties fo:text-align="center" style:justify-single-word="false"/>
+ </style:style>
+ <style:page-layout style:name="Mpm1" style:page-usage="mirrored">
+ <style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm" style:writing-mode="lr-tb" style:footnote-max-height="0cm">
+ <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:line-style="none" style:adjustment="left" style:rel-width="25%" style:color="#000000"/>
+ </style:page-layout-properties>
+ <style:header-style/>
+ <style:footer-style>
+ <style:header-footer-properties fo:min-height="0.6cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0.499cm" style:dynamic-spacing="false"/>
+ </style:footer-style>
+ </style:page-layout>
+ <style:page-layout style:name="Mpm2">
+ <style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm" style:writing-mode="lr-tb" style:footnote-max-height="0cm">
+ <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:line-style="solid" style:adjustment="left" style:rel-width="25%" style:color="#000000"/>
+ </style:page-layout-properties>
+ <style:header-style/>
+ <style:footer-style/>
+ </style:page-layout>
+ <style:page-layout style:name="Mpm3" style:page-usage="mirrored">
+ <style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" style:num-format="i" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm" style:writing-mode="lr-tb" style:footnote-max-height="0cm">
+ <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:line-style="solid" style:adjustment="left" style:rel-width="25%" style:color="#000000"/>
+ </style:page-layout-properties>
+ <style:header-style/>
+ <style:footer-style>
+ <style:header-footer-properties fo:min-height="0cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0.499cm"/>
+ </style:footer-style>
+ </style:page-layout>
+ <style:page-layout style:name="Mpm4" style:page-usage="right">
+ <style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm" fo:background-color="transparent" style:writing-mode="lr-tb" style:footnote-max-height="0cm">
+ <style:background-image/>
+ <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:line-style="solid" style:adjustment="left" style:rel-width="25%" style:color="#000000"/>
+ </style:page-layout-properties>
+ <style:header-style/>
+ <style:footer-style>
+ <style:header-footer-properties fo:min-height="0.6cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0.499cm" style:dynamic-spacing="false"/>
+ </style:footer-style>
+ </style:page-layout>
+ <style:page-layout style:name="Mpm5" style:page-usage="mirrored">
+ <style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" style:num-format="1" style:print-orientation="portrait" fo:margin-top="2cm" fo:margin-bottom="2cm" fo:margin-left="2cm" fo:margin-right="2cm" style:writing-mode="lr-tb" style:footnote-max-height="0cm">
+ <style:footnote-sep style:width="0.018cm" style:distance-before-sep="0.101cm" style:distance-after-sep="0.101cm" style:line-style="solid" style:adjustment="left" style:rel-width="25%" style:color="#000000"/>
+ </style:page-layout-properties>
+ <style:header-style/>
+ <style:footer-style>
+ <style:header-footer-properties fo:min-height="0.6cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:margin-top="0.499cm" style:dynamic-spacing="false"/>
+ </style:footer-style>
+ </style:page-layout>
+ </office:automatic-styles>
+ <office:master-styles>
+ <style:master-page style:name="Standard" style:page-layout-name="Mpm1">
+ <style:footer>
+ <text:p text:style-name="MP1"><text:page-number text:select-page="current"></text:page-number></text:p>
+ </style:footer>
+ </style:master-page>
+ <style:master-page style:name="OrgTitlePage" style:page-layout-name="Mpm2" style:next-style-name="OrgFrontMatterPage"/>
+ <style:master-page style:name="OrgFrontMatterPage" style:page-layout-name="Mpm3">
+ <style:footer>
+ <text:p text:style-name="MP1"><text:page-number text:select-page="current"/></text:p>
+ </style:footer>
+ </style:master-page>
+ <style:master-page style:name="OrgFirstPage" style:page-layout-name="Mpm4" style:next-style-name="OrgPage">
+ <style:footer>
+ <text:p text:style-name="MP1"><text:page-number text:select-page="current"/></text:p>
+ </style:footer>
+ </style:master-page>
+ <style:master-page style:name="OrgPage" style:page-layout-name="Mpm5">
+ <style:footer>
+ <text:p text:style-name="MP1"><text:page-number text:select-page="current"/></text:p>
+ </style:footer>
+ </style:master-page>
+ </office:master-styles>
+</office:document-styles>
diff --git a/etc/styles/README b/etc/styles/README
new file mode 100644
index 0000000..d04f434
--- /dev/null
+++ b/etc/styles/README
@@ -0,0 +1,36 @@
+The files OrgOdtContentTemplate.xml and OrgOdtStyles.xml have the
+following copyright information:
+
+Copyright (C) 2010-2014 Free Software Foundation, Inc.
+
+These files are part of GNU Emacs.
+
+GNU Emacs is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+GNU Emacs is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+
+Author: Jambunathan K <kjambunathan at gmail dot com>
+Keywords: outlines, hypermedia, calendar, wp
+Homepage: http://orgmode.org
+
+Commentary:
+
+These files are part of Org-mode's OpenDocument export module.
+
+OrgOdtContentTemplate.xml provides a template within which the content
+of an exported document is enclosed. This file contributes to
+"content.xml" file within an exported document and acts as a
+repository of automatic styles.
+
+OrgOdtStyles.xml contributes to "styles.xml" file within an exported
+document and acts as a repository of custom styles.
diff --git a/lisp/Makefile b/lisp/Makefile
new file mode 100644
index 0000000..89f504d
--- /dev/null
+++ b/lisp/Makefile
@@ -0,0 +1,93 @@
+.NOTPARALLEL: # always run this make serially
+.SUFFIXES: # we don't need default suffix rules
+ifeq ($(MAKELEVEL), 0)
+ $(error This make needs to be started as a sub-make from the toplevel directory.)
+endif
+
+ifneq ($(ORG_ADD_CONTRIB),)
+ _ORG_ADD_EL_ := \
+ $(notdir \
+ $(wildcard \
+ $(addsuffix .el, \
+ $(addprefix ../contrib/lisp/, \
+ $(basename \
+ $(notdir $(ORG_ADD_CONTRIB)))))))
+endif
+
+LISPV := org-version.el
+LISPI := org-loaddefs.el
+LISPA := $(LISPV) $(LISPI)
+LISPB := $(LISPA:%el=%elc) org-install.elc
+LISPF := $(filter-out $(LISPA),$(sort $(wildcard *.el) $(_ORG_ADD_EL_)))
+LISPC := $(filter-out $(LISPB) $(LISPN:%el=%elc),$(LISPF:%el=%elc))
+_ORGCM_ := dirall single source slint1 slint2
+-include local.mk
+
+.PHONY: all compile compile-dirty \
+ $(_ORGCM_) $(_ORGCM_:%=compile-%) \
+ autoloads addcontrib \
+ install clean cleanauto cleanall cleanelc clean-install
+
+# do not clean here, done in toplevel make
+all compile compile-dirty:: autoloads
+ifeq ($(filter-out $(_ORGCM_),$(ORGCM)),)
+ $(MAKE) compile-$(ORGCM)
+else
+ $(error ORGCM has illegal value $(ORGCM) (valid: $(_ORGCM_)))
+endif
+
+compile-dirall: dirall
+compile-single: single $(LISPC)
+compile-source: source dirall
+compile-slint1: dirall slint1
+compile-slint2: source dirall slint1
+
+# internal
+dirall:
+ @$(info ==================== $@ ====================)
+ @$(ELCDIR)
+single:
+ @$(info ==================== $@ ====================)
+source: cleanelc
+ @$(info ==================== $@ ====================)
+ @$(foreach elc,$(LISPC),$(MAKE) $(elc) && $(RM) $(elc);)
+slint1:
+ @$(info ==================== $@ ====================)
+ @$(foreach elc,$(LISPC),$(RM) $(elc); $(MAKE) $(elc);)
+
+%.elc: %.el
+ @$(info Compiling single $(abspath $<)...)
+ -@$(ELC) $<
+
+addcontrib:
+ifneq ($(ORG_ADD_CONTRIB),)
+ $(CP) $(addprefix ../contrib/lisp/,$(_ORG_ADD_EL_)) .
+endif
+
+autoloads: cleanauto addcontrib $(LISPI) $(LISPV)
+
+$(LISPV): $(LISPF)
+ @echo "org-version: $(ORGVERSION) ($(GITVERSION))"
+ @$(RM) $(@)
+ @$(MAKE_ORG_VERSION)
+
+$(LISPI): $(LISPV) $(LISPF)
+ @echo "org-loaddefs: $(ORGVERSION) ($(GITVERSION))"
+ @$(RM) $(@)
+ @$(MAKE_ORG_INSTALL)
+
+install: compile $(LISPF)
+ if [ ! -d $(DESTDIR)$(lispdir) ] ; then \
+ $(MKDIR) $(DESTDIR)$(lispdir) ; \
+ fi ;
+ $(CP) $(LISPC) $(LISPF) $(LISPA) $(DESTDIR)$(lispdir)
+
+cleanauto clean cleanall::
+ $(RM) $(LISPA) $(LISPB)
+clean cleanall cleanelc::
+ $(RM) *.elc
+
+clean-install:
+ if [ -d $(DESTDIR)$(lispdir) ] ; then \
+ $(RM) $(DESTDIR)$(lispdir)/org*.el* $(DESTDIR)$(lispdir)/ob*.el* $(DESTDIR)$(lispdir)/ox*.el* ; \
+ fi ;
diff --git a/lisp/ob-C.el b/lisp/ob-C.el
new file mode 100644
index 0000000..2bdda68
--- /dev/null
+++ b/lisp/ob-C.el
@@ -0,0 +1,448 @@
+;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Thierry Banel
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating C, C++, D code.
+;;
+;; very limited implementation:
+;; - currently only support :results output
+;; - not much in the way of error feedback
+
+;;; Code:
+
+(require 'cc-mode)
+(require 'ob)
+
+
+(declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("C++" . "cpp"))
+(add-to-list 'org-babel-tangle-lang-exts '("D" . "d"))
+
+(defvar org-babel-default-header-args:C '())
+
+(defcustom org-babel-C-compiler "gcc"
+ "Command used to compile a C source code file into an executable.
+May be either a command in the path, like gcc
+or an absolute path name, like /usr/local/bin/gcc
+parameter may be used, like gcc -v"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defcustom org-babel-C++-compiler "g++"
+ "Command used to compile a C++ source code file into an executable.
+May be either a command in the path, like g++
+or an absolute path name, like /usr/local/bin/g++
+parameter may be used, like g++ -v"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defcustom org-babel-D-compiler "rdmd"
+ "Command used to compile and execute a D source code file.
+May be either a command in the path, like rdmd
+or an absolute path name, like /usr/local/bin/rdmd
+parameter may be used, like rdmd --chatty"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defvar org-babel-c-variant nil
+ "Internal variable used to hold which type of C (e.g. C or C++ or D)
+is currently being evaluated.")
+
+(defun org-babel-execute:cpp (body params)
+ "Execute BODY according to PARAMS.
+This function calls `org-babel-execute:C++'."
+ (org-babel-execute:C++ body params))
+
+(defun org-babel-expand-body:cpp (body params)
+ "Expand a block of C++ code with org-babel according to its
+header arguments."
+ (org-babel-expand-body:C++ body params))
+
+(defun org-babel-execute:C++ (body params)
+ "Execute a block of C++ code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let ((org-babel-c-variant 'cpp)) (org-babel-C-execute body params)))
+
+(defun org-babel-expand-body:C++ (body params)
+ "Expand a block of C++ code with org-babel according to its
+header arguments."
+ (let ((org-babel-c-variant 'cpp)) (org-babel-C-expand-C++ body params)))
+
+(defun org-babel-execute:D (body params)
+ "Execute a block of D code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let ((org-babel-c-variant 'd)) (org-babel-C-execute body params)))
+
+(defun org-babel-expand-body:D (body params)
+ "Expand a block of D code with org-babel according to its
+header arguments."
+ (let ((org-babel-c-variant 'd)) (org-babel-C-expand-D body params)))
+
+(defun org-babel-execute:C (body params)
+ "Execute a block of C code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let ((org-babel-c-variant 'c)) (org-babel-C-execute body params)))
+
+(defun org-babel-expand-body:C (body params)
+ "Expand a block of C code with org-babel according to its
+header arguments."
+ (let ((org-babel-c-variant 'c)) (org-babel-C-expand-C body params)))
+
+(defun org-babel-C-execute (body params)
+ "This function should only be called by `org-babel-execute:C'
+or `org-babel-execute:C++' or `org-babel-execute:D'."
+ (let* ((tmp-src-file (org-babel-temp-file
+ "C-src-"
+ (pcase org-babel-c-variant
+ (`c ".c") (`cpp ".cpp") (`d ".d"))))
+ (tmp-bin-file ;not used for D
+ (org-babel-process-file-name
+ (org-babel-temp-file "C-bin-" org-babel-exeext)))
+ (cmdline (cdr (assq :cmdline params)))
+ (cmdline (if cmdline (concat " " cmdline) ""))
+ (flags (cdr (assq :flags params)))
+ (flags (mapconcat 'identity
+ (if (listp flags) flags (list flags)) " "))
+ (libs (org-babel-read
+ (or (cdr (assq :libs params))
+ (org-entry-get nil "libs" t))
+ nil))
+ (libs (mapconcat #'identity
+ (if (listp libs) libs (list libs))
+ " "))
+ (full-body
+ (pcase org-babel-c-variant
+ (`c (org-babel-C-expand-C body params))
+ (`cpp (org-babel-C-expand-C++ body params))
+ (`d (org-babel-C-expand-D body params)))))
+ (with-temp-file tmp-src-file (insert full-body))
+ (pcase org-babel-c-variant
+ ((or `c `cpp)
+ (org-babel-eval
+ (format "%s -o %s %s %s %s"
+ (pcase org-babel-c-variant
+ (`c org-babel-C-compiler)
+ (`cpp org-babel-C++-compiler))
+ tmp-bin-file
+ flags
+ (org-babel-process-file-name tmp-src-file)
+ libs)
+ ""))
+ (`d nil)) ;; no separate compilation for D
+ (let ((results
+ (org-babel-eval
+ (pcase org-babel-c-variant
+ ((or `c `cpp)
+ (concat tmp-bin-file cmdline))
+ (`d
+ (format "%s %s %s %s"
+ org-babel-D-compiler
+ flags
+ (org-babel-process-file-name tmp-src-file)
+ cmdline)))
+ "")))
+ (when results
+ (setq results (org-trim (org-remove-indentation results)))
+ (org-babel-reassemble-table
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (org-babel-read results t)
+ (let ((tmp-file (org-babel-temp-file "c-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))
+ )))
+
+(defun org-babel-C-expand-C++ (body params)
+ "Expand a block of C or C++ code with org-babel according to
+its header arguments."
+ (org-babel-C-expand-C body params))
+
+(defun org-babel-C-expand-C (body params)
+ "Expand a block of C or C++ code with org-babel according to
+its header arguments."
+ (let ((vars (org-babel--get-vars params))
+ (colnames (cdr (assq :colname-names params)))
+ (main-p (not (string= (cdr (assq :main params)) "no")))
+ (includes (org-babel-read
+ (or (cdr (assq :includes params))
+ (org-entry-get nil "includes" t))
+ nil))
+ (defines (org-babel-read
+ (or (cdr (assq :defines params))
+ (org-entry-get nil "defines" t))
+ nil)))
+ (when (stringp includes)
+ (setq includes (split-string includes)))
+ (when (stringp defines)
+ (let ((y nil)
+ (result (list t)))
+ (dolist (x (split-string defines))
+ (if (null y)
+ (setq y x)
+ (nconc result (list (concat y " " x)))
+ (setq y nil)))
+ (setq defines (cdr result))))
+ (mapconcat 'identity
+ (list
+ ;; includes
+ (mapconcat
+ (lambda (inc) (format "#include %s" inc))
+ includes "\n")
+ ;; defines
+ (mapconcat
+ (lambda (inc) (format "#define %s" inc))
+ (if (listp defines) defines (list defines)) "\n")
+ ;; variables
+ (mapconcat 'org-babel-C-var-to-C vars "\n")
+ ;; table sizes
+ (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
+ ;; tables headers utility
+ (when colnames
+ (org-babel-C-utility-header-to-C))
+ ;; tables headers
+ (mapconcat 'org-babel-C-header-to-C colnames "\n")
+ ;; body
+ (if main-p
+ (org-babel-C-ensure-main-wrap body)
+ body) "\n") "\n")))
+
+(defun org-babel-C-expand-D (body params)
+ "Expand a block of D code with org-babel according to
+its header arguments."
+ (let ((vars (org-babel--get-vars params))
+ (colnames (cdr (assq :colname-names params)))
+ (main-p (not (string= (cdr (assq :main params)) "no")))
+ (imports (or (cdr (assq :imports params))
+ (org-babel-read (org-entry-get nil "imports" t)))))
+ (when (stringp imports)
+ (setq imports (split-string imports)))
+ (setq imports (append imports '("std.stdio" "std.conv")))
+ (mapconcat 'identity
+ (list
+ "module mmm;"
+ ;; imports
+ (mapconcat
+ (lambda (inc) (format "import %s;" inc))
+ imports "\n")
+ ;; variables
+ (mapconcat 'org-babel-C-var-to-C vars "\n")
+ ;; table sizes
+ (mapconcat 'org-babel-C-table-sizes-to-C vars "\n")
+ ;; tables headers utility
+ (when colnames
+ (org-babel-C-utility-header-to-C))
+ ;; tables headers
+ (mapconcat 'org-babel-C-header-to-C colnames "\n")
+ ;; body
+ (if main-p
+ (org-babel-C-ensure-main-wrap body)
+ body) "\n") "\n")))
+
+(defun org-babel-C-ensure-main-wrap (body)
+ "Wrap BODY in a \"main\" function call if none exists."
+ (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body)
+ body
+ (format "int main() {\n%s\nreturn 0;\n}\n" body)))
+
+(defun org-babel-prep-session:C (_session _params)
+ "This function does nothing as C is a compiled language with no
+support for sessions"
+ (error "C is a compiled language -- no support for sessions"))
+
+(defun org-babel-load-session:C (_session _body _params)
+ "This function does nothing as C is a compiled language with no
+support for sessions"
+ (error "C is a compiled language -- no support for sessions"))
+
+;; helper functions
+
+(defun org-babel-C-format-val (type val)
+ "Handle the FORMAT part of TYPE with the data from VAL."
+ (let ((format-data (cadr type)))
+ (if (stringp format-data)
+ (cons "" (format format-data val))
+ (funcall format-data val))))
+
+(defun org-babel-C-val-to-C-type (val)
+ "Determine the type of VAL.
+Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type.
+FORMAT can be either a format string or a function which is called with VAL."
+ (let* ((basetype (org-babel-C-val-to-base-type val))
+ (type
+ (pcase basetype
+ (`integerp '("int" "%d"))
+ (`floatp '("double" "%f"))
+ (`stringp
+ (list
+ (if (eq org-babel-c-variant 'd) "string" "const char*")
+ "\"%s\""))
+ (_ (error "unknown type %S" basetype)))))
+ (cond
+ ((integerp val) type) ;; an integer declared in the #+begin_src line
+ ((floatp val) type) ;; a numeric declared in the #+begin_src line
+ ((and (listp val) (listp (car val))) ;; a table
+ `(,(car type)
+ (lambda (val)
+ (cons
+ (format "[%d][%d]" (length val) (length (car val)))
+ (concat
+ (if (eq org-babel-c-variant 'd) "[\n" "{\n")
+ (mapconcat
+ (lambda (v)
+ (concat
+ (if (eq org-babel-c-variant 'd) " [" " {")
+ (mapconcat (lambda (w) (format ,(cadr type) w)) v ",")
+ (if (eq org-babel-c-variant 'd) "]" "}")))
+ val
+ ",\n")
+ (if (eq org-babel-c-variant 'd) "\n]" "\n}"))))))
+ ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line
+ `(,(car type)
+ (lambda (val)
+ (cons
+ (format "[%d]" (length val))
+ (concat
+ (if (eq org-babel-c-variant 'd) "[" "{")
+ (mapconcat (lambda (v) (format ,(cadr type) v)) val ",")
+ (if (eq org-babel-c-variant 'd) "]" "}"))))))
+ (t ;; treat unknown types as string
+ type))))
+
+(defun org-babel-C-val-to-base-type (val)
+ "Determine the base type of VAL which may be
+`integerp' if all base values are integers
+`floatp' if all base values are either floating points or integers
+`stringp' otherwise."
+ (cond
+ ((integerp val) 'integerp)
+ ((floatp val) 'floatp)
+ ((or (listp val) (vectorp val))
+ (let ((type nil))
+ (mapc (lambda (v)
+ (pcase (org-babel-C-val-to-base-type v)
+ (`stringp (setq type 'stringp))
+ (`floatp
+ (if (or (not type) (eq type 'integerp))
+ (setq type 'floatp)))
+ (`integerp
+ (unless type (setq type 'integerp)))))
+ val)
+ type))
+ (t 'stringp)))
+
+(defun org-babel-C-var-to-C (pair)
+ "Convert an elisp val into a string of C code specifying a var
+of the same value."
+ ;; TODO list support
+ (let ((var (car pair))
+ (val (cdr pair)))
+ (when (symbolp val)
+ (setq val (symbol-name val))
+ (when (= (length val) 1)
+ (setq val (string-to-char val))))
+ (let* ((type-data (org-babel-C-val-to-C-type val))
+ (type (car type-data))
+ (formated (org-babel-C-format-val type-data val))
+ (suffix (car formated))
+ (data (cdr formated)))
+ (format "%s %s%s = %s;"
+ type
+ var
+ suffix
+ data))))
+
+(defun org-babel-C-table-sizes-to-C (pair)
+ "Create constants of table dimensions, if PAIR is a table."
+ (when (listp (cdr pair))
+ (cond
+ ((listp (cadr pair)) ;; a table
+ (concat
+ (format "const int %s_rows = %d;" (car pair) (length (cdr pair)))
+ "\n"
+ (format "const int %s_cols = %d;" (car pair) (length (cadr pair)))))
+ (t ;; a list declared in the #+begin_src line
+ (format "const int %s_cols = %d;" (car pair) (length (cdr pair)))))))
+
+(defun org-babel-C-utility-header-to-C ()
+ "Generate a utility function to convert a column name
+into a column number."
+ (pcase org-babel-c-variant
+ ((or `c `cpp)
+ "int get_column_num (int nbcols, const char** header, const char* column)
+{
+ int c;
+ for (c=0; c<nbcols; c++)
+ if (strcmp(header[c],column)==0)
+ return c;
+ return -1;
+}
+")
+ (`d
+ "int get_column_num (string[] header, string column)
+{
+ foreach (c, h; header)
+ if (h==column)
+ return to!int(c);
+ return -1;
+}
+")))
+
+(defun org-babel-C-header-to-C (head)
+ "Convert an elisp list of header table into a C or D vector
+specifying a variable with the name of the table."
+ (let ((table (car head))
+ (headers (cdr head)))
+ (concat
+ (format
+ (pcase org-babel-c-variant
+ ((or `c `cpp) "const char* %s_header[%d] = {%s};")
+ (`d "string %s_header[%d] = [%s];"))
+ table
+ (length headers)
+ (mapconcat (lambda (h) (format "%S" h)) headers ","))
+ "\n"
+ (pcase org-babel-c-variant
+ ((or `c `cpp)
+ (format
+ "const char* %s_h (int row, const char* col) { return %s[row][get_column_num(%d,%s_header,col)]; }"
+ table table (length headers) table))
+ (`d
+ (format
+ "string %s_h (size_t row, string col) { return %s[row][get_column_num(%s_header,col)]; }"
+ table table table))))))
+
+(provide 'ob-C)
+
+;;; ob-C.el ends here
diff --git a/lisp/ob-J.el b/lisp/ob-J.el
new file mode 100644
index 0000000..eba4bc6
--- /dev/null
+++ b/lisp/ob-J.el
@@ -0,0 +1,186 @@
+;;; ob-J.el --- Babel Functions for J -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Oleh Krehel
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating J code.
+;;
+;; Session interaction depends on `j-console' from package `j-mode'
+;; (available in MELPA).
+
+;;; Code:
+
+(require 'ob)
+
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function j-console-ensure-session "ext:j-console" ())
+
+(defcustom org-babel-J-command "jconsole"
+ "Command to call J."
+ :group 'org-babel
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type 'string)
+
+(defun org-babel-expand-body:J (body _params &optional _processed-params)
+ "Expand BODY according to PARAMS, return the expanded body.
+PROCESSED-PARAMS isn't used yet."
+ (org-babel-J-interleave-echos-except-functions body))
+
+(defun org-babel-J-interleave-echos (body)
+ "Interleave echo',' between each source line of BODY."
+ (mapconcat #'identity (split-string body "\n") "\necho','\n"))
+
+(defun org-babel-J-interleave-echos-except-functions (body)
+ "Interleave echo',' between source lines of BODY that aren't functions."
+ (if (obj-string-match-m "\\(?:^\\|\n\\)[^\n]*\\(?:0\\|1\\|2\\|3\\|4\\|dyad\\) : 0\n.*\n)\\(?:\n\\|$\\)" body)
+ (let ((s1 (substring body 0 (match-beginning 0)))
+ (s2 (match-string 0 body))
+ (s3 (substring body (match-end 0))))
+ (concat
+ (if (string= s1 "")
+ ""
+ (concat (org-babel-J-interleave-echos s1)
+ "\necho','\n"))
+ s2
+ "\necho','\n"
+ (org-babel-J-interleave-echos-except-functions s3)))
+ (org-babel-J-interleave-echos body)))
+
+(defalias 'org-babel-execute:j 'org-babel-execute:J)
+
+(defun org-babel-execute:J (body params)
+ "Execute a block of J code BODY.
+PARAMS are given by org-babel.
+This function is called by `org-babel-execute-src-block'"
+ (message "executing J source code block")
+ (let* ((processed-params (org-babel-process-params params))
+ (sessionp (cdr (assq :session params)))
+ (full-body (org-babel-expand-body:J
+ body params processed-params))
+ (tmp-script-file (org-babel-temp-file "J-src")))
+ (org-babel-j-initiate-session sessionp)
+ (org-babel-J-strip-whitespace
+ (if (string= sessionp "none")
+ (progn
+ (with-temp-file tmp-script-file
+ (insert full-body))
+ (org-babel-eval (format "%s < %s" org-babel-J-command tmp-script-file) ""))
+ (org-babel-J-eval-string full-body)))))
+
+(defun org-babel-J-eval-string (str)
+ "Sends STR to the `j-console-cmd' session and exectues it."
+ (let ((session (j-console-ensure-session)))
+ (with-current-buffer (process-buffer session)
+ (goto-char (point-max))
+ (insert (format "\n%s\n" str))
+ (let ((beg (point)))
+ (comint-send-input)
+ (sit-for .1)
+ (buffer-substring-no-properties
+ beg (point-max))))))
+
+(defun org-babel-J-strip-whitespace (str)
+ "Remove whitespace from jconsole output STR."
+ (mapconcat
+ #'identity
+ (delete "" (mapcar
+ #'org-babel-J-print-block
+ (split-string str "^ *,\n" t)))
+ "\n\n"))
+
+(defun obj-get-string-alignment (str)
+ "Return a number to describe STR alignment.
+STR represents a table.
+Positive/negative/zero result means right/left/undetermined.
+Don't trust first line."
+ (let* ((str (org-trim str))
+ (lines (split-string str "\n" t))
+ n1 n2)
+ (cond ((<= (length lines) 1)
+ 0)
+ ((= (length lines) 2)
+ ;; numbers are right-aligned
+ (if (and
+ (numberp (read (car lines)))
+ (numberp (read (cadr lines)))
+ (setq n1 (obj-match-second-space-right (nth 0 lines)))
+ (setq n2 (obj-match-second-space-right (nth 1 lines))))
+ n2
+ 0))
+ ((not (obj-match-second-space-left (nth 0 lines)))
+ 0)
+ ((and
+ (setq n1 (obj-match-second-space-left (nth 1 lines)))
+ (setq n2 (obj-match-second-space-left (nth 2 lines)))
+ (= n1 n2))
+ n1)
+ ((and
+ (setq n1 (obj-match-second-space-right (nth 1 lines)))
+ (setq n2 (obj-match-second-space-right (nth 2 lines)))
+ (= n1 n2))
+ (- n1))
+ (t 0))))
+
+(defun org-babel-J-print-block (x)
+ "Prettify jconsole output X."
+ (let* ((x (org-trim x))
+ (a (obj-get-string-alignment x))
+ (lines (split-string x "\n" t))
+ b)
+ (cond ((< a 0)
+ (setq b (obj-match-second-space-right (nth 0 lines)))
+ (concat (make-string (+ a b) ? ) x))
+ ((> a 0)
+ (setq b (obj-match-second-space-left (nth 0 lines)))
+ (concat (make-string (- a b) ? ) x))
+ (t x))))
+
+(defun obj-match-second-space-left (s)
+ "Return position of leftmost space in second space block of S or nil."
+ (and (string-match "^ *[^ ]+\\( \\)" s)
+ (match-beginning 1)))
+
+(defun obj-match-second-space-right (s)
+ "Return position of rightmost space in second space block of S or nil."
+ (and (string-match "^ *[^ ]+ *\\( \\)[^ ]" s)
+ (match-beginning 1)))
+
+(defun obj-string-match-m (regexp string &optional start)
+ "Call (string-match REGEXP STRING START).
+REGEXP is modified so that .* matches newlines as well."
+ (string-match
+ (replace-regexp-in-string "\\.\\*" "[\0-\377[:nonascii:]]*" regexp)
+ string
+ start))
+
+(defun org-babel-j-initiate-session (&optional session)
+ "Initiate a J session.
+SESSION is a parameter given by org-babel."
+ (unless (string= session "none")
+ (require 'j-console)
+ (j-console-ensure-session)))
+
+(provide 'ob-J)
+
+;;; ob-J.el ends here
diff --git a/lisp/ob-R.el b/lisp/ob-R.el
new file mode 100644
index 0000000..3accade
--- /dev/null
+++ b/lisp/ob-R.el
@@ -0,0 +1,469 @@
+;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research, R, statistics
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating R code
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ob)
+
+(declare-function orgtbl-to-tsv "org-table" (table params))
+(declare-function R "ext:essd-r" (&optional start-args))
+(declare-function inferior-ess-send-input "ext:ess-inf" ())
+(declare-function ess-make-buffer-current "ext:ess-inf" ())
+(declare-function ess-eval-buffer "ext:ess-inf" (vis))
+(declare-function ess-wait-for-process "ext:ess-inf"
+ (&optional proc sec-prompt wait force-redisplay))
+
+(defconst org-babel-header-args:R
+ '((width . :any)
+ (height . :any)
+ (bg . :any)
+ (units . :any)
+ (pointsize . :any)
+ (antialias . :any)
+ (quality . :any)
+ (compression . :any)
+ (res . :any)
+ (type . :any)
+ (family . :any)
+ (title . :any)
+ (fonts . :any)
+ (version . :any)
+ (paper . :any)
+ (encoding . :any)
+ (pagecentre . :any)
+ (colormodel . :any)
+ (useDingbats . :any)
+ (horizontal . :any)
+ (results . ((file list vector table scalar verbatim)
+ (raw html latex org code pp drawer)
+ (replace silent none append prepend)
+ (output value graphics))))
+ "R-specific header arguments.")
+
+(defconst ob-R-safe-header-args
+ (append org-babel-safe-header-args
+ '(:width :height :bg :units :pointsize :antialias :quality
+ :compression :res :type :family :title :fonts
+ :version :paper :encoding :pagecentre :colormodel
+ :useDingbats :horizontal))
+ "Header args which are safe for R babel blocks.
+
+See `org-babel-safe-header-args' for documentation of the format of
+this variable.")
+
+(defvar org-babel-default-header-args:R '())
+(put 'org-babel-default-header-args:R 'safe-local-variable
+ (org-babel-header-args-safe-fn ob-R-safe-header-args))
+
+(defcustom org-babel-R-command "R --slave --no-save"
+ "Name of command to use for executing R code."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defvar ess-current-process-name) ; dynamically scoped
+(defvar ess-local-process-name) ; dynamically scoped
+(defun org-babel-edit-prep:R (info)
+ (let ((session (cdr (assq :session (nth 2 info)))))
+ (when (and session
+ (string-prefix-p "*" session)
+ (string-suffix-p "*" session))
+ (org-babel-R-initiate-session session nil))))
+
+;; The usage of utils::read.table() ensures that the command
+;; read.table() can be found even in circumstances when the utils
+;; package is not in the search path from R.
+(defconst ob-R-transfer-variable-table-with-header
+ "%s <- local({
+ con <- textConnection(
+ %S
+ )
+ res <- utils::read.table(
+ con,
+ header = %s,
+ row.names = %s,
+ sep = \"\\t\",
+ as.is = TRUE
+ )
+ close(con)
+ res
+ })"
+ "R code used to transfer a table defined as a variable from org to R.
+
+This function is used when the table contains a header.")
+
+(defconst ob-R-transfer-variable-table-without-header
+ "%s <- local({
+ con <- textConnection(
+ %S
+ )
+ res <- utils::read.table(
+ con,
+ header = %s,
+ row.names = %s,
+ sep = \"\\t\",
+ as.is = TRUE,
+ fill = TRUE,
+ col.names = paste(\"V\", seq_len(%d), sep =\"\")
+ )
+ close(con)
+ res
+ })"
+ "R code used to transfer a table defined as a variable from org to R.
+
+This function is used when the table does not contain a header.")
+
+(defun org-babel-expand-body:R (body params &optional _graphics-file)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (mapconcat 'identity
+ (append
+ (when (cdr (assq :prologue params))
+ (list (cdr (assq :prologue params))))
+ (org-babel-variable-assignments:R params)
+ (list body)
+ (when (cdr (assq :epilogue params))
+ (list (cdr (assq :epilogue params)))))
+ "\n"))
+
+(defun org-babel-execute:R (body params)
+ "Execute a block of R code.
+This function is called by `org-babel-execute-src-block'."
+ (save-excursion
+ (let* ((result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (session (org-babel-R-initiate-session
+ (cdr (assq :session params)) params))
+ (colnames-p (cdr (assq :colnames params)))
+ (rownames-p (cdr (assq :rownames params)))
+ (graphics-file (and (member "graphics" (assq :result-params params))
+ (org-babel-graphical-output-file params)))
+ (full-body
+ (let ((inside
+ (list (org-babel-expand-body:R body params graphics-file))))
+ (mapconcat 'identity
+ (if graphics-file
+ (append
+ (list (org-babel-R-construct-graphics-device-call
+ graphics-file params))
+ inside
+ (list "},error=function(e){plot(x=-1:1, y=-1:1, type='n', xlab='', ylab='', axes=FALSE); text(x=0, y=0, labels=e$message, col='red'); paste('ERROR', e$message, sep=' : ')}); dev.off()"))
+ inside)
+ "\n")))
+ (result
+ (org-babel-R-evaluate
+ session full-body result-type result-params
+ (or (equal "yes" colnames-p)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) colnames-p))
+ (or (equal "yes" rownames-p)
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) rownames-p)))))
+ (if graphics-file nil result))))
+
+(defun org-babel-prep-session:R (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-R-initiate-session session params))
+ (var-lines (org-babel-variable-assignments:R params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:R (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:R session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:R (params)
+ "Return list of R statements assigning the block's variables."
+ (let ((vars (org-babel--get-vars params)))
+ (mapcar
+ (lambda (pair)
+ (org-babel-R-assign-elisp
+ (car pair) (cdr pair)
+ (equal "yes" (cdr (assq :colnames params)))
+ (equal "yes" (cdr (assq :rownames params)))))
+ (mapcar
+ (lambda (i)
+ (cons (car (nth i vars))
+ (org-babel-reassemble-table
+ (cdr (nth i vars))
+ (cdr (nth i (cdr (assq :colname-names params))))
+ (cdr (nth i (cdr (assq :rowname-names params)))))))
+ (number-sequence 0 (1- (length vars)))))))
+
+(defun org-babel-R-quote-tsv-field (s)
+ "Quote field S for export to R."
+ (if (stringp s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
+ (format "%S" s)))
+
+(defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
+ "Construct R code assigning the elisp VALUE to a variable named NAME."
+ (if (listp value)
+ (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value)))
+ (max (if lengths (apply 'max lengths) 0))
+ (min (if lengths (apply 'min lengths) 0)))
+ ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
+ (unless (listp (car value)) (setq value (list value)))
+ (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
+ (header (if (or (eq (nth 1 value) 'hline) colnames-p)
+ "TRUE" "FALSE"))
+ (row-names (if rownames-p "1" "NULL")))
+ (if (= max min)
+ (format ob-R-transfer-variable-table-with-header
+ name file header row-names)
+ (format ob-R-transfer-variable-table-without-header
+ name file header row-names max))))
+ (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
+ ((floatp value) (format "%s <- %s" name value))
+ ((stringp value) (format "%s <- %S" name (org-no-properties value)))
+ (t (format "%s <- %S" name (prin1-to-string value))))))
+
+
+(defvar ess-ask-for-ess-directory) ; dynamically scoped
+(defun org-babel-R-initiate-session (session params)
+ "If there is not a current R process then create one."
+ (unless (string= session "none")
+ (let ((session (or session "*R*"))
+ (ess-ask-for-ess-directory
+ (and (boundp 'ess-ask-for-ess-directory)
+ ess-ask-for-ess-directory
+ (not (cdr (assq :dir params))))))
+ (if (org-babel-comint-buffer-livep session)
+ session
+ (save-window-excursion
+ (when (get-buffer session)
+ ;; Session buffer exists, but with dead process
+ (set-buffer session))
+ (require 'ess) (R)
+ (let ((R-proc (get-process (or ess-local-process-name
+ ess-current-process-name))))
+ (while (process-get R-proc 'callbacks)
+ (ess-wait-for-process R-proc)))
+ (rename-buffer
+ (if (bufferp session)
+ (buffer-name session)
+ (if (stringp session)
+ session
+ (buffer-name))))
+ (current-buffer))))))
+
+(defun org-babel-R-associate-session (session)
+ "Associate R code buffer with an R session.
+Make SESSION be the inferior ESS process associated with the
+current code buffer."
+ (setq ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-make-buffer-current))
+
+(defvar org-babel-R-graphics-devices
+ '((:bmp "bmp" "filename")
+ (:jpg "jpeg" "filename")
+ (:jpeg "jpeg" "filename")
+ (:tikz "tikz" "file")
+ (:tiff "tiff" "filename")
+ (:png "png" "filename")
+ (:svg "svg" "file")
+ (:pdf "pdf" "file")
+ (:ps "postscript" "file")
+ (:postscript "postscript" "file"))
+ "An alist mapping graphics file types to R functions.
+
+Each member of this list is a list with three members:
+1. the file extension of the graphics file, as an elisp :keyword
+2. the R graphics device function to call to generate such a file
+3. the name of the argument to this function which specifies the
+ file to write to (typically \"file\" or \"filename\")")
+
+(defun org-babel-R-construct-graphics-device-call (out-file params)
+ "Construct the call to the graphics device."
+ (let* ((allowed-args '(:width :height :bg :units :pointsize
+ :antialias :quality :compression :res
+ :type :family :title :fonts :version
+ :paper :encoding :pagecentre :colormodel
+ :useDingbats :horizontal))
+ (device (file-name-extension out-file))
+ (device-info (or (assq (intern (concat ":" device))
+ org-babel-R-graphics-devices)
+ (assq :png org-babel-R-graphics-devices)))
+ (extra-args (cdr (assq :R-dev-args params))) filearg args)
+ (setq device (nth 1 device-info))
+ (setq filearg (nth 2 device-info))
+ (setq args (mapconcat
+ (lambda (pair)
+ (if (member (car pair) allowed-args)
+ (format ",%s=%S"
+ (substring (symbol-name (car pair)) 1)
+ (cdr pair)) ""))
+ params ""))
+ (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
+ device filearg out-file args
+ (if extra-args "," "") (or extra-args ""))))
+
+(defconst org-babel-R-eoe-indicator "'org_babel_R_eoe'")
+(defconst org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
+
+(defconst org-babel-R-write-object-command "{
+ function(object,transfer.file) {
+ object
+ invisible(
+ if (
+ inherits(
+ try(
+ {
+ tfile<-tempfile()
+ write.table(object, file=tfile, sep=\"\\t\",
+ na=\"nil\",row.names=%s,col.names=%s,
+ quote=FALSE)
+ file.rename(tfile,transfer.file)
+ },
+ silent=TRUE),
+ \"try-error\"))
+ {
+ if(!file.exists(transfer.file))
+ file.create(transfer.file)
+ }
+ )
+ }
+}(object=%s,transfer.file=\"%s\")"
+ "A template for an R command to evaluate a block of code and write the result to a file.
+
+Has four %s escapes to be filled in:
+1. Row names, \"TRUE\" or \"FALSE\"
+2. Column names, \"TRUE\" or \"FALSE\"
+3. The code to be run (must be an expression, not a statement)
+4. The name of the file to write to")
+
+(defun org-babel-R-evaluate
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate R code in BODY."
+ (if session
+ (org-babel-R-evaluate-session
+ session body result-type result-params column-names-p row-names-p)
+ (org-babel-R-evaluate-external-process
+ body result-type result-params column-names-p row-names-p)))
+
+(defun org-babel-R-evaluate-external-process
+ (body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in external R process.
+If RESULT-TYPE equals `output' then return standard output as a
+string. If RESULT-TYPE equals `value' then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (let ((tmp-file (org-babel-temp-file "R-")))
+ (org-babel-eval org-babel-R-command
+ (format org-babel-R-write-object-command
+ (if row-names-p "TRUE" "FALSE")
+ (if column-names-p
+ (if row-names-p "NA" "TRUE")
+ "FALSE")
+ (format "{function ()\n{\n%s\n}}()" body)
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (org-babel-R-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (org-babel-chomp (buffer-string) "\n"))
+ (org-babel-import-elisp-from-file tmp-file '(16)))
+ column-names-p)))
+ (output (org-babel-eval org-babel-R-command body))))
+
+(defvar ess-eval-visibly-p)
+
+(defun org-babel-R-evaluate-session
+ (session body result-type result-params column-names-p row-names-p)
+ "Evaluate BODY in SESSION.
+If RESULT-TYPE equals `output' then return standard output as a
+string. If RESULT-TYPE equals `value' then return the value of the
+last statement in BODY, as elisp."
+ (cl-case result-type
+ (value
+ (with-temp-buffer
+ (insert (org-babel-chomp body))
+ (let ((ess-local-process-name
+ (process-name (get-buffer-process session)))
+ (ess-eval-visibly-p nil))
+ (ess-eval-buffer nil)))
+ (let ((tmp-file (org-babel-temp-file "R-")))
+ (org-babel-comint-eval-invisibly-and-wait-for-file
+ session tmp-file
+ (format org-babel-R-write-object-command
+ (if row-names-p "TRUE" "FALSE")
+ (if column-names-p
+ (if row-names-p "NA" "TRUE")
+ "FALSE")
+ ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
+ (org-babel-R-process-value-result
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (insert-file-contents tmp-file)
+ (org-babel-chomp (buffer-string) "\n"))
+ (org-babel-import-elisp-from-file tmp-file '(16)))
+ column-names-p)))
+ (output
+ (mapconcat
+ 'org-babel-chomp
+ (butlast
+ (delq nil
+ (mapcar
+ (lambda (line) (when (> (length line) 0) line))
+ (mapcar
+ (lambda (line) ;; cleanup extra prompts left in output
+ (if (string-match
+ "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)"
+ (car (split-string line "\n")))
+ (substring line (match-end 1))
+ line))
+ (org-babel-comint-with-output (session org-babel-R-eoe-output)
+ (insert (mapconcat 'org-babel-chomp
+ (list body org-babel-R-eoe-indicator)
+ "\n"))
+ (inferior-ess-send-input)))))) "\n"))))
+
+(defun org-babel-R-process-value-result (result column-names-p)
+ "R-specific processing of return value.
+Insert hline if column names in output have been requested."
+ (if column-names-p
+ (cons (car result) (cons 'hline (cdr result)))
+ result))
+
+(provide 'ob-R)
+
+
+
+;;; ob-R.el ends here
diff --git a/lisp/ob-abc.el b/lisp/ob-abc.el
new file mode 100644
index 0000000..0ce503d
--- /dev/null
+++ b/lisp/ob-abc.el
@@ -0,0 +1,92 @@
+;;; ob-abc.el --- Org Babel Functions for ABC -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: William Waites
+;; Keywords: literate programming, music
+;; Homepage: http://www.tardis.ed.ac.uk/wwaites
+;; Version: 0.01
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;;; This file adds support to Org Babel for music in ABC notation.
+;;; It requires that the abcm2ps program is installed.
+;;; See http://moinejf.free.fr/
+
+(require 'ob)
+
+;; optionally define a file extension for this language
+(add-to-list 'org-babel-tangle-lang-exts '("abc" . "abc"))
+
+;; optionally declare default header arguments for this language
+(defvar org-babel-default-header-args:abc
+ '((:results . "file") (:exports . "results"))
+ "Default arguments to use when evaluating an ABC source block.")
+
+(defun org-babel-expand-body:abc (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (mapc
+ (lambda (pair)
+ (let ((name (symbol-name (car pair)))
+ (value (cdr pair)))
+ (setq body
+ (replace-regexp-in-string
+ (concat "\$" (regexp-quote name))
+ (if (stringp value) value (format "%S" value))
+ body))))
+ vars)
+ body))
+
+(defun org-babel-execute:abc (body params)
+ "Execute a block of ABC code with org-babel. This function is
+ called by `org-babel-execute-src-block'"
+ (message "executing Abc source code block")
+ (let* ((cmdline (cdr (assq :cmdline params)))
+ (out-file (let ((file (cdr (assq :file params))))
+ (if file (replace-regexp-in-string "\.pdf$" ".ps" file)
+ (error "abc code block requires :file header argument"))))
+ (in-file (org-babel-temp-file "abc-"))
+ (render (concat "abcm2ps" " " cmdline
+ " -O " (org-babel-process-file-name out-file)
+ " " (org-babel-process-file-name in-file))))
+ (with-temp-file in-file (insert (org-babel-expand-body:abc body params)))
+ (org-babel-eval render "")
+ ;;; handle where abcm2ps changes the file name (to support multiple files
+ (when (or (string= (file-name-extension out-file) "eps")
+ (string= (file-name-extension out-file) "svg"))
+ (rename-file (concat
+ (file-name-sans-extension out-file) "001."
+ (file-name-extension out-file))
+ out-file t))
+ ;;; if we were asked for a pdf...
+ (when (string= (file-name-extension (cdr (assq :file params))) "pdf")
+ (org-babel-eval (concat "ps2pdf" " " out-file " " (cdr (assq :file params))) ""))
+ ;;; indicate that the file has been written
+ nil))
+
+;; This function should be used to assign any variables in params in
+;; the context of the session environment.
+(defun org-babel-prep-session:abc (_session _params)
+ "Return an error because abc does not support sessions."
+ (error "ABC does not support sessions"))
+
+(provide 'ob-abc)
+;;; ob-abc.el ends here
diff --git a/lisp/ob-asymptote.el b/lisp/ob-asymptote.el
new file mode 100644
index 0000000..1dbf484
--- /dev/null
+++ b/lisp/ob-asymptote.el
@@ -0,0 +1,139 @@
+;;; ob-asymptote.el --- Babel Functions for Asymptote -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating asymptote source code.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in asymptote
+;;
+;; 2) we are generally only going to return results of type "file"
+;;
+;; 3) we are adding the "file" and "cmdline" header arguments, if file
+;; is omitted then the -V option is passed to the asy command for
+;; interactive viewing
+
+;;; Requirements:
+
+;; - The asymptote program :: http://asymptote.sourceforge.net/
+;;
+;; - asy-mode :: Major mode for editing asymptote files
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("asymptote" . "asy"))
+
+(defvar org-babel-default-header-args:asymptote
+ '((:results . "file") (:exports . "results"))
+ "Default arguments when evaluating an Asymptote source block.")
+
+(defun org-babel-execute:asymptote (body params)
+ "Execute a block of Asymptote code.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((out-file (cdr (assq :file params)))
+ (format (or (file-name-extension out-file)
+ "pdf"))
+ (cmdline (cdr (assq :cmdline params)))
+ (in-file (org-babel-temp-file "asymptote-"))
+ (cmd
+ (concat "asy "
+ (if out-file
+ (concat
+ "-globalwrite -f " format
+ " -o " (org-babel-process-file-name out-file))
+ "-V")
+ " " cmdline
+ " " (org-babel-process-file-name in-file))))
+ (with-temp-file in-file
+ (insert (org-babel-expand-body:generic
+ body params
+ (org-babel-variable-assignments:asymptote params))))
+ (message cmd) (shell-command cmd)
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:asymptote (_session _params)
+ "Return an error if the :session header argument is set.
+Asymptote does not support sessions"
+ (error "Asymptote does not support sessions"))
+
+(defun org-babel-variable-assignments:asymptote (params)
+ "Return list of asymptote statements assigning the block's variables."
+ (mapcar #'org-babel-asymptote-var-to-asymptote
+ (org-babel--get-vars params)))
+
+(defun org-babel-asymptote-var-to-asymptote (pair)
+ "Convert an elisp value into an Asymptote variable.
+The elisp value PAIR is converted into Asymptote code specifying
+a variable of the same value."
+ (let ((var (car pair))
+ (val (let ((v (cdr pair)))
+ (if (symbolp v) (symbol-name v) v))))
+ (cond
+ ((integerp val)
+ (format "int %S=%S;" var val))
+ ((floatp val)
+ (format "real %S=%S;" var val))
+ ((stringp val)
+ (format "string %S=\"%s\";" var val))
+ ((and (listp val) (not (listp (car val))))
+ (let* ((type (org-babel-asymptote-define-type val))
+ (fmt (if (eq 'string type) "\"%s\"" "%s"))
+ (vect (mapconcat (lambda (e) (format fmt e)) val ", ")))
+ (format "%s[] %S={%s};" type var vect)))
+ ((listp val)
+ (let* ((type (org-babel-asymptote-define-type val))
+ (fmt (if (eq 'string type) "\"%s\"" "%s"))
+ (array (mapconcat (lambda (row)
+ (concat "{"
+ (mapconcat (lambda (e) (format fmt e))
+ row ", ")
+ "}"))
+ val ",")))
+ (format "%S[][] %S={%s};" type var array))))))
+
+(defun org-babel-asymptote-define-type (data)
+ "Determine type of DATA.
+
+DATA is a list. Return type as a symbol.
+
+The type is `string' if any element in DATA is a string.
+Otherwise, it is either `real', if some elements are floats, or
+`int'."
+ (letrec ((type 'int)
+ (find-type
+ (lambda (row)
+ (dolist (e row type)
+ (cond ((listp e) (setq type (funcall find-type e)))
+ ((stringp e) (throw 'exit 'string))
+ ((floatp e) (setq type 'real)))))))
+ (catch 'exit (funcall find-type data)) type))
+
+(provide 'ob-asymptote)
+
+
+
+;;; ob-asymptote.el ends here
diff --git a/lisp/ob-awk.el b/lisp/ob-awk.el
new file mode 100644
index 0000000..2db4eea
--- /dev/null
+++ b/lisp/ob-awk.el
@@ -0,0 +1,111 @@
+;;; ob-awk.el --- Babel Functions for Awk -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Babel's awk can use special header argument:
+;;
+;; - :in-file takes a path to a file of data to be processed by awk
+;;
+;; - :stdin takes an Org data or code block reference, the value of
+;; which will be passed to the awk process through STDIN
+
+;;; Code:
+(require 'ob)
+(require 'org-compat)
+
+(declare-function org-babel-ref-resolve "ob-ref" (ref))
+(declare-function orgtbl-to-generic "org-table" (table params))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("awk" . "awk"))
+
+(defvar org-babel-awk-command "awk"
+ "Name of the awk executable command.")
+
+(defun org-babel-expand-body:awk (body _params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ body)
+
+(defun org-babel-execute:awk (body params)
+ "Execute a block of Awk code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (message "executing Awk source code block")
+ (let* ((result-params (cdr (assq :result-params params)))
+ (cmd-line (cdr (assq :cmd-line params)))
+ (in-file (cdr (assq :in-file params)))
+ (full-body (org-babel-expand-body:awk body params))
+ (code-file (let ((file (org-babel-temp-file "awk-")))
+ (with-temp-file file (insert full-body)) file))
+ (stdin (let ((stdin (cdr (assq :stdin params))))
+ (when stdin
+ (let ((tmp (org-babel-temp-file "awk-stdin-"))
+ (res (org-babel-ref-resolve stdin)))
+ (with-temp-file tmp
+ (insert (org-babel-awk-var-to-awk res)))
+ tmp))))
+ (cmd (mapconcat #'identity
+ (append
+ (list org-babel-awk-command
+ "-f" code-file cmd-line)
+ (mapcar (lambda (pair)
+ (format "-v %s='%s'"
+ (car pair)
+ (org-babel-awk-var-to-awk
+ (cdr pair))))
+ (org-babel--get-vars params))
+ (list in-file))
+ " ")))
+ (org-babel-reassemble-table
+ (let ((results
+ (cond
+ (stdin (with-temp-buffer
+ (call-process-shell-command cmd stdin (current-buffer))
+ (buffer-string)))
+ (t (org-babel-eval cmd "")))))
+ (when results
+ (org-babel-result-cond result-params
+ results
+ (let ((tmp (org-babel-temp-file "awk-results-")))
+ (with-temp-file tmp (insert results))
+ (org-babel-import-elisp-from-file tmp)))))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defun org-babel-awk-var-to-awk (var &optional sep)
+ "Return a printed value of VAR suitable for parsing with awk."
+ (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
+ (cond
+ ((and (listp var) (listp (car var)))
+ (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var)))
+ ((listp var)
+ (mapconcat echo-var var "\n"))
+ (t (funcall echo-var var)))))
+
+(provide 'ob-awk)
+
+
+
+;;; ob-awk.el ends here
diff --git a/lisp/ob-calc.el b/lisp/ob-calc.el
new file mode 100644
index 0000000..d4b7260
--- /dev/null
+++ b/lisp/ob-calc.el
@@ -0,0 +1,110 @@
+;;; ob-calc.el --- Babel Functions for Calc -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating calc code
+
+;;; Code:
+(require 'ob)
+(require 'calc)
+(require 'calc-trail)
+(require 'calc-store)
+
+(declare-function calc-store-into "calc-store" (&optional var))
+(declare-function calc-recall "calc-store" (&optional var))
+(declare-function math-evaluate-expr "calc-ext" (x))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-default-header-args:calc nil
+ "Default arguments for evaluating an calc source block.")
+
+(defun org-babel-expand-body:calc (body _params)
+ "Expand BODY according to PARAMS, return the expanded body." body)
+
+(defvar org--var-syms) ; Dynamically scoped from org-babel-execute:calc
+
+(defun org-babel-execute:calc (body params)
+ "Execute a block of calc code with Babel."
+ (unless (get-buffer "*Calculator*")
+ (save-window-excursion (calc) (calc-quit)))
+ (let* ((vars (org-babel--get-vars params))
+ (org--var-syms (mapcar #'car vars))
+ (var-names (mapcar #'symbol-name org--var-syms)))
+ (mapc
+ (lambda (pair)
+ (calc-push-list (list (cdr pair)))
+ (calc-store-into (car pair)))
+ vars)
+ (mapc
+ (lambda (line)
+ (when (> (length line) 0)
+ (cond
+ ;; simple variable name
+ ((member line var-names) (calc-recall (intern line)))
+ ;; stack operation
+ ((string= "'" (substring line 0 1))
+ (funcall (lookup-key calc-mode-map (substring line 1)) nil))
+ ;; complex expression
+ (t
+ (calc-push-list
+ (list (let ((res (calc-eval line)))
+ (cond
+ ((numberp res) res)
+ ((math-read-number res) (math-read-number res))
+ ((listp res) (error "Calc error \"%s\" on input \"%s\""
+ (cadr res) line))
+ (t (replace-regexp-in-string
+ "'" ""
+ (calc-eval
+ (math-evaluate-expr
+ ;; resolve user variables, calc built in
+ ;; variables are handled automatically
+ ;; upstream by calc
+ (mapcar #'org-babel-calc-maybe-resolve-var
+ ;; parse line into calc objects
+ (car (math-read-exprs line)))))))))
+ ))))))
+ (mapcar #'org-trim
+ (split-string (org-babel-expand-body:calc body params) "[\n\r]"))))
+ (save-excursion
+ (with-current-buffer (get-buffer "*Calculator*")
+ (prog1
+ (calc-eval (calc-top 1))
+ (calc-pop 1)))))
+
+(defun org-babel-calc-maybe-resolve-var (el)
+ (if (consp el)
+ (if (and (eq 'var (car el)) (member (cadr el) org--var-syms))
+ (progn
+ (calc-recall (cadr el))
+ (prog1 (calc-top 1)
+ (calc-pop 1)))
+ (mapcar #'org-babel-calc-maybe-resolve-var el))
+ el))
+
+(provide 'ob-calc)
+
+
+
+;;; ob-calc.el ends here
diff --git a/lisp/ob-clojure.el b/lisp/ob-clojure.el
new file mode 100644
index 0000000..3956157
--- /dev/null
+++ b/lisp/ob-clojure.el
@@ -0,0 +1,118 @@
+;;; ob-clojure.el --- Babel Functions for Clojure -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Joel Boehland, Eric Schulte, Oleh Krehel
+;;
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Support for evaluating clojure code
+
+;; Requirements:
+
+;; - clojure (at least 1.2.0)
+;; - clojure-mode
+;; - either cider or SLIME
+
+;; For Cider, see https://github.com/clojure-emacs/cider
+
+;; For SLIME, the best way to install these components is by following
+;; the directions as set out by Phil Hagelberg (Technomancy) on the
+;; web page: http://technomancy.us/126
+
+;;; Code:
+(require 'cl-lib)
+(require 'ob)
+
+(declare-function cider-current-connection "ext:cider-client" (&optional type))
+(declare-function cider-current-session "ext:cider-client" ())
+(declare-function nrepl-dict-get "ext:nrepl-client" (dict key))
+(declare-function nrepl-sync-request:eval "ext:nrepl-client"
+ (input connection session &optional ns))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function slime-eval "ext:slime" (sexp &optional package))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("clojure" . "clj"))
+
+(defvar org-babel-default-header-args:clojure '())
+(defvar org-babel-header-args:clojure '((package . :any)))
+
+(defcustom org-babel-clojure-backend
+ (cond ((featurep 'cider) 'cider)
+ (t 'slime))
+ "Backend used to evaluate Clojure code blocks."
+ :group 'org-babel
+ :type '(choice
+ (const :tag "cider" cider)
+ (const :tag "SLIME" slime)))
+
+(defun org-babel-expand-body:clojure (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let* ((vars (org-babel--get-vars params))
+ (result-params (cdr (assq :result-params params)))
+ (print-level nil) (print-length nil)
+ (body (org-trim
+ (if (null vars) (org-trim body)
+ (concat "(let ["
+ (mapconcat
+ (lambda (var)
+ (format "%S (quote %S)" (car var) (cdr var)))
+ vars "\n ")
+ "]\n" body ")")))))
+ (if (or (member "code" result-params)
+ (member "pp" result-params))
+ (format "(clojure.pprint/pprint (do %s))" body)
+ body)))
+
+(defun org-babel-execute:clojure (body params)
+ "Execute a block of Clojure code with Babel."
+ (let ((expanded (org-babel-expand-body:clojure body params))
+ result)
+ (cl-case org-babel-clojure-backend
+ (cider
+ (require 'cider)
+ (let ((result-params (cdr (assq :result-params params))))
+ (setq result
+ (nrepl-dict-get
+ (nrepl-sync-request:eval
+ expanded (cider-current-connection) (cider-current-session))
+ (if (or (member "output" result-params)
+ (member "pp" result-params))
+ "out"
+ "value")))))
+ (slime
+ (require 'slime)
+ (with-temp-buffer
+ (insert expanded)
+ (setq result
+ (slime-eval
+ `(swank:eval-and-grab-output
+ ,(buffer-substring-no-properties (point-min) (point-max)))
+ (cdr (assq :package params)))))))
+ (org-babel-result-cond (cdr (assq :result-params params))
+ result
+ (condition-case nil (org-babel-script-escape result)
+ (error result)))))
+
+(provide 'ob-clojure)
+
+;;; ob-clojure.el ends here
diff --git a/lisp/ob-comint.el b/lisp/ob-comint.el
new file mode 100644
index 0000000..cc60f4e
--- /dev/null
+++ b/lisp/ob-comint.el
@@ -0,0 +1,161 @@
+;;; ob-comint.el --- Babel Functions for Interaction with Comint Buffers -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research, comint
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; These functions build on comint to ease the sending and receiving
+;; of commands and results from comint buffers.
+
+;; Note that the buffers in this file are analogous to sessions in
+;; org-babel at large.
+
+;;; Code:
+(require 'ob-core)
+(require 'org-compat)
+(require 'comint)
+(require 'tramp)
+
+(defun org-babel-comint-buffer-livep (buffer)
+ "Check if BUFFER is a comint buffer with a live process."
+ (let ((buffer (if buffer (get-buffer buffer))))
+ (and buffer (buffer-live-p buffer) (get-buffer-process buffer) buffer)))
+
+(defmacro org-babel-comint-in-buffer (buffer &rest body)
+ "Check BUFFER and execute BODY.
+BUFFER is checked with `org-babel-comint-buffer-livep'. BODY is
+executed inside the protection of `save-excursion' and
+`save-match-data'."
+ (declare (indent 1))
+ `(progn
+ (unless (org-babel-comint-buffer-livep ,buffer)
+ (error "Buffer %s does not exist or has no process" ,buffer))
+ (save-match-data
+ (with-current-buffer ,buffer
+ (save-excursion
+ (let ((comint-input-filter (lambda (_input) nil)))
+ ,@body))))))
+(def-edebug-spec org-babel-comint-in-buffer (form body))
+
+(defmacro org-babel-comint-with-output (meta &rest body)
+ "Evaluate BODY in BUFFER and return process output.
+Will wait until EOE-INDICATOR appears in the output, then return
+all process output. If REMOVE-ECHO and FULL-BODY are present and
+non-nil, then strip echo'd body from the returned output. META
+should be a list containing the following where the last two
+elements are optional.
+
+ (BUFFER EOE-INDICATOR REMOVE-ECHO FULL-BODY)
+
+This macro ensures that the filter is removed in case of an error
+or user `keyboard-quit' during execution of body."
+ (declare (indent 1))
+ (let ((buffer (nth 0 meta))
+ (eoe-indicator (nth 1 meta))
+ (remove-echo (nth 2 meta))
+ (full-body (nth 3 meta)))
+ `(org-babel-comint-in-buffer ,buffer
+ (let* ((string-buffer "")
+ (comint-output-filter-functions
+ (cons (lambda (text) (setq string-buffer (concat string-buffer text)))
+ comint-output-filter-functions))
+ dangling-text)
+ ;; got located, and save dangling text
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (let ((start (point))
+ (end (point-max)))
+ (setq dangling-text (buffer-substring start end))
+ (delete-region start end))
+ ;; pass FULL-BODY to process
+ ,@body
+ ;; wait for end-of-evaluation indicator
+ (while (progn
+ (goto-char comint-last-input-end)
+ (not (save-excursion
+ (and (re-search-forward
+ (regexp-quote ,eoe-indicator) nil t)
+ (re-search-forward
+ comint-prompt-regexp nil t)))))
+ (accept-process-output (get-buffer-process (current-buffer)))
+ ;; thought the following this would allow async
+ ;; background running, but I was wrong...
+ ;; (run-with-timer .5 .5 'accept-process-output
+ ;; (get-buffer-process (current-buffer)))
+ )
+ ;; replace cut dangling text
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert dangling-text)
+
+ ;; remove echo'd FULL-BODY from input
+ (when (and ,remove-echo ,full-body
+ (string-match
+ (replace-regexp-in-string
+ "\n" "[\r\n]+" (regexp-quote (or ,full-body "")))
+ string-buffer))
+ (setq string-buffer (substring string-buffer (match-end 0))))
+ (split-string string-buffer comint-prompt-regexp)))))
+(def-edebug-spec org-babel-comint-with-output (sexp body))
+
+(defun org-babel-comint-input-command (buffer cmd)
+ "Pass CMD to BUFFER.
+The input will not be echoed."
+ (org-babel-comint-in-buffer buffer
+ (goto-char (process-mark (get-buffer-process buffer)))
+ (insert cmd)
+ (comint-send-input)
+ (org-babel-comint-wait-for-output buffer)))
+
+(defun org-babel-comint-wait-for-output (buffer)
+ "Wait until output arrives from BUFFER.
+Note: this is only safe when waiting for the result of a single
+statement (not large blocks of code)."
+ (org-babel-comint-in-buffer buffer
+ (while (progn
+ (goto-char comint-last-input-end)
+ (not (and (re-search-forward comint-prompt-regexp nil t)
+ (goto-char (match-beginning 0))
+ (string= (face-name (face-at-point))
+ "comint-highlight-prompt"))))
+ (accept-process-output (get-buffer-process buffer)))))
+
+(defun org-babel-comint-eval-invisibly-and-wait-for-file
+ (buffer file string &optional period)
+ "Evaluate STRING in BUFFER invisibly.
+Don't return until FILE exists. Code in STRING must ensure that
+FILE exists at end of evaluation."
+ (unless (org-babel-comint-buffer-livep buffer)
+ (error "Buffer %s does not exist or has no process" buffer))
+ (when (file-exists-p file) (delete-file file))
+ (process-send-string
+ (get-buffer-process buffer)
+ (if (= (aref string (1- (length string))) ?\n) string (concat string "\n")))
+ ;; From Tramp 2.1.19 the following cache flush is not necessary
+ (when (file-remote-p default-directory)
+ (with-parsed-tramp-file-name default-directory nil
+ (tramp-flush-directory-property v "")))
+ (while (not (file-exists-p file)) (sit-for (or period 0.25))))
+
+(provide 'ob-comint)
+
+
+
+;;; ob-comint.el ends here
diff --git a/lisp/ob-coq.el b/lisp/ob-coq.el
new file mode 100644
index 0000000..93d2b1f
--- /dev/null
+++ b/lisp/ob-coq.el
@@ -0,0 +1,78 @@
+;;; ob-coq.el --- Babel Functions for Coq -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Rudimentary support for evaluating Coq code blocks. Currently only
+;; session evaluation is supported. Requires both coq.el and
+;; coq-inferior.el, both of which are distributed with Coq.
+;;
+;; http://coq.inria.fr/
+
+;;; Code:
+(require 'ob)
+
+(declare-function run-coq "ext:coq-inferior.el" (cmd))
+(declare-function coq-proc "ext:coq-inferior.el" ())
+
+(defvar coq-program-name "coqtop"
+ "Name of the coq toplevel to run.")
+
+(defvar org-babel-coq-buffer "*coq*"
+ "Buffer in which to evaluate coq code blocks.")
+
+(defun org-babel-coq-clean-prompt (string)
+ (if (string-match "^[^[:space:]]+ < " string)
+ (substring string 0 (match-beginning 0))
+ string))
+
+(defun org-babel-execute:coq (body params)
+ (let ((full-body (org-babel-expand-body:generic body params))
+ (session (org-babel-coq-initiate-session))
+ (pt (lambda ()
+ (marker-position
+ (process-mark (get-buffer-process (current-buffer)))))))
+ (org-babel-coq-clean-prompt
+ (org-babel-comint-in-buffer session
+ (let ((start (funcall pt)))
+ (with-temp-buffer
+ (insert full-body)
+ (comint-send-region (coq-proc) (point-min) (point-max))
+ (comint-send-string (coq-proc)
+ (if (string= (buffer-substring (- (point-max) 1) (point-max)) ".")
+ "\n"
+ ".\n")))
+ (while (equal start (funcall pt)) (sleep-for 0.1))
+ (buffer-substring start (funcall pt)))))))
+
+(defun org-babel-coq-initiate-session ()
+ "Initiate a coq session.
+If there is not a current inferior-process-buffer in SESSION then
+create one. Return the initialized session."
+ (unless (fboundp 'run-coq)
+ (error "`run-coq' not defined, load coq-inferior.el"))
+ (save-window-excursion (run-coq coq-program-name))
+ (sit-for 0.1)
+ (get-buffer org-babel-coq-buffer))
+
+(provide 'ob-coq)
diff --git a/lisp/ob-core.el b/lisp/ob-core.el
new file mode 100644
index 0000000..c630b70
--- /dev/null
+++ b/lisp/ob-core.el
@@ -0,0 +1,3135 @@
+;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Code:
+(require 'cl-lib)
+(require 'ob-eval)
+(require 'org-macs)
+(require 'org-compat)
+
+(defconst org-babel-exeext
+ (if (memq system-type '(windows-nt cygwin))
+ ".exe"
+ nil))
+
+(defvar org-babel-library-of-babel)
+(defvar org-edit-src-content-indentation)
+(defvar org-src-lang-modes)
+(defvar org-src-preserve-indentation)
+
+(declare-function org-at-item-p "org-list" ())
+(declare-function org-at-table-p "org" (&optional table-type))
+(declare-function org-babel-lob-execute-maybe "ob-lob" ())
+(declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
+(declare-function org-babel-ref-headline-body "ob-ref" ())
+(declare-function org-babel-ref-parse "ob-ref" (assignment))
+(declare-function org-babel-ref-resolve "ob-ref" (ref))
+(declare-function org-babel-ref-split-args "ob-ref" (arg-string))
+(declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
+(declare-function org-completing-read "org" (&rest args))
+(declare-function org-current-level "org" ())
+(declare-function org-cycle "org" (&optional arg))
+(declare-function org-do-remove-indentation "org" (&optional n))
+(declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
+(declare-function org-edit-src-exit "org-src" ())
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-normalize-string "org-element" (s))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
+(declare-function org-escape-code-in-region "org-src" (beg end))
+(declare-function org-get-indentation "org" (&optional line))
+(declare-function org-get-indentation "org" (&optional line))
+(declare-function org-in-regexp "org" (regexp &optional nlines visually))
+(declare-function org-indent-line "org" ())
+(declare-function org-list-get-list-end "org-list" (item struct prevs))
+(declare-function org-list-prevs-alist "org-list" (struct))
+(declare-function org-list-struct "org-list" ())
+(declare-function org-list-to-generic "org-list" (LIST PARAMS))
+(declare-function org-list-to-lisp "org-list" (&optional delete))
+(declare-function org-macro-escape-arguments "org-macro" (&rest args))
+(declare-function org-make-options-regexp "org" (kwds &optional extra))
+(declare-function org-mark-ring-push "org" (&optional pos buffer))
+(declare-function org-narrow-to-subtree "org" ())
+(declare-function org-next-block "org" (arg &optional backward block-regexp))
+(declare-function org-number-sequence "org-compat" (from &optional to inc))
+(declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
+(declare-function org-outline-overlay-data "org" (&optional use-markers))
+(declare-function org-previous-block "org" (arg &optional block-regexp))
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-reverse-string "org" (string))
+(declare-function org-set-outline-overlay-data "org" (data))
+(declare-function org-show-context "org" (&optional key))
+(declare-function org-split-string "org" (string &optional separators))
+(declare-function org-src-coderef-format "org-src" (element))
+(declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
+(declare-function org-table-align "org-table" ())
+(declare-function org-table-end "org-table" (&optional table-type))
+(declare-function org-table-import "org-table" (file arg))
+(declare-function org-table-to-lisp "org-table" (&optional txt))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function org-unescape-code-in-string "org-src" (s))
+(declare-function org-uniquify "org" (list))
+(declare-function orgtbl-to-generic "org-table" (table params))
+(declare-function orgtbl-to-orgtbl "org-table" (table params))
+(declare-function outline-show-all "outline" ())
+(declare-function tramp-compat-make-temp-file "tramp-compat" (filename &optional dir-flag))
+
+(defgroup org-babel nil
+ "Code block evaluation and management in `org-mode' documents."
+ :tag "Babel"
+ :group 'org)
+
+(defcustom org-confirm-babel-evaluate t
+ "Confirm before evaluation.
+\\<org-mode-map>\
+Require confirmation before interactively evaluating code
+blocks in Org buffers. The default value of this variable is t,
+meaning confirmation is required for any code block evaluation.
+This variable can be set to nil to inhibit any future
+confirmation requests. This variable can also be set to a
+function which takes two arguments the language of the code block
+and the body of the code block. Such a function should then
+return a non-nil value if the user should be prompted for
+execution or nil if no prompt is required.
+
+Warning: Disabling confirmation may result in accidental
+evaluation of potentially harmful code. It may be advisable
+remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
+as further protection
+against accidental code block evaluation. The
+`org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
+remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
+ :group 'org-babel
+ :version "24.1"
+ :type '(choice boolean function))
+;; don't allow this variable to be changed through file settings
+(put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
+
+(defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
+ "\\<org-mode-map>\
+Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
+ :group 'org-babel
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-babel-results-keyword "RESULTS"
+ "Keyword used to name results generated by code blocks.
+It should be \"RESULTS\". However any capitalization may be
+used."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string
+ :safe (lambda (v)
+ (and (stringp v)
+ (eq (compare-strings "RESULTS" nil nil v nil nil t)
+ t))))
+
+(defcustom org-babel-noweb-wrap-start "<<"
+ "String used to begin a noweb reference in a code block.
+See also `org-babel-noweb-wrap-end'."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-noweb-wrap-end ">>"
+ "String used to end a noweb reference in a code block.
+See also `org-babel-noweb-wrap-start'."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-inline-result-wrap "=%s="
+ "Format string used to wrap inline results.
+This string must include a \"%s\" which will be replaced by the results."
+ :group 'org-babel
+ :type 'string)
+(put 'org-babel-inline-result-wrap
+ 'safe-local-variable
+ (lambda (value)
+ (and (stringp value)
+ (string-match-p "%s" value))))
+
+(defcustom org-babel-hash-show-time nil
+ "Non-nil means show the time the code block was evaluated in the result hash."
+ :group 'org-babel
+ :type 'boolean
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :safe #'booleanp)
+
+(defun org-babel-noweb-wrap (&optional regexp)
+ (concat org-babel-noweb-wrap-start
+ (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
+ org-babel-noweb-wrap-end))
+
+(defvar org-babel-src-name-regexp
+ "^[ \t]*#\\+name:[ \t]*"
+ "Regular expression used to match a source name line.")
+
+(defvar org-babel-multi-line-header-regexp
+ "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
+ "Regular expression used to match multi-line header arguments.")
+
+(defvar org-babel-src-block-regexp
+ (concat
+ ;; (1) indentation (2) lang
+ "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
+ ;; (3) switches
+ "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
+ ;; (4) header arguments
+ "\\([^\n]*\\)\n"
+ ;; (5) body
+ "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
+ "Regexp used to identify code blocks.")
+
+(defun org-babel--get-vars (params)
+ "Return the babel variable assignments in PARAMS.
+
+PARAMS is a quasi-alist of header args, which may contain
+multiple entries for the key `:var'. This function returns a
+list of the cdr of all the `:var' entries."
+ (mapcar #'cdr
+ (cl-remove-if-not (lambda (x) (eq (car x) :var)) params)))
+
+(defvar org-babel-exp-reference-buffer nil
+ "Buffer containing original contents of the exported buffer.
+This is used by Babel to resolve references in source blocks.
+Its value is dynamically bound during export.")
+
+(defun org-babel-check-confirm-evaluate (info)
+ "Check whether INFO allows code block evaluation.
+
+Returns nil if evaluation is disallowed, t if it is
+unconditionally allowed, and the symbol `query' if the user
+should be asked whether to allow evaluation."
+ (let* ((headers (nth 2 info))
+ (eval (or (cdr (assq :eval headers))
+ (when (assq :noeval headers) "no")))
+ (eval-no (member eval '("no" "never")))
+ (export org-babel-exp-reference-buffer)
+ (eval-no-export (and export (member eval '("no-export" "never-export"))))
+ (noeval (or eval-no eval-no-export))
+ (query (or (equal eval "query")
+ (and export (equal eval "query-export"))
+ (if (functionp org-confirm-babel-evaluate)
+ (save-excursion
+ (goto-char (nth 5 info))
+ (funcall org-confirm-babel-evaluate
+ ;; language, code block body
+ (nth 0 info) (nth 1 info)))
+ org-confirm-babel-evaluate))))
+ (cond
+ (noeval nil)
+ (query 'query)
+ (t t))))
+
+(defun org-babel-check-evaluate (info)
+ "Check if code block INFO should be evaluated.
+Do not query the user, but do display an informative message if
+evaluation is blocked. Returns non-nil if evaluation is not blocked."
+ (let ((confirmed (org-babel-check-confirm-evaluate info)))
+ (unless confirmed
+ (message "Evaluation of this %s code block%sis disabled."
+ (nth 0 info)
+ (let ((name (nth 4 info)))
+ (if name (format " (%s) " name) " "))))
+ confirmed))
+
+;; Dynamically scoped for asynchronous export.
+(defvar org-babel-confirm-evaluate-answer-no)
+
+(defun org-babel-confirm-evaluate (info)
+ "Confirm evaluation of the code block INFO.
+
+This query can also be suppressed by setting the value of
+`org-confirm-babel-evaluate' to nil, in which case all future
+interactive code block evaluations will proceed without any
+confirmation from the user.
+
+Note disabling confirmation may result in accidental evaluation
+of potentially harmful code.
+
+The variable `org-babel-confirm-evaluate-answer-no' is used by
+the async export process, which requires a non-interactive
+environment, to override this check."
+ (let* ((evalp (org-babel-check-confirm-evaluate info))
+ (lang (nth 0 info))
+ (name (nth 4 info))
+ (name-string (if name (format " (%s) " name) " ")))
+ (pcase evalp
+ (`nil nil)
+ (`t t)
+ (`query (or
+ (and (not (bound-and-true-p
+ org-babel-confirm-evaluate-answer-no))
+ (yes-or-no-p
+ (format "Evaluate this %s code block%son your system? "
+ lang name-string)))
+ (progn
+ (message "Evaluation of this %s code block%sis aborted."
+ lang name-string)
+ nil)))
+ (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x)))))
+
+;;;###autoload
+(defun org-babel-execute-safely-maybe ()
+ (unless org-babel-no-eval-on-ctrl-c-ctrl-c
+ (org-babel-execute-maybe)))
+
+;;;###autoload
+(defun org-babel-execute-maybe ()
+ (interactive)
+ (or (org-babel-execute-src-block-maybe)
+ (org-babel-lob-execute-maybe)))
+
+(defmacro org-babel-when-in-src-block (&rest body)
+ "Execute BODY if point is in a source block and return t.
+
+Otherwise do nothing and return nil."
+ `(if (memq (org-element-type (org-element-context))
+ '(inline-src-block src-block))
+ (progn
+ ,@body
+ t)
+ nil))
+
+(defun org-babel-execute-src-block-maybe ()
+ "Conditionally execute a source block.
+Detect if this is context for a Babel src-block and if so
+then run `org-babel-execute-src-block'."
+ (interactive)
+ (org-babel-when-in-src-block
+ (org-babel-eval-wipe-error-buffer)
+ (org-babel-execute-src-block current-prefix-arg)))
+
+;;;###autoload
+(defun org-babel-view-src-block-info ()
+ "Display information on the current source block.
+This includes header arguments, language and name, and is largely
+a window into the `org-babel-get-src-block-info' function."
+ (interactive)
+ (let ((info (org-babel-get-src-block-info 'light))
+ (full (lambda (it) (> (length it) 0)))
+ (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
+ (when info
+ (with-help-window (help-buffer)
+ (let ((name (nth 4 info))
+ (lang (nth 0 info))
+ (switches (nth 3 info))
+ (header-args (nth 2 info)))
+ (when name (funcall printf "Name: %s\n" name))
+ (when lang (funcall printf "Lang: %s\n" lang))
+ (funcall printf "Properties:\n")
+ (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t))
+ (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t))
+
+ (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
+ (funcall printf "Header Arguments:\n")
+ (dolist (pair (sort header-args
+ (lambda (a b) (string< (symbol-name (car a))
+ (symbol-name (car b))))))
+ (when (funcall full (format "%s" (cdr pair)))
+ (funcall printf "\t%S%s\t%s\n"
+ (car pair)
+ (if (> (length (format "%S" (car pair))) 7) "" "\t")
+ (cdr pair)))))))))
+
+;;;###autoload
+(defun org-babel-expand-src-block-maybe ()
+ "Conditionally expand a source block.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-expand-src-block'."
+ (interactive)
+ (org-babel-when-in-src-block
+ (org-babel-expand-src-block current-prefix-arg)))
+
+;;;###autoload
+(defun org-babel-load-in-session-maybe ()
+ "Conditionally load a source block in a session.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-load-in-session'."
+ (interactive)
+ (org-babel-when-in-src-block
+ (org-babel-load-in-session current-prefix-arg)))
+
+(add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
+
+;;;###autoload
+(defun org-babel-pop-to-session-maybe ()
+ "Conditionally pop to a session.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-switch-to-session'."
+ (interactive)
+ (org-babel-when-in-src-block
+ (org-babel-switch-to-session current-prefix-arg)))
+
+(add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
+
+(defconst org-babel-common-header-args-w-values
+ '((cache . ((no yes)))
+ (cmdline . :any)
+ (colnames . ((nil no yes)))
+ (comments . ((no link yes org both noweb)))
+ (dir . :any)
+ (eval . ((yes no no-export strip-export never-export eval never
+ query)))
+ (exports . ((code results both none)))
+ (epilogue . :any)
+ (file . :any)
+ (file-desc . :any)
+ (file-ext . :any)
+ (hlines . ((no yes)))
+ (mkdirp . ((yes no)))
+ (no-expand)
+ (noeval)
+ (noweb . ((yes no tangle no-export strip-export)))
+ (noweb-ref . :any)
+ (noweb-sep . :any)
+ (output-dir . :any)
+ (padline . ((yes no)))
+ (post . :any)
+ (prologue . :any)
+ (results . ((file list vector table scalar verbatim)
+ (raw html latex org code pp drawer)
+ (replace silent none append prepend)
+ (output value)))
+ (rownames . ((no yes)))
+ (sep . :any)
+ (session . :any)
+ (shebang . :any)
+ (tangle . ((tangle yes no :any)))
+ (tangle-mode . ((#o755 #o555 #o444 :any)))
+ (var . :any)
+ (wrap . :any)))
+
+(defconst org-babel-header-arg-names
+ (mapcar #'car org-babel-common-header-args-w-values)
+ "Common header arguments used by org-babel.
+Note that individual languages may define their own language
+specific header arguments as well.")
+
+(defconst org-babel-safe-header-args
+ '(:cache :colnames :comments :exports :epilogue :hlines :noeval
+ :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
+ :sep :session :tangle :wrap
+ (:eval . ("never" "query"))
+ (:results . (lambda (str) (not (string-match "file" str)))))
+ "A list of safe header arguments for babel source blocks.
+
+The list can have entries of the following forms:
+- :ARG -> :ARG is always a safe header arg
+- (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
+ `equal' to one of the VALs.
+- (:ARG . FN) -> :ARG is safe as a header arg if the function FN
+ returns non-nil. FN is passed one
+ argument, the value of the header arg
+ (as a string).")
+
+(defmacro org-babel-header-args-safe-fn (safe-list)
+ "Return a function that determines whether a list of header args are safe.
+
+Intended usage is:
+\(put \\='org-babel-default-header-args \\='safe-local-variable
+ (org-babel-header-args-safe-p org-babel-safe-header-args)
+
+This allows org-babel languages to extend the list of safe values for
+their `org-babel-default-header-args:foo' variable.
+
+For the format of SAFE-LIST, see `org-babel-safe-header-args'."
+ `(lambda (value)
+ (and (listp value)
+ (cl-every
+ (lambda (pair)
+ (and (consp pair)
+ (org-babel-one-header-arg-safe-p pair ,safe-list)))
+ value))))
+
+(defvar org-babel-default-header-args
+ '((:session . "none") (:results . "replace") (:exports . "code")
+ (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
+ "Default arguments to use when evaluating a source block.")
+(put 'org-babel-default-header-args 'safe-local-variable
+ (org-babel-header-args-safe-fn org-babel-safe-header-args))
+
+(defvar org-babel-default-inline-header-args
+ '((:session . "none") (:results . "replace")
+ (:exports . "results") (:hlines . "yes"))
+ "Default arguments to use when evaluating an inline source block.")
+(put 'org-babel-default-inline-header-args 'safe-local-variable
+ (org-babel-header-args-safe-fn org-babel-safe-header-args))
+
+(defconst org-babel-name-regexp
+ (format "^[ \t]*#\\+%s:[ \t]*"
+ ;; FIXME: TBLNAME is for backward compatibility.
+ (regexp-opt '("NAME" "TBLNAME")))
+ "Regexp matching a NAME keyword.")
+
+(defconst org-babel-result-regexp
+ (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
+ org-babel-results-keyword
+ ;; <%Y-%m-%d %H:%M:%S>
+ "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \
+[0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>")
+ "Regular expression used to match result lines.
+If the results are associated with a hash key then the hash will
+be saved in match group 1.")
+
+(defconst org-babel-result-w-name-regexp
+ (concat org-babel-result-regexp "\\(?9:[^ \t\n\r\v\f]+\\)")
+ "Regexp matching a RESULTS keyword with a name.
+Name is saved in match group 9.")
+
+(defvar org-babel-min-lines-for-block-output 10
+ "The minimum number of lines for block output.
+If number of lines of output is equal to or exceeds this
+value, the output is placed in a #+begin_example...#+end_example
+block. Otherwise the output is marked as literal by inserting
+colons at the starts of the lines. This variable only takes
+effect if the :results output option is in effect.")
+
+(defvar org-babel-noweb-error-all-langs nil
+ "Raise errors when noweb references don't resolve.
+Also see `org-babel-noweb-error-langs' to control noweb errors on
+a language by language bases.")
+
+(defvar org-babel-noweb-error-langs nil
+ "Languages for which Babel will raise literate programming errors.
+List of languages for which errors should be raised when the
+source code block satisfying a noweb reference in this language
+can not be resolved. Also see `org-babel-noweb-error-all-langs'
+to raise errors for all languages.")
+
+(defvar org-babel-hash-show 4
+ "Number of initial characters to show of a hidden results hash.")
+
+(defvar org-babel-after-execute-hook nil
+ "Hook for functions to be called after `org-babel-execute-src-block'")
+
+(defun org-babel-named-src-block-regexp-for-name (&optional name)
+ "This generates a regexp used to match a src block named NAME.
+If NAME is nil, match any name. Matched name is then put in
+match group 9. Other match groups are defined in
+`org-babel-src-block-regexp'."
+ (concat org-babel-src-name-regexp
+ (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" )
+ "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
+ "\n"
+ (substring org-babel-src-block-regexp 1)))
+
+(defun org-babel-named-data-regexp-for-name (name)
+ "This generates a regexp used to match data named NAME."
+ (concat org-babel-name-regexp (regexp-quote name) "[ \t]*$"))
+
+(defun org-babel--normalize-body (datum)
+ "Normalize body for element or object DATUM.
+DATUM is a source block element or an inline source block object.
+Remove final newline character and spurious indentation."
+ (let* ((value (org-element-property :value datum))
+ (body (if (string-suffix-p "\n" value)
+ (substring value 0 -1)
+ value)))
+ (cond ((eq (org-element-type datum) 'inline-src-block)
+ ;; Newline characters and indentation in an inline
+ ;; src-block are not meaningful, since they could come from
+ ;; some paragraph filling. Treat them as a white space.
+ (replace-regexp-in-string "\n[ \t]*" " " body))
+ ((or org-src-preserve-indentation
+ (org-element-property :preserve-indent datum))
+ body)
+ (t (org-remove-indentation body)))))
+
+;;; functions
+(defvar org-babel-current-src-block-location nil
+ "Marker pointing to the src block currently being executed.
+This may also point to a call line or an inline code block. If
+multiple blocks are being executed (e.g., in chained execution
+through use of the :var header argument) this marker points to
+the outer-most code block.")
+
+(defvar *this*)
+
+(defun org-babel-get-src-block-info (&optional light datum)
+ "Extract information from a source block or inline source block.
+
+Optional argument LIGHT does not resolve remote variable
+references; a process which could likely result in the execution
+of other code blocks.
+
+By default, consider the block at point. However, when optional
+argument DATUM is provided, extract information from that parsed
+object instead.
+
+Return nil if point is not on a source block. Otherwise, return
+a list with the following pattern:
+
+ (language body arguments switches name start coderef)"
+ (let* ((datum (or datum (org-element-context)))
+ (type (org-element-type datum))
+ (inline (eq type 'inline-src-block)))
+ (when (memq type '(inline-src-block src-block))
+ (let* ((lang (org-element-property :language datum))
+ (lang-headers (intern
+ (concat "org-babel-default-header-args:" lang)))
+ (name (org-element-property :name datum))
+ (info
+ (list
+ lang
+ (org-babel--normalize-body datum)
+ (apply #'org-babel-merge-params
+ (if inline org-babel-default-inline-header-args
+ org-babel-default-header-args)
+ (and (boundp lang-headers) (eval lang-headers t))
+ (append
+ ;; If DATUM is provided, make sure we get node
+ ;; properties applicable to its location within
+ ;; the document.
+ (org-with-point-at (org-element-property :begin datum)
+ (org-babel-params-from-properties lang))
+ (mapcar #'org-babel-parse-header-arguments
+ (cons (org-element-property :parameters datum)
+ (org-element-property :header datum)))))
+ (or (org-element-property :switches datum) "")
+ name
+ (org-element-property (if inline :begin :post-affiliated)
+ datum)
+ (and (not inline) (org-src-coderef-format datum)))))
+ (unless light
+ (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
+ (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info)))
+ info))))
+
+;;;###autoload
+(defun org-babel-execute-src-block (&optional arg info params)
+ "Execute the current source code block.
+Insert the results of execution into the buffer. Source code
+execution and the collection and formatting of results can be
+controlled through a variety of header arguments.
+
+With prefix argument ARG, force re-execution even if an existing
+result cached in the buffer would otherwise have been returned.
+
+Optionally supply a value for INFO in the form returned by
+`org-babel-get-src-block-info'.
+
+Optionally supply a value for PARAMS which will be merged with
+the header arguments specified at the front of the source code
+block."
+ (interactive)
+ (let* ((org-babel-current-src-block-location
+ (or org-babel-current-src-block-location
+ (nth 5 info)
+ (org-babel-where-is-src-block-head)))
+ (info (if info (copy-tree info) (org-babel-get-src-block-info))))
+ ;; Merge PARAMS with INFO before considering source block
+ ;; evaluation since both could disagree.
+ (cl-callf org-babel-merge-params (nth 2 info) params)
+ (when (org-babel-check-evaluate info)
+ (cl-callf org-babel-process-params (nth 2 info))
+ (let* ((params (nth 2 info))
+ (cache (let ((c (cdr (assq :cache params))))
+ (and (not arg) c (string= "yes" c))))
+ (new-hash (and cache (org-babel-sha1-hash info)))
+ (old-hash (and cache (org-babel-current-result-hash)))
+ (current-cache (and new-hash (equal new-hash old-hash))))
+ (cond
+ (current-cache
+ (save-excursion ;Return cached result.
+ (goto-char (org-babel-where-is-src-block-result nil info))
+ (forward-line)
+ (skip-chars-forward " \t")
+ (let ((result (org-babel-read-result)))
+ (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
+ result)))
+ ((org-babel-confirm-evaluate info)
+ (let* ((lang (nth 0 info))
+ (result-params (cdr (assq :result-params params)))
+ ;; Expand noweb references in BODY and remove any
+ ;; coderef.
+ (body
+ (let ((coderef (nth 6 info))
+ (expand
+ (if (org-babel-noweb-p params :eval)
+ (org-babel-expand-noweb-references info)
+ (nth 1 info))))
+ (if (not coderef) expand
+ (replace-regexp-in-string
+ (org-src-coderef-regexp coderef) "" expand nil nil 1))))
+ (dir (cdr (assq :dir params)))
+ (default-directory
+ (or (and dir (file-name-as-directory (expand-file-name dir)))
+ default-directory))
+ (cmd (intern (concat "org-babel-execute:" lang)))
+ result)
+ (unless (fboundp cmd)
+ (error "No org-babel-execute function for %s!" lang))
+ (message "executing %s code block%s..."
+ (capitalize lang)
+ (let ((name (nth 4 info)))
+ (if name (format " (%s)" name) "")))
+ (if (member "none" result-params)
+ (progn (funcall cmd body params)
+ (message "result silenced"))
+ (setq result
+ (let ((r (funcall cmd body params)))
+ (if (and (eq (cdr (assq :result-type params)) 'value)
+ (or (member "vector" result-params)
+ (member "table" result-params))
+ (not (listp r)))
+ (list (list r))
+ r)))
+ (let ((file (cdr (assq :file params))))
+ ;; If non-empty result and :file then write to :file.
+ (when file
+ (when result
+ (with-temp-file file
+ (insert (org-babel-format-result
+ result (cdr (assq :sep params))))))
+ (setq result file))
+ ;; Possibly perform post process provided its
+ ;; appropriate. Dynamically bind "*this*" to the
+ ;; actual results of the block.
+ (let ((post (cdr (assq :post params))))
+ (when post
+ (let ((*this* (if (not file) result
+ (org-babel-result-to-file
+ file
+ (let ((desc (assq :file-desc params)))
+ (and desc (or (cdr desc) result)))))))
+ (setq result (org-babel-ref-resolve post))
+ (when file
+ (setq result-params (remove "file" result-params))))))
+ (org-babel-insert-result
+ result result-params info new-hash lang)))
+ (run-hooks 'org-babel-after-execute-hook)
+ result)))))))
+
+(defun org-babel-expand-body:generic (body params &optional var-lines)
+ "Expand BODY with PARAMS.
+Expand a block of code with org-babel according to its header
+arguments. This generic implementation of body expansion is
+called for languages which have not defined their own specific
+org-babel-expand-body:lang function."
+ (let ((pro (cdr (assq :prologue params)))
+ (epi (cdr (assq :epilogue params))))
+ (mapconcat #'identity
+ (append (when pro (list pro))
+ var-lines
+ (list body)
+ (when epi (list epi)))
+ "\n")))
+
+;;;###autoload
+(defun org-babel-expand-src-block (&optional _arg info params)
+ "Expand the current source code block.
+Expand according to the source code block's header
+arguments and pop open the results in a preview buffer."
+ (interactive)
+ (let* ((info (or info (org-babel-get-src-block-info)))
+ (lang (nth 0 info))
+ (params (setf (nth 2 info)
+ (sort (org-babel-merge-params (nth 2 info) params)
+ (lambda (el1 el2) (string< (symbol-name (car el1))
+ (symbol-name (car el2)))))))
+ (body (setf (nth 1 info)
+ (if (org-babel-noweb-p params :eval)
+ (org-babel-expand-noweb-references info) (nth 1 info))))
+ (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
+ (assignments-cmd (intern (concat "org-babel-variable-assignments:"
+ lang)))
+ (expanded
+ (if (fboundp expand-cmd) (funcall expand-cmd body params)
+ (org-babel-expand-body:generic
+ body params (and (fboundp assignments-cmd)
+ (funcall assignments-cmd params))))))
+ (if (called-interactively-p 'any)
+ (org-edit-src-code
+ expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
+ expanded)))
+
+(defun org-babel-edit-distance (s1 s2)
+ "Return the edit (levenshtein) distance between strings S1 S2."
+ (let* ((l1 (length s1))
+ (l2 (length s2))
+ (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
+ (number-sequence 1 (1+ l1)))))
+ (in (lambda (i j) (aref (aref dist i) j))))
+ (setf (aref (aref dist 0) 0) 0)
+ (dolist (j (number-sequence 1 l2))
+ (setf (aref (aref dist 0) j) j))
+ (dolist (i (number-sequence 1 l1))
+ (setf (aref (aref dist i) 0) i)
+ (dolist (j (number-sequence 1 l2))
+ (setf (aref (aref dist i) j)
+ (min
+ (1+ (funcall in (1- i) j))
+ (1+ (funcall in i (1- j)))
+ (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
+ (funcall in (1- i) (1- j)))))))
+ (funcall in l1 l2)))
+
+(defun org-babel-combine-header-arg-lists (original &rest others)
+ "Combine a number of lists of header argument names and arguments."
+ (let ((results (copy-sequence original)))
+ (dolist (new-list others)
+ (dolist (arg-pair new-list)
+ (let ((header (car arg-pair)))
+ (setq results
+ (cons arg-pair (cl-remove-if
+ (lambda (pair) (equal header (car pair)))
+ results))))))
+ results))
+
+;;;###autoload
+(defun org-babel-check-src-block ()
+ "Check for misspelled header arguments in the current code block."
+ (interactive)
+ ;; TODO: report malformed code block
+ ;; TODO: report incompatible combinations of header arguments
+ ;; TODO: report uninitialized variables
+ (let ((too-close 2) ;; <- control closeness to report potential match
+ (names (mapcar #'symbol-name org-babel-header-arg-names)))
+ (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
+ (and (org-babel-where-is-src-block-head)
+ (org-babel-parse-header-arguments
+ (org-no-properties
+ (match-string 4))))))
+ (dolist (name names)
+ (when (and (not (string= header name))
+ (<= (org-babel-edit-distance header name) too-close)
+ (not (member header names)))
+ (error "Supplied header \"%S\" is suspiciously close to \"%S\""
+ header name))))
+ (message "No suspicious header arguments found.")))
+
+;;;###autoload
+(defun org-babel-insert-header-arg (&optional header-arg value)
+ "Insert a header argument selecting from lists of common args and values."
+ (interactive)
+ (let* ((info (org-babel-get-src-block-info 'light))
+ (lang (car info))
+ (begin (nth 5 info))
+ (lang-headers (intern (concat "org-babel-header-args:" lang)))
+ (headers (org-babel-combine-header-arg-lists
+ org-babel-common-header-args-w-values
+ (when (boundp lang-headers) (eval lang-headers t))))
+ (header-arg (or header-arg
+ (completing-read
+ "Header Arg: "
+ (mapcar
+ (lambda (header-spec) (symbol-name (car header-spec)))
+ headers))))
+ (vals (cdr (assoc (intern header-arg) headers)))
+ (value (or value
+ (cond
+ ((eq vals :any)
+ (read-from-minibuffer "value: "))
+ ((listp vals)
+ (mapconcat
+ (lambda (group)
+ (let ((arg (completing-read
+ "Value: "
+ (cons "default"
+ (mapcar #'symbol-name group)))))
+ (if (and arg (not (string= "default" arg)))
+ (concat arg " ")
+ "")))
+ vals ""))))))
+ (save-excursion
+ (goto-char begin)
+ (goto-char (point-at-eol))
+ (unless (= (char-before (point)) ?\ ) (insert " "))
+ (insert ":" header-arg) (when value (insert " " value)))))
+
+;; Add support for completing-read insertion of header arguments after ":"
+(defun org-babel-header-arg-expand ()
+ "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
+ (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
+ (org-babel-enter-header-arg-w-completion (match-string 2))))
+
+(defun org-babel-enter-header-arg-w-completion (&optional lang)
+ "Insert header argument appropriate for LANG with completion."
+ (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
+ (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t)))
+ (headers-w-values (org-babel-combine-header-arg-lists
+ org-babel-common-header-args-w-values lang-headers))
+ (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
+ (header (org-completing-read "Header Arg: " headers))
+ (args (cdr (assoc (intern header) headers-w-values)))
+ (arg (when (and args (listp args))
+ (org-completing-read
+ (format "%s: " header)
+ (mapcar #'symbol-name (apply #'append args))))))
+ (insert (concat header " " (or arg "")))
+ (cons header arg)))
+
+(add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
+
+;;;###autoload
+(defun org-babel-load-in-session (&optional _arg info)
+ "Load the body of the current source-code block.
+Evaluate the header arguments for the source block before
+entering the session. After loading the body this pops open the
+session."
+ (interactive)
+ (let* ((info (or info (org-babel-get-src-block-info)))
+ (lang (nth 0 info))
+ (params (nth 2 info))
+ (body (if (not info)
+ (user-error "No src code block at point")
+ (setf (nth 1 info)
+ (if (org-babel-noweb-p params :eval)
+ (org-babel-expand-noweb-references info)
+ (nth 1 info)))))
+ (session (cdr (assq :session params)))
+ (dir (cdr (assq :dir params)))
+ (default-directory
+ (or (and dir (file-name-as-directory dir)) default-directory))
+ (cmd (intern (concat "org-babel-load-session:" lang))))
+ (unless (fboundp cmd)
+ (error "No org-babel-load-session function for %s!" lang))
+ (pop-to-buffer (funcall cmd session body params))
+ (end-of-line 1)))
+
+;;;###autoload
+(defun org-babel-initiate-session (&optional arg info)
+ "Initiate session for current code block.
+If called with a prefix argument then resolve any variable
+references in the header arguments and assign these variables in
+the session. Copy the body of the code block to the kill ring."
+ (interactive "P")
+ (let* ((info (or info (org-babel-get-src-block-info (not arg))))
+ (lang (nth 0 info))
+ (body (nth 1 info))
+ (params (nth 2 info))
+ (session (cdr (assq :session params)))
+ (dir (cdr (assq :dir params)))
+ (default-directory
+ (or (and dir (file-name-as-directory dir)) default-directory))
+ (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
+ (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
+ (when (and (stringp session) (string= session "none"))
+ (error "This block is not using a session!"))
+ (unless (fboundp init-cmd)
+ (error "No org-babel-initiate-session function for %s!" lang))
+ (with-temp-buffer (insert (org-trim body))
+ (copy-region-as-kill (point-min) (point-max)))
+ (when arg
+ (unless (fboundp prep-cmd)
+ (error "No org-babel-prep-session function for %s!" lang))
+ (funcall prep-cmd session params))
+ (funcall init-cmd session params)))
+
+;;;###autoload
+(defun org-babel-switch-to-session (&optional arg info)
+ "Switch to the session of the current code block.
+Uses `org-babel-initiate-session' to start the session. If called
+with a prefix argument then this is passed on to
+`org-babel-initiate-session'."
+ (interactive "P")
+ (pop-to-buffer (org-babel-initiate-session arg info))
+ (end-of-line 1))
+
+(defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
+
+(defvar org-src-window-setup)
+
+;;;###autoload
+(defun org-babel-switch-to-session-with-code (&optional arg _info)
+ "Switch to code buffer and display session."
+ (interactive "P")
+ (let ((swap-windows
+ (lambda ()
+ (let ((other-window-buffer (window-buffer (next-window))))
+ (set-window-buffer (next-window) (current-buffer))
+ (set-window-buffer (selected-window) other-window-buffer))
+ (other-window 1)))
+ (info (org-babel-get-src-block-info))
+ (org-src-window-setup 'reorganize-frame))
+ (save-excursion
+ (org-babel-switch-to-session arg info))
+ (org-edit-src-code)
+ (funcall swap-windows)))
+
+;;;###autoload
+(defmacro org-babel-do-in-edit-buffer (&rest body)
+ "Evaluate BODY in edit buffer if there is a code block at point.
+Return t if a code block was found at point, nil otherwise."
+ `(let ((org-src-window-setup 'switch-invisibly))
+ (when (and (org-babel-where-is-src-block-head)
+ (org-edit-src-code))
+ (unwind-protect (progn ,@body)
+ (org-edit-src-exit))
+ t)))
+(def-edebug-spec org-babel-do-in-edit-buffer (body))
+
+(defun org-babel-do-key-sequence-in-edit-buffer (key)
+ "Read key sequence and execute the command in edit buffer.
+Enter a key sequence to be executed in the language major-mode
+edit buffer. For example, TAB will alter the contents of the
+Org code block according to the effect of TAB in the language
+major mode buffer. For languages that support interactive
+sessions, this can be used to send code from the Org buffer
+to the session for evaluation using the native major mode
+evaluation mechanisms."
+ (interactive "kEnter key-sequence to execute in edit buffer: ")
+ (org-babel-do-in-edit-buffer
+ (call-interactively
+ (key-binding (or key (read-key-sequence nil))))))
+
+(defvar org-bracket-link-regexp)
+
+(defun org-babel-active-location-p ()
+ (memq (org-element-type (save-match-data (org-element-context)))
+ '(babel-call inline-babel-call inline-src-block src-block)))
+
+;;;###autoload
+(defun org-babel-open-src-block-result (&optional re-run)
+ "If `point' is on a src block then open the results of the
+source code block, otherwise return nil. With optional prefix
+argument RE-RUN the source-code block is evaluated even if
+results already exist."
+ (interactive "P")
+ (let ((info (org-babel-get-src-block-info 'light)))
+ (when info
+ (save-excursion
+ ;; go to the results, if there aren't any then run the block
+ (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
+ (progn (org-babel-execute-src-block)
+ (org-babel-where-is-src-block-result))))
+ (end-of-line 1)
+ (while (looking-at "[\n\r\t\f ]") (forward-char 1))
+ ;; open the results
+ (if (looking-at org-bracket-link-regexp)
+ ;; file results
+ (org-open-at-point)
+ (let ((r (org-babel-format-result
+ (org-babel-read-result) (cdr (assq :sep (nth 2 info))))))
+ (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
+ (delete-region (point-min) (point-max))
+ (insert r)))
+ t))))
+
+;;;###autoload
+(defmacro org-babel-map-src-blocks (file &rest body)
+ "Evaluate BODY forms on each source-block in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer. During evaluation of BODY the following local variables
+are set relative to the currently matched code block.
+
+full-block ------- string holding the entirety of the code block
+beg-block -------- point at the beginning of the code block
+end-block -------- point at the end of the matched code block
+lang ------------- string holding the language of the code block
+beg-lang --------- point at the beginning of the lang
+end-lang --------- point at the end of the lang
+switches --------- string holding the switches
+beg-switches ----- point at the beginning of the switches
+end-switches ----- point at the end of the switches
+header-args ------ string holding the header-args
+beg-header-args -- point at the beginning of the header-args
+end-header-args -- point at the end of the header-args
+body ------------- string holding the body of the code block
+beg-body --------- point at the beginning of the body
+end-body --------- point at the end of the body"
+ (declare (indent 1))
+ (let ((tempvar (make-symbol "file")))
+ `(let* ((case-fold-search t)
+ (,tempvar ,file)
+ (visited-p (or (null ,tempvar)
+ (get-file-buffer (expand-file-name ,tempvar))))
+ (point (point)) to-be-removed)
+ (save-window-excursion
+ (when ,tempvar (find-file ,tempvar))
+ (setq to-be-removed (current-buffer))
+ (goto-char (point-min))
+ (while (re-search-forward org-babel-src-block-regexp nil t)
+ (when (org-babel-active-location-p)
+ (goto-char (match-beginning 0))
+ (let ((full-block (match-string 0))
+ (beg-block (match-beginning 0))
+ (end-block (match-end 0))
+ (lang (match-string 2))
+ (beg-lang (match-beginning 2))
+ (end-lang (match-end 2))
+ (switches (match-string 3))
+ (beg-switches (match-beginning 3))
+ (end-switches (match-end 3))
+ (header-args (match-string 4))
+ (beg-header-args (match-beginning 4))
+ (end-header-args (match-end 4))
+ (body (match-string 5))
+ (beg-body (match-beginning 5))
+ (end-body (match-end 5)))
+ ;; Silence byte-compiler in case `body' doesn't use all
+ ;; those variables.
+ (ignore full-block beg-block end-block lang
+ beg-lang end-lang switches beg-switches
+ end-switches header-args beg-header-args
+ end-header-args body beg-body end-body)
+ ,@body
+ (goto-char end-block)))))
+ (unless visited-p (kill-buffer to-be-removed))
+ (goto-char point))))
+(def-edebug-spec org-babel-map-src-blocks (form body))
+
+;;;###autoload
+(defmacro org-babel-map-inline-src-blocks (file &rest body)
+ "Evaluate BODY forms on each inline source block in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer."
+ (declare (indent 1) (debug (form body)))
+ (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
+ `(let* ((case-fold-search t)
+ (,tempvar ,file)
+ (,visitedp (or (null ,tempvar)
+ (get-file-buffer (expand-file-name ,tempvar))))
+ (,point (point))
+ ,to-be-removed)
+ (save-window-excursion
+ (when ,tempvar (find-file ,tempvar))
+ (setq ,to-be-removed (current-buffer))
+ (goto-char (point-min))
+ (while (re-search-forward "src_\\S-" nil t)
+ (let ((,datum (save-match-data (org-element-context))))
+ (when (eq (org-element-type ,datum) 'inline-src-block)
+ (goto-char (match-beginning 0))
+ (let ((,end (copy-marker (org-element-property :end ,datum))))
+ ,@body
+ (goto-char ,end)
+ (set-marker ,end nil))))))
+ (unless ,visitedp (kill-buffer ,to-be-removed))
+ (goto-char ,point))))
+
+;;;###autoload
+(defmacro org-babel-map-call-lines (file &rest body)
+ "Evaluate BODY forms on each call line in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer."
+ (declare (indent 1) (debug (form body)))
+ (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
+ `(let* ((case-fold-search t)
+ (,tempvar ,file)
+ (,visitedp (or (null ,tempvar)
+ (get-file-buffer (expand-file-name ,tempvar))))
+ (,point (point))
+ ,to-be-removed)
+ (save-window-excursion
+ (when ,tempvar (find-file ,tempvar))
+ (setq ,to-be-removed (current-buffer))
+ (goto-char (point-min))
+ (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t)
+ (let ((,datum (save-match-data (org-element-context))))
+ (when (memq (org-element-type ,datum)
+ '(babel-call inline-babel-call))
+ (goto-char (match-beginning 0))
+ (let ((,end (copy-marker (org-element-property :end ,datum))))
+ ,@body
+ (goto-char ,end)
+ (set-marker ,end nil))))))
+ (unless ,visitedp (kill-buffer ,to-be-removed))
+ (goto-char ,point))))
+
+;;;###autoload
+(defmacro org-babel-map-executables (file &rest body)
+ "Evaluate BODY forms on each active Babel code in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer."
+ (declare (indent 1) (debug (form body)))
+ (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
+ `(let* ((case-fold-search t)
+ (,tempvar ,file)
+ (,visitedp (or (null ,tempvar)
+ (get-file-buffer (expand-file-name ,tempvar))))
+ (,point (point))
+ ,to-be-removed)
+ (save-window-excursion
+ (when ,tempvar (find-file ,tempvar))
+ (setq ,to-be-removed (current-buffer))
+ (goto-char (point-min))
+ (while (re-search-forward
+ "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t)
+ (let ((,datum (save-match-data (org-element-context))))
+ (when (memq (org-element-type ,datum)
+ '(babel-call inline-babel-call inline-src-block
+ src-block))
+ (goto-char (match-beginning 0))
+ (let ((,end (copy-marker (org-element-property :end ,datum))))
+ ,@body
+ (goto-char ,end)
+ (set-marker ,end nil))))))
+ (unless ,visitedp (kill-buffer ,to-be-removed))
+ (goto-char ,point))))
+
+;;;###autoload
+(defun org-babel-execute-buffer (&optional arg)
+ "Execute source code blocks in a buffer.
+Call `org-babel-execute-src-block' on every source block in
+the current buffer."
+ (interactive "P")
+ (org-babel-eval-wipe-error-buffer)
+ (org-save-outline-visibility t
+ (org-babel-map-executables nil
+ (if (memq (org-element-type (org-element-context))
+ '(babel-call inline-babel-call))
+ (org-babel-lob-execute-maybe)
+ (org-babel-execute-src-block arg)))))
+
+;;;###autoload
+(defun org-babel-execute-subtree (&optional arg)
+ "Execute source code blocks in a subtree.
+Call `org-babel-execute-src-block' on every source block in
+the current subtree."
+ (interactive "P")
+ (save-restriction
+ (save-excursion
+ (org-narrow-to-subtree)
+ (org-babel-execute-buffer arg)
+ (widen))))
+
+;;;###autoload
+(defun org-babel-sha1-hash (&optional info)
+ "Generate an sha1 hash based on the value of info."
+ (interactive)
+ (let ((print-level nil)
+ (info (or info (org-babel-get-src-block-info))))
+ (setf (nth 2 info)
+ (sort (copy-sequence (nth 2 info))
+ (lambda (a b) (string< (car a) (car b)))))
+ (let* ((rm (lambda (lst)
+ (dolist (p '("replace" "silent" "none"
+ "append" "prepend"))
+ (setq lst (remove p lst)))
+ lst))
+ (norm (lambda (arg)
+ (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
+ (copy-sequence (cdr arg))
+ (cdr arg))))
+ (when (and v (not (and (sequencep v)
+ (not (consp v))
+ (= (length v) 0))))
+ (cond
+ ((and (listp v) ; lists are sorted
+ (member (car arg) '(:result-params)))
+ (sort (funcall rm v) #'string<))
+ ((and (stringp v) ; strings are sorted
+ (member (car arg) '(:results :exports)))
+ (mapconcat #'identity (sort (funcall rm (split-string v))
+ #'string<) " "))
+ (t v))))))
+ ;; expanded body
+ (lang (nth 0 info))
+ (params (nth 2 info))
+ (body (if (org-babel-noweb-p params :eval)
+ (org-babel-expand-noweb-references info) (nth 1 info)))
+ (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
+ (assignments-cmd (intern (concat "org-babel-variable-assignments:"
+ lang)))
+ (expanded
+ (if (fboundp expand-cmd) (funcall expand-cmd body params)
+ (org-babel-expand-body:generic
+ body params (and (fboundp assignments-cmd)
+ (funcall assignments-cmd params))))))
+ (let* ((it (format "%s-%s"
+ (mapconcat
+ #'identity
+ (delq nil (mapcar (lambda (arg)
+ (let ((normalized (funcall norm arg)))
+ (when normalized
+ (format "%S" normalized))))
+ (nth 2 info))) ":")
+ expanded))
+ (hash (sha1 it)))
+ (when (called-interactively-p 'interactive) (message hash))
+ hash))))
+
+(defun org-babel-current-result-hash (&optional info)
+ "Return the current in-buffer hash."
+ (let ((result (org-babel-where-is-src-block-result nil info)))
+ (when result
+ (org-with-wide-buffer
+ (goto-char result)
+ (looking-at org-babel-result-regexp)
+ (match-string-no-properties 1)))))
+
+(defun org-babel-set-current-result-hash (hash info)
+ "Set the current in-buffer hash to HASH."
+ (org-with-wide-buffer
+ (goto-char (org-babel-where-is-src-block-result nil info))
+ (looking-at org-babel-result-regexp)
+ (goto-char (match-beginning 1))
+ (mapc #'delete-overlay (overlays-at (point)))
+ (forward-char org-babel-hash-show)
+ (mapc #'delete-overlay (overlays-at (point)))
+ (replace-match hash nil nil nil 1)
+ (beginning-of-line)
+ (org-babel-hide-hash)))
+
+(defun org-babel-hide-hash ()
+ "Hide the hash in the current results line.
+Only the initial `org-babel-hash-show' characters of the hash
+will remain visible."
+ (add-to-invisibility-spec '(org-babel-hide-hash . t))
+ (save-excursion
+ (when (and (re-search-forward org-babel-result-regexp nil t)
+ (match-string 1))
+ (let* ((start (match-beginning 1))
+ (hide-start (+ org-babel-hash-show start))
+ (end (match-end 1))
+ (hash (match-string 1))
+ ov1 ov2)
+ (setq ov1 (make-overlay start hide-start))
+ (setq ov2 (make-overlay hide-start end))
+ (overlay-put ov2 'invisible 'org-babel-hide-hash)
+ (overlay-put ov1 'babel-hash hash)))))
+
+(defun org-babel-hide-all-hashes ()
+ "Hide the hash in the current buffer.
+Only the initial `org-babel-hash-show' characters of each hash
+will remain visible. This function should be called as part of
+the `org-mode-hook'."
+ (save-excursion
+ (while (and (not org-babel-hash-show-time)
+ (re-search-forward org-babel-result-regexp nil t))
+ (goto-char (match-beginning 0))
+ (org-babel-hide-hash)
+ (goto-char (match-end 0)))))
+(add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
+
+(defun org-babel-hash-at-point (&optional point)
+ "Return the value of the hash at POINT.
+\\<org-mode-map>\
+The hash is also added as the last element of the kill ring.
+This can be called with `\\[org-ctrl-c-ctrl-c]'."
+ (interactive)
+ (let ((hash (car (delq nil (mapcar
+ (lambda (ol) (overlay-get ol 'babel-hash))
+ (overlays-at (or point (point))))))))
+ (when hash (kill-new hash) (message hash))))
+
+(defun org-babel-result-hide-spec ()
+ "Hide portions of results lines.
+Add `org-babel-hide-result' as an invisibility spec for hiding
+portions of results lines."
+ (add-to-invisibility-spec '(org-babel-hide-result . t)))
+(add-hook 'org-mode-hook 'org-babel-result-hide-spec)
+
+(defvar org-babel-hide-result-overlays nil
+ "Overlays hiding results.")
+
+(defun org-babel-result-hide-all ()
+ "Fold all results in the current buffer."
+ (interactive)
+ (org-babel-show-result-all)
+ (save-excursion
+ (while (re-search-forward org-babel-result-regexp nil t)
+ (save-excursion (goto-char (match-beginning 0))
+ (org-babel-hide-result-toggle-maybe)))))
+
+(defun org-babel-show-result-all ()
+ "Unfold all results in the current buffer."
+ (mapc 'delete-overlay org-babel-hide-result-overlays)
+ (setq org-babel-hide-result-overlays nil))
+
+;;;###autoload
+(defun org-babel-hide-result-toggle-maybe ()
+ "Toggle visibility of result at point."
+ (interactive)
+ (let ((case-fold-search t))
+ (if (save-excursion
+ (beginning-of-line 1)
+ (looking-at org-babel-result-regexp))
+ (progn (org-babel-hide-result-toggle)
+ t) ;; to signal that we took action
+ nil))) ;; to signal that we did not
+
+(defun org-babel-hide-result-toggle (&optional force)
+ "Toggle the visibility of the current result."
+ (interactive)
+ (save-excursion
+ (beginning-of-line)
+ (if (re-search-forward org-babel-result-regexp nil t)
+ (let ((start (progn (beginning-of-line 2) (- (point) 1)))
+ (end (progn
+ (while (looking-at org-babel-multi-line-header-regexp)
+ (forward-line 1))
+ (goto-char (- (org-babel-result-end) 1)) (point)))
+ ov)
+ (if (memq t (mapcar (lambda (overlay)
+ (eq (overlay-get overlay 'invisible)
+ 'org-babel-hide-result))
+ (overlays-at start)))
+ (when (or (not force) (eq force 'off))
+ (mapc (lambda (ov)
+ (when (member ov org-babel-hide-result-overlays)
+ (setq org-babel-hide-result-overlays
+ (delq ov org-babel-hide-result-overlays)))
+ (when (eq (overlay-get ov 'invisible)
+ 'org-babel-hide-result)
+ (delete-overlay ov)))
+ (overlays-at start)))
+ (setq ov (make-overlay start end))
+ (overlay-put ov 'invisible 'org-babel-hide-result)
+ ;; make the block accessible to isearch
+ (overlay-put
+ ov 'isearch-open-invisible
+ (lambda (ov)
+ (when (member ov org-babel-hide-result-overlays)
+ (setq org-babel-hide-result-overlays
+ (delq ov org-babel-hide-result-overlays)))
+ (when (eq (overlay-get ov 'invisible)
+ 'org-babel-hide-result)
+ (delete-overlay ov))))
+ (push ov org-babel-hide-result-overlays)))
+ (error "Not looking at a result line"))))
+
+;; org-tab-after-check-for-cycling-hook
+(add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
+;; Remove overlays when changing major mode
+(add-hook 'org-mode-hook
+ (lambda () (add-hook 'change-major-mode-hook
+ 'org-babel-show-result-all 'append 'local)))
+
+(defvar org-file-properties)
+(defun org-babel-params-from-properties (&optional lang)
+ "Retrieve parameters specified as properties.
+Return a list of association lists of source block params
+specified in the properties of the current outline entry."
+ (save-match-data
+ (list
+ ;; header arguments specified with the header-args property at
+ ;; point of call.
+ (org-babel-parse-header-arguments
+ (org-entry-get org-babel-current-src-block-location
+ "header-args"
+ 'inherit))
+ (and lang ; language-specific header arguments at point of call
+ (org-babel-parse-header-arguments
+ (org-entry-get org-babel-current-src-block-location
+ (concat "header-args:" lang)
+ 'inherit))))))
+
+(defun org-babel-balanced-split (string alts)
+ "Split STRING on instances of ALTS.
+ALTS is a character, or cons of two character options where each
+option may be either the numeric code of a single character or
+a list of character alternatives. For example, to split on
+balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
+ (with-temp-buffer
+ (insert string)
+ (goto-char (point-min))
+ (let ((splitp (lambda (past next)
+ ;; Non-nil when there should be a split after NEXT
+ ;; character. PAST is the character before NEXT.
+ (pcase alts
+ (`(,(and first (pred consp)) . ,(and second (pred consp)))
+ (and (memq past first) (memq next second)))
+ (`(,first . ,(and second (pred consp)))
+ (and (eq past first) (memq next second)))
+ (`(,(and first (pred consp)) . ,second)
+ (and (memq past first) (eq next second)))
+ (`(,first . ,second)
+ (and (eq past first) (eq next second)))
+ ((pred (eq next)) t)
+ (_ nil))))
+ (partial nil)
+ (result nil))
+ (while (not (eobp))
+ (cond
+ ((funcall splitp (char-before) (char-after))
+ ;; There is a split after point. If ALTS is two-folds,
+ ;; remove last parsed character as it belongs to ALTS.
+ (when (consp alts) (pop partial))
+ ;; Include elements parsed so far in RESULTS and flush
+ ;; partial parsing.
+ (when partial
+ (push (apply #'string (nreverse partial)) result)
+ (setq partial nil))
+ (forward-char))
+ ((memq (char-after) '(?\( ?\[))
+ ;; Include everything between balanced brackets.
+ (let* ((origin (point))
+ (after (char-after))
+ (openings (list after)))
+ (forward-char)
+ (while (and openings (re-search-forward "[]()]" nil t))
+ (pcase (char-before)
+ ((and match (or ?\[ ?\()) (push match openings))
+ (?\] (when (eq ?\[ (car openings)) (pop openings)))
+ (_ (when (eq ?\( (car openings)) (pop openings)))))
+ (if (null openings)
+ (setq partial
+ (nconc (nreverse (string-to-list
+ (buffer-substring origin (point))))
+ partial))
+ ;; Un-balanced bracket. Backtrack.
+ (push after partial)
+ (goto-char (1+ origin)))))
+ ((and (eq ?\" (char-after)) (not (eq ?\\ (char-before))))
+ ;; Include everything from current double quote to next
+ ;; non-escaped double quote.
+ (let ((origin (point)))
+ (if (re-search-forward "[^\\]\"" nil t)
+ (setq partial
+ (nconc (nreverse (string-to-list
+ (buffer-substring origin (point))))
+ partial))
+ ;; No closing double quote. Backtrack.
+ (push ?\" partial)
+ (forward-char))))
+ (t (push (char-after) partial)
+ (forward-char))))
+ ;; Add pending parsing and return result.
+ (when partial (push (apply #'string (nreverse partial)) result))
+ (nreverse result))))
+
+(defun org-babel-join-splits-near-ch (ch list)
+ "Join splits where \"=\" is on either end of the split."
+ (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
+ (first= (lambda (str) (= ch (aref str 0)))))
+ (reverse
+ (cl-reduce (lambda (acc el)
+ (let ((head (car acc)))
+ (if (and head (or (funcall last= head) (funcall first= el)))
+ (cons (concat head el) (cdr acc))
+ (cons el acc))))
+ list :initial-value nil))))
+
+(defun org-babel-parse-header-arguments (arg-string)
+ "Parse a string of header arguments returning an alist."
+ (when (> (length arg-string) 0)
+ (org-babel-parse-multiple-vars
+ (delq nil
+ (mapcar
+ (lambda (arg)
+ (if (string-match
+ "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
+ arg)
+ (cons (intern (match-string 1 arg))
+ (org-babel-read (org-babel-chomp (match-string 2 arg))))
+ (cons (intern (org-babel-chomp arg)) nil)))
+ (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
+ (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
+
+(defun org-babel-parse-multiple-vars (header-arguments)
+ "Expand multiple variable assignments behind a single :var keyword.
+
+This allows expression of multiple variables with one :var as
+shown below.
+
+#+PROPERTY: var foo=1, bar=2"
+ (let (results)
+ (mapc (lambda (pair)
+ (if (eq (car pair) :var)
+ (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
+ (org-babel-join-splits-near-ch
+ 61 (org-babel-balanced-split (cdr pair) 32)))
+ (push pair results)))
+ header-arguments)
+ (nreverse results)))
+
+(defun org-babel-process-params (params)
+ "Expand variables in PARAMS and add summary parameters."
+ (let* ((processed-vars (mapcar (lambda (el)
+ (if (consp el)
+ el
+ (org-babel-ref-parse el)))
+ (org-babel--get-vars params)))
+ (vars-and-names (if (and (assq :colname-names params)
+ (assq :rowname-names params))
+ (list processed-vars)
+ (org-babel-disassemble-tables
+ processed-vars
+ (cdr (assq :hlines params))
+ (cdr (assq :colnames params))
+ (cdr (assq :rownames params)))))
+ (raw-result (or (cdr (assq :results params)) ""))
+ (result-params (delete-dups
+ (append
+ (split-string (if (stringp raw-result)
+ raw-result
+ (eval raw-result t)))
+ (cdr (assq :result-params params))))))
+ (append
+ (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
+ (list
+ (cons :colname-names (or (cdr (assq :colname-names params))
+ (cadr vars-and-names)))
+ (cons :rowname-names (or (cdr (assq :rowname-names params))
+ (cl-caddr vars-and-names)))
+ (cons :result-params result-params)
+ (cons :result-type (cond ((member "output" result-params) 'output)
+ ((member "value" result-params) 'value)
+ (t 'value))))
+ (cl-remove-if
+ (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
+ :result-type :var)))
+ params))))
+
+;; row and column names
+(defun org-babel-del-hlines (table)
+ "Remove all `hline's from TABLE."
+ (remq 'hline table))
+
+(defun org-babel-get-colnames (table)
+ "Return the column names of TABLE.
+Return a cons cell, the `car' of which contains the TABLE less
+colnames, and the `cdr' of which contains a list of the column
+names."
+ (if (eq 'hline (nth 1 table))
+ (cons (cddr table) (car table))
+ (cons (cdr table) (car table))))
+
+(defun org-babel-get-rownames (table)
+ "Return the row names of TABLE.
+Return a cons cell, the `car' of which contains the TABLE less
+rownames, and the `cdr' of which contains a list of the rownames.
+Note: this function removes any hlines in TABLE."
+ (let* ((table (org-babel-del-hlines table))
+ (rownames (funcall (lambda ()
+ (let ((tp table))
+ (mapcar
+ (lambda (_row)
+ (prog1
+ (pop (car tp))
+ (setq tp (cdr tp))))
+ table))))))
+ (cons table rownames)))
+
+(defun org-babel-put-colnames (table colnames)
+ "Add COLNAMES to TABLE if they exist."
+ (if colnames (apply 'list colnames 'hline table) table))
+
+(defun org-babel-put-rownames (table rownames)
+ "Add ROWNAMES to TABLE if they exist."
+ (if rownames
+ (mapcar (lambda (row)
+ (if (listp row)
+ (cons (or (pop rownames) "") row)
+ row)) table)
+ table))
+
+(defun org-babel-pick-name (names selector)
+ "Select one out of an alist of row or column names.
+SELECTOR can be either a list of names in which case those names
+will be returned directly, or an index into the list NAMES in
+which case the indexed names will be return."
+ (if (listp selector)
+ selector
+ (when names
+ (if (and selector (symbolp selector) (not (equal t selector)))
+ (cdr (assoc selector names))
+ (if (integerp selector)
+ (nth (- selector 1) names)
+ (cdr (car (last names))))))))
+
+(defun org-babel-disassemble-tables (vars hlines colnames rownames)
+ "Parse tables for further processing.
+Process the variables in VARS according to the HLINES,
+ROWNAMES and COLNAMES header arguments. Return a list consisting
+of the vars, cnames and rnames."
+ (let (cnames rnames)
+ (list
+ (mapcar
+ (lambda (var)
+ (when (listp (cdr var))
+ (when (and (not (equal colnames "no"))
+ (or colnames (and (eq (nth 1 (cdr var)) 'hline)
+ (not (member 'hline (cddr (cdr var)))))))
+ (let ((both (org-babel-get-colnames (cdr var))))
+ (setq cnames (cons (cons (car var) (cdr both))
+ cnames))
+ (setq var (cons (car var) (car both)))))
+ (when (and rownames (not (equal rownames "no")))
+ (let ((both (org-babel-get-rownames (cdr var))))
+ (setq rnames (cons (cons (car var) (cdr both))
+ rnames))
+ (setq var (cons (car var) (car both)))))
+ (when (and hlines (not (equal hlines "yes")))
+ (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
+ var)
+ vars)
+ (reverse cnames) (reverse rnames))))
+
+(defun org-babel-reassemble-table (table colnames rownames)
+ "Add column and row names to a table.
+Given a TABLE and set of COLNAMES and ROWNAMES add the names
+to the table for reinsertion to org-mode."
+ (if (listp table)
+ (let ((table (if (and rownames (= (length table) (length rownames)))
+ (org-babel-put-rownames table rownames) table)))
+ (if (and colnames (listp (car table)) (= (length (car table))
+ (length colnames)))
+ (org-babel-put-colnames table colnames) table))
+ table))
+
+(defun org-babel-where-is-src-block-head (&optional src-block)
+ "Find where the current source block begins.
+
+If optional argument SRC-BLOCK is `src-block' type element, find
+its current beginning instead.
+
+Return the point at the beginning of the current source block.
+Specifically at the beginning of the #+BEGIN_SRC line. Also set
+match-data relatively to `org-babel-src-block-regexp', which see.
+If the point is not on a source block then return nil."
+ (let ((element (or src-block (org-element-at-point))))
+ (when (eq (org-element-type element) 'src-block)
+ (let ((end (org-element-property :end element)))
+ (org-with-wide-buffer
+ ;; Ensure point is not on a blank line after the block.
+ (beginning-of-line)
+ (skip-chars-forward " \r\t\n" end)
+ (when (< (point) end)
+ (prog1 (goto-char (org-element-property :post-affiliated element))
+ (looking-at org-babel-src-block-regexp))))))))
+
+;;;###autoload
+(defun org-babel-goto-src-block-head ()
+ "Go to the beginning of the current code block."
+ (interactive)
+ (let ((head (org-babel-where-is-src-block-head)))
+ (if head (goto-char head) (error "Not currently in a code block"))))
+
+;;;###autoload
+(defun org-babel-goto-named-src-block (name)
+ "Go to a named source-code block."
+ (interactive
+ (let ((completion-ignore-case t)
+ (case-fold-search t)
+ (all-block-names (org-babel-src-block-names)))
+ (list (completing-read
+ "source-block name: " all-block-names nil t
+ (let* ((context (org-element-context))
+ (type (org-element-type context))
+ (noweb-ref
+ (and (memq type '(inline-src-block src-block))
+ (org-in-regexp (org-babel-noweb-wrap)))))
+ (cond
+ (noweb-ref
+ (buffer-substring
+ (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
+ (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
+ ((memq type '(babel-call inline-babel-call)) ;#+CALL:
+ (org-element-property :call context))
+ ((car (org-element-property :results context))) ;#+RESULTS:
+ ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
+ (and symbol
+ (member-ignore-case symbol all-block-names)
+ symbol)))
+ (t "")))))))
+ (let ((point (org-babel-find-named-block name)))
+ (if point
+ ;; Taken from `org-open-at-point'.
+ (progn (org-mark-ring-push) (goto-char point) (org-show-context))
+ (message "source-code block `%s' not found in this buffer" name))))
+
+(defun org-babel-find-named-block (name)
+ "Find a named source-code block.
+Return the location of the source block identified by source
+NAME, or nil if no such block exists. Set match data according
+to `org-babel-named-src-block-regexp'."
+ (save-excursion
+ (goto-char (point-min))
+ (ignore-errors
+ (org-next-block 1 nil (org-babel-named-src-block-regexp-for-name name)))))
+
+(defun org-babel-src-block-names (&optional file)
+ "Returns the names of source blocks in FILE or the current buffer."
+ (when file (find-file file))
+ (save-excursion
+ (goto-char (point-min))
+ (let ((re (org-babel-named-src-block-regexp-for-name))
+ names)
+ (while (ignore-errors (org-next-block 1 nil re))
+ (push (match-string-no-properties 9) names))
+ names)))
+
+;;;###autoload
+(defun org-babel-goto-named-result (name)
+ "Go to a named result."
+ (interactive
+ (let ((completion-ignore-case t))
+ (list (completing-read "Source-block name: "
+ (org-babel-result-names) nil t))))
+ (let ((point (org-babel-find-named-result name)))
+ (if point
+ ;; taken from `org-open-at-point'
+ (progn (goto-char point) (org-show-context))
+ (message "result `%s' not found in this buffer" name))))
+
+(defun org-babel-find-named-result (name)
+ "Find a named result.
+Return the location of the result named NAME in the current
+buffer or nil if no such result exists."
+ (save-excursion
+ (goto-char (point-min))
+ (let ((case-fold-search t)
+ (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
+ org-babel-results-keyword
+ (regexp-quote name))))
+ (catch :found
+ (while (re-search-forward re nil t)
+ (let ((element (org-element-at-point)))
+ (when (or (eq (org-element-type element) 'keyword)
+ (< (point)
+ (org-element-property :post-affiliated element)))
+ (throw :found (line-beginning-position)))))))))
+
+(defun org-babel-result-names (&optional file)
+ "Returns the names of results in FILE or the current buffer."
+ (save-excursion
+ (when file (find-file file)) (goto-char (point-min))
+ (let ((case-fold-search t) names)
+ (while (re-search-forward org-babel-result-w-name-regexp nil t)
+ (setq names (cons (match-string-no-properties 9) names)))
+ names)))
+
+;;;###autoload
+(defun org-babel-next-src-block (&optional arg)
+ "Jump to the next source block.
+With optional prefix argument ARG, jump forward ARG many source blocks."
+ (interactive "p")
+ (org-next-block arg nil org-babel-src-block-regexp))
+
+;;;###autoload
+(defun org-babel-previous-src-block (&optional arg)
+ "Jump to the previous source block.
+With optional prefix argument ARG, jump backward ARG many source blocks."
+ (interactive "p")
+ (org-previous-block arg org-babel-src-block-regexp))
+
+(defvar org-babel-load-languages)
+
+;;;###autoload
+(defun org-babel-mark-block ()
+ "Mark current src block."
+ (interactive)
+ (let ((head (org-babel-where-is-src-block-head)))
+ (when head
+ (save-excursion
+ (goto-char head)
+ (looking-at org-babel-src-block-regexp))
+ (push-mark (match-end 5) nil t)
+ (goto-char (match-beginning 5)))))
+
+(defun org-babel-demarcate-block (&optional arg)
+ "Wrap or split the code in the region or on the point.
+When called from inside of a code block the current block is
+split. When called from outside of a code block a new code block
+is created. In both cases if the region is demarcated and if the
+region is not active then the point is demarcated."
+ (interactive "P")
+ (let* ((info (org-babel-get-src-block-info 'light))
+ (start (org-babel-where-is-src-block-head))
+ (block (and start (match-string 0)))
+ (headers (and start (match-string 4)))
+ (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
+ (lower-case-p (and block
+ (let (case-fold-search)
+ (string-match-p "#\\+begin_src" block)))))
+ (if info
+ (mapc
+ (lambda (place)
+ (save-excursion
+ (goto-char place)
+ (let ((lang (nth 0 info))
+ (indent (make-string (org-get-indentation) ?\s)))
+ (when (string-match "^[[:space:]]*$"
+ (buffer-substring (point-at-bol)
+ (point-at-eol)))
+ (delete-region (point-at-bol) (point-at-eol)))
+ (insert (concat
+ (if (looking-at "^") "" "\n")
+ indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
+ (if arg stars indent) "\n"
+ indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
+ lang
+ (if (> (length headers) 1)
+ (concat " " headers) headers)
+ (if (looking-at "[\n\r]")
+ ""
+ (concat "\n" (make-string (current-column) ? )))))))
+ (move-end-of-line 2))
+ (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
+ (let ((start (point))
+ (lang (completing-read
+ "Lang: "
+ (mapcar #'symbol-name
+ (delete-dups
+ (append (mapcar #'car org-babel-load-languages)
+ (mapcar (lambda (el) (intern (car el)))
+ org-src-lang-modes))))))
+ (body (delete-and-extract-region
+ (if (org-region-active-p) (mark) (point)) (point))))
+ (insert (concat (if (looking-at "^") "" "\n")
+ (if arg (concat stars "\n") "")
+ (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
+ lang "\n"
+ body
+ (if (or (= (length body) 0)
+ (string-suffix-p "\r" body)
+ (string-suffix-p "\n" body)) "" "\n")
+ (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
+ (goto-char start) (move-end-of-line 1)))))
+
+(defun org-babel--insert-results-keyword (name hash)
+ "Insert RESULTS keyword with NAME value at point.
+If NAME is nil, results are anonymous. HASH is a string used as
+the results hash, or nil. Leave point before the keyword."
+ (save-excursion (insert "\n")) ;open line to indent.
+ (org-indent-line)
+ (delete-char 1)
+ (insert (concat "#+" org-babel-results-keyword
+ (cond ((not hash) nil)
+ (org-babel-hash-show-time
+ (format "[%s %s]"
+ (format-time-string "<%F %T>")
+ hash))
+ (t (format "[%s]" hash)))
+ ":"
+ (when name (concat " " name))
+ "\n"))
+ ;; Make sure results are going to be followed by at least one blank
+ ;; line so they do not get merged with the next element, e.g.,
+ ;;
+ ;; #+results:
+ ;; : 1
+ ;;
+ ;; : fixed-width area, unrelated to the above.
+ (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
+ (beginning-of-line 0)
+ (when hash (org-babel-hide-hash)))
+
+(defun org-babel--clear-results-maybe (hash)
+ "Clear results when hash doesn't match HASH.
+
+When results hash does not match HASH, remove RESULTS keyword at
+point, along with related contents. Do nothing if HASH is nil.
+
+Return a non-nil value if results were cleared. In this case,
+leave point where new results should be inserted."
+ (when hash
+ (looking-at org-babel-result-regexp)
+ (unless (string= (match-string 1) hash)
+ (let* ((e (org-element-at-point))
+ (post (copy-marker (org-element-property :post-affiliated e))))
+ ;; Delete contents.
+ (delete-region post
+ (save-excursion
+ (goto-char (org-element-property :end e))
+ (skip-chars-backward " \t\n")
+ (line-beginning-position 2)))
+ ;; Delete RESULT keyword. However, if RESULTS keyword is
+ ;; orphaned, ignore this part. The deletion above already
+ ;; took care of it.
+ (unless (= (point) post)
+ (delete-region (line-beginning-position)
+ (line-beginning-position 2)))
+ (goto-char post)
+ (set-marker post nil)
+ t))))
+
+(defun org-babel-where-is-src-block-result (&optional insert _info hash)
+ "Find where the current source block results begin.
+
+Return the point at the beginning of the result of the current
+source block, specifically at the beginning of the results line.
+
+If no result exists for this block return nil, unless optional
+argument INSERT is non-nil. In this case, create a results line
+following the source block and return the position at its
+beginning. In the case of inline code, remove the results part
+instead.
+
+If optional argument HASH is a string, remove contents related to
+RESULTS keyword if its hash is different. Then update the latter
+to HASH."
+ (let ((context (org-element-context)))
+ (catch :found
+ (org-with-wide-buffer
+ (pcase (org-element-type context)
+ ((or `inline-babel-call `inline-src-block)
+ ;; Results for inline objects are located right after them.
+ ;; There is no RESULTS line to insert either.
+ (let ((limit (org-element-property
+ :contents-end (org-element-property :parent context))))
+ (goto-char (org-element-property :end context))
+ (skip-chars-forward " \t\n" limit)
+ (throw :found
+ (and
+ (< (point) limit)
+ (let ((result (org-element-context)))
+ (and (eq (org-element-type result) 'macro)
+ (string= (org-element-property :key result)
+ "results")
+ (if (not insert) (point)
+ (delete-region
+ (point)
+ (progn
+ (goto-char (org-element-property :end result))
+ (skip-chars-backward " \t")
+ (point)))
+ (point))))))))
+ ((or `babel-call `src-block)
+ (let* ((name (org-element-property :name context))
+ (named-results (and name (org-babel-find-named-result name))))
+ (goto-char (or named-results (org-element-property :end context)))
+ (cond
+ ;; Existing results named after the current source.
+ (named-results
+ (when (org-babel--clear-results-maybe hash)
+ (org-babel--insert-results-keyword name hash))
+ (throw :found (point)))
+ ;; Named results expect but none to be found.
+ (name)
+ ;; No possible anonymous results at the very end of
+ ;; buffer or outside CONTEXT parent.
+ ((eq (point)
+ (or (org-element-property
+ :contents-end (org-element-property :parent context))
+ (point-max))))
+ ;; Check if next element is an anonymous result below
+ ;; the current block.
+ ((let* ((next (org-element-at-point))
+ (end (save-excursion
+ (goto-char
+ (org-element-property :post-affiliated next))
+ (line-end-position)))
+ (empty-result-re (concat org-babel-result-regexp "$"))
+ (case-fold-search t))
+ (re-search-forward empty-result-re end t))
+ (beginning-of-line)
+ (when (org-babel--clear-results-maybe hash)
+ (org-babel--insert-results-keyword nil hash))
+ (throw :found (point))))))
+ ;; Ignore other elements.
+ (_ (throw :found nil))))
+ ;; No result found. Insert a RESULTS keyword below element, if
+ ;; appropriate. In this case, ensure there is an empty line
+ ;; after the previous element.
+ (when insert
+ (save-excursion
+ (goto-char (min (org-element-property :end context) (point-max)))
+ (skip-chars-backward " \t\n")
+ (forward-line)
+ (unless (bolp) (insert "\n"))
+ (insert "\n")
+ (org-babel--insert-results-keyword
+ (org-element-property :name context) hash)
+ (point))))))
+
+(defun org-babel-read-element (element)
+ "Read ELEMENT into emacs-lisp.
+Return nil if ELEMENT cannot be read."
+ (org-with-wide-buffer
+ (goto-char (org-element-property :post-affiliated element))
+ (pcase (org-element-type element)
+ (`fixed-width
+ (let ((v (org-trim (org-element-property :value element))))
+ (or (org-babel--string-to-number v) v)))
+ (`table (org-babel-read-table))
+ (`plain-list (org-babel-read-list))
+ (`example-block
+ (let ((v (org-element-property :value element)))
+ (if (or org-src-preserve-indentation
+ (org-element-property :preserve-indent element))
+ v
+ (org-remove-indentation v))))
+ (`export-block
+ (org-remove-indentation (org-element-property :value element)))
+ (`paragraph
+ ;; Treat paragraphs containing a single link specially.
+ (skip-chars-forward " \t")
+ (if (and (looking-at org-bracket-link-regexp)
+ (save-excursion
+ (goto-char (match-end 0))
+ (skip-chars-forward " \r\t\n")
+ (<= (org-element-property :end element)
+ (point))))
+ (org-babel-read-link)
+ (buffer-substring-no-properties
+ (org-element-property :contents-begin element)
+ (org-element-property :contents-end element))))
+ ((or `center-block `quote-block `verse-block `special-block)
+ (org-remove-indentation
+ (buffer-substring-no-properties
+ (org-element-property :contents-begin element)
+ (org-element-property :contents-end element))))
+ (_ nil))))
+
+(defun org-babel-read-result ()
+ "Read the result at point into emacs-lisp."
+ (and (not (save-excursion
+ (beginning-of-line)
+ (looking-at-p "[ \t]*$")))
+ (org-babel-read-element (org-element-at-point))))
+
+(defun org-babel-read-table ()
+ "Read the table at point into emacs-lisp."
+ (mapcar (lambda (row)
+ (if (and (symbolp row) (equal row 'hline)) row
+ (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
+ (org-table-to-lisp)))
+
+(defun org-babel-read-list ()
+ "Read the list at point into emacs-lisp."
+ (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
+ (cdr (org-list-to-lisp))))
+
+(defvar org-link-types-re)
+(defun org-babel-read-link ()
+ "Read the link at point into emacs-lisp.
+If the path of the link is a file path it is expanded using
+`expand-file-name'."
+ (let* ((case-fold-search t)
+ (raw (and (looking-at org-bracket-link-regexp)
+ (org-no-properties (match-string 1))))
+ (type (and (string-match org-link-types-re raw)
+ (match-string 1 raw))))
+ (cond
+ ((not type) (expand-file-name raw))
+ ((string= type "file")
+ (and (string-match "file\\(.*\\):\\(.+\\)" raw)
+ (expand-file-name (match-string 2 raw))))
+ (t raw))))
+
+(defun org-babel-format-result (result &optional sep)
+ "Format RESULT for writing to file."
+ (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
+ (if (listp result)
+ ;; table result
+ (orgtbl-to-generic
+ result (list :sep (or sep "\t") :fmt echo-res))
+ ;; scalar result
+ (funcall echo-res result))))
+
+(defun org-babel-insert-result (result &optional result-params info hash lang)
+ "Insert RESULT into the current buffer.
+
+By default RESULT is inserted after the end of the current source
+block. The RESULT of an inline source block usually will be
+wrapped inside a `results' macro and placed on the same line as
+the inline source block. The macro is stripped upon export.
+Multiline and non-scalar RESULTS from inline source blocks are
+not allowed. With optional argument RESULT-PARAMS controls
+insertion of results in the Org mode file. RESULT-PARAMS can
+take the following values:
+
+replace - (default option) insert results after the source block
+ or inline source block replacing any previously
+ inserted results.
+
+silent -- no results are inserted into the Org buffer but
+ the results are echoed to the minibuffer and are
+ ingested by Emacs (a potentially time consuming
+ process).
+
+file ---- the results are interpreted as a file path, and are
+ inserted into the buffer using the Org file syntax.
+
+list ---- the results are interpreted as an Org list.
+
+raw ----- results are added directly to the Org file. This is
+ a good option if you code block will output Org
+ formatted text.
+
+drawer -- results are added directly to the Org file as with
+ \"raw\", but are wrapped in a RESULTS drawer or results
+ macro, allowing them to later be replaced or removed
+ automatically.
+
+org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
+ org\" block depending on whether the current source block is
+ inline or not. They are not comma-escaped when inserted,
+ but Org syntax here will be discarded when exporting the
+ file.
+
+html ---- results are added inside of a #+BEGIN_EXPORT HTML block
+ or html export snippet depending on whether the current
+ source block is inline or not. This is a good option
+ if your code block will output html formatted text.
+
+latex --- results are added inside of a #+BEGIN_EXPORT LATEX
+ block or latex export snippet depending on whether the
+ current source block is inline or not. This is a good
+ option if your code block will output latex formatted
+ text.
+
+code ---- the results are extracted in the syntax of the source
+ code of the language being evaluated and are added
+ inside of a source block with the source-code language
+ set appropriately. Also, source block inlining is
+ preserved in this case. Note this relies on the
+ optional LANG argument.
+
+list ---- the results are rendered as a list. This option not
+ allowed for inline src blocks.
+
+table --- the results are rendered as a table. This option not
+ allowed for inline src blocks.
+
+INFO may provide the values of these header arguments (in the
+`header-arguments-alist' see the docstring for
+`org-babel-get-src-block-info'):
+
+:file --- the name of the file to which output should be written.
+
+:wrap --- the effect is similar to `latex' in RESULT-PARAMS but
+ using the argument supplied to specify the export block
+ or snippet type."
+ (cond ((stringp result)
+ (setq result (org-no-properties result))
+ (when (member "file" result-params)
+ (setq result (org-babel-result-to-file
+ result (when (assq :file-desc (nth 2 info))
+ (or (cdr (assq :file-desc (nth 2 info)))
+ result))))))
+ ((listp result))
+ (t (setq result (format "%S" result))))
+ (if (and result-params (member "silent" result-params))
+ (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
+ result)
+ (let ((inline (let ((context (org-element-context)))
+ (and (memq (org-element-type context)
+ '(inline-babel-call inline-src-block))
+ context))))
+ (when inline
+ (let ((warning
+ (or (and (member "table" result-params) "`:results table'")
+ (and (listp result) "list result")
+ (and (string-match-p "\n." result) "multiline result")
+ (and (member "list" result-params) "`:results list'"))))
+ (when warning
+ (user-error "Inline error: %s cannot be used" warning))))
+ (save-excursion
+ (let* ((visible-beg (point-min-marker))
+ (visible-end (copy-marker (point-max) t))
+ (inline (let ((context (org-element-context)))
+ (and (memq (org-element-type context)
+ '(inline-babel-call inline-src-block))
+ context)))
+ (existing-result (org-babel-where-is-src-block-result t nil hash))
+ (results-switches (cdr (assq :results_switches (nth 2 info))))
+ ;; When results exist outside of the current visible
+ ;; region of the buffer, be sure to widen buffer to
+ ;; update them.
+ (outside-scope (and existing-result
+ (buffer-narrowed-p)
+ (or (> visible-beg existing-result)
+ (<= visible-end existing-result))))
+ beg end indent)
+ ;; Ensure non-inline results end in a newline.
+ (when (and (org-string-nw-p result)
+ (not inline)
+ (not (string-equal (substring result -1) "\n")))
+ (setq result (concat result "\n")))
+ (unwind-protect
+ (progn
+ (when outside-scope (widen))
+ (if existing-result (goto-char existing-result)
+ (goto-char (org-element-property :end inline))
+ (skip-chars-backward " \t"))
+ (unless inline
+ (setq indent (org-get-indentation))
+ (forward-line 1))
+ (setq beg (point))
+ (cond
+ (inline
+ ;; Make sure new results are separated from the
+ ;; source code by one space.
+ (unless existing-result
+ (insert " ")
+ (setq beg (point))))
+ ((member "replace" result-params)
+ (delete-region (point) (org-babel-result-end)))
+ ((member "append" result-params)
+ (goto-char (org-babel-result-end)) (setq beg (point-marker)))
+ ((member "prepend" result-params))) ; already there
+ (setq results-switches
+ (if results-switches (concat " " results-switches) ""))
+ (let ((wrap (lambda (start finish &optional no-escape no-newlines
+ inline-start inline-finish)
+ (when inline
+ (setq start inline-start)
+ (setq finish inline-finish)
+ (setq no-newlines t))
+ (goto-char end)
+ (insert (concat finish (unless no-newlines "\n")))
+ (goto-char beg)
+ (insert (concat start (unless no-newlines "\n")))
+ (unless no-escape
+ (org-escape-code-in-region (min (point) end) end))
+ (goto-char end)
+ (unless no-newlines (goto-char (point-at-eol)))
+ (setq end (point-marker))))
+ (tabulablep
+ (lambda (r)
+ ;; Non-nil when result R can be turned into
+ ;; a table.
+ (and (listp r)
+ (null (cdr (last r)))
+ (cl-every
+ (lambda (e) (or (atom e) (null (cdr (last e)))))
+ result)))))
+ ;; insert results based on type
+ (cond
+ ;; Do nothing for an empty result.
+ ((null result))
+ ;; Insert a list if preferred.
+ ((member "list" result-params)
+ (insert
+ (org-trim
+ (org-list-to-generic
+ (cons 'unordered
+ (mapcar
+ (lambda (e)
+ (list (if (stringp e) e (format "%S" e))))
+ (if (listp result) result
+ (split-string result "\n" t))))
+ '(:splicep nil :istart "- " :iend "\n")))
+ "\n"))
+ ;; Try hard to print RESULT as a table. Give up if
+ ;; it contains an improper list.
+ ((funcall tabulablep result)
+ (goto-char beg)
+ (insert (concat (orgtbl-to-orgtbl
+ (if (cl-every
+ (lambda (e)
+ (or (eq e 'hline) (listp e)))
+ result)
+ result
+ (list result))
+ nil)
+ "\n"))
+ (goto-char beg)
+ (when (org-at-table-p) (org-table-align))
+ (goto-char (org-table-end)))
+ ;; Print verbatim a list that cannot be turned into
+ ;; a table.
+ ((listp result) (insert (format "%s\n" result)))
+ ((member "file" result-params)
+ (when inline
+ (setq result (org-macro-escape-arguments result)))
+ (insert result))
+ ((and inline (not (member "raw" result-params)))
+ (insert (org-macro-escape-arguments
+ (org-babel-chomp result "\n"))))
+ (t (goto-char beg) (insert result)))
+ (setq end (point-marker))
+ ;; possibly wrap result
+ (cond
+ ((assq :wrap (nth 2 info))
+ (let ((name (or (cdr (assq :wrap (nth 2 info))) "RESULTS")))
+ (funcall wrap (concat "#+BEGIN_" name)
+ (concat "#+END_" (car (org-split-string name)))
+ nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
+ ((member "html" result-params)
+ (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
+ "{{{results(@@html:" "@@)}}}"))
+ ((member "latex" result-params)
+ (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
+ "{{{results(@@latex:" "@@)}}}"))
+ ((member "org" result-params)
+ (goto-char beg) (when (org-at-table-p) (org-cycle))
+ (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil
+ "{{{results(src_org{" "})}}}"))
+ ((member "code" result-params)
+ (let ((lang (or lang "none")))
+ (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches)
+ "#+END_SRC" nil nil
+ (format "{{{results(src_%s[%s]{" lang results-switches)
+ "})}}}")))
+ ((member "raw" result-params)
+ (goto-char beg) (when (org-at-table-p) (org-cycle)))
+ ((or (member "drawer" result-params)
+ ;; Stay backward compatible with <7.9.2
+ (member "wrap" result-params))
+ (goto-char beg) (when (org-at-table-p) (org-cycle))
+ (funcall wrap ":RESULTS:" ":END:" 'no-escape nil
+ "{{{results(" ")}}}"))
+ ((and inline (member "file" result-params))
+ (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
+ ((and (not (funcall tabulablep result))
+ (not (member "file" result-params)))
+ (let ((org-babel-inline-result-wrap
+ ;; Hard code {{{results(...)}}} on top of customization.
+ (format "{{{results(%s)}}}"
+ org-babel-inline-result-wrap)))
+ (org-babel-examplify-region beg end results-switches inline)
+ (setq end (point))))))
+ ;; Possibly indent results in par with #+results line.
+ (when (and (not inline) (numberp indent) (> indent 0)
+ ;; In this case `table-align' does the work
+ ;; for us.
+ (not (and (listp result)
+ (member "append" result-params))))
+ (indent-rigidly beg end indent))
+ (if (null result)
+ (if (member "value" result-params)
+ (message "Code block returned no value.")
+ (message "Code block produced no output."))
+ (message "Code block evaluation complete.")))
+ (when outside-scope (narrow-to-region visible-beg visible-end))
+ (set-marker visible-beg nil)
+ (set-marker visible-end nil)))))))
+
+(defun org-babel-remove-result (&optional info keep-keyword)
+ "Remove the result of the current source block."
+ (interactive)
+ (let ((location (org-babel-where-is-src-block-result nil info)))
+ (when location
+ (save-excursion
+ (goto-char location)
+ (when (looking-at (concat org-babel-result-regexp ".*$"))
+ (delete-region
+ (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
+ (progn (forward-line 1) (org-babel-result-end))))))))
+
+(defun org-babel-remove-inline-result (&optional datum)
+ "Remove the result of the current inline-src-block or babel call.
+The result must be wrapped in a `results' macro to be removed.
+Leading white space is trimmed."
+ (interactive)
+ (let* ((el (or datum (org-element-context))))
+ (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
+ (org-with-wide-buffer
+ (goto-char (org-element-property :end el))
+ (skip-chars-backward " \t")
+ (let ((result (save-excursion
+ (skip-chars-forward
+ " \t\n"
+ (org-element-property
+ :contents-end (org-element-property :parent el)))
+ (org-element-context))))
+ (when (and (eq (org-element-type result) 'macro)
+ (string= (org-element-property :key result) "results"))
+ (delete-region ; And leading whitespace.
+ (point)
+ (progn (goto-char (org-element-property :end result))
+ (skip-chars-backward " \t\n")
+ (point)))))))))
+
+(defun org-babel-remove-result-one-or-many (x)
+ "Remove the result of the current source block.
+If called with a prefix argument, remove all result blocks
+in the buffer."
+ (interactive "P")
+ (if x
+ (org-babel-map-src-blocks nil (org-babel-remove-result))
+ (org-babel-remove-result)))
+
+(defun org-babel-result-end ()
+ "Return the point at the end of the current set of results."
+ (save-excursion
+ (cond
+ ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
+ ((org-at-item-p) (let* ((struct (org-list-struct))
+ (prvs (org-list-prevs-alist struct)))
+ (org-list-get-list-end (point-at-bol) struct prvs)))
+ ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
+ (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
+ (forward-char 1) (point)))
+ (t
+ (let ((case-fold-search t))
+ (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
+ (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
+ nil t)
+ (forward-char 1))
+ (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
+ (forward-line 1))))
+ (point)))))
+
+(defun org-babel-result-to-file (result &optional description)
+ "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
+If the `default-directory' is different from the containing
+file's directory then expand relative links."
+ (when (stringp result)
+ (format "[[file:%s]%s]"
+ (if (and default-directory
+ buffer-file-name
+ (not (string= (expand-file-name default-directory)
+ (expand-file-name
+ (file-name-directory buffer-file-name)))))
+ (expand-file-name result default-directory)
+ result)
+ (if description (concat "[" description "]") ""))))
+
+(defvar org-babel-capitalize-example-region-markers nil
+ "Make true to capitalize begin/end example markers inserted by code blocks.")
+
+(defun org-babel-examplify-region (beg end &optional results-switches inline)
+ "Comment out region using the inline `==' or `: ' org example quote."
+ (interactive "*r")
+ (let ((maybe-cap
+ (lambda (str)
+ (if org-babel-capitalize-example-region-markers (upcase str) str))))
+ (if inline
+ (save-excursion
+ (goto-char beg)
+ (insert (format org-babel-inline-result-wrap
+ (delete-and-extract-region beg end))))
+ (let ((size (count-lines beg end)))
+ (save-excursion
+ (cond ((= size 0)) ; do nothing for an empty result
+ ((< size org-babel-min-lines-for-block-output)
+ (goto-char beg)
+ (dotimes (_ size)
+ (beginning-of-line 1) (insert ": ") (forward-line 1)))
+ (t
+ (goto-char beg)
+ (insert (if results-switches
+ (format "%s%s\n"
+ (funcall maybe-cap "#+begin_example")
+ results-switches)
+ (funcall maybe-cap "#+begin_example\n")))
+ (let ((p (point)))
+ (if (markerp end) (goto-char end) (forward-char (- end beg)))
+ (org-escape-code-in-region p (point)))
+ (insert (funcall maybe-cap "#+end_example\n")))))))))
+
+(defun org-babel-update-block-body (new-body)
+ "Update the body of the current code block to NEW-BODY."
+ (let ((element (org-element-at-point)))
+ (unless (eq (org-element-type element) 'src-block)
+ (error "Not in a source block"))
+ (goto-char (org-babel-where-is-src-block-head element))
+ (let* ((ind (org-get-indentation))
+ (body-start (line-beginning-position 2))
+ (body (org-element-normalize-string
+ (if (or org-src-preserve-indentation
+ (org-element-property :preserve-indent element))
+ new-body
+ (with-temp-buffer
+ (insert (org-remove-indentation new-body))
+ (indent-rigidly
+ (point-min)
+ (point-max)
+ (+ ind org-edit-src-content-indentation))
+ (buffer-string))))))
+ (delete-region body-start
+ (org-with-wide-buffer
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \t\n")
+ (line-beginning-position)))
+ (goto-char body-start)
+ (insert body))))
+
+(defun org-babel-merge-params (&rest plists)
+ "Combine all parameter association lists in PLISTS.
+Later elements of PLISTS override the values of previous elements.
+This takes into account some special considerations for certain
+parameters when merging lists."
+ (let* ((results-exclusive-groups
+ (mapcar (lambda (group) (mapcar #'symbol-name group))
+ (cdr (assq 'results org-babel-common-header-args-w-values))))
+ (exports-exclusive-groups
+ (mapcar (lambda (group) (mapcar #'symbol-name group))
+ (cdr (assq 'exports org-babel-common-header-args-w-values))))
+ (merge
+ (lambda (exclusive-groups &rest result-params)
+ ;; Maintain exclusivity of mutually exclusive parameters,
+ ;; as defined in EXCLUSIVE-GROUPS while merging lists in
+ ;; RESULT-PARAMS.
+ (let (output)
+ (dolist (new-params result-params (delete-dups output))
+ (dolist (new-param new-params)
+ (dolist (exclusive-group exclusive-groups)
+ (when (member new-param exclusive-group)
+ (setq output (cl-remove-if
+ (lambda (o) (member o exclusive-group))
+ output))))
+ (push new-param output))))))
+ (variable-index 0) ;Handle positional arguments.
+ clearnames
+ params ;Final parameters list.
+ ;; Some keywords accept multiple values. We need to treat
+ ;; them specially.
+ vars results exports)
+ (dolist (plist plists)
+ (dolist (pair plist)
+ (pcase pair
+ (`(:var . ,value)
+ (let ((name (cond
+ ((listp value) (car value))
+ ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
+ (intern (match-string 1 value)))
+ (t nil))))
+ (cond
+ (name
+ (setq vars
+ (append (if (not (assoc name vars)) vars
+ (push name clearnames)
+ (cl-remove-if (lambda (p) (equal name (car p)))
+ vars))
+ (list (cons name pair)))))
+ ((and vars (nth variable-index vars))
+ ;; If no name is given and we already have named
+ ;; variables then assign to named variables in order.
+ (let ((name (car (nth variable-index vars))))
+ ;; Clear out colnames and rownames for replace vars.
+ (push name clearnames)
+ (setf (cddr (nth variable-index vars))
+ (concat (symbol-name name) "=" value))
+ (cl-incf variable-index)))
+ (t (error "Variable \"%s\" must be assigned a default value"
+ (cdr pair))))))
+ (`(:results . ,value)
+ (setq results (funcall merge
+ results-exclusive-groups
+ results
+ (split-string
+ (if (stringp value) value (eval value t))))))
+ (`(,(or :file :file-ext) . ,value)
+ ;; `:file' and `:file-ext' are regular keywords but they
+ ;; imply a "file" `:results' and a "results" `:exports'.
+ (when value
+ (setq results
+ (funcall merge results-exclusive-groups results '("file")))
+ (unless (or (member "both" exports)
+ (member "none" exports)
+ (member "code" exports))
+ (setq exports
+ (funcall merge
+ exports-exclusive-groups exports '("results"))))
+ (push pair params)))
+ (`(:exports . ,value)
+ (setq exports (funcall merge
+ exports-exclusive-groups
+ exports
+ (split-string (or value "")))))
+ ;; Regular keywords: any value overwrites the previous one.
+ (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
+ ;; Handle `:var' and clear out colnames and rownames for replaced
+ ;; variables.
+ (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
+ params))
+ (dolist (name clearnames)
+ (dolist (param '(:colname-names :rowname-names))
+ (when (assq param params)
+ (setf (cdr (assq param params))
+ (cl-remove-if (lambda (pair) (equal name (car pair)))
+ (cdr (assq param params))))
+ (setq params
+ (cl-remove-if (lambda (pair) (and (equal (car pair) param)
+ (null (cdr pair))))
+ params)))))
+ ;; Handle other special keywords, which accept multiple values.
+ (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
+ (cons :exports (mapconcat #'identity exports " ")))
+ params))
+ ;; Return merged params.
+ params))
+
+(defvar org-babel-use-quick-and-dirty-noweb-expansion nil
+ "Set to true to use regular expressions to expand noweb references.
+This results in much faster noweb reference expansion but does
+not properly allow code blocks to inherit the \":noweb-ref\"
+header argument from buffer or subtree wide properties.")
+
+(defun org-babel-noweb-p (params context)
+ "Check if PARAMS require expansion in CONTEXT.
+CONTEXT may be one of :tangle, :export or :eval."
+ (let ((allowed-values (cl-case context
+ (:tangle '("yes" "tangle" "no-export" "strip-export"))
+ (:eval '("yes" "no-export" "strip-export" "eval"))
+ (:export '("yes")))))
+ (cl-some (lambda (v) (member v allowed-values))
+ (split-string (or (cdr (assq :noweb params)) "")))))
+
+(defun org-babel-expand-noweb-references (&optional info parent-buffer)
+ "Expand Noweb references in the body of the current source code block.
+
+For example the following reference would be replaced with the
+body of the source-code block named `example-block'.
+
+<<example-block>>
+
+Note that any text preceding the <<foo>> construct on a line will
+be interposed between the lines of the replacement text. So for
+example if <<foo>> is placed behind a comment, then the entire
+replacement text will also be commented.
+
+This function must be called from inside of the buffer containing
+the source-code block which holds BODY.
+
+In addition the following syntax can be used to insert the
+results of evaluating the source-code block named `example-block'.
+
+<<example-block()>>
+
+Any optional arguments can be passed to example-block by placing
+the arguments inside the parenthesis following the convention
+defined by `org-babel-lob'. For example
+
+<<example-block(a=9)>>
+
+would set the value of argument \"a\" equal to \"9\". Note that
+these arguments are not evaluated in the current source-code
+block but are passed literally to the \"example-block\"."
+ (let* ((parent-buffer (or parent-buffer (current-buffer)))
+ (info (or info (org-babel-get-src-block-info 'light)))
+ (lang (nth 0 info))
+ (body (nth 1 info))
+ (ob-nww-start org-babel-noweb-wrap-start)
+ (ob-nww-end org-babel-noweb-wrap-end)
+ (comment (string= "noweb" (cdr (assq :comments (nth 2 info)))))
+ (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
+ ":noweb-ref[ \t]+" "\\)"))
+ (new-body "")
+ (nb-add (lambda (text) (setq new-body (concat new-body text))))
+ (c-wrap (lambda (text)
+ (with-temp-buffer
+ (funcall (intern (concat lang "-mode")))
+ (comment-region (point) (progn (insert text) (point)))
+ (org-trim (buffer-string)))))
+ index source-name evaluate prefix)
+ (with-temp-buffer
+ (setq-local org-babel-noweb-wrap-start ob-nww-start)
+ (setq-local org-babel-noweb-wrap-end ob-nww-end)
+ (insert body) (goto-char (point-min))
+ (setq index (point))
+ (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
+ (save-match-data (setf source-name (match-string 1)))
+ (save-match-data (setq evaluate (string-match "(.*)" source-name)))
+ (save-match-data
+ (setq prefix
+ (buffer-substring (match-beginning 0)
+ (save-excursion
+ (beginning-of-line 1) (point)))))
+ ;; add interval to new-body (removing noweb reference)
+ (goto-char (match-beginning 0))
+ (funcall nb-add (buffer-substring index (point)))
+ (goto-char (match-end 0))
+ (setq index (point))
+ (funcall
+ nb-add
+ (with-current-buffer parent-buffer
+ (save-restriction
+ (widen)
+ (mapconcat ;; Interpose PREFIX between every line.
+ #'identity
+ (split-string
+ (if evaluate
+ (let ((raw (org-babel-ref-resolve source-name)))
+ (if (stringp raw) raw (format "%S" raw)))
+ (or
+ ;; Retrieve from the library of babel.
+ (nth 2 (assoc (intern source-name)
+ org-babel-library-of-babel))
+ ;; Return the contents of headlines literally.
+ (save-excursion
+ (when (org-babel-ref-goto-headline-id source-name)
+ (org-babel-ref-headline-body)))
+ ;; Find the expansion of reference in this buffer.
+ (let ((rx (concat rx-prefix source-name "[ \t\n]"))
+ expansion)
+ (save-excursion
+ (goto-char (point-min))
+ (if org-babel-use-quick-and-dirty-noweb-expansion
+ (while (re-search-forward rx nil t)
+ (let* ((i (org-babel-get-src-block-info 'light))
+ (body (org-babel-expand-noweb-references i))
+ (sep (or (cdr (assq :noweb-sep (nth 2 i)))
+ "\n"))
+ (full (if comment
+ (let ((cs (org-babel-tangle-comment-links i)))
+ (concat (funcall c-wrap (car cs)) "\n"
+ body "\n"
+ (funcall c-wrap (cadr cs))))
+ body)))
+ (setq expansion (cons sep (cons full expansion)))))
+ (org-babel-map-src-blocks nil
+ (let ((i (org-babel-get-src-block-info 'light)))
+ (when (equal (or (cdr (assq :noweb-ref (nth 2 i)))
+ (nth 4 i))
+ source-name)
+ (let* ((body (org-babel-expand-noweb-references i))
+ (sep (or (cdr (assq :noweb-sep (nth 2 i)))
+ "\n"))
+ (full (if comment
+ (let ((cs (org-babel-tangle-comment-links i)))
+ (concat (funcall c-wrap (car cs)) "\n"
+ body "\n"
+ (funcall c-wrap (cadr cs))))
+ body)))
+ (setq expansion
+ (cons sep (cons full expansion)))))))))
+ (and expansion
+ (mapconcat #'identity (nreverse (cdr expansion)) "")))
+ ;; Possibly raise an error if named block doesn't exist.
+ (if (or org-babel-noweb-error-all-langs
+ (member lang org-babel-noweb-error-langs))
+ (error "%s" (concat
+ (org-babel-noweb-wrap source-name)
+ "could not be resolved (see "
+ "`org-babel-noweb-error-langs')"))
+ "")))
+ "[\n\r]") (concat "\n" prefix))))))
+ (funcall nb-add (buffer-substring index (point-max))))
+ new-body))
+
+(defun org-babel--script-escape-inner (str)
+ (let (in-single in-double backslash out)
+ (mapc
+ (lambda (ch)
+ (setq
+ out
+ (if backslash
+ (progn
+ (setq backslash nil)
+ (cond
+ ((and in-single (eq ch ?'))
+ ;; Escaped single quote inside single quoted string:
+ ;; emit just a single quote, since we've changed the
+ ;; outer quotes to double.
+ (cons ch out))
+ ((eq ch ?\")
+ ;; Escaped double quote
+ (if in-single
+ ;; This should be interpreted as backslash+quote,
+ ;; not an escape. Emit a three backslashes
+ ;; followed by a quote (because one layer of
+ ;; quoting will be stripped by `org-babel-read').
+ (append (list ch ?\\ ?\\ ?\\) out)
+ ;; Otherwise we are in a double-quoted string. Emit
+ ;; a single escaped quote
+ (append (list ch ?\\) out)))
+ ((eq ch ?\\)
+ ;; Escaped backslash: emit a single escaped backslash
+ (append (list ?\\ ?\\) out))
+ ;; Other: emit a quoted backslash followed by whatever
+ ;; the character was (because one layer of quoting will
+ ;; be stripped by `org-babel-read').
+ (t (append (list ch ?\\ ?\\) out))))
+ (cl-case ch
+ (?\[ (if (or in-double in-single)
+ (cons ?\[ out)
+ (cons ?\( out)))
+ (?\] (if (or in-double in-single)
+ (cons ?\] out)
+ (cons ?\) out)))
+ (?\{ (if (or in-double in-single)
+ (cons ?\{ out)
+ (cons ?\( out)))
+ (?\} (if (or in-double in-single)
+ (cons ?\} out)
+ (cons ?\) out)))
+ (?, (if (or in-double in-single)
+ (cons ?, out) (cons ?\s out)))
+ (?\' (if in-double
+ (cons ?\' out)
+ (setq in-single (not in-single)) (cons ?\" out)))
+ (?\" (if in-single
+ (append (list ?\" ?\\) out)
+ (setq in-double (not in-double)) (cons ?\" out)))
+ (?\\ (unless (or in-single in-double)
+ (error "Can't handle backslash outside string in `org-babel-script-escape'"))
+ (setq backslash t)
+ out)
+ (t (cons ch out))))))
+ (string-to-list str))
+ (when (or in-single in-double)
+ (error "Unterminated string in `org-babel-script-escape'"))
+ (apply #'string (reverse out))))
+
+(defun org-babel-script-escape (str &optional force)
+ "Safely convert tables into elisp lists."
+ (unless (stringp str)
+ (error "`org-babel-script-escape' expects a string"))
+ (let ((escaped
+ (cond
+ ((and (> (length str) 2)
+ (or (and (string-equal "[" (substring str 0 1))
+ (string-equal "]" (substring str -1)))
+ (and (string-equal "{" (substring str 0 1))
+ (string-equal "}" (substring str -1)))
+ (and (string-equal "(" (substring str 0 1))
+ (string-equal ")" (substring str -1)))))
+
+ (concat "'" (org-babel--script-escape-inner str)))
+ ((or force
+ (and (> (length str) 2)
+ (or (and (string-equal "'" (substring str 0 1))
+ (string-equal "'" (substring str -1)))
+ ;; We need to pass double-quoted strings
+ ;; through the backslash-twiddling bits, even
+ ;; though we don't need to change their
+ ;; delimiters.
+ (and (string-equal "\"" (substring str 0 1))
+ (string-equal "\"" (substring str -1))))))
+ (org-babel--script-escape-inner str))
+ (t str))))
+ (condition-case nil (org-babel-read escaped) (error escaped))))
+
+(defun org-babel-read (cell &optional inhibit-lisp-eval)
+ "Convert the string value of CELL to a number if appropriate.
+Otherwise if CELL looks like lisp (meaning it starts with a
+\"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
+lisp, otherwise return it unmodified as a string. Optional
+argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
+situations in which is it not appropriate."
+ (cond ((not (org-string-nw-p cell)) cell)
+ ((org-babel--string-to-number cell))
+ ((and (not inhibit-lisp-eval)
+ (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
+ (string= cell "*this*")))
+ (eval (read cell) t))
+ ((eq (string-to-char cell) ?\") (read cell))
+ (t (org-no-properties cell))))
+
+(defun org-babel--string-to-number (string)
+ "If STRING represents a number return its value.
+Otherwise return nil."
+ (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string)
+ (string-to-number string)))
+
+(defun org-babel-import-elisp-from-file (file-name &optional separator)
+ "Read the results located at FILE-NAME into an elisp table.
+If the table is trivial, then return it as a scalar."
+ (let (result)
+ (save-window-excursion
+ (with-temp-buffer
+ (condition-case err
+ (progn
+ (org-table-import file-name separator)
+ (delete-file file-name)
+ (setq result (mapcar (lambda (row)
+ (mapcar #'org-babel-string-read row))
+ (org-table-to-lisp))))
+ (error (message "Error reading results: %s" err) nil)))
+ (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
+ (if (consp (car result))
+ (if (null (cdr (car result)))
+ (caar result)
+ result)
+ (car result))
+ result))))
+
+(defun org-babel-string-read (cell)
+ "Strip nested \"s from around strings."
+ (org-babel-read (or (and (stringp cell)
+ (string-match "\\\"\\(.+\\)\\\"" cell)
+ (match-string 1 cell))
+ cell) t))
+
+(defun org-babel-chomp (string &optional regexp)
+ "Strip a trailing space or carriage return from STRING.
+The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
+can be specified as the REGEXP argument."
+ (let ((regexp (or regexp "[ \f\t\n\r\v]")))
+ (while (and (> (length string) 0)
+ (string-match regexp (substring string -1)))
+ (setq string (substring string 0 -1)))
+ string))
+
+(defun org-babel-process-file-name (name &optional no-quote-p)
+ "Prepare NAME to be used in an external process.
+If NAME specifies a remote location, the remote portion of the
+name is removed, since in that case the process will be executing
+remotely. The file name is then processed by `expand-file-name'.
+Unless second argument NO-QUOTE-P is non-nil, the file name is
+additionally processed by `shell-quote-argument'"
+ (let ((f (org-babel-local-file-name (expand-file-name name))))
+ (if no-quote-p f (shell-quote-argument f))))
+
+(defvar org-babel-temporary-directory)
+(unless (or noninteractive (boundp 'org-babel-temporary-directory))
+ (defvar org-babel-temporary-directory
+ (or (and (boundp 'org-babel-temporary-directory)
+ (file-exists-p org-babel-temporary-directory)
+ org-babel-temporary-directory)
+ (make-temp-file "babel-" t))
+ "Directory to hold temporary files created to execute code blocks.
+Used by `org-babel-temp-file'. This directory will be removed on
+Emacs shutdown."))
+
+(defcustom org-babel-remote-temporary-directory "/tmp/"
+ "Directory to hold temporary files on remote hosts."
+ :group 'org-babel
+ :type 'string)
+
+(defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
+ "Call the code to parse raw string results according to RESULT-PARAMS."
+ (declare (indent 1)
+ (debug (form form &rest form)))
+ (org-with-gensyms (params)
+ `(let ((,params ,result-params))
+ (unless (member "none" ,params)
+ (if (or (member "scalar" ,params)
+ (member "verbatim" ,params)
+ (member "html" ,params)
+ (member "code" ,params)
+ (member "pp" ,params)
+ (member "file" ,params)
+ (and (or (member "output" ,params)
+ (member "raw" ,params)
+ (member "org" ,params)
+ (member "drawer" ,params))
+ (not (member "table" ,params))))
+ ,scalar-form
+ ,@table-forms)))))
+(def-edebug-spec org-babel-result-cond (form form body))
+
+(defun org-babel-temp-file (prefix &optional suffix)
+ "Create a temporary file in the `org-babel-temporary-directory'.
+Passes PREFIX and SUFFIX directly to `make-temp-file' with the
+value of `temporary-file-directory' temporarily set to the value
+of `org-babel-temporary-directory'."
+ (if (file-remote-p default-directory)
+ (let ((prefix
+ (concat (file-remote-p default-directory)
+ (expand-file-name
+ prefix org-babel-remote-temporary-directory))))
+ (make-temp-file prefix nil suffix))
+ (let ((temporary-file-directory
+ (or (and (boundp 'org-babel-temporary-directory)
+ (file-exists-p org-babel-temporary-directory)
+ org-babel-temporary-directory)
+ temporary-file-directory)))
+ (make-temp-file prefix nil suffix))))
+
+(defun org-babel-remove-temporary-directory ()
+ "Remove `org-babel-temporary-directory' on Emacs shutdown."
+ (when (and (boundp 'org-babel-temporary-directory)
+ (file-exists-p org-babel-temporary-directory))
+ ;; taken from `delete-directory' in files.el
+ (condition-case nil
+ (progn
+ (mapc (lambda (file)
+ ;; This test is equivalent to
+ ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
+ ;; but more efficient
+ (if (eq t (car (file-attributes file)))
+ (delete-directory file)
+ (delete-file file)))
+ ;; We do not want to delete "." and "..".
+ (directory-files org-babel-temporary-directory 'full
+ "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
+ (delete-directory org-babel-temporary-directory))
+ (error
+ (message "Failed to remove temporary Org-babel directory %s"
+ (if (boundp 'org-babel-temporary-directory)
+ org-babel-temporary-directory
+ "[directory not defined]"))))))
+
+(add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
+
+(defun org-babel-one-header-arg-safe-p (pair safe-list)
+ "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
+
+For the format of SAFE-LIST, see `org-babel-safe-header-args'."
+ (and (consp pair)
+ (keywordp (car pair))
+ (stringp (cdr pair))
+ (or
+ (memq (car pair) safe-list)
+ (let ((entry (assq (car pair) safe-list)))
+ (and entry
+ (consp entry)
+ (cond ((functionp (cdr entry))
+ (funcall (cdr entry) (cdr pair)))
+ ((listp (cdr entry))
+ (member (cdr pair) (cdr entry)))
+ (t nil)))))))
+
+(defun org-babel-generate-file-param (src-name params)
+ "Calculate the filename for source block results.
+
+The directory is calculated from the :output-dir property of the
+source block; if not specified, use the current directory.
+
+If the source block has a #+NAME and the :file parameter does not
+contain any period characters, then the :file parameter is
+treated as an extension, and the output file name is the
+concatenation of the directory (as calculated above), the block
+name, a period, and the parameter value as a file extension.
+Otherwise, the :file parameter is treated as a full file name,
+and the output file name is the directory (as calculated above)
+plus the parameter value."
+ (let* ((file-cons (assq :file params))
+ (file-ext-cons (assq :file-ext params))
+ (file-ext (cdr-safe file-ext-cons))
+ (dir (cdr-safe (assq :output-dir params)))
+ fname)
+ ;; create the output-dir if it does not exist
+ (when dir
+ (make-directory dir t))
+ (if file-cons
+ ;; :file given; add :output-dir if given
+ (when dir
+ (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
+ ;; :file not given; compute from name and :file-ext if possible
+ (when (and src-name file-ext)
+ (if dir
+ (setq fname (concat (file-name-as-directory (or dir ""))
+ src-name "." file-ext))
+ (setq fname (concat src-name "." file-ext)))
+ (setq params (cons (cons :file fname) params))))
+ params))
+
+(defun org-babel-graphical-output-file (params)
+ "File where a babel block should send graphical output, per PARAMS.
+Return nil if no graphical output is expected. Raise an error if
+the output file is ill-defined."
+ (let ((file (cdr (assq :file params))))
+ (cond (file (and (member "graphics" (cdr (assq :result-params params)))
+ file))
+ ((assq :file-ext params)
+ (user-error ":file-ext given but no :file generated; did you forget \
+to name a block?"))
+ (t (user-error "No :file header argument given; cannot create \
+graphical result")))))
+
+(defun org-babel-make-language-alias (new old)
+ "Make source blocks of type NEW aliases for those of type OLD.
+
+NEW and OLD should be strings. This function should be called
+after the babel API for OLD-type source blocks is fully defined.
+
+Callers of this function will probably want to add an entry to
+`org-src-lang-modes' as well."
+ (dolist (fn '("execute" "expand-body" "prep-session"
+ "variable-assignments" "load-session"))
+ (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
+ (when (and sym (fboundp sym))
+ (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
+ ;; Technically we don't need a `dolist' for just one variable, but
+ ;; we keep it for symmetry/ease of future expansion.
+ (dolist (var '("default-header-args"))
+ (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
+ (when (and sym (boundp sym))
+ (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
+
+(defun org-babel-strip-quotes (string)
+ "Strip \\\"s from around a string, if applicable."
+ (org-unbracket-string "\"" "\"" string))
+
+(provide 'ob-core)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ob-core.el ends here
diff --git a/lisp/ob-css.el b/lisp/ob-css.el
new file mode 100644
index 0000000..4203b12
--- /dev/null
+++ b/lisp/ob-css.el
@@ -0,0 +1,48 @@
+;;; ob-css.el --- Babel Functions for CSS -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Since CSS can't be executed, this file exists solely for tangling
+;; CSS from Org files.
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:css '())
+
+(defun org-babel-execute:css (body _params)
+ "Execute a block of CSS code.
+This function is called by `org-babel-execute-src-block'."
+ body)
+
+(defun org-babel-prep-session:css (_session _params)
+ "Return an error if the :session header argument is set.
+CSS does not support sessions."
+ (error "CSS sessions are nonsensical"))
+
+(provide 'ob-css)
+
+
+
+;;; ob-css.el ends here
diff --git a/lisp/ob-ditaa.el b/lisp/ob-ditaa.el
new file mode 100644
index 0000000..89b5d24
--- /dev/null
+++ b/lisp/ob-ditaa.el
@@ -0,0 +1,124 @@
+;;; ob-ditaa.el --- Babel Functions for ditaa -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating ditaa source code.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in ditaa
+;;
+;; 2) we are generally only going to return results of type "file"
+;;
+;; 3) we are adding the "file" and "cmdline" header arguments
+;;
+;; 4) there are no variables (at least for now)
+
+;;; Code:
+(require 'ob)
+(require 'org-compat)
+
+(defvar org-babel-default-header-args:ditaa
+ '((:results . "file")
+ (:exports . "results")
+ (:java . "-Dfile.encoding=UTF-8"))
+ "Default arguments for evaluating a ditaa source block.")
+
+(defcustom org-ditaa-jar-path (expand-file-name
+ "ditaa.jar"
+ (file-name-as-directory
+ (expand-file-name
+ "scripts"
+ (file-name-as-directory
+ (expand-file-name
+ "../contrib"
+ (file-name-directory (org-find-library-dir "org")))))))
+ "Path to the ditaa jar executable."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-ditaa-java-cmd "java"
+ "Java executable to use when evaluating ditaa blocks."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-ditaa-eps-jar-path
+ (expand-file-name "DitaaEps.jar" (file-name-directory org-ditaa-jar-path))
+ "Path to the DitaaEps.jar executable."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-ditaa-jar-option "-jar"
+ "Option for the ditaa jar file.
+Do not leave leading or trailing spaces in this string."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defun org-babel-execute:ditaa (body params)
+ "Execute a block of Ditaa code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((out-file (or (cdr (assq :file params))
+ (error
+ "ditaa code block requires :file header argument")))
+ (cmdline (cdr (assq :cmdline params)))
+ (java (cdr (assq :java params)))
+ (in-file (org-babel-temp-file "ditaa-"))
+ (eps (cdr (assq :eps params)))
+ (eps-file (when eps
+ (org-babel-process-file-name (concat in-file ".eps"))))
+ (pdf-cmd (when (and (or (string= (file-name-extension out-file) "pdf")
+ (cdr (assq :pdf params))))
+ (concat
+ "epstopdf"
+ " " eps-file
+ " -o=" (org-babel-process-file-name out-file))))
+ (cmd (concat org-babel-ditaa-java-cmd
+ " " java " " org-ditaa-jar-option " "
+ (shell-quote-argument
+ (expand-file-name
+ (if eps org-ditaa-eps-jar-path org-ditaa-jar-path)))
+ " " cmdline
+ " " (org-babel-process-file-name in-file)
+ " " (if pdf-cmd
+ eps-file
+ (org-babel-process-file-name out-file)))))
+ (unless (file-exists-p org-ditaa-jar-path)
+ (error "Could not find ditaa.jar at %s" org-ditaa-jar-path))
+ (with-temp-file in-file (insert body))
+ (message cmd) (shell-command cmd)
+ (when pdf-cmd (message pdf-cmd) (shell-command pdf-cmd))
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:ditaa (_session _params)
+ "Return an error because ditaa does not support sessions."
+ (error "Ditaa does not support sessions"))
+
+(provide 'ob-ditaa)
+
+
+
+;;; ob-ditaa.el ends here
diff --git a/lisp/ob-dot.el b/lisp/ob-dot.el
new file mode 100644
index 0000000..81442bf
--- /dev/null
+++ b/lisp/ob-dot.el
@@ -0,0 +1,90 @@
+;;; ob-dot.el --- Babel Functions for dot -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating dot source code.
+;;
+;; For information on dot see http://www.graphviz.org/
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in dot
+;;
+;; 2) we are generally only going to return results of type "file"
+;;
+;; 3) we are adding the "file" and "cmdline" header arguments
+;;
+;; 4) there are no variables (at least for now)
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:dot
+ '((:results . "file") (:exports . "results"))
+ "Default arguments to use when evaluating a dot source block.")
+
+(defun org-babel-expand-body:dot (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (mapc
+ (lambda (pair)
+ (let ((name (symbol-name (car pair)))
+ (value (cdr pair)))
+ (setq body
+ (replace-regexp-in-string
+ (concat "$" (regexp-quote name))
+ (if (stringp value) value (format "%S" value))
+ body
+ t
+ t))))
+ vars)
+ body))
+
+(defun org-babel-execute:dot (body params)
+ "Execute a block of Dot code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((out-file (cdr (or (assq :file params)
+ (error "You need to specify a :file parameter"))))
+ (cmdline (or (cdr (assq :cmdline params))
+ (format "-T%s" (file-name-extension out-file))))
+ (cmd (or (cdr (assq :cmd params)) "dot"))
+ (in-file (org-babel-temp-file "dot-")))
+ (with-temp-file in-file
+ (insert (org-babel-expand-body:dot body params)))
+ (org-babel-eval
+ (concat cmd
+ " " (org-babel-process-file-name in-file)
+ " " cmdline
+ " -o " (org-babel-process-file-name out-file)) "")
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:dot (_session _params)
+ "Return an error because Dot does not support sessions."
+ (error "Dot does not support sessions"))
+
+(provide 'ob-dot)
+
+
+
+;;; ob-dot.el ends here
diff --git a/lisp/ob-ebnf.el b/lisp/ob-ebnf.el
new file mode 100644
index 0000000..410570b
--- /dev/null
+++ b/lisp/ob-ebnf.el
@@ -0,0 +1,83 @@
+;;; ob-ebnf.el --- Babel Functions for EBNF -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: Michael Gauland
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+;; Version: 1.00
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+
+;;; Commentary:
+
+;;; Org-Babel support for using ebnf2ps to generate encapsulated postscript
+;;; railroad diagrams. It recogises these arguments:
+;;;
+;;; :file is required; it must include the extension '.eps.' All the rules
+;;; in the block will be drawn in the same file. This is done by
+;;; inserting a '[<file>' comment at the start of the block (see the
+;;; documentation for ebnf-eps-buffer for more information).
+;;;
+;;; :style specifies a value in ebnf-style-database. This provides the
+;;; ability to customise the output. The style can also specify the
+;;; grammar syntax (by setting ebnf-syntax); note that only ebnf,
+;;; iso-ebnf, and yacc are supported by this file.
+
+;;; Requirements:
+
+;;; Code:
+(require 'ob)
+(require 'ebnf2ps)
+
+;; optionally declare default header arguments for this language
+(defvar org-babel-default-header-args:ebnf '((:style . nil)))
+
+;; Use ebnf-eps-buffer to produce an encapsulated postscript file.
+;;
+(defun org-babel-execute:ebnf (body params)
+ "Execute a block of Ebnf code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (save-excursion
+ (let* ((dest-file (cdr (assq :file params)))
+ (dest-dir (file-name-directory dest-file))
+ (dest-root (file-name-sans-extension
+ (file-name-nondirectory dest-file)))
+ (style (cdr (assq :style params)))
+ (result nil))
+ (with-temp-buffer
+ (when style (ebnf-push-style style))
+ (let ((comment-format
+ (cond ((string= ebnf-syntax 'yacc) "/*%s*/")
+ ((string= ebnf-syntax 'ebnf) ";%s")
+ ((string= ebnf-syntax 'iso-ebnf) "(*%s*)")
+ (t (setq result
+ (format "EBNF error: format %s not supported."
+ ebnf-syntax))))))
+ (setq ebnf-eps-prefix dest-dir)
+ (insert (format comment-format (format "[%s" dest-root)))
+ (newline)
+ (insert body)
+ (newline)
+ (insert (format comment-format (format "]%s" dest-root)))
+ (ebnf-eps-buffer)
+ (when style (ebnf-pop-style))))
+ result)))
+
+(provide 'ob-ebnf)
+;;; ob-ebnf.el ends here
diff --git a/lisp/ob-emacs-lisp.el b/lisp/ob-emacs-lisp.el
new file mode 100644
index 0000000..c0bd12a
--- /dev/null
+++ b/lisp/ob-emacs-lisp.el
@@ -0,0 +1,94 @@
+;;; ob-emacs-lisp.el --- Babel Functions for Emacs-lisp Code -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating emacs-lisp code
+
+;;; Code:
+(require 'ob)
+
+(defconst org-babel-header-args:emacs-lisp '((lexical . :any))
+ "Emacs-lisp specific header arguments.")
+
+(defvar org-babel-default-header-args:emacs-lisp '((:lexical . "no"))
+ "Default arguments for evaluating an emacs-lisp source block.
+
+A value of \"yes\" or t causes src blocks to be eval'd using
+lexical scoping. It can also be an alist mapping symbols to
+their value. It is used as the optional LEXICAL argument to
+`eval', which see.")
+
+(defun org-babel-expand-body:emacs-lisp (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let* ((vars (org-babel--get-vars params))
+ (result-params (cdr (assq :result-params params)))
+ (print-level nil) (print-length nil)
+ (body (if (> (length vars) 0)
+ (concat "(let ("
+ (mapconcat
+ (lambda (var)
+ (format "%S" (print `(,(car var) ',(cdr var)))))
+ vars "\n ")
+ ")\n" body "\n)")
+ (concat body "\n"))))
+ (if (or (member "code" result-params)
+ (member "pp" result-params))
+ (concat "(pp " body ")") body)))
+
+(defun org-babel-execute:emacs-lisp (body params)
+ "Execute a block of emacs-lisp code with Babel."
+ (save-window-excursion
+ (let* ((lexical (cdr (assq :lexical params)))
+ (result
+ (eval (read (format (if (member "output"
+ (cdr (assq :result-params params)))
+ "(with-output-to-string %s)"
+ "(progn %s)")
+ (org-babel-expand-body:emacs-lisp
+ body params)))
+
+ (if (listp lexical)
+ lexical
+ (member lexical '("yes" "t"))))))
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (let ((print-level nil)
+ (print-length nil))
+ (if (or (member "scalar" (cdr (assq :result-params params)))
+ (member "verbatim" (cdr (assq :result-params params))))
+ (format "%S" result)
+ (format "%s" result)))
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params))))))))
+
+(org-babel-make-language-alias "elisp" "emacs-lisp")
+
+(provide 'ob-emacs-lisp)
+
+
+
+;;; ob-emacs-lisp.el ends here
diff --git a/lisp/ob-eval.el b/lisp/ob-eval.el
new file mode 100644
index 0000000..324cf5f
--- /dev/null
+++ b/lisp/ob-eval.el
@@ -0,0 +1,149 @@
+;;; ob-eval.el --- Babel Functions for External Code Evaluation -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research, comint
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; These functions build existing Emacs support for executing external
+;; shell commands.
+
+;;; Code:
+(require 'org-macs)
+
+(defvar org-babel-error-buffer-name "*Org-Babel Error Output*")
+(declare-function org-babel-temp-file "ob-core" (prefix &optional suffix))
+
+(defun org-babel-eval-error-notify (exit-code stderr)
+ "Open a buffer to display STDERR and a message with the value of EXIT-CODE."
+ (let ((buf (get-buffer-create org-babel-error-buffer-name)))
+ (with-current-buffer buf
+ (goto-char (point-max))
+ (save-excursion (insert stderr)))
+ (display-buffer buf))
+ (message "Babel evaluation exited with code %S" exit-code))
+
+(defun org-babel-eval (cmd body)
+ "Run CMD on BODY.
+If CMD succeeds then return its results, otherwise display
+STDERR with `org-babel-eval-error-notify'."
+ (let ((err-buff (get-buffer-create " *Org-Babel Error*")) exit-code)
+ (with-current-buffer err-buff (erase-buffer))
+ (with-temp-buffer
+ (insert body)
+ (setq exit-code
+ (org-babel--shell-command-on-region
+ (point-min) (point-max) cmd err-buff))
+ (if (or (not (numberp exit-code)) (> exit-code 0))
+ (progn
+ (with-current-buffer err-buff
+ (org-babel-eval-error-notify exit-code (buffer-string)))
+ (save-excursion
+ (when (get-buffer org-babel-error-buffer-name)
+ (with-current-buffer org-babel-error-buffer-name
+ (unless (derived-mode-p 'compilation-mode)
+ (compilation-mode))
+ ;; Compilation-mode enforces read-only, but Babel expects the buffer modifiable.
+ (setq buffer-read-only nil))))
+ nil)
+ (buffer-string)))))
+
+(defun org-babel-eval-read-file (file)
+ "Return the contents of FILE as a string."
+ (with-temp-buffer (insert-file-contents file)
+ (buffer-string)))
+
+(defun org-babel--shell-command-on-region (start end command error-buffer)
+ "Execute COMMAND in an inferior shell with region as input.
+
+Stripped down version of shell-command-on-region for internal use
+in Babel only. This lets us work around errors in the original
+function in various versions of Emacs.
+"
+ (let ((input-file (org-babel-temp-file "ob-input-"))
+ (error-file (if error-buffer (org-babel-temp-file "ob-error-") nil))
+ ;; Unfortunately, `executable-find' does not support file name
+ ;; handlers. Therefore, we could use it in the local case
+ ;; only.
+ (shell-file-name
+ (cond ((and (not (file-remote-p default-directory))
+ (executable-find shell-file-name))
+ shell-file-name)
+ ((file-executable-p
+ (concat (file-remote-p default-directory) shell-file-name))
+ shell-file-name)
+ ("/bin/sh")))
+ exit-status)
+ ;; There is an error in `process-file' when `error-file' exists.
+ ;; This is fixed in Emacs trunk as of 2012-12-21; let's use this
+ ;; workaround for now.
+ (unless (file-remote-p default-directory)
+ (delete-file error-file))
+ ;; we always call this with 'replace, remove conditional
+ ;; Replace specified region with output from command.
+ (let ((swap (< start end)))
+ (goto-char start)
+ (push-mark (point) 'nomsg)
+ (write-region start end input-file)
+ (delete-region start end)
+ (setq exit-status
+ (process-file shell-file-name input-file
+ (if error-file
+ (list t error-file)
+ t)
+ nil shell-command-switch command))
+ (when swap (exchange-point-and-mark)))
+
+ (when (and input-file (file-exists-p input-file)
+ ;; bind org-babel--debug-input around the call to keep
+ ;; the temporary input files available for inspection
+ (not (when (boundp 'org-babel--debug-input)
+ org-babel--debug-input)))
+ (delete-file input-file))
+
+ (when (and error-file (file-exists-p error-file))
+ (when (< 0 (nth 7 (file-attributes error-file)))
+ (with-current-buffer (get-buffer-create error-buffer)
+ (let ((pos-from-end (- (point-max) (point))))
+ (or (bobp)
+ (insert "\f\n"))
+ ;; Do no formatting while reading error file,
+ ;; because that can run a shell command, and we
+ ;; don't want that to cause an infinite recursion.
+ (format-insert-file error-file nil)
+ ;; Put point after the inserted errors.
+ (goto-char (- (point-max) pos-from-end)))
+ (current-buffer)))
+ (delete-file error-file))
+ exit-status))
+
+(defun org-babel-eval-wipe-error-buffer ()
+ "Delete the contents of the Org code block error buffer.
+This buffer is named by `org-babel-error-buffer-name'."
+ (when (get-buffer org-babel-error-buffer-name)
+ (with-current-buffer org-babel-error-buffer-name
+ (delete-region (point-min) (point-max)))))
+
+(provide 'ob-eval)
+
+
+
+;;; ob-eval.el ends here
diff --git a/lisp/ob-exp.el b/lisp/ob-exp.el
new file mode 100644
index 0000000..2556362
--- /dev/null
+++ b/lisp/ob-exp.el
@@ -0,0 +1,412 @@
+;;; ob-exp.el --- Exportation of Babel Source Blocks -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Code:
+(require 'ob-core)
+
+(declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-escape-code-in-string "org-src" (s))
+(declare-function org-export-copy-buffer "ox" ())
+(declare-function org-fill-template "org" (template alist))
+(declare-function org-get-indentation "org" (&optional line))
+(declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
+
+(defvar org-src-preserve-indentation)
+
+(defcustom org-export-babel-evaluate t
+ "Switch controlling code evaluation during export.
+When set to nil no code will be evaluated as part of the export
+process and no header argumentss will be obeyed. When set to
+`inline-only', only inline code blocks will be executed. Users
+who wish to avoid evaluating code on export should use the header
+argument `:eval never-export'."
+ :group 'org-babel
+ :version "24.1"
+ :type '(choice (const :tag "Never" nil)
+ (const :tag "Only inline code" inline-only)
+ (const :tag "Always" t)))
+(put 'org-export-babel-evaluate 'safe-local-variable #'null)
+
+(defmacro org-babel-exp--at-source (&rest body)
+ "Evaluate BODY at the source of the Babel block at point.
+Source is located in `org-babel-exp-reference-buffer'. The value
+returned is the value of the last form in BODY. Assume that
+point is at the beginning of the Babel block."
+ (declare (indent 1) (debug body))
+ `(let ((source (get-text-property (point) 'org-reference)))
+ (with-current-buffer org-babel-exp-reference-buffer
+ (org-with-wide-buffer
+ (goto-char source)
+ ,@body))))
+
+(defun org-babel-exp-src-block ()
+ "Process source block for export.
+Depending on the \":export\" header argument, replace the source
+code block like this:
+
+both ---- display the code and the results
+
+code ---- the default, display the code inside the block but do
+ not process
+
+results - just like none only the block is run on export ensuring
+ that its results are present in the Org mode buffer
+
+none ---- do not display either code or results upon export
+
+Assume point is at block opening line."
+ (interactive)
+ (save-excursion
+ (let* ((info (org-babel-get-src-block-info 'light))
+ (lang (nth 0 info))
+ (raw-params (nth 2 info))
+ hash)
+ ;; bail if we couldn't get any info from the block
+ (unless noninteractive
+ (message "org-babel-exp process %s at position %d..."
+ lang
+ (line-beginning-position)))
+ (when info
+ ;; if we're actually going to need the parameters
+ (when (member (cdr (assq :exports (nth 2 info))) '("both" "results"))
+ (let ((lang-headers (intern (concat "org-babel-default-header-args:"
+ lang))))
+ (org-babel-exp--at-source
+ (setf (nth 2 info)
+ (org-babel-process-params
+ (apply #'org-babel-merge-params
+ org-babel-default-header-args
+ (and (boundp lang-headers)
+ (symbol-value lang-headers))
+ (append (org-babel-params-from-properties lang)
+ (list raw-params)))))))
+ (setf hash (org-babel-sha1-hash info)))
+ (org-babel-exp-do-export info 'block hash)))))
+
+(defcustom org-babel-exp-call-line-template
+ ""
+ "Template used to export call lines.
+This template may be customized to include the call line name
+with any export markup. The template is filled out using
+`org-fill-template', and the following %keys may be used.
+
+ line --- call line
+
+An example value would be \"\\n: call: %line\" to export the call line
+wrapped in a verbatim environment.
+
+Note: the results are inserted separately after the contents of
+this template."
+ :group 'org-babel
+ :type 'string)
+
+(defun org-babel-exp-process-buffer ()
+ "Execute all Babel blocks in current buffer."
+ (interactive)
+ (when org-export-babel-evaluate
+ (save-window-excursion
+ (let ((case-fold-search t)
+ (regexp (if (eq org-export-babel-evaluate 'inline-only)
+ "\\(call\\|src\\)_"
+ "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)"))
+ ;; Get a pristine copy of current buffer so Babel
+ ;; references are properly resolved and source block
+ ;; context is preserved.
+ (org-babel-exp-reference-buffer (org-export-copy-buffer)))
+ (unwind-protect
+ (save-excursion
+ ;; First attach to every source block their original
+ ;; position, so that they can be retrieved within
+ ;; `org-babel-exp-reference-buffer', even after heavy
+ ;; modifications on current buffer.
+ ;;
+ ;; False positives are harmless, so we don't check if
+ ;; we're really at some Babel object. Moreover,
+ ;; `line-end-position' ensures that we propertize
+ ;; a noticeable part of the object, without affecting
+ ;; multiple objects on the same line.
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (let ((s (match-beginning 0)))
+ (put-text-property s (line-end-position) 'org-reference s)))
+ ;; Evaluate from top to bottom every Babel block
+ ;; encountered.
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (unless (save-match-data (org-in-commented-heading-p))
+ (let* ((object? (match-end 1))
+ (element (save-match-data
+ (if object? (org-element-context)
+ ;; No deep inspection if we're
+ ;; just looking for an element.
+ (org-element-at-point))))
+ (type
+ (pcase (org-element-type element)
+ ;; Discard block elements if we're looking
+ ;; for inline objects. False results
+ ;; happen when, e.g., "call_" syntax is
+ ;; located within affiliated keywords:
+ ;;
+ ;; #+name: call_src
+ ;; #+begin_src ...
+ ((and (or `babel-call `src-block) (guard object?))
+ nil)
+ (type type)))
+ (begin
+ (copy-marker (org-element-property :begin element)))
+ (end
+ (copy-marker
+ (save-excursion
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (point)))))
+ (pcase type
+ (`inline-src-block
+ (let* ((info
+ (org-babel-get-src-block-info nil element))
+ (params (nth 2 info)))
+ (setf (nth 1 info)
+ (if (and (cdr (assq :noweb params))
+ (string= "yes"
+ (cdr (assq :noweb params))))
+ (org-babel-expand-noweb-references
+ info org-babel-exp-reference-buffer)
+ (nth 1 info)))
+ (goto-char begin)
+ (let ((replacement
+ (org-babel-exp-do-export info 'inline)))
+ (if (equal replacement "")
+ ;; Replacement code is empty: remove
+ ;; inline source block, including extra
+ ;; white space that might have been
+ ;; created when inserting results.
+ (delete-region begin
+ (progn (goto-char end)
+ (skip-chars-forward " \t")
+ (point)))
+ ;; Otherwise: remove inline src block but
+ ;; preserve following white spaces. Then
+ ;; insert value.
+ (delete-region begin end)
+ (insert replacement)))))
+ ((or `babel-call `inline-babel-call)
+ (org-babel-exp-do-export (org-babel-lob-get-info element)
+ 'lob)
+ (let ((rep
+ (org-fill-template
+ org-babel-exp-call-line-template
+ `(("line" .
+ ,(org-element-property :value element))))))
+ ;; If replacement is empty, completely remove
+ ;; the object/element, including any extra
+ ;; white space that might have been created
+ ;; when including results.
+ (if (equal rep "")
+ (delete-region
+ begin
+ (progn (goto-char end)
+ (if (not (eq type 'babel-call))
+ (progn (skip-chars-forward " \t")
+ (point))
+ (skip-chars-forward " \r\t\n")
+ (line-beginning-position))))
+ ;; Otherwise, preserve trailing
+ ;; spaces/newlines and then, insert
+ ;; replacement string.
+ (goto-char begin)
+ (delete-region begin end)
+ (insert rep))))
+ (`src-block
+ (let ((match-start (copy-marker (match-beginning 0)))
+ (ind (org-get-indentation)))
+ ;; Take care of matched block: compute
+ ;; replacement string. In particular, a nil
+ ;; REPLACEMENT means the block is left as-is
+ ;; while an empty string removes the block.
+ (let ((replacement
+ (progn (goto-char match-start)
+ (org-babel-exp-src-block))))
+ (cond ((not replacement) (goto-char end))
+ ((equal replacement "")
+ (goto-char end)
+ (skip-chars-forward " \r\t\n")
+ (beginning-of-line)
+ (delete-region begin (point)))
+ (t
+ (goto-char match-start)
+ (delete-region (point)
+ (save-excursion
+ (goto-char end)
+ (line-end-position)))
+ (insert replacement)
+ (if (or org-src-preserve-indentation
+ (org-element-property
+ :preserve-indent element))
+ ;; Indent only code block
+ ;; markers.
+ (save-excursion
+ (skip-chars-backward " \r\t\n")
+ (indent-line-to ind)
+ (goto-char match-start)
+ (indent-line-to ind))
+ ;; Indent everything.
+ (indent-rigidly
+ match-start (point) ind)))))
+ (set-marker match-start nil))))
+ (set-marker begin nil)
+ (set-marker end nil)))))
+ (kill-buffer org-babel-exp-reference-buffer)
+ (remove-text-properties (point-min) (point-max) '(org-reference)))))))
+
+(defun org-babel-exp-do-export (info type &optional hash)
+ "Return a string with the exported content of a code block.
+The function respects the value of the :exports header argument."
+ (let ((silently (lambda () (let ((session (cdr (assq :session (nth 2 info)))))
+ (unless (equal "none" session)
+ (org-babel-exp-results info type 'silent)))))
+ (clean (lambda () (if (eq type 'inline)
+ (org-babel-remove-inline-result)
+ (org-babel-remove-result info)))))
+ (pcase (or (cdr (assq :exports (nth 2 info))) "code")
+ ("none" (funcall silently) (funcall clean) "")
+ ("code" (funcall silently) (funcall clean) (org-babel-exp-code info type))
+ ("results" (org-babel-exp-results info type nil hash) "")
+ ("both"
+ (org-babel-exp-results info type nil hash)
+ (org-babel-exp-code info type)))))
+
+(defcustom org-babel-exp-code-template
+ "#+BEGIN_SRC %lang%switches%flags\n%body\n#+END_SRC"
+ "Template used to export the body of code blocks.
+This template may be customized to include additional information
+such as the code block name, or the values of particular header
+arguments. The template is filled out using `org-fill-template',
+and the following %keys may be used.
+
+ lang ------ the language of the code block
+ name ------ the name of the code block
+ body ------ the body of the code block
+ switches -- the switches associated to the code block
+ flags ----- the flags passed to the code block
+
+In addition to the keys mentioned above, every header argument
+defined for the code block may be used as a key and will be
+replaced with its value."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-exp-inline-code-template
+ "src_%lang[%switches%flags]{%body}"
+ "Template used to export the body of inline code blocks.
+This template may be customized to include additional information
+such as the code block name, or the values of particular header
+arguments. The template is filled out using `org-fill-template',
+and the following %keys may be used.
+
+ lang ------ the language of the code block
+ name ------ the name of the code block
+ body ------ the body of the code block
+ switches -- the switches associated to the code block
+ flags ----- the flags passed to the code block
+
+In addition to the keys mentioned above, every header argument
+defined for the code block may be used as a key and will be
+replaced with its value."
+ :group 'org-babel
+ :type 'string
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+(defun org-babel-exp-code (info type)
+ "Return the original code block formatted for export."
+ (setf (nth 1 info)
+ (if (string= "strip-export" (cdr (assq :noweb (nth 2 info))))
+ (replace-regexp-in-string
+ (org-babel-noweb-wrap) "" (nth 1 info))
+ (if (org-babel-noweb-p (nth 2 info) :export)
+ (org-babel-expand-noweb-references
+ info org-babel-exp-reference-buffer)
+ (nth 1 info))))
+ (org-fill-template
+ (if (eq type 'inline)
+ org-babel-exp-inline-code-template
+ org-babel-exp-code-template)
+ `(("lang" . ,(nth 0 info))
+ ("body" . ,(org-escape-code-in-string (nth 1 info)))
+ ("switches" . ,(let ((f (nth 3 info)))
+ (and (org-string-nw-p f) (concat " " f))))
+ ("flags" . ,(let ((f (assq :flags (nth 2 info))))
+ (and f (concat " " (cdr f)))))
+ ,@(mapcar (lambda (pair)
+ (cons (substring (symbol-name (car pair)) 1)
+ (format "%S" (cdr pair))))
+ (nth 2 info))
+ ("name" . ,(or (nth 4 info) "")))))
+
+(defun org-babel-exp-results (info type &optional silent hash)
+ "Evaluate and return the results of the current code block for export.
+Results are prepared in a manner suitable for export by Org mode.
+This function is called by `org-babel-exp-do-export'. The code
+block will be evaluated. Optional argument SILENT can be used to
+inhibit insertion of results into the buffer."
+ (unless (and hash (equal hash (org-babel-current-result-hash)))
+ (let ((lang (nth 0 info))
+ (body (if (org-babel-noweb-p (nth 2 info) :eval)
+ (org-babel-expand-noweb-references
+ info org-babel-exp-reference-buffer)
+ (nth 1 info)))
+ (info (copy-sequence info))
+ (org-babel-current-src-block-location (point-marker)))
+ ;; Skip code blocks which we can't evaluate.
+ (when (fboundp (intern (concat "org-babel-execute:" lang)))
+ (org-babel-eval-wipe-error-buffer)
+ (setf (nth 1 info) body)
+ (setf (nth 2 info)
+ (org-babel-exp--at-source
+ (org-babel-process-params
+ (org-babel-merge-params
+ (nth 2 info)
+ `((:results . ,(if silent "silent" "replace")))))))
+ (pcase type
+ (`block (org-babel-execute-src-block nil info))
+ (`inline
+ ;; Position the point on the inline source block
+ ;; allowing `org-babel-insert-result' to check that the
+ ;; block is inline.
+ (goto-char (nth 5 info))
+ (org-babel-execute-src-block nil info))
+ (`lob
+ (save-excursion
+ (goto-char (nth 5 info))
+ (let (org-confirm-babel-evaluate)
+ (org-babel-execute-src-block nil info)))))))))
+
+
+(provide 'ob-exp)
+
+;;; ob-exp.el ends here
diff --git a/lisp/ob-forth.el b/lisp/ob-forth.el
new file mode 100644
index 0000000..152cf72
--- /dev/null
+++ b/lisp/ob-forth.el
@@ -0,0 +1,87 @@
+;;; ob-forth.el --- Babel Functions for Forth -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2014-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research, forth
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Requires the gforth forth compiler and `forth-mode' (see below).
+;; https://www.gnu.org/software/gforth/
+
+;;; Requirements:
+
+;; Session evaluation requires the gforth forth compiler as well as
+;; `forth-mode' which is distributed with gforth (in gforth.el).
+
+;;; Code:
+(require 'ob)
+
+(declare-function forth-proc "ext:gforth" ())
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-default-header-args:forth '((:session . "yes"))
+ "Default header arguments for forth code blocks.")
+
+(defun org-babel-execute:forth (body params)
+ "Execute a block of Forth code with org-babel.
+This function is called by `org-babel-execute-src-block'"
+ (if (string= "none" (cdr (assq :session params)))
+ (error "Non-session evaluation not supported for Forth code blocks")
+ (let ((all-results (org-babel-forth-session-execute body params)))
+ (if (member "output" (cdr (assq :result-params params)))
+ (mapconcat #'identity all-results "\n")
+ (car (last all-results))))))
+
+(defun org-babel-forth-session-execute (body params)
+ (require 'forth-mode)
+ (let ((proc (forth-proc))
+ (rx " \\(\n:\\|compiled\n\\\|ok\n\\)")
+ (result-start))
+ (with-current-buffer (process-buffer (forth-proc))
+ (mapcar (lambda (line)
+ (setq result-start (progn (goto-char (process-mark proc))
+ (point)))
+ (comint-send-string proc (concat line "\n"))
+ ;; wait for forth to say "ok"
+ (while (not (progn (goto-char result-start)
+ (re-search-forward rx nil t)))
+ (accept-process-output proc 0.01))
+ (let ((case (match-string 1)))
+ (cond
+ ((string= "ok\n" case)
+ ;; Collect intermediate output.
+ (buffer-substring (+ result-start 1 (length line))
+ (match-beginning 0)))
+ ((string= "compiled\n" case))
+ ;; Ignore partial compilation.
+ ((string= "\n:" case)
+ ;; Report errors.
+ (org-babel-eval-error-notify 1
+ (buffer-substring
+ (+ (match-beginning 0) 1) (point-max))) nil))))
+ (split-string (org-trim
+ (org-babel-expand-body:generic body params))
+ "\n"
+ 'omit-nulls)))))
+
+(provide 'ob-forth)
+
+;;; ob-forth.el ends here
diff --git a/lisp/ob-fortran.el b/lisp/ob-fortran.el
new file mode 100644
index 0000000..d059245
--- /dev/null
+++ b/lisp/ob-fortran.el
@@ -0,0 +1,168 @@
+;;; ob-fortran.el --- Babel Functions for Fortran -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Authors: Sergey Litvinov
+;; Eric Schulte
+;; Keywords: literate programming, reproducible research, fortran
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating fortran code.
+
+;;; Code:
+(require 'ob)
+(require 'cc-mode)
+(require 'cl-lib)
+
+(declare-function org-entry-get "org"
+ (pom property &optional inherit literal-nil))
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("fortran" . "F90"))
+
+(defvar org-babel-default-header-args:fortran '())
+
+(defvar org-babel-fortran-compiler "gfortran"
+ "fortran command used to compile a fortran source code file into an
+ executable.")
+
+(defun org-babel-execute:fortran (body params)
+ "This function should only be called by `org-babel-execute:fortran'"
+ (let* ((tmp-src-file (org-babel-temp-file "fortran-src-" ".F90"))
+ (tmp-bin-file (org-babel-temp-file "fortran-bin-" org-babel-exeext))
+ (cmdline (cdr (assq :cmdline params)))
+ (flags (cdr (assq :flags params)))
+ (full-body (org-babel-expand-body:fortran body params)))
+ (with-temp-file tmp-src-file (insert full-body))
+ (org-babel-eval
+ (format "%s -o %s %s %s"
+ org-babel-fortran-compiler
+ (org-babel-process-file-name tmp-bin-file)
+ (mapconcat 'identity
+ (if (listp flags) flags (list flags)) " ")
+ (org-babel-process-file-name tmp-src-file)) "")
+ (let ((results
+ (org-trim
+ (org-remove-indentation
+ (org-babel-eval
+ (concat tmp-bin-file (if cmdline (concat " " cmdline) "")) "")))))
+ (org-babel-reassemble-table
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (org-babel-read results)
+ (let ((tmp-file (org-babel-temp-file "f-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(defun org-babel-expand-body:fortran (body params)
+ "Expand a block of fortran or fortran code with org-babel according to
+its header arguments."
+ (let ((vars (org-babel--get-vars params))
+ (main-p (not (string= (cdr (assq :main params)) "no")))
+ (includes (or (cdr (assq :includes params))
+ (org-babel-read (org-entry-get nil "includes" t))))
+ (defines (org-babel-read
+ (or (cdr (assq :defines params))
+ (org-babel-read (org-entry-get nil "defines" t))))))
+ (mapconcat 'identity
+ (list
+ ;; includes
+ (mapconcat
+ (lambda (inc) (format "#include %s" inc))
+ (if (listp includes) includes (list includes)) "\n")
+ ;; defines
+ (mapconcat
+ (lambda (inc) (format "#define %s" inc))
+ (if (listp defines) defines (list defines)) "\n")
+ ;; body
+ (if main-p
+ (org-babel-fortran-ensure-main-wrap
+ (concat
+ ;; variables
+ (mapconcat 'org-babel-fortran-var-to-fortran vars "\n")
+ body) params)
+ body) "\n") "\n")))
+
+(defun org-babel-fortran-ensure-main-wrap (body params)
+ "Wrap body in a \"program ... end program\" block if none exists."
+ (if (string-match "^[ \t]*program[ \t]*.*" (capitalize body))
+ (let ((vars (org-babel--get-vars params)))
+ (if vars (error "Cannot use :vars if `program' statement is present"))
+ body)
+ (format "program main\n%s\nend program main\n" body)))
+
+(defun org-babel-prep-session:fortran (_session _params)
+ "This function does nothing as fortran is a compiled language with no
+support for sessions"
+ (error "Fortran is a compiled languages -- no support for sessions"))
+
+(defun org-babel-load-session:fortran (_session _body _params)
+ "This function does nothing as fortran is a compiled language with no
+support for sessions"
+ (error "Fortran is a compiled languages -- no support for sessions"))
+
+;; helper functions
+
+(defun org-babel-fortran-var-to-fortran (pair)
+ "Convert an elisp val into a string of fortran code specifying a var
+of the same value."
+ ;; TODO list support
+ (let ((var (car pair))
+ (val (cdr pair)))
+ (when (symbolp val)
+ (setq val (symbol-name val))
+ (when (= (length val) 1)
+ (setq val (string-to-char val))))
+ (cond
+ ((integerp val)
+ (format "integer, parameter :: %S = %S\n" var val))
+ ((floatp val)
+ (format "real, parameter :: %S = %S\n" var val))
+ ((or (integerp val))
+ (format "character, parameter :: %S = '%S'\n" var val))
+ ((stringp val)
+ (format "character(len=%d), parameter :: %S = '%s'\n"
+ (length val) var val))
+ ;; val is a matrix
+ ((and (listp val) (cl-every #'listp val))
+ (format "real, parameter :: %S(%d,%d) = transpose( reshape( %s , (/ %d, %d /) ) )\n"
+ var (length val) (length (car val))
+ (org-babel-fortran-transform-list val)
+ (length (car val)) (length val)))
+ ((listp val)
+ (format "real, parameter :: %S(%d) = %s\n"
+ var (length val) (org-babel-fortran-transform-list val)))
+ (t
+ (error "the type of parameter %s is not supported by ob-fortran" var)))))
+
+(defun org-babel-fortran-transform-list (val)
+ "Return a fortran representation of enclose syntactic lists."
+ (if (listp val)
+ (concat "(/" (mapconcat #'org-babel-fortran-transform-list val ", ") "/)")
+ (format "%S" val)))
+
+(provide 'ob-fortran)
+
+;;; ob-fortran.el ends here
diff --git a/lisp/ob-gnuplot.el b/lisp/ob-gnuplot.el
new file mode 100644
index 0000000..400823b
--- /dev/null
+++ b/lisp/ob-gnuplot.el
@@ -0,0 +1,278 @@
+;;; ob-gnuplot.el --- Babel Functions for Gnuplot -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating gnuplot source code.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) we are generally only going to return results of type "file"
+;;
+;; 2) we are adding the "file" and "cmdline" header arguments
+
+;;; Requirements:
+
+;; - gnuplot :: http://www.gnuplot.info/
+;;
+;; - gnuplot-mode :: http://cars9.uchicago.edu/~ravel/software/gnuplot-mode.html
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-time-string-to-time "org" (s &optional buffer pos))
+(declare-function org-combine-plists "org" (&rest plists))
+(declare-function orgtbl-to-generic "org-table" (table params))
+(declare-function gnuplot-mode "ext:gnuplot-mode" ())
+(declare-function gnuplot-send-string-to-gnuplot "ext:gnuplot-mode" (str txt))
+(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot-mode" ())
+
+(defvar org-babel-default-header-args:gnuplot
+ '((:results . "file") (:exports . "results") (:session . nil))
+ "Default arguments to use when evaluating a gnuplot source block.")
+
+(defvar org-babel-header-args:gnuplot
+ '((title . :any)
+ (lines . :any)
+ (sets . :any)
+ (x-labels . :any)
+ (y-labels . :any)
+ (timefmt . :any)
+ (time-ind . :any)
+ (missing . :any)
+ (term . :any))
+ "Gnuplot specific header args.")
+
+(defvar org-babel-gnuplot-timestamp-fmt nil) ; Dynamically scoped.
+
+(defvar *org-babel-gnuplot-missing* nil)
+
+(defcustom *org-babel-gnuplot-terms*
+ '((eps . "postscript eps"))
+ "List of file extensions and the associated gnuplot terminal."
+ :group 'org-babel
+ :type '(repeat (cons (symbol :tag "File extension")
+ (string :tag "Gnuplot terminal"))))
+
+(defun org-babel-gnuplot-process-vars (params)
+ "Extract variables from PARAMS and process the variables.
+Dumps all vectors into files and returns an association list
+of variable names and the related value to be used in the gnuplot
+code."
+ (let ((*org-babel-gnuplot-missing* (cdr (assq :missing params))))
+ (mapcar
+ (lambda (pair)
+ (cons
+ (car pair) ;; variable name
+ (let* ((val (cdr pair)) ;; variable value
+ (lp (listp val)))
+ (if lp
+ (org-babel-gnuplot-table-to-data
+ (let* ((first (car val))
+ (tablep (or (listp first) (symbolp first))))
+ (if tablep val (mapcar 'list val)))
+ (org-babel-temp-file "gnuplot-") params)
+ val))))
+ (org-babel--get-vars params))))
+
+(defun org-babel-expand-body:gnuplot (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (save-window-excursion
+ (let* ((vars (org-babel-gnuplot-process-vars params))
+ (out-file (cdr (assq :file params)))
+ (prologue (cdr (assq :prologue params)))
+ (epilogue (cdr (assq :epilogue params)))
+ (term (or (cdr (assq :term params))
+ (when out-file
+ (let ((ext (file-name-extension out-file)))
+ (or (cdr (assoc (intern (downcase ext))
+ *org-babel-gnuplot-terms*))
+ ext)))))
+ (title (cdr (assq :title params)))
+ (lines (cdr (assq :line params)))
+ (sets (cdr (assq :set params)))
+ (x-labels (cdr (assq :xlabels params)))
+ (y-labels (cdr (assq :ylabels params)))
+ (timefmt (cdr (assq :timefmt params)))
+ (time-ind (or (cdr (assq :timeind params))
+ (when timefmt 1)))
+ (add-to-body (lambda (text) (setq body (concat text "\n" body)))))
+ ;; append header argument settings to body
+ (when title (funcall add-to-body (format "set title '%s'" title)))
+ (when lines (mapc (lambda (el) (funcall add-to-body el)) lines))
+ (when sets
+ (mapc (lambda (el) (funcall add-to-body (format "set %s" el))) sets))
+ (when x-labels
+ (funcall add-to-body
+ (format "set xtics (%s)"
+ (mapconcat (lambda (pair)
+ (format "\"%s\" %d"
+ (cdr pair) (car pair)))
+ x-labels ", "))))
+ (when y-labels
+ (funcall add-to-body
+ (format "set ytics (%s)"
+ (mapconcat (lambda (pair)
+ (format "\"%s\" %d"
+ (cdr pair) (car pair)))
+ y-labels ", "))))
+ (when time-ind
+ (funcall add-to-body "set xdata time")
+ (funcall add-to-body (concat "set timefmt \""
+ (or timefmt
+ "%Y-%m-%d-%H:%M:%S") "\"")))
+ (when out-file
+ ;; set the terminal at the top of the block
+ (funcall add-to-body (format "set output \"%s\"" out-file))
+ ;; and close the terminal at the bottom of the block
+ (setq body (concat body "\nset output\n")))
+ (when term (funcall add-to-body (format "set term %s" term)))
+ ;; insert variables into code body: this should happen last
+ ;; placing the variables at the *top* of the code in case their
+ ;; values are used later
+ (funcall add-to-body
+ (mapconcat #'identity
+ (org-babel-variable-assignments:gnuplot params)
+ "\n"))
+ ;; replace any variable names preceded by '$' with the actual
+ ;; value of the variable
+ (mapc (lambda (pair)
+ (setq body (replace-regexp-in-string
+ (format "\\$%s" (car pair)) (cdr pair) body)))
+ vars)
+ (when prologue (funcall add-to-body prologue))
+ (when epilogue (setq body (concat body "\n" epilogue))))
+ body))
+
+(defun org-babel-execute:gnuplot (body params)
+ "Execute a block of Gnuplot code.
+This function is called by `org-babel-execute-src-block'."
+ (require 'gnuplot)
+ (let ((session (cdr (assq :session params)))
+ (result-type (cdr (assq :results params)))
+ (body (org-babel-expand-body:gnuplot body params))
+ output)
+ (save-window-excursion
+ ;; evaluate the code body with gnuplot
+ (if (string= session "none")
+ (let ((script-file (org-babel-temp-file "gnuplot-script-")))
+ (with-temp-file script-file
+ (insert (concat body "\n")))
+ (message "gnuplot \"%s\"" script-file)
+ (setq output
+ (shell-command-to-string
+ (format
+ "gnuplot \"%s\""
+ (org-babel-process-file-name
+ script-file
+ (if (member system-type '(cygwin windows-nt ms-dos))
+ t nil)))))
+ (message "%s" output))
+ (with-temp-buffer
+ (insert (concat body "\n"))
+ (gnuplot-mode)
+ (gnuplot-send-buffer-to-gnuplot)))
+ (if (member "output" (split-string result-type))
+ output
+ nil)))) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:gnuplot (session params)
+ "Prepare SESSION according to the header arguments in PARAMS."
+ (let* ((session (org-babel-gnuplot-initiate-session session))
+ (var-lines (org-babel-variable-assignments:gnuplot params)))
+ (message "%S" session)
+ (org-babel-comint-in-buffer session
+ (dolist (var-line var-lines)
+ (insert var-line)
+ (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)
+ (sit-for .1)
+ (goto-char (point-max))))
+ session))
+
+(defun org-babel-load-session:gnuplot (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:gnuplot session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+(defun org-babel-variable-assignments:gnuplot (params)
+ "Return list of gnuplot statements assigning the block's variables."
+ (mapcar
+ (lambda (pair) (format "%s = \"%s\"" (car pair) (cdr pair)))
+ (org-babel-gnuplot-process-vars params)))
+
+(defvar gnuplot-buffer)
+(defun org-babel-gnuplot-initiate-session (&optional session _params)
+ "Initiate a gnuplot session.
+If there is not a current inferior-process-buffer in SESSION
+then create one. Return the initialized session. The current
+`gnuplot-mode' doesn't provide support for multiple sessions."
+ (require 'gnuplot)
+ (unless (string= session "none")
+ (save-window-excursion
+ (gnuplot-send-string-to-gnuplot "" "line")
+ gnuplot-buffer)))
+
+(defun org-babel-gnuplot-quote-timestamp-field (s)
+ "Convert S from timestamp to Unix time and export to gnuplot."
+ (format-time-string org-babel-gnuplot-timestamp-fmt
+ (org-time-string-to-time s)))
+
+(defvar org-table-number-regexp)
+(defvar org-ts-regexp3)
+(defun org-babel-gnuplot-quote-tsv-field (s)
+ "Quote S for export to gnuplot."
+ (unless (stringp s)
+ (setq s (format "%s" s)))
+ (if (string-match org-table-number-regexp s) s
+ (if (string-match org-ts-regexp3 s)
+ (org-babel-gnuplot-quote-timestamp-field s)
+ (if (zerop (length s))
+ (or *org-babel-gnuplot-missing* s)
+ (if (string-match "[ \"]" s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"")
+ "\"")
+ s)))))
+
+(defun org-babel-gnuplot-table-to-data (table data-file params)
+ "Export TABLE to DATA-FILE in a format readable by gnuplot.
+Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
+ (with-temp-file data-file
+ (insert (let ((org-babel-gnuplot-timestamp-fmt
+ (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S")))
+ (orgtbl-to-generic
+ table
+ (org-combine-plists
+ '(:sep "\t" :fmt org-babel-gnuplot-quote-tsv-field)
+ params)))))
+ data-file)
+
+(provide 'ob-gnuplot)
+
+
+
+;;; ob-gnuplot.el ends here
diff --git a/lisp/ob-groovy.el b/lisp/ob-groovy.el
new file mode 100644
index 0000000..69993c0
--- /dev/null
+++ b/lisp/ob-groovy.el
@@ -0,0 +1,116 @@
+;;; ob-groovy.el --- Babel Functions for Groovy -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: Miro Bezjak
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;; Currently only supports the external execution. No session support yet.
+
+;;; Requirements:
+;; - Groovy language :: http://groovy.codehaus.org
+;; - Groovy major mode :: Can be installed from MELPA or
+;; https://github.com/russel/Emacs-Groovy-Mode
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts) ;; Autoloaded
+(add-to-list 'org-babel-tangle-lang-exts '("groovy" . "groovy"))
+(defvar org-babel-default-header-args:groovy '())
+(defcustom org-babel-groovy-command "groovy"
+ "Name of the command to use for executing Groovy code.
+May be either a command in the path, like groovy
+or an absolute path name, like /usr/local/bin/groovy
+parameters may be used, like groovy -v"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defun org-babel-execute:groovy (body params)
+ "Execute a block of Groovy code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (message "executing Groovy source code block")
+ (let* ((processed-params (org-babel-process-params params))
+ (session (org-babel-groovy-initiate-session (nth 0 processed-params)))
+ (result-params (nth 2 processed-params))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params))
+ (result (org-babel-groovy-evaluate
+ session full-body result-type result-params)))
+
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defvar org-babel-groovy-wrapper-method
+
+ "class Runner extends Script {
+ def out = new PrintWriter(new ByteArrayOutputStream())
+ def run() { %s }
+}
+
+println(new Runner().run())
+")
+
+
+(defun org-babel-groovy-evaluate
+ (session body &optional result-type result-params)
+ "Evaluate BODY in external Groovy process.
+If RESULT-TYPE equals `output' then return standard output as a string.
+If RESULT-TYPE equals `value' then return the value of the last statement
+in BODY as elisp."
+ (when session (error "Sessions are not (yet) supported for Groovy"))
+ (pcase result-type
+ (`output
+ (let ((src-file (org-babel-temp-file "groovy-")))
+ (progn (with-temp-file src-file (insert body))
+ (org-babel-eval
+ (concat org-babel-groovy-command " " src-file) ""))))
+ (`value
+ (let* ((src-file (org-babel-temp-file "groovy-"))
+ (wrapper (format org-babel-groovy-wrapper-method body)))
+ (with-temp-file src-file (insert wrapper))
+ (let ((raw (org-babel-eval
+ (concat org-babel-groovy-command " " src-file) "")))
+ (org-babel-result-cond result-params
+ raw
+ (org-babel-script-escape raw)))))))
+
+
+(defun org-babel-prep-session:groovy (_session _params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (error "Sessions are not (yet) supported for Groovy"))
+
+(defun org-babel-groovy-initiate-session (&optional _session)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session. Sessions are not
+supported in Groovy."
+ nil)
+
+(provide 'ob-groovy)
+
+
+
+;;; ob-groovy.el ends here
diff --git a/lisp/ob-haskell.el b/lisp/ob-haskell.el
new file mode 100644
index 0000000..ecce6dc
--- /dev/null
+++ b/lisp/ob-haskell.el
@@ -0,0 +1,213 @@
+;;; ob-haskell.el --- Babel Functions for Haskell -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating haskell source code. This one will
+;; be sort of tricky because haskell programs must be compiled before
+;; they can be run, but haskell code can also be run through an
+;; interactive interpreter.
+;;
+;; For now lets only allow evaluation using the haskell interpreter.
+
+;;; Requirements:
+
+;; - haskell-mode :: http://www.iro.umontreal.ca/~monnier/elisp/#haskell-mode
+;;
+;; - inf-haskell :: http://www.iro.umontreal.ca/~monnier/elisp/#haskell-mode
+;;
+;; - (optionally) lhs2tex :: http://people.cs.uu.nl/andres/lhs2tex/
+
+;;; Code:
+(require 'ob)
+(require 'comint)
+
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function haskell-mode "ext:haskell-mode" ())
+(declare-function run-haskell "ext:inf-haskell" (&optional arg))
+(declare-function inferior-haskell-load-file
+ "ext:inf-haskell" (&optional reload))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("haskell" . "hs"))
+
+(defvar org-babel-default-header-args:haskell
+ '((:padlines . "no")))
+
+(defvar org-babel-haskell-lhs2tex-command "lhs2tex")
+
+(defvar org-babel-haskell-eoe "\"org-babel-haskell-eoe\"")
+
+(defun org-babel-execute:haskell (body params)
+ "Execute a block of Haskell code."
+ (let* ((session (cdr (assq :session params)))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params
+ (org-babel-variable-assignments:haskell params)))
+ (session (org-babel-haskell-initiate-session session params))
+ (raw (org-babel-comint-with-output
+ (session org-babel-haskell-eoe t full-body)
+ (insert (org-trim full-body))
+ (comint-send-input nil t)
+ (insert org-babel-haskell-eoe)
+ (comint-send-input nil t)))
+ (results (mapcar
+ #'org-babel-strip-quotes
+ (cdr (member org-babel-haskell-eoe
+ (reverse (mapcar #'org-trim raw)))))))
+ (org-babel-reassemble-table
+ (let ((result
+ (pcase result-type
+ (`output (mapconcat #'identity (reverse (cdr results)) "\n"))
+ (`value (car results)))))
+ (org-babel-result-cond (cdr (assq :result-params params))
+ result (org-babel-script-escape result)))
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colname-names params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rowname-names params))))))
+
+(defun org-babel-haskell-initiate-session (&optional _session _params)
+ "Initiate a haskell session.
+If there is not a current inferior-process-buffer in SESSION
+then create one. Return the initialized session."
+ (require 'inf-haskell)
+ (or (get-buffer "*haskell*")
+ (save-window-excursion (run-haskell) (sleep-for 0.25) (current-buffer))))
+
+(defun org-babel-load-session:haskell (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let* ((buffer (org-babel-prep-session:haskell session params))
+ (load-file (concat (org-babel-temp-file "haskell-load-") ".hs")))
+ (with-temp-buffer
+ (insert body) (write-file load-file)
+ (haskell-mode) (inferior-haskell-load-file))
+ buffer)))
+
+(defun org-babel-prep-session:haskell (session params)
+ "Prepare SESSION according to the header arguments in PARAMS."
+ (save-window-excursion
+ (let ((buffer (org-babel-haskell-initiate-session session)))
+ (org-babel-comint-in-buffer buffer
+ (mapc (lambda (line)
+ (insert line)
+ (comint-send-input nil t))
+ (org-babel-variable-assignments:haskell params)))
+ (current-buffer))))
+
+(defun org-babel-variable-assignments:haskell (params)
+ "Return list of haskell statements assigning the block's variables."
+ (mapcar (lambda (pair)
+ (format "let %s = %s"
+ (car pair)
+ (org-babel-haskell-var-to-haskell (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-haskell-var-to-haskell (var)
+ "Convert an elisp value VAR into a haskell variable.
+The elisp VAR is converted to a string of haskell source code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-haskell-var-to-haskell var ", ") "]")
+ (format "%S" var)))
+
+(defvar org-export-copy-to-kill-ring)
+(declare-function org-export-to-file "ox"
+ (backend file
+ &optional async subtreep visible-only body-only
+ ext-plist post-process))
+(defun org-babel-haskell-export-to-lhs (&optional arg)
+ "Export to a .lhs file with all haskell code blocks escaped.
+When called with a prefix argument the resulting
+.lhs file will be exported to a .tex file. This function will
+create two new files, base-name.lhs and base-name.tex where
+base-name is the name of the current Org file.
+
+Note that all standard Babel literate programming
+constructs (header arguments, no-web syntax etc...) are ignored."
+ (interactive "P")
+ (let* ((contents (buffer-string))
+ (haskell-regexp
+ (concat "^\\([ \t]*\\)#\\+begin_src[ \t]haskell*\\(.*\\)?[\r\n]"
+ "\\([^\000]*?\\)[\r\n][ \t]*#\\+end_src.*"))
+ (base-name (file-name-sans-extension (buffer-file-name)))
+ (tmp-file (org-babel-temp-file "haskell-"))
+ (tmp-org-file (concat tmp-file ".org"))
+ (tmp-tex-file (concat tmp-file ".tex"))
+ (lhs-file (concat base-name ".lhs"))
+ (tex-file (concat base-name ".tex"))
+ (command (concat org-babel-haskell-lhs2tex-command
+ " " (org-babel-process-file-name lhs-file)
+ " > " (org-babel-process-file-name tex-file)))
+ (preserve-indentp org-src-preserve-indentation)
+ indentation)
+ ;; escape haskell source-code blocks
+ (with-temp-file tmp-org-file
+ (insert contents)
+ (goto-char (point-min))
+ (while (re-search-forward haskell-regexp nil t)
+ (save-match-data (setq indentation (length (match-string 1))))
+ (replace-match (save-match-data
+ (concat
+ "#+begin_export latex\n\\begin{code}\n"
+ (if (or preserve-indentp
+ (string-match "-i" (match-string 2)))
+ (match-string 3)
+ (org-remove-indentation (match-string 3)))
+ "\n\\end{code}\n#+end_export\n"))
+ t t)
+ (indent-code-rigidly (match-beginning 0) (match-end 0) indentation)))
+ (save-excursion
+ ;; export to latex w/org and save as .lhs
+ (require 'ox-latex)
+ (find-file tmp-org-file)
+ ;; Ensure we do not clutter kill ring with incomplete results.
+ (let (org-export-copy-to-kill-ring)
+ (org-export-to-file 'latex tmp-tex-file))
+ (kill-buffer nil)
+ (delete-file tmp-org-file)
+ (find-file tmp-tex-file)
+ (goto-char (point-min)) (forward-line 2)
+ (insert "%include polycode.fmt\n")
+ ;; ensure all \begin/end{code} statements start at the first column
+ (while (re-search-forward "^[ \t]+\\\\begin{code}[^\000]+\\\\end{code}" nil t)
+ (replace-match (save-match-data (org-remove-indentation (match-string 0)))
+ t t))
+ (setq contents (buffer-string))
+ (save-buffer) (kill-buffer nil))
+ (delete-file tmp-tex-file)
+ ;; save org exported latex to a .lhs file
+ (with-temp-file lhs-file (insert contents))
+ (if (not arg)
+ (find-file lhs-file)
+ ;; process .lhs file with lhs2tex
+ (message "running %s" command) (shell-command command) (find-file tex-file))))
+
+(provide 'ob-haskell)
+
+
+
+;;; ob-haskell.el ends here
diff --git a/lisp/ob-io.el b/lisp/ob-io.el
new file mode 100644
index 0000000..5dd6110
--- /dev/null
+++ b/lisp/ob-io.el
@@ -0,0 +1,108 @@
+;;; ob-io.el --- Babel Functions for Io -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Andrzej Lichnerowicz
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;; Currently only supports the external execution. No session support yet.
+;; :results output -- runs in scripting mode
+;; :results output repl -- runs in repl mode
+
+;;; Requirements:
+;; - Io language :: http://iolanguage.org/
+;; - Io major mode :: Can be installed from Io sources
+;; https://github.com/stevedekorte/io/blob/master/extras/SyntaxHighlighters/Emacs/io-mode.el
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts) ;; Autoloaded
+(add-to-list 'org-babel-tangle-lang-exts '("io" . "io"))
+(defvar org-babel-default-header-args:io '())
+(defvar org-babel-io-command "io"
+ "Name of the command to use for executing Io code.")
+
+(defun org-babel-execute:io (body params)
+ "Execute a block of Io code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (message "executing Io source code block")
+ (let* ((processed-params (org-babel-process-params params))
+ (session (org-babel-io-initiate-session (nth 0 processed-params)))
+ (result-params (nth 2 processed-params))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params))
+ (result (org-babel-io-evaluate
+ session full-body result-type result-params)))
+
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defvar org-babel-io-wrapper-method
+ "(
+%s
+) asString print
+")
+
+
+(defun org-babel-io-evaluate (session body &optional result-type result-params)
+ "Evaluate BODY in external Io process.
+If RESULT-TYPE equals `output' then return standard output as a string.
+If RESULT-TYPE equals `value' then return the value of the last statement
+in BODY as elisp."
+ (when session (error "Sessions are not (yet) supported for Io"))
+ (pcase result-type
+ (`output
+ (if (member "repl" result-params)
+ (org-babel-eval org-babel-io-command body)
+ (let ((src-file (org-babel-temp-file "io-")))
+ (progn (with-temp-file src-file (insert body))
+ (org-babel-eval
+ (concat org-babel-io-command " " src-file) "")))))
+ (`value (let* ((src-file (org-babel-temp-file "io-"))
+ (wrapper (format org-babel-io-wrapper-method body)))
+ (with-temp-file src-file (insert wrapper))
+ (let ((raw (org-babel-eval
+ (concat org-babel-io-command " " src-file) "")))
+ (org-babel-result-cond result-params
+ raw
+ (org-babel-script-escape raw)))))))
+
+
+(defun org-babel-prep-session:io (_session _params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (error "Sessions are not (yet) supported for Io"))
+
+(defun org-babel-io-initiate-session (&optional _session)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session. Sessions are not
+supported in Io."
+ nil)
+
+(provide 'ob-io)
+
+
+
+;;; ob-io.el ends here
diff --git a/lisp/ob-java.el b/lisp/ob-java.el
new file mode 100644
index 0000000..7e72023
--- /dev/null
+++ b/lisp/ob-java.el
@@ -0,0 +1,85 @@
+;;; ob-java.el --- Babel Functions for Java -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Currently this only supports the external compilation and execution
+;; of java code blocks (i.e., no session support).
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("java" . "java"))
+
+(defcustom org-babel-java-command "java"
+ "Name of the java command.
+May be either a command in the path, like java
+or an absolute path name, like /usr/local/bin/java
+parameters may be used, like java -verbose"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defcustom org-babel-java-compiler "javac"
+ "Name of the java compiler.
+May be either a command in the path, like javac
+or an absolute path name, like /usr/local/bin/javac
+parameters may be used, like javac -verbose"
+ :group 'org-babel
+ :version "24.3"
+ :type 'string)
+
+(defun org-babel-execute:java (body params)
+ (let* ((classname (or (cdr (assq :classname params))
+ (error
+ "Can't compile a java block without a classname")))
+ (packagename (file-name-directory classname))
+ (src-file (concat classname ".java"))
+ (cmpflag (or (cdr (assq :cmpflag params)) ""))
+ (cmdline (or (cdr (assq :cmdline params)) ""))
+ (full-body (org-babel-expand-body:generic body params)))
+ (with-temp-file src-file (insert full-body))
+ (org-babel-eval
+ (concat org-babel-java-compiler " " cmpflag " " src-file) "")
+ ;; created package-name directories if missing
+ (unless (or (not packagename) (file-exists-p packagename))
+ (make-directory packagename 'parents))
+ (let ((results (org-babel-eval (concat org-babel-java-command
+ " " cmdline " " classname) "")))
+ (org-babel-reassemble-table
+ (org-babel-result-cond (cdr (assq :result-params params))
+ (org-babel-read results)
+ (let ((tmp-file (org-babel-temp-file "c-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(provide 'ob-java)
+
+
+
+;;; ob-java.el ends here
diff --git a/lisp/ob-js.el b/lisp/ob-js.el
new file mode 100644
index 0000000..91be6b0
--- /dev/null
+++ b/lisp/ob-js.el
@@ -0,0 +1,164 @@
+;;; ob-js.el --- Babel Functions for Javascript -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research, js
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Now working with SBCL for both session and external evaluation.
+;;
+;; This certainly isn't optimally robust, but it seems to be working
+;; for the basic use cases.
+
+;;; Requirements:
+
+;; - a non-browser javascript engine such as node.js http://nodejs.org/
+;; or mozrepl http://wiki.github.com/bard/mozrepl/
+;;
+;; - for session based evaluation mozrepl and moz.el are required see
+;; http://wiki.github.com/bard/mozrepl/emacs-integration for
+;; configuration instructions
+
+;;; Code:
+(require 'ob)
+
+(declare-function run-mozilla "ext:moz" (arg))
+
+(defvar org-babel-default-header-args:js '()
+ "Default header arguments for js code blocks.")
+
+(defvar org-babel-js-eoe "org-babel-js-eoe"
+ "String to indicate that evaluation has completed.")
+
+(defcustom org-babel-js-cmd "node"
+ "Name of command used to evaluate js blocks."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defvar org-babel-js-function-wrapper
+ "require('sys').print(require('sys').inspect(function(){\n%s\n}()));"
+ "Javascript code to print value of body.")
+
+(defun org-babel-execute:js (body params)
+ "Execute a block of Javascript code with org-babel.
+This function is called by `org-babel-execute-src-block'"
+ (let* ((org-babel-js-cmd (or (cdr (assq :cmd params)) org-babel-js-cmd))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:js params)))
+ (result (if (not (string= (cdr (assq :session params)) "none"))
+ ;; session evaluation
+ (let ((session (org-babel-prep-session:js
+ (cdr (assq :session params)) params)))
+ (nth 1
+ (org-babel-comint-with-output
+ (session (format "%S" org-babel-js-eoe) t body)
+ (mapc
+ (lambda (line)
+ (insert (org-babel-chomp line))
+ (comint-send-input nil t))
+ (list body (format "%S" org-babel-js-eoe))))))
+ ;; external evaluation
+ (let ((script-file (org-babel-temp-file "js-script-")))
+ (with-temp-file script-file
+ (insert
+ ;; return the value or the output
+ (if (string= result-type "value")
+ (format org-babel-js-function-wrapper full-body)
+ full-body)))
+ (org-babel-eval
+ (format "%s %s" org-babel-js-cmd
+ (org-babel-process-file-name script-file)) "")))))
+ (org-babel-result-cond (cdr (assq :result-params params))
+ result (org-babel-js-read result))))
+
+(defun org-babel-js-read (results)
+ "Convert RESULTS into an appropriate elisp value.
+If RESULTS look like a table, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (org-babel-read
+ (if (and (stringp results)
+ (string-prefix-p "[" results)
+ (string-suffix-p "]" results))
+ (org-babel-read
+ (concat "'"
+ (replace-regexp-in-string
+ "\\[" "(" (replace-regexp-in-string
+ "\\]" ")" (replace-regexp-in-string
+ ",[[:space:]]" " "
+ (replace-regexp-in-string
+ "'" "\"" results))))))
+ results)))
+
+(defun org-babel-js-var-to-js (var)
+ "Convert VAR into a js variable.
+Convert an elisp value into a string of js source code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-js-var-to-js var ", ") "]")
+ (replace-regexp-in-string "\n" "\\\\n" (format "%S" var))))
+
+(defun org-babel-prep-session:js (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-js-initiate-session session))
+ (var-lines (org-babel-variable-assignments:js params)))
+ (when session
+ (org-babel-comint-in-buffer session
+ (sit-for .5) (goto-char (point-max))
+ (mapc (lambda (var)
+ (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)
+ (sit-for .1) (goto-char (point-max))) var-lines)))
+ session))
+
+(defun org-babel-variable-assignments:js (params)
+ "Return list of Javascript statements assigning the block's variables."
+ (mapcar
+ (lambda (pair) (format "var %s=%s;"
+ (car pair) (org-babel-js-var-to-js (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-js-initiate-session (&optional session)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session."
+ (unless (string= session "none")
+ (cond
+ ((string= "mozrepl" org-babel-js-cmd)
+ (require 'moz)
+ (let ((session-buffer (save-window-excursion
+ (run-mozilla nil)
+ (rename-buffer session)
+ (current-buffer))))
+ (if (org-babel-comint-buffer-livep session-buffer)
+ (progn (sit-for .25) session-buffer)
+ (sit-for .5)
+ (org-babel-js-initiate-session session))))
+ ((string= "node" org-babel-js-cmd )
+ (error "Session evaluation with node.js is not supported"))
+ (t
+ (error "Sessions are only supported with mozrepl add \":cmd mozrepl\"")))))
+
+(provide 'ob-js)
+
+
+
+;;; ob-js.el ends here
diff --git a/lisp/ob-keys.el b/lisp/ob-keys.el
new file mode 100644
index 0000000..f5fb910
--- /dev/null
+++ b/lisp/ob-keys.el
@@ -0,0 +1,106 @@
+;;; ob-keys.el --- Key Bindings for Babel -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Add Org Babel keybindings to the Org mode keymap for exposing
+;; Org Babel functions. These will all share a common prefix. See
+;; the value of `org-babel-key-bindings' for a list of interactive
+;; functions and their associated keys.
+
+;;; Code:
+(require 'ob-core)
+
+(defvar org-babel-key-prefix "\C-c\C-v"
+ "The key prefix for Babel interactive key-bindings.
+See `org-babel-key-bindings' for the list of interactive babel
+functions which are assigned key bindings, and see
+`org-babel-map' for the actual babel keymap.")
+
+(defvar org-babel-map (make-sparse-keymap)
+ "The keymap for interactive Babel functions.")
+
+;;;###autoload
+(defun org-babel-describe-bindings ()
+ "Describe all keybindings behind `org-babel-key-prefix'."
+ (interactive)
+ (describe-bindings org-babel-key-prefix))
+
+(defvar org-babel-key-bindings
+ '(("p" . org-babel-previous-src-block)
+ ("\C-p" . org-babel-previous-src-block)
+ ("n" . org-babel-next-src-block)
+ ("\C-n" . org-babel-next-src-block)
+ ("e" . org-babel-execute-maybe)
+ ("\C-e" . org-babel-execute-maybe)
+ ("o" . org-babel-open-src-block-result)
+ ("\C-o" . org-babel-open-src-block-result)
+ ("\C-v" . org-babel-expand-src-block)
+ ("v" . org-babel-expand-src-block)
+ ("u" . org-babel-goto-src-block-head)
+ ("\C-u" . org-babel-goto-src-block-head)
+ ("g" . org-babel-goto-named-src-block)
+ ("r" . org-babel-goto-named-result)
+ ("\C-r" . org-babel-goto-named-result)
+ ("\C-b" . org-babel-execute-buffer)
+ ("b" . org-babel-execute-buffer)
+ ("\C-s" . org-babel-execute-subtree)
+ ("s" . org-babel-execute-subtree)
+ ("\C-d" . org-babel-demarcate-block)
+ ("d" . org-babel-demarcate-block)
+ ("\C-t" . org-babel-tangle)
+ ("t" . org-babel-tangle)
+ ("\C-f" . org-babel-tangle-file)
+ ("f" . org-babel-tangle-file)
+ ("\C-c" . org-babel-check-src-block)
+ ("c" . org-babel-check-src-block)
+ ("\C-j" . org-babel-insert-header-arg)
+ ("j" . org-babel-insert-header-arg)
+ ("\C-l" . org-babel-load-in-session)
+ ("l" . org-babel-load-in-session)
+ ("\C-i" . org-babel-lob-ingest)
+ ("i" . org-babel-lob-ingest)
+ ("\C-I" . org-babel-view-src-block-info)
+ ("I" . org-babel-view-src-block-info)
+ ("\C-z" . org-babel-switch-to-session)
+ ("z" . org-babel-switch-to-session-with-code)
+ ("\C-a" . org-babel-sha1-hash)
+ ("a" . org-babel-sha1-hash)
+ ("h" . org-babel-describe-bindings)
+ ("\C-x" . org-babel-do-key-sequence-in-edit-buffer)
+ ("x" . org-babel-do-key-sequence-in-edit-buffer)
+ ("k" . org-babel-remove-result-one-or-many)
+ ("\C-\M-h" . org-babel-mark-block))
+ "Alist of key bindings and interactive Babel functions.
+This list associates interactive Babel functions
+with keys. Each element of this list will add an entry to the
+`org-babel-map' using the letter key which is the `car' of the
+a-list placed behind the generic `org-babel-key-prefix'.")
+
+(provide 'ob-keys)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ob-keys.el ends here
diff --git a/lisp/ob-latex.el b/lisp/ob-latex.el
new file mode 100644
index 0000000..763ffb1
--- /dev/null
+++ b/lisp/ob-latex.el
@@ -0,0 +1,226 @@
+;;; ob-latex.el --- Babel Functions for LaTeX -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating LaTeX source code.
+;;
+;; Currently on evaluation this returns raw LaTeX code, unless a :file
+;; header argument is given in which case small png or pdf files will
+;; be created directly form the latex source code.
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-create-formula-image "org" (string tofile options buffer &optional type))
+(declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
+(declare-function org-latex-guess-inputenc "ox-latex" (header))
+(declare-function org-splice-latex-header "org" (tpl def-pkg pkg snippets-p &optional extra))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("latex" . "tex"))
+
+(defvar org-format-latex-header) ; From org.el
+(defvar org-format-latex-options) ; From org.el
+(defvar org-latex-default-packages-alist) ; From org.el
+(defvar org-latex-packages-alist) ; From org.el
+
+(defvar org-babel-default-header-args:latex
+ '((:results . "latex") (:exports . "results"))
+ "Default arguments to use when evaluating a LaTeX source block.")
+
+(defconst org-babel-header-args:latex
+ '((border . :any)
+ (fit . :any)
+ (imagemagick . ((nil t)))
+ (iminoptions . :any)
+ (imoutoptions . :any)
+ (packages . :any)
+ (pdfheight . :any)
+ (pdfpng . :any)
+ (pdfwidth . :any)
+ (headers . :any)
+ (packages . :any)
+ (buffer . ((yes no))))
+ "LaTeX-specific header arguments.")
+
+(defcustom org-babel-latex-htlatex "htlatex"
+ "The htlatex command to enable conversion of latex to SVG or HTML."
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-latex-htlatex-packages
+ '("[usenames]{color}" "{tikz}" "{color}" "{listings}" "{amsmath}")
+ "Packages to use for htlatex export."
+ :group 'org-babel
+ :type '(repeat (string)))
+
+(defun org-babel-expand-body:latex (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (mapc (lambda (pair) ;; replace variables
+ (setq body
+ (replace-regexp-in-string
+ (regexp-quote (format "%S" (car pair)))
+ (if (stringp (cdr pair))
+ (cdr pair) (format "%S" (cdr pair)))
+ body))) (org-babel--get-vars params))
+ (org-trim body))
+
+(defun org-babel-execute:latex (body params)
+ "Execute a block of Latex code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (setq body (org-babel-expand-body:latex body params))
+ (if (cdr (assq :file params))
+ (let* ((out-file (cdr (assq :file params)))
+ (extension (file-name-extension out-file))
+ (tex-file (org-babel-temp-file "latex-" ".tex"))
+ (border (cdr (assq :border params)))
+ (imagemagick (cdr (assq :imagemagick params)))
+ (im-in-options (cdr (assq :iminoptions params)))
+ (im-out-options (cdr (assq :imoutoptions params)))
+ (fit (or (cdr (assq :fit params)) border))
+ (height (and fit (cdr (assq :pdfheight params))))
+ (width (and fit (cdr (assq :pdfwidth params))))
+ (headers (cdr (assq :headers params)))
+ (in-buffer (not (string= "no" (cdr (assq :buffer params)))))
+ (org-latex-packages-alist
+ (append (cdr (assq :packages params)) org-latex-packages-alist)))
+ (cond
+ ((and (string-suffix-p ".png" out-file) (not imagemagick))
+ (org-create-formula-image
+ body out-file org-format-latex-options in-buffer))
+ ((string-suffix-p ".tikz" out-file)
+ (when (file-exists-p out-file) (delete-file out-file))
+ (with-temp-file out-file
+ (insert body)))
+ ((and (or (string= "svg" extension)
+ (string= "html" extension))
+ (executable-find org-babel-latex-htlatex))
+ ;; TODO: this is a very different way of generating the
+ ;; frame latex document than in the pdf case. Ideally, both
+ ;; would be unified. This would prevent bugs creeping in
+ ;; such as the one fixed on Aug 16 2014 whereby :headers was
+ ;; not included in the SVG/HTML case.
+ (with-temp-file tex-file
+ (insert (concat
+ "\\documentclass[preview]{standalone}
+\\def\\pgfsysdriver{pgfsys-tex4ht.def}
+"
+ (mapconcat (lambda (pkg)
+ (concat "\\usepackage" pkg))
+ org-babel-latex-htlatex-packages
+ "\n")
+ (if headers
+ (concat "\n"
+ (if (listp headers)
+ (mapconcat #'identity headers "\n")
+ headers) "\n")
+ "")
+ "\\begin{document}"
+ body
+ "\\end{document}")))
+ (when (file-exists-p out-file) (delete-file out-file))
+ (let ((default-directory (file-name-directory tex-file)))
+ (shell-command (format "%s %s" org-babel-latex-htlatex tex-file)))
+ (cond
+ ((file-exists-p (concat (file-name-sans-extension tex-file) "-1.svg"))
+ (if (string-suffix-p ".svg" out-file)
+ (progn
+ (shell-command "pwd")
+ (shell-command (format "mv %s %s"
+ (concat (file-name-sans-extension tex-file) "-1.svg")
+ out-file)))
+ (error "SVG file produced but HTML file requested")))
+ ((file-exists-p (concat (file-name-sans-extension tex-file) ".html"))
+ (if (string-suffix-p ".html" out-file)
+ (shell-command "mv %s %s"
+ (concat (file-name-sans-extension tex-file)
+ ".html")
+ out-file)
+ (error "HTML file produced but SVG file requested")))))
+ ((or (string= "pdf" extension) imagemagick)
+ (with-temp-file tex-file
+ (require 'ox-latex)
+ (insert
+ (org-latex-guess-inputenc
+ (org-splice-latex-header
+ org-format-latex-header
+ (delq
+ nil
+ (mapcar
+ (lambda (el)
+ (unless (and (listp el) (string= "hyperref" (cadr el)))
+ el))
+ org-latex-default-packages-alist))
+ org-latex-packages-alist
+ nil))
+ (if fit "\n\\usepackage[active, tightpage]{preview}\n" "")
+ (if border (format "\\setlength{\\PreviewBorder}{%s}" border) "")
+ (if height (concat "\n" (format "\\pdfpageheight %s" height)) "")
+ (if width (concat "\n" (format "\\pdfpagewidth %s" width)) "")
+ (if headers
+ (concat "\n"
+ (if (listp headers)
+ (mapconcat #'identity headers "\n")
+ headers) "\n")
+ "")
+ (if fit
+ (concat "\n\\begin{document}\n\\begin{preview}\n" body
+ "\n\\end{preview}\n\\end{document}\n")
+ (concat "\n\\begin{document}\n" body "\n\\end{document}\n"))))
+ (when (file-exists-p out-file) (delete-file out-file))
+ (let ((transient-pdf-file (org-babel-latex-tex-to-pdf tex-file)))
+ (cond
+ ((string= "pdf" extension)
+ (rename-file transient-pdf-file out-file))
+ (imagemagick
+ (org-babel-latex-convert-pdf
+ transient-pdf-file out-file im-in-options im-out-options)
+ (when (file-exists-p transient-pdf-file)
+ (delete-file transient-pdf-file)))
+ (t
+ (error "Can not create %s files, please specify a .png or .pdf file or try the :imagemagick header argument"
+ extension))))))
+ nil) ;; signal that output has already been written to file
+ body))
+
+(defun org-babel-latex-convert-pdf (pdffile out-file im-in-options im-out-options)
+ "Generate a file from a pdf file using imagemagick."
+ (let ((cmd (concat "convert " im-in-options " " pdffile " "
+ im-out-options " " out-file)))
+ (message "Converting pdffile file %s..." cmd)
+ (shell-command cmd)))
+
+(defun org-babel-latex-tex-to-pdf (file)
+ "Generate a pdf file according to the contents FILE."
+ (require 'ox-latex)
+ (org-latex-compile file))
+
+(defun org-babel-prep-session:latex (_session _params)
+ "Return an error because LaTeX doesn't support sessions."
+ (error "LaTeX does not support sessions"))
+
+
+(provide 'ob-latex)
+;;; ob-latex.el ends here
diff --git a/lisp/ob-ledger.el b/lisp/ob-ledger.el
new file mode 100644
index 0000000..c02069e
--- /dev/null
+++ b/lisp/ob-ledger.el
@@ -0,0 +1,70 @@
+;;; ob-ledger.el --- Babel Functions for Ledger -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric S Fraga
+;; Keywords: literate programming, reproducible research, accounting
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating ledger entries.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in ledger
+;;
+;; 2) we are generally only going to return output from the ledger program
+;;
+;; 3) we are adding the "cmdline" header argument
+;;
+;; 4) there are no variables
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:ledger
+ '((:results . "output") (:cmdline . "bal"))
+ "Default arguments to use when evaluating a ledger source block.")
+
+(defun org-babel-execute:ledger (body params)
+ "Execute a block of Ledger entries with org-babel. This function is
+called by `org-babel-execute-src-block'."
+ (message "executing Ledger source code block")
+ (let ((cmdline (cdr (assq :cmdline params)))
+ (in-file (org-babel-temp-file "ledger-"))
+ (out-file (org-babel-temp-file "ledger-output-")))
+ (with-temp-file in-file (insert body))
+ (message "%s" (concat "ledger"
+ " -f " (org-babel-process-file-name in-file)
+ " " cmdline))
+ (with-output-to-string
+ (shell-command (concat "ledger"
+ " -f " (org-babel-process-file-name in-file)
+ " " cmdline
+ " > " (org-babel-process-file-name out-file))))
+ (with-temp-buffer (insert-file-contents out-file) (buffer-string))))
+
+(defun org-babel-prep-session:ledger (_session _params)
+ (error "Ledger does not support sessions"))
+
+(provide 'ob-ledger)
+
+
+
+;;; ob-ledger.el ends here
diff --git a/lisp/ob-lilypond.el b/lisp/ob-lilypond.el
new file mode 100644
index 0000000..37a7a6b
--- /dev/null
+++ b/lisp/ob-lilypond.el
@@ -0,0 +1,412 @@
+;;; ob-lilypond.el --- Babel Functions for Lilypond -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Martyn Jago
+;; Keywords: babel language, literate programming
+;; Homepage: http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Installation, ob-lilypond documentation, and examples are available at
+;; http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html
+;;
+;; Lilypond documentation can be found at
+;; http://lilypond.org/manuals.html
+;;
+;; This depends on epstopdf --- See http://www.ctan.org/pkg/epstopdf.
+
+;;; Code:
+(require 'ob)
+(require 'outline)
+(defalias 'lilypond-mode 'LilyPond-mode)
+
+(add-to-list 'org-babel-tangle-lang-exts '("LilyPond" . "ly"))
+
+(defvar org-babel-default-header-args:lilypond '()
+ "Default header arguments for lilypond code blocks.
+NOTE: The arguments are determined at lilypond compile time.
+See (org-babel-lilypond-set-header-args)")
+
+(defvar org-babel-lilypond-compile-post-tangle t
+ "Following the org-babel-tangle (C-c C-v t) command,
+org-babel-lilypond-compile-post-tangle determines whether ob-lilypond should
+automatically attempt to compile the resultant tangled file.
+If the value is nil, no automated compilation takes place.
+Default value is t")
+
+(defvar org-babel-lilypond-display-pdf-post-tangle t
+ "Following a successful LilyPond compilation
+org-babel-lilypond-display-pdf-post-tangle determines whether to automate the
+drawing / redrawing of the resultant pdf. If the value is nil,
+the pdf is not automatically redrawn. Default value is t")
+
+(defvar org-babel-lilypond-play-midi-post-tangle t
+ "Following a successful LilyPond compilation
+org-babel-lilypond-play-midi-post-tangle determines whether to automate the
+playing of the resultant midi file. If the value is nil,
+the midi file is not automatically played. Default value is t")
+
+(defvar org-babel-lilypond-ly-command ""
+ "Command to execute lilypond on your system.
+Do not set it directly. Customize `org-babel-lilypond-commands' instead.")
+(defvar org-babel-lilypond-pdf-command ""
+ "Command to show a PDF file on your system.
+Do not set it directly. Customize `org-babel-lilypond-commands' instead.")
+(defvar org-babel-lilypond-midi-command ""
+ "Command to play a MIDI file on your system.
+Do not set it directly. Customize `org-babel-lilypond-commands' instead.")
+(defcustom org-babel-lilypond-commands
+ (cond
+ ((eq system-type 'darwin)
+ '("/Applications/lilypond.app/Contents/Resources/bin/lilypond" "open" "open"))
+ ((eq system-type 'windows-nt)
+ '("lilypond" "" ""))
+ (t
+ '("lilypond" "xdg-open" "xdg-open")))
+ "Commands to run lilypond and view or play the results.
+These should be executables that take a filename as an argument.
+On some system it is possible to specify the filename directly
+and the viewer or player will be determined from the file type;
+you can leave the string empty on this case."
+ :group 'org-babel
+ :type '(list
+ (string :tag "Lilypond ")
+ (string :tag "PDF Viewer ")
+ (string :tag "MIDI Player"))
+ :version "24.3"
+ :package-version '(Org . "8.2.7")
+ :set
+ (lambda (_symbol value)
+ (setq
+ org-babel-lilypond-ly-command (nth 0 value)
+ org-babel-lilypond-pdf-command (nth 1 value)
+ org-babel-lilypond-midi-command (nth 2 value))))
+
+(defvar org-babel-lilypond-gen-png nil
+ "Non-nil means image generation (PNG) is turned on by default.")
+
+(defvar org-babel-lilypond-gen-svg nil
+ "Non-nil means image generation (SVG) is be turned on by default.")
+
+(defvar org-babel-lilypond-gen-html nil
+ "Non-nil means HTML generation is turned on by default.")
+
+(defvar org-babel-lilypond-gen-pdf nil
+ "Non-nil means PDF generation is be turned on by default.")
+
+(defvar org-babel-lilypond-use-eps nil
+ "Non-nil forces the compiler to use the EPS backend.")
+
+(defvar org-babel-lilypond-arrange-mode nil
+ "Non-nil turns Arrange mode on.
+In Arrange mode the following settings are altered from default:
+:tangle yes, :noweb yes
+:results silent :comments yes.
+In addition lilypond block execution causes tangling of all lilypond
+blocks.")
+
+(defun org-babel-expand-body:lilypond (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (mapc
+ (lambda (pair)
+ (let ((name (symbol-name (car pair)))
+ (value (cdr pair)))
+ (setq body
+ (replace-regexp-in-string
+ (concat "$" (regexp-quote name))
+ (if (stringp value) value (format "%S" value))
+ body))))
+ vars)
+ body))
+
+(defun org-babel-execute:lilypond (body params)
+ "This function is called by `org-babel-execute-src-block'.
+Depending on whether we are in arrange mode either:
+1. Attempt to execute lilypond block according to header settings
+ (This is the default basic mode)
+2. Tangle all lilypond blocks and process the result (arrange mode)"
+ (org-babel-lilypond-set-header-args org-babel-lilypond-arrange-mode)
+ (if org-babel-lilypond-arrange-mode
+ (org-babel-lilypond-tangle)
+ (org-babel-lilypond-process-basic body params)))
+
+(defun org-babel-lilypond-tangle ()
+ "ob-lilypond specific tangle, attempts to invoke
+=ly-execute-tangled-ly= if tangle is successful. Also passes
+specific arguments to =org-babel-tangle="
+ (interactive)
+ (if (org-babel-tangle nil "yes" "lilypond")
+ (org-babel-lilypond-execute-tangled-ly) nil))
+
+(defun org-babel-lilypond-process-basic (body params)
+ "Execute a lilypond block in basic mode."
+ (let* ((out-file (cdr (assq :file params)))
+ (cmdline (or (cdr (assq :cmdline params))
+ ""))
+ (in-file (org-babel-temp-file "lilypond-")))
+
+ (with-temp-file in-file
+ (insert (org-babel-expand-body:generic body params)))
+ (org-babel-eval
+ (concat
+ org-babel-lilypond-ly-command
+ " -dbackend=eps "
+ "-dno-gs-load-fonts "
+ "-dinclude-eps-fonts "
+ (or (cdr (assoc (file-name-extension out-file)
+ '(("pdf" . "--pdf ")
+ ("ps" . "--ps ")
+ ("png" . "--png "))))
+ "--png ")
+ "--output="
+ (file-name-sans-extension out-file)
+ " "
+ cmdline
+ in-file) "")) nil)
+
+(defun org-babel-prep-session:lilypond (_session _params)
+ "Return an error because LilyPond exporter does not support sessions."
+ (error "Sorry, LilyPond does not currently support sessions!"))
+
+(defun org-babel-lilypond-execute-tangled-ly ()
+ "Compile result of block tangle with lilypond.
+If error in compilation, attempt to mark the error in lilypond org file"
+ (when org-babel-lilypond-compile-post-tangle
+ (let ((org-babel-lilypond-tangled-file (org-babel-lilypond-switch-extension
+ (buffer-file-name) ".lilypond"))
+ (org-babel-lilypond-temp-file (org-babel-lilypond-switch-extension
+ (buffer-file-name) ".ly")))
+ (if (not (file-exists-p org-babel-lilypond-tangled-file))
+ (error "Error: Tangle Failed!")
+ (when (file-exists-p org-babel-lilypond-temp-file)
+ (delete-file org-babel-lilypond-temp-file))
+ (rename-file org-babel-lilypond-tangled-file
+ org-babel-lilypond-temp-file))
+ (switch-to-buffer-other-window "*lilypond*")
+ (erase-buffer)
+ (org-babel-lilypond-compile-lilyfile org-babel-lilypond-temp-file)
+ (goto-char (point-min))
+ (if (org-babel-lilypond-check-for-compile-error org-babel-lilypond-temp-file)
+ (error "Error in Compilation!")
+ (other-window -1)
+ (org-babel-lilypond-attempt-to-open-pdf org-babel-lilypond-temp-file)
+ (org-babel-lilypond-attempt-to-play-midi org-babel-lilypond-temp-file)))))
+
+(defun org-babel-lilypond-compile-lilyfile (file-name &optional test)
+ "Compile lilypond file and check for compile errors
+FILE-NAME is full path to lilypond (.ly) file"
+ (message "Compiling LilyPond...")
+ (let ((arg-1 org-babel-lilypond-ly-command) ;program
+ (arg-2 nil) ;infile
+ (arg-3 "*lilypond*") ;buffer
+ (arg-4 t) ;display
+ (arg-5 (if org-babel-lilypond-gen-png "--png" "")) ;&rest...
+ (arg-6 (if org-babel-lilypond-gen-html "--html" ""))
+ (arg-7 (if org-babel-lilypond-gen-pdf "--pdf" ""))
+ (arg-8 (if org-babel-lilypond-use-eps "-dbackend=eps" ""))
+ (arg-9 (if org-babel-lilypond-gen-svg "-dbackend=svg" ""))
+ (arg-10 (concat "--output=" (file-name-sans-extension file-name)))
+ (arg-11 file-name))
+ (if test
+ `(,arg-1 ,arg-2 ,arg-3 ,arg-4 ,arg-5 ,arg-6
+ ,arg-7 ,arg-8 ,arg-9 ,arg-10 ,arg-11)
+ (call-process
+ arg-1 arg-2 arg-3 arg-4 arg-5 arg-6
+ arg-7 arg-8 arg-9 arg-10 arg-11))))
+
+(defun org-babel-lilypond-check-for-compile-error (file-name &optional test)
+ "Check for compile error.
+This is performed by parsing the *lilypond* buffer
+containing the output message from the compilation.
+FILE-NAME is full path to lilypond file.
+If TEST is t just return nil if no error found, and pass
+nil as file-name since it is unused in this context"
+ (let ((is-error (search-forward "error:" nil t)))
+ (if test
+ is-error
+ (when is-error
+ (org-babel-lilypond-process-compile-error file-name)))))
+
+(defun org-babel-lilypond-process-compile-error (file-name)
+ "Process the compilation error that has occurred.
+FILE-NAME is full path to lilypond file"
+ (let ((line-num (org-babel-lilypond-parse-line-num)))
+ (let ((error-lines (org-babel-lilypond-parse-error-line file-name line-num)))
+ (org-babel-lilypond-mark-error-line file-name error-lines)
+ (error "Error: Compilation Failed!"))))
+
+(defun org-babel-lilypond-mark-error-line (file-name line)
+ "Mark the erroneous lines in the lilypond org buffer.
+FILE-NAME is full path to lilypond file.
+LINE is the erroneous line"
+ (switch-to-buffer-other-window
+ (concat (file-name-nondirectory
+ (org-babel-lilypond-switch-extension file-name ".org"))))
+ (let ((temp (point)))
+ (goto-char (point-min))
+ (setq case-fold-search nil)
+ (if (search-forward line nil t)
+ (progn
+ (outline-show-all)
+ (set-mark (point))
+ (goto-char (- (point) (length line))))
+ (goto-char temp))))
+
+(defun org-babel-lilypond-parse-line-num (&optional buffer)
+ "Extract error line number."
+ (when buffer (set-buffer buffer))
+ (let ((start
+ (and (search-backward ":" nil t)
+ (search-backward ":" nil t)
+ (search-backward ":" nil t)
+ (search-backward ":" nil t))))
+ (when start
+ (forward-char)
+ (let ((num (string-to-number
+ (buffer-substring
+ (+ 1 start)
+ (- (search-forward ":" nil t) 1)))))
+ (and (numberp num) num)))))
+
+(defun org-babel-lilypond-parse-error-line (file-name lineNo)
+ "Extract the erroneous line from the tangled .ly file
+FILE-NAME is full path to lilypond file.
+LINENO is the number of the erroneous line"
+ (with-temp-buffer
+ (insert-file-contents (org-babel-lilypond-switch-extension file-name ".ly")
+ nil nil nil t)
+ (if (> lineNo 0)
+ (progn
+ (goto-char (point-min))
+ (forward-line (- lineNo 1))
+ (buffer-substring (point) (point-at-eol)))
+ nil)))
+
+(defun org-babel-lilypond-attempt-to-open-pdf (file-name &optional test)
+ "Attempt to display the generated pdf file
+FILE-NAME is full path to lilypond file
+If TEST is non-nil, the shell command is returned and is not run"
+ (when org-babel-lilypond-display-pdf-post-tangle
+ (let ((pdf-file (org-babel-lilypond-switch-extension file-name ".pdf")))
+ (if (file-exists-p pdf-file)
+ (let ((cmd-string
+ (concat org-babel-lilypond-pdf-command " " pdf-file)))
+ (if test
+ cmd-string
+ (start-process
+ "\"Audition pdf\""
+ "*lilypond*"
+ org-babel-lilypond-pdf-command
+ pdf-file)))
+ (message "No pdf file generated so can't display!")))))
+
+(defun org-babel-lilypond-attempt-to-play-midi (file-name &optional test)
+ "Attempt to play the generated MIDI file
+FILE-NAME is full path to lilypond file
+If TEST is non-nil, the shell command is returned and is not run"
+ (when org-babel-lilypond-play-midi-post-tangle
+ (let ((midi-file (org-babel-lilypond-switch-extension file-name ".midi")))
+ (if (file-exists-p midi-file)
+ (let ((cmd-string
+ (concat org-babel-lilypond-midi-command " " midi-file)))
+ (if test
+ cmd-string
+ (start-process
+ "\"Audition midi\""
+ "*lilypond*"
+ org-babel-lilypond-midi-command
+ midi-file)))
+ (message "No midi file generated so can't play!")))))
+
+(defun org-babel-lilypond-toggle-midi-play ()
+ "Toggle whether midi will be played following a successful compilation."
+ (interactive)
+ (setq org-babel-lilypond-play-midi-post-tangle
+ (not org-babel-lilypond-play-midi-post-tangle))
+ (message (concat "Post-Tangle MIDI play has been "
+ (if org-babel-lilypond-play-midi-post-tangle
+ "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-toggle-pdf-display ()
+ "Toggle whether pdf will be displayed following a successful compilation."
+ (interactive)
+ (setq org-babel-lilypond-display-pdf-post-tangle
+ (not org-babel-lilypond-display-pdf-post-tangle))
+ (message (concat "Post-Tangle PDF display has been "
+ (if org-babel-lilypond-display-pdf-post-tangle
+ "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-toggle-png-generation ()
+ "Toggle whether png image will be generated by compilation."
+ (interactive)
+ (setq org-babel-lilypond-gen-png (not org-babel-lilypond-gen-png))
+ (message (concat "PNG image generation has been "
+ (if org-babel-lilypond-gen-png "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-toggle-html-generation ()
+ "Toggle whether html will be generated by compilation."
+ (interactive)
+ (setq org-babel-lilypond-gen-html (not org-babel-lilypond-gen-html))
+ (message (concat "HTML generation has been "
+ (if org-babel-lilypond-gen-html "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-toggle-pdf-generation ()
+ "Toggle whether pdf will be generated by compilation."
+ (interactive)
+ (setq org-babel-lilypond-gen-pdf (not org-babel-lilypond-gen-pdf))
+ (message (concat "PDF generation has been "
+ (if org-babel-lilypond-gen-pdf "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-toggle-arrange-mode ()
+ "Toggle whether in Arrange mode or Basic mode."
+ (interactive)
+ (setq org-babel-lilypond-arrange-mode
+ (not org-babel-lilypond-arrange-mode))
+ (message (concat "Arrange mode has been "
+ (if org-babel-lilypond-arrange-mode "ENABLED." "DISABLED."))))
+
+(defun org-babel-lilypond-switch-extension (file-name ext)
+ "Utility command to swap current FILE-NAME extension with EXT"
+ (concat (file-name-sans-extension
+ file-name) ext))
+
+(defun org-babel-lilypond-get-header-args (mode)
+ "Default arguments to use when evaluating a lilypond
+source block. These depend upon whether we are in arrange
+mode i.e. ARRANGE-MODE is t"
+ (cond (mode
+ '((:tangle . "yes")
+ (:noweb . "yes")
+ (:results . "silent")
+ (:cache . "yes")
+ (:comments . "yes")))
+ (t
+ '((:results . "file")
+ (:exports . "results")))))
+
+(defun org-babel-lilypond-set-header-args (mode)
+ "Set org-babel-default-header-args:lilypond
+dependent on ORG-BABEL-LILYPOND-ARRANGE-MODE"
+ (setq org-babel-default-header-args:lilypond
+ (org-babel-lilypond-get-header-args mode)))
+
+(provide 'ob-lilypond)
+
+;;; ob-lilypond.el ends here
diff --git a/lisp/ob-lisp.el b/lisp/ob-lisp.el
new file mode 100644
index 0000000..1e381d0
--- /dev/null
+++ b/lisp/ob-lisp.el
@@ -0,0 +1,127 @@
+;;; ob-lisp.el --- Babel Functions for Common Lisp -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Joel Boehland
+;; Eric Schulte
+;; David T. O'Toole <dto@gnu.org>
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Support for evaluating Common Lisp code, relies on SLY or SLIME
+;;; for all eval.
+
+;;; Requirements:
+
+;; Requires SLY (Sylvester the Cat's Common Lisp IDE) or SLIME
+;; (Superior Lisp Interaction Mode for Emacs). See:
+;; - https://github.com/capitaomorte/sly
+;; - http://common-lisp.net/project/slime/
+
+;;; Code:
+(require 'ob)
+
+(declare-function sly-eval "ext:sly" (sexp &optional package))
+(declare-function slime-eval "ext:slime" (sexp &optional package))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("lisp" . "lisp"))
+
+(defvar org-babel-default-header-args:lisp '())
+(defvar org-babel-header-args:lisp '((package . :any)))
+
+(defcustom org-babel-lisp-eval-fn #'slime-eval
+ "The function to be called to evaluate code on the Lisp side.
+Valid values include `slime-eval' and `sly-eval'."
+ :group 'org-babel
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type 'function)
+
+(defcustom org-babel-lisp-dir-fmt
+ "(let ((*default-pathname-defaults* #P%S\n)) %%s\n)"
+ "Format string used to wrap code bodies to set the current directory.
+For example a value of \"(progn ;; %s\\n %%s)\" would ignore the
+current directory string."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defun org-babel-expand-body:lisp (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let* ((vars (org-babel--get-vars params))
+ (result-params (cdr (assq :result-params params)))
+ (print-level nil) (print-length nil)
+ (body (if (null vars) (org-trim body)
+ (concat "(let ("
+ (mapconcat
+ (lambda (var)
+ (format "(%S (quote %S))" (car var) (cdr var)))
+ vars "\n ")
+ ")\n" body ")"))))
+ (if (or (member "code" result-params)
+ (member "pp" result-params))
+ (format "(pprint %s)" body)
+ body)))
+
+(defun org-babel-execute:lisp (body params)
+ "Execute a block of Common Lisp code with Babel.
+BODY is the contents of the block, as a string. PARAMS is
+a property list containing the parameters of the block."
+ (require (pcase org-babel-lisp-eval-fn
+ (`slime-eval 'slime)
+ (`sly-eval 'sly)))
+ (org-babel-reassemble-table
+ (let ((result
+ (funcall (if (member "output" (cdr (assq :result-params params)))
+ #'car #'cadr)
+ (with-temp-buffer
+ (insert (org-babel-expand-body:lisp body params))
+ (funcall org-babel-lisp-eval-fn
+ `(swank:eval-and-grab-output
+ ,(let ((dir (if (assq :dir params)
+ (cdr (assq :dir params))
+ default-directory)))
+ (format
+ (if dir (format org-babel-lisp-dir-fmt dir)
+ "(progn %s\n)")
+ (buffer-substring-no-properties
+ (point-min) (point-max)))))
+ (cdr (assq :package params)))))))
+ (org-babel-result-cond (cdr (assq :result-params params))
+ result
+ (condition-case nil
+ (read (org-babel-lisp-vector-to-list result))
+ (error result))))
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params)))))
+
+(defun org-babel-lisp-vector-to-list (results)
+ ;; TODO: better would be to replace #(...) with [...]
+ (replace-regexp-in-string "#(" "(" results))
+
+(provide 'ob-lisp)
+
+
+
+;;; ob-lisp.el ends here
diff --git a/lisp/ob-lob.el b/lisp/ob-lob.el
new file mode 100644
index 0000000..b6f50d3
--- /dev/null
+++ b/lisp/ob-lob.el
@@ -0,0 +1,151 @@
+;;; ob-lob.el --- Functions Supporting the Library of Babel -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Code:
+(require 'cl-lib)
+(require 'ob-core)
+(require 'ob-table)
+
+(declare-function org-babel-ref-split-args "ob-ref" (arg-string))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+
+(defvar org-babel-library-of-babel nil
+ "Library of source-code blocks.
+This is an association list. Populate the library by calling
+`org-babel-lob-ingest' on files containing source blocks.")
+
+(defvar org-babel-default-lob-header-args '((:exports . "results"))
+ "Default header arguments to use when exporting Babel calls.
+By default, a Babel call inherits its arguments from the source
+block being called. Header arguments defined in this variable
+take precedence over these. It is useful for properties that
+should not be inherited from a source block.")
+
+(defun org-babel-lob-ingest (&optional file)
+ "Add all named source blocks defined in FILE to `org-babel-library-of-babel'."
+ (interactive "fFile: ")
+ (let ((lob-ingest-count 0))
+ (org-babel-map-src-blocks file
+ (let* ((info (org-babel-get-src-block-info 'light))
+ (source-name (nth 4 info)))
+ (when source-name
+ (setq source-name (intern source-name)
+ org-babel-library-of-babel
+ (cons (cons source-name info)
+ (assq-delete-all source-name org-babel-library-of-babel))
+ lob-ingest-count (1+ lob-ingest-count)))))
+ (message "%d src block%s added to Library of Babel"
+ lob-ingest-count (if (> lob-ingest-count 1) "s" ""))
+ lob-ingest-count))
+
+;; Functions for executing lob one-liners.
+
+;;;###autoload
+(defun org-babel-lob-execute-maybe ()
+ "Execute a Library of Babel source block, if appropriate.
+Detect if this is context for a Library Of Babel source block and
+if so then run the appropriate source block from the Library."
+ (interactive)
+ (let ((info (org-babel-lob-get-info)))
+ (when info
+ (org-babel-execute-src-block nil info)
+ t)))
+
+(defun org-babel-lob--src-info (name)
+ "Return internal representation for Babel data named NAME.
+NAME is a string. This function looks into the current document
+for a Babel call or source block. If none is found, it looks
+after NAME in the Library of Babel. Eventually, if that also
+fails, it returns nil."
+ ;; During export, look into the pristine copy of the document being
+ ;; exported instead of the current one, which could miss some data.
+ (with-current-buffer (or org-babel-exp-reference-buffer (current-buffer))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (catch :found
+ (let ((case-fold-search t)
+ (regexp (org-babel-named-data-regexp-for-name name)))
+ (while (re-search-forward regexp nil t)
+ (let ((element (org-element-at-point)))
+ (when (equal name (org-element-property :name element))
+ (throw :found
+ (pcase (org-element-type element)
+ (`src-block (org-babel-get-src-block-info t element))
+ (`babel-call (org-babel-lob-get-info element))
+ ;; Non-executable data found. Since names are
+ ;; supposed to be unique throughout a document,
+ ;; bail out.
+ (_ nil))))))
+ ;; No element named NAME in buffer. Try Library of Babel.
+ (cdr (assoc-string name org-babel-library-of-babel)))))))
+
+;;;###autoload
+(defun org-babel-lob-get-info (&optional datum)
+ "Return internal representation for Library of Babel function call.
+Consider DATUM, when provided, or element at point. Return nil
+when not on an appropriate location. Otherwise return a list
+compatible with `org-babel-get-src-block-info', which see."
+ (let* ((context (or datum (org-element-context)))
+ (type (org-element-type context)))
+ (when (memq type '(babel-call inline-babel-call))
+ (pcase (org-babel-lob--src-info (org-element-property :call context))
+ (`(,language ,body ,header ,_ ,_ ,_ ,coderef)
+ (let ((begin (org-element-property (if (eq type 'inline-babel-call)
+ :begin
+ :post-affiliated)
+ context)))
+ (list language
+ body
+ (apply #'org-babel-merge-params
+ header
+ org-babel-default-lob-header-args
+ (append
+ (org-with-wide-buffer
+ (goto-char begin)
+ (org-babel-params-from-properties language))
+ (list
+ (org-babel-parse-header-arguments
+ (org-element-property :inside-header context))
+ (let ((args (org-element-property :arguments context)))
+ (and args
+ (mapcar (lambda (ref) (cons :var ref))
+ (org-babel-ref-split-args args))))
+ (org-babel-parse-header-arguments
+ (org-element-property :end-header context)))))
+ nil
+ (org-element-property :name context)
+ begin
+ coderef)))
+ (_ nil)))))
+
+(provide 'ob-lob)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ob-lob.el ends here
diff --git a/lisp/ob-lua.el b/lisp/ob-lua.el
new file mode 100644
index 0000000..fa60b0e
--- /dev/null
+++ b/lisp/ob-lua.el
@@ -0,0 +1,403 @@
+;;; ob-lua.el --- Org Babel functions for Lua evaluation -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2014, 2016, 2017 Free Software Foundation, Inc.
+
+;; Authors: Dieter Schoen
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;; Requirements:
+;; for session support, lua-mode is needed.
+;; lua-mode is not part of GNU Emacs/orgmode, but can be obtained
+;; from marmalade or melpa.
+;; The source respository is here:
+;; https://github.com/immerrr/lua-mode
+
+;; However, sessions are not yet working.
+
+;; Org-Babel support for evaluating lua source code.
+
+;;; Code:
+(require 'ob)
+(require 'cl-lib)
+
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function lua-shell "ext:lua-mode" (&optional argprompt))
+(declare-function lua-toggle-shells "ext:lua-mode" (arg))
+(declare-function run-lua "ext:lua" (cmd &optional dedicated show))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("lua" . "lua"))
+
+(defvar org-babel-default-header-args:lua '())
+
+(defcustom org-babel-lua-command "lua"
+ "Name of the command for executing Lua code."
+ :version "24.5"
+ :package-version '(Org . "8.3")
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-lua-mode 'lua-mode
+ "Preferred lua mode for use in running lua interactively.
+This will typically be 'lua-mode."
+ :group 'org-babel
+ :version "24.5"
+ :package-version '(Org . "8.3")
+ :type 'symbol)
+
+(defcustom org-babel-lua-hline-to "None"
+ "Replace hlines in incoming tables with this when translating to lua."
+ :group 'org-babel
+ :version "24.5"
+ :package-version '(Org . "8.3")
+ :type 'string)
+
+(defcustom org-babel-lua-None-to 'hline
+ "Replace 'None' in lua tables with this before returning."
+ :group 'org-babel
+ :version "24.5"
+ :package-version '(Org . "8.3")
+ :type 'symbol)
+
+(defun org-babel-execute:lua (body params)
+ "Execute a block of Lua code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((session (org-babel-lua-initiate-session
+ (cdr (assq :session params))))
+ (result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (return-val (when (and (eq result-type 'value) (not session))
+ (cdr (assq :return params))))
+ (preamble (cdr (assq :preamble params)))
+ (full-body
+ (org-babel-expand-body:generic
+ (concat body (if return-val (format "\nreturn %s" return-val) ""))
+ params (org-babel-variable-assignments:lua params)))
+ (result (org-babel-lua-evaluate
+ session full-body result-type result-params preamble)))
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:lua (session params)
+ "Prepare SESSION according to the header arguments in PARAMS.
+VARS contains resolved variable references"
+ (let* ((session (org-babel-lua-initiate-session session))
+ (var-lines
+ (org-babel-variable-assignments:lua params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:lua (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:lua session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:lua (params)
+ "Return a list of Lua statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (format "%s=%s"
+ (car pair)
+ (org-babel-lua-var-to-lua (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-lua-var-to-lua (var)
+ "Convert an elisp value to a lua variable.
+Convert an elisp value, VAR, into a string of lua source code
+specifying a variable of the same value."
+ (if (listp var)
+ (if (and (= 1 (length var)) (not (listp (car var))))
+ (org-babel-lua-var-to-lua (car var))
+ (if (and
+ (= 2 (length var))
+ (not (listp (car var))))
+ (concat
+ (substring-no-properties (car var))
+ "="
+ (org-babel-lua-var-to-lua (cdr var)))
+ (concat "{" (mapconcat #'org-babel-lua-var-to-lua var ", ") "}")))
+ (if (eq var 'hline)
+ org-babel-lua-hline-to
+ (format
+ (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
+ (if (stringp var) (substring-no-properties var) var)))))
+
+(defun org-babel-lua-table-or-string (results)
+ "Convert RESULTS into an appropriate elisp value.
+If the results look like a list or tuple, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (let ((res (org-babel-script-escape results)))
+ (if (listp res)
+ (mapcar (lambda (el) (if (eq el 'None)
+ org-babel-lua-None-to el))
+ res)
+ res)))
+
+(defvar org-babel-lua-buffers '((:default . "*Lua*")))
+
+(defun org-babel-lua-session-buffer (session)
+ "Return the buffer associated with SESSION."
+ (cdr (assoc session org-babel-lua-buffers)))
+
+(defun org-babel-lua-with-earmuffs (session)
+ (let ((name (if (stringp session) session (format "%s" session))))
+ (if (and (string= "*" (substring name 0 1))
+ (string= "*" (substring name (- (length name) 1))))
+ name
+ (format "*%s*" name))))
+
+(defun org-babel-lua-without-earmuffs (session)
+ (let ((name (if (stringp session) session (format "%s" session))))
+ (if (and (string= "*" (substring name 0 1))
+ (string= "*" (substring name (- (length name) 1))))
+ (substring name 1 (- (length name) 1))
+ name)))
+
+(defvar lua-default-interpreter)
+(defvar lua-which-bufname)
+(defvar lua-shell-buffer-name)
+(defun org-babel-lua-initiate-session-by-key (&optional session)
+ "Initiate a lua session.
+If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session."
+ ;; (require org-babel-lua-mode)
+ (save-window-excursion
+ (let* ((session (if session (intern session) :default))
+ (lua-buffer (org-babel-lua-session-buffer session))
+ ;; (cmd (if (member system-type '(cygwin windows-nt ms-dos))
+ ;; (concat org-babel-lua-command " -i")
+ ;; org-babel-lua-command))
+ )
+ (cond
+ ((and (eq 'lua-mode org-babel-lua-mode)
+ (fboundp 'lua-start-process)) ; lua-mode.el
+ ;; Make sure that lua-which-bufname is initialized, as otherwise
+ ;; it will be overwritten the first time a Lua buffer is
+ ;; created.
+ ;;(lua-toggle-shells lua-default-interpreter)
+ ;; `lua-shell' creates a buffer whose name is the value of
+ ;; `lua-which-bufname' with '*'s at the beginning and end
+ (let* ((bufname (if (and lua-buffer (buffer-live-p lua-buffer))
+ (replace-regexp-in-string ;; zap surrounding *
+ "^\\*\\([^*]+\\)\\*$" "\\1" (buffer-name lua-buffer))
+ (concat "Lua-" (symbol-name session))))
+ (lua-which-bufname bufname))
+ (lua-start-process)
+ (setq lua-buffer (org-babel-lua-with-earmuffs bufname))))
+ (t
+ (error "No function available for running an inferior Lua")))
+ (setq org-babel-lua-buffers
+ (cons (cons session lua-buffer)
+ (assq-delete-all session org-babel-lua-buffers)))
+ session)))
+
+(defun org-babel-lua-initiate-session (&optional session _params)
+ "Create a session named SESSION according to PARAMS."
+ (unless (string= session "none")
+ (error "Sessions currently not supported, work in progress")
+ (org-babel-lua-session-buffer
+ (org-babel-lua-initiate-session-by-key session))))
+
+(defvar org-babel-lua-eoe-indicator "--eoe"
+ "A string to indicate that evaluation has completed.")
+
+(defvar org-babel-lua-wrapper-method
+ "
+function main()
+%s
+end
+
+fd=io.open(\"%s\", \"w\")
+fd:write( main() )
+fd:close()")
+(defvar org-babel-lua-pp-wrapper-method
+ "
+-- table to string
+function t2s(t, indent)
+ if indent == nil then
+ indent = \"\"
+ end
+ if type(t) == \"table\" then
+ ts = \"\"
+ for k,v in pairs(t) do
+ if type(v) == \"table\" then
+ ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
+ t2s(v, indent .. \" \")
+ else
+ ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
+ t2s(v, indent .. \" \") .. \"\\n\"
+ end
+ end
+ return ts
+ else
+ return tostring(t)
+ end
+end
+
+
+function main()
+%s
+end
+
+fd=io.open(\"%s\", \"w\")
+fd:write(t2s(main()))
+fd:close()")
+
+(defun org-babel-lua-evaluate
+ (session body &optional result-type result-params preamble)
+ "Evaluate BODY as Lua code."
+ (if session
+ (org-babel-lua-evaluate-session
+ session body result-type result-params)
+ (org-babel-lua-evaluate-external-process
+ body result-type result-params preamble)))
+
+(defun org-babel-lua-evaluate-external-process
+ (body &optional result-type result-params preamble)
+ "Evaluate BODY in external lua process.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (let ((raw
+ (pcase result-type
+ (`output (org-babel-eval org-babel-lua-command
+ (concat (if preamble (concat preamble "\n"))
+ body)))
+ (`value (let ((tmp-file (org-babel-temp-file "lua-")))
+ (org-babel-eval
+ org-babel-lua-command
+ (concat
+ (if preamble (concat preamble "\n") "")
+ (format
+ (if (member "pp" result-params)
+ org-babel-lua-pp-wrapper-method
+ org-babel-lua-wrapper-method)
+ (mapconcat
+ (lambda (line) (format "\t%s" line))
+ (split-string
+ (org-remove-indentation
+ (org-trim body))
+ "[\r\n]") "\n")
+ (org-babel-process-file-name tmp-file 'noquote))))
+ (org-babel-eval-read-file tmp-file))))))
+ (org-babel-result-cond result-params
+ raw
+ (org-babel-lua-table-or-string (org-trim raw)))))
+
+(defun org-babel-lua-evaluate-session
+ (session body &optional result-type result-params)
+ "Pass BODY to the Lua process in SESSION.
+If RESULT-TYPE equals 'output then return standard output as a
+string. If RESULT-TYPE equals 'value then return the value of the
+last statement in BODY, as elisp."
+ (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
+ (dump-last-value
+ (lambda
+ (tmp-file pp)
+ (mapc
+ (lambda (statement) (insert statement) (funcall send-wait))
+ (if pp
+ (list
+ "-- table to string
+function t2s(t, indent)
+ if indent == nil then
+ indent = \"\"
+ end
+ if type(t) == \"table\" then
+ ts = \"\"
+ for k,v in pairs(t) do
+ if type(v) == \"table\" then
+ ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" ..
+ t2s(v, indent .. \" \")
+ else
+ ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" ..
+ t2s(v, indent .. \" \") .. \"\\n\"
+ end
+ end
+ return ts
+ else
+ return tostring(t)
+ end
+end
+"
+ (concat "fd:write(_))
+fd:close()"
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (list (format "fd=io.open(\"%s\", \"w\")
+fd:write( _ )
+fd:close()"
+ (org-babel-process-file-name tmp-file
+ 'noquote)))))))
+ (input-body (lambda (body)
+ (mapc (lambda (line) (insert line) (funcall send-wait))
+ (split-string body "[\r\n]"))
+ (funcall send-wait)))
+ (results
+ (pcase result-type
+ (`output
+ (mapconcat
+ #'org-trim
+ (butlast
+ (org-babel-comint-with-output
+ (session org-babel-lua-eoe-indicator t body)
+ (funcall input-body body)
+ (funcall send-wait) (funcall send-wait)
+ (insert org-babel-lua-eoe-indicator)
+ (funcall send-wait))
+ 2) "\n"))
+ (`value
+ (let ((tmp-file (org-babel-temp-file "lua-")))
+ (org-babel-comint-with-output
+ (session org-babel-lua-eoe-indicator nil body)
+ (let ((comint-process-echoes nil))
+ (funcall input-body body)
+ (funcall dump-last-value tmp-file
+ (member "pp" result-params))
+ (funcall send-wait) (funcall send-wait)
+ (insert org-babel-lua-eoe-indicator)
+ (funcall send-wait)))
+ (org-babel-eval-read-file tmp-file))))))
+ (unless (string= (substring org-babel-lua-eoe-indicator 1 -1) results)
+ (org-babel-result-cond result-params
+ results
+ (org-babel-lua-table-or-string results)))))
+
+(defun org-babel-lua-read-string (string)
+ "Strip 's from around Lua string."
+ (org-unbracket-string "'" "'" string))
+
+(provide 'ob-lua)
+
+
+
+;;; ob-lua.el ends here
diff --git a/lisp/ob-makefile.el b/lisp/ob-makefile.el
new file mode 100644
index 0000000..2aa04fd
--- /dev/null
+++ b/lisp/ob-makefile.el
@@ -0,0 +1,48 @@
+;;; ob-makefile.el --- Babel Functions for Makefile -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Thomas S. Dye
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file exists solely for tangling a Makefile from Org files.
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:makefile '())
+
+(defun org-babel-execute:makefile (body _params)
+ "Execute a block of makefile code.
+This function is called by `org-babel-execute-src-block'."
+ body)
+
+(defun org-babel-prep-session:makefile (_session _params)
+ "Return an error if the :session header argument is set. Make
+does not support sessions."
+ (error "Makefile sessions are nonsensical"))
+
+(provide 'ob-makefile)
+
+
+
+;;; ob-makefile.el ends here
diff --git a/lisp/ob-matlab.el b/lisp/ob-matlab.el
new file mode 100644
index 0000000..23cfa36
--- /dev/null
+++ b/lisp/ob-matlab.el
@@ -0,0 +1,47 @@
+;;; ob-matlab.el --- Babel support for Matlab -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Functions that are common to org-babel support for matlab and
+;; octave are in org-babel-octave.el
+
+;;; Requirements:
+
+;; Matlab
+
+;; matlab.el required for interactive emacs sessions and matlab-mode
+;; major mode for source code editing buffer
+;; http://matlab-emacs.sourceforge.net/
+
+;;; Code:
+(require 'ob)
+(require 'ob-octave)
+
+;; see ob-octave for matlab implementation
+
+(provide 'ob-matlab)
+
+
+
+;;; ob-matlab.el ends here
diff --git a/lisp/ob-maxima.el b/lisp/ob-maxima.el
new file mode 100644
index 0000000..0a4d835
--- /dev/null
+++ b/lisp/ob-maxima.el
@@ -0,0 +1,127 @@
+;;; ob-maxima.el --- Babel Functions for Maxima -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric S Fraga
+;; Eric Schulte
+;; Keywords: literate programming, reproducible research, maxima
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating maxima entries.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in maxima
+;;
+;; 2) we are adding the "cmdline" header argument
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("maxima" . "max"))
+
+(defvar org-babel-default-header-args:maxima '())
+
+(defcustom org-babel-maxima-command
+ (if (boundp 'maxima-command) maxima-command "maxima")
+ "Command used to call maxima on the shell."
+ :group 'org-babel
+ :type 'string)
+
+(defun org-babel-maxima-expand (body params)
+ "Expand a block of Maxima code according to its header arguments."
+ (let ((vars (org-babel--get-vars params)))
+ (mapconcat 'identity
+ (list
+ ;; graphic output
+ (let ((graphic-file (ignore-errors (org-babel-graphical-output-file params))))
+ (if graphic-file
+ (format
+ "set_plot_option ([gnuplot_term, png]); set_plot_option ([gnuplot_out_file, %S]);"
+ graphic-file)
+ ""))
+ ;; variables
+ (mapconcat 'org-babel-maxima-var-to-maxima vars "\n")
+ ;; body
+ body
+ "gnuplot_close ()$")
+ "\n")))
+
+(defun org-babel-execute:maxima (body params)
+ "Execute a block of Maxima entries with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (message "executing Maxima source code block")
+ (let ((result-params (split-string (or (cdr (assq :results params)) "")))
+ (result
+ (let* ((cmdline (or (cdr (assq :cmdline params)) ""))
+ (in-file (org-babel-temp-file "maxima-" ".max"))
+ (cmd (format "%s --very-quiet -r 'batchload(%S)$' %s"
+ org-babel-maxima-command in-file cmdline)))
+ (with-temp-file in-file (insert (org-babel-maxima-expand body params)))
+ (message cmd)
+ ;; " | grep -v batch | grep -v 'replaced' | sed '/^$/d' "
+ (let ((raw (org-babel-eval cmd "")))
+ (mapconcat
+ #'identity
+ (delq nil
+ (mapcar (lambda (line)
+ (unless (or (string-match "batch" line)
+ (string-match "^rat: replaced .*$" line)
+ (string-match "^;;; Loading #P" line)
+ (= 0 (length line)))
+ line))
+ (split-string raw "[\r\n]"))) "\n")))))
+ (if (ignore-errors (org-babel-graphical-output-file params))
+ nil
+ (org-babel-result-cond result-params
+ result
+ (let ((tmp-file (org-babel-temp-file "maxima-res-")))
+ (with-temp-file tmp-file (insert result))
+ (org-babel-import-elisp-from-file tmp-file))))))
+
+
+(defun org-babel-prep-session:maxima (_session _params)
+ (error "Maxima does not support sessions"))
+
+(defun org-babel-maxima-var-to-maxima (pair)
+ "Convert an elisp val into a string of maxima code specifying a var
+of the same value."
+ (let ((var (car pair))
+ (val (cdr pair)))
+ (when (symbolp val)
+ (setq val (symbol-name val))
+ (when (= (length val) 1)
+ (setq val (string-to-char val))))
+ (format "%S: %s$" var
+ (org-babel-maxima-elisp-to-maxima val))))
+
+(defun org-babel-maxima-elisp-to-maxima (val)
+ "Return a string of maxima code which evaluates to VAL."
+ (if (listp val)
+ (concat "[" (mapconcat #'org-babel-maxima-elisp-to-maxima val ", ") "]")
+ (format "%s" val)))
+
+
+(provide 'ob-maxima)
+
+
+
+;;; ob-maxima.el ends here
diff --git a/lisp/ob-mscgen.el b/lisp/ob-mscgen.el
new file mode 100644
index 0000000..5c9dccc
--- /dev/null
+++ b/lisp/ob-mscgen.el
@@ -0,0 +1,84 @@
+;;; ob-msc.el --- Babel Functions for Mscgen -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Juan Pechiar
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This software provides EMACS org-babel export support for message
+;; sequence charts. The mscgen utility is used for processing the
+;; sequence definition, and must therefore be installed in the system.
+;;
+;; Mscgen is available and documented at
+;; http://www.mcternan.me.uk/mscgen/index.html
+;;
+;; This code is directly inspired by Eric Schulte's ob-dot.el
+;;
+;; Example:
+;;
+;; #+begin_src mscgen :file example.png
+;; msc {
+;; A,B;
+;; A -> B [ label = "send message" ];
+;; A <- B [ label = "get answer" ];
+;; }
+;; #+end_src
+;;
+;; Header for alternative file type:
+;;
+;; #+begin_src mscgen :file ex2.svg :filetype svg
+
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in mscgen
+;; 2) we are generally only going to return results of type "file"
+;; 3) we are adding the "file" and "filetype" header arguments
+;; 4) there are no variables
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:mscgen
+ '((:results . "file") (:exports . "results"))
+ "Default arguments to use when evaluating a mscgen source block.")
+
+(defun org-babel-execute:mscgen (body params)
+ "Execute a block of Mscgen code with Babel.
+This function is called by `org-babel-execute-src-block'.
+Default filetype is png. Modify by setting :filetype parameter to
+mscgen supported formats."
+ (let* ((out-file (or (cdr (assq :file params)) "output.png" ))
+ (filetype (or (cdr (assq :filetype params)) "png" )))
+ (unless (cdr (assq :file params))
+ (error "
+ERROR: no output file specified. Add \":file name.png\" to the src header"))
+ (org-babel-eval (concat "mscgen -T " filetype " -o " out-file) body)
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:mscgen (_session _params)
+ "Raise an error because Mscgen doesn't support sessions."
+ (error "Mscgen does not support sessions"))
+
+(provide 'ob-mscgen)
+
+
+
+;;; ob-msc.el ends here
diff --git a/lisp/ob-ocaml.el b/lisp/ob-ocaml.el
new file mode 100644
index 0000000..7997ff0
--- /dev/null
+++ b/lisp/ob-ocaml.el
@@ -0,0 +1,171 @@
+;;; ob-ocaml.el --- Babel Functions for Ocaml -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating ocaml source code. This one will
+;; be sort of tricky because ocaml programs must be compiled before
+;; they can be run, but ocaml code can also be run through an
+;; interactive interpreter.
+;;
+;; For now lets only allow evaluation using the ocaml interpreter.
+
+;;; Requirements:
+
+;; - tuareg-mode :: http://www-rocq.inria.fr/~acohen/tuareg/
+
+;;; Code:
+(require 'ob)
+(require 'comint)
+
+(declare-function tuareg-run-caml "ext:tuareg" ())
+(declare-function tuareg-run-ocaml "ext:tuareg" ())
+(declare-function tuareg-interactive-send-input "ext:tuareg" ())
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("ocaml" . "ml"))
+
+(defvar org-babel-default-header-args:ocaml '())
+
+(defvar org-babel-ocaml-eoe-indicator "\"org-babel-ocaml-eoe\";;")
+(defvar org-babel-ocaml-eoe-output "org-babel-ocaml-eoe")
+
+(defcustom org-babel-ocaml-command "ocaml"
+ "Name of the command for executing Ocaml code."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-babel
+ :type 'string)
+
+(defun org-babel-execute:ocaml (body params)
+ "Execute a block of Ocaml code with Babel."
+ (let* ((full-body (org-babel-expand-body:generic
+ body params
+ (org-babel-variable-assignments:ocaml params)))
+ (session (org-babel-prep-session:ocaml
+ (cdr (assq :session params)) params))
+ (raw (org-babel-comint-with-output
+ (session org-babel-ocaml-eoe-output nil full-body)
+ (insert
+ (concat
+ (org-babel-chomp full-body) ";;\n"
+ org-babel-ocaml-eoe-indicator))
+ (tuareg-interactive-send-input)))
+ (clean
+ (car (let ((re (regexp-quote org-babel-ocaml-eoe-output)) out)
+ (delq nil (mapcar (lambda (line)
+ (if out
+ (progn (setq out nil) line)
+ (when (string-match re line)
+ (progn (setq out t) nil))))
+ (mapcar #'org-trim (reverse raw)))))))
+ (raw (org-trim clean))
+ (result-params (cdr (assq :result-params params))))
+ (string-match
+ "\\(\\(.*\n\\)*\\)[^:\n]+ : \\([^=\n]+\\) =\\(\n\\| \\)\\(.+\\)$"
+ raw)
+ (let ((output (match-string 1 raw))
+ (type (match-string 3 raw))
+ (value (match-string 5 raw)))
+ (org-babel-reassemble-table
+ (org-babel-result-cond result-params
+ (cond
+ ((member "verbatim" result-params) raw)
+ ((member "output" result-params) output)
+ (t raw))
+ (if (and value type)
+ (org-babel-ocaml-parse-output value type)
+ raw))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(defvar tuareg-interactive-buffer-name)
+(defun org-babel-prep-session:ocaml (session _params)
+ "Prepare SESSION according to the header arguments in PARAMS."
+ (require 'tuareg)
+ (let ((tuareg-interactive-buffer-name (if (and (not (string= session "none"))
+ (not (string= session "default"))
+ (stringp session))
+ session
+ tuareg-interactive-buffer-name)))
+ (save-window-excursion (if (fboundp 'tuareg-run-process-if-needed)
+ (tuareg-run-process-if-needed org-babel-ocaml-command)
+ (tuareg-run-caml)))
+ (get-buffer tuareg-interactive-buffer-name)))
+
+(defun org-babel-variable-assignments:ocaml (params)
+ "Return list of ocaml statements assigning the block's variables."
+ (mapcar
+ (lambda (pair) (format "let %s = %s;;" (car pair)
+ (org-babel-ocaml-elisp-to-ocaml (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-ocaml-elisp-to-ocaml (val)
+ "Return a string of ocaml code which evaluates to VAL."
+ (if (listp val)
+ (concat "[|" (mapconcat #'org-babel-ocaml-elisp-to-ocaml val "; ") "|]")
+ (format "%S" val)))
+
+(defun org-babel-ocaml-parse-output (value type)
+ "Parse VALUE of type TYPE.
+VALUE and TYPE are string output from an ocaml process."
+ (cond
+ ((string= "string" type)
+ (org-babel-read value))
+ ((or (string= "int" type)
+ (string= "float" type))
+ (string-to-number value))
+ ((string-match "list" type)
+ (org-babel-ocaml-read-list value))
+ ((string-match "array" type)
+ (org-babel-ocaml-read-array value))
+ (t (message "don't recognize type %s" type) value)))
+
+(defun org-babel-ocaml-read-list (results)
+ "Convert RESULTS into an elisp table or string.
+If the results look like a table, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ ;; XXX: This probably does not behave as expected when a semicolon
+ ;; is in a string in a list. The same comment applies to
+ ;; `org-babel-ocaml-read-array' below (with even more failure
+ ;; modes).
+ (org-babel-script-escape (replace-regexp-in-string ";" "," results)))
+
+(defun org-babel-ocaml-read-array (results)
+ "Convert RESULTS into an elisp table or string.
+If the results look like a table, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (org-babel-script-escape
+ (replace-regexp-in-string
+ "\\[|" "[" (replace-regexp-in-string
+ "|\\]" "]" (replace-regexp-in-string
+ "; " "," results)))))
+
+(provide 'ob-ocaml)
+
+
+
+;;; ob-ocaml.el ends here
diff --git a/lisp/ob-octave.el b/lisp/ob-octave.el
new file mode 100644
index 0000000..90735b1
--- /dev/null
+++ b/lisp/ob-octave.el
@@ -0,0 +1,266 @@
+;;; ob-octave.el --- Babel Functions for Octave and Matlab -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Requirements:
+
+;; octave
+;; octave-mode.el and octave-inf.el come with GNU emacs
+
+;;; Code:
+(require 'ob)
+
+(declare-function matlab-shell "ext:matlab-mode")
+(declare-function matlab-shell-run-region "ext:matlab-mode")
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-default-header-args:matlab '())
+(defvar org-babel-default-header-args:octave '())
+
+(defvar org-babel-matlab-shell-command "matlab -nosplash"
+ "Shell command to run matlab as an external process.")
+(defvar org-babel-octave-shell-command "octave -q"
+ "Shell command to run octave as an external process.")
+
+(defvar org-babel-matlab-with-emacs-link nil
+ "If non-nil use matlab-shell-run-region for session evaluation.
+ This will use EmacsLink if (matlab-with-emacs-link) evaluates
+ to a non-nil value.")
+
+(defvar org-babel-matlab-emacs-link-wrapper-method
+ "%s
+if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid);
+else, save -ascii %s ans
+end
+delete('%s')
+")
+(defvar org-babel-octave-wrapper-method
+ "%s
+if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid);
+else, dlmwrite('%s', ans, '\\t')
+end")
+
+(defvar org-babel-octave-eoe-indicator "'org_babel_eoe'")
+
+(defvar org-babel-octave-eoe-output "ans = org_babel_eoe")
+
+(defun org-babel-execute:matlab (body params)
+ "Execute a block of matlab code with Babel."
+ (org-babel-execute:octave body params 'matlab))
+
+(defun org-babel-execute:octave (body params &optional matlabp)
+ "Execute a block of octave code with Babel."
+ (let* ((session
+ (funcall (intern (format "org-babel-%s-initiate-session"
+ (if matlabp "matlab" "octave")))
+ (cdr (assq :session params)) params))
+ (result-type (cdr (assq :result-type params)))
+ (full-body
+ (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:octave params)))
+ (gfx-file (ignore-errors (org-babel-graphical-output-file params)))
+ (result (org-babel-octave-evaluate
+ session
+ (if gfx-file
+ (mapconcat 'identity
+ (list
+ "set (0, \"defaultfigurevisible\", \"off\");"
+ full-body
+ (format "print -dpng %s" gfx-file))
+ "\n")
+ full-body)
+ result-type matlabp)))
+ (if gfx-file
+ nil
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
+
+(defun org-babel-prep-session:matlab (session params)
+ "Prepare SESSION according to PARAMS."
+ (org-babel-prep-session:octave session params 'matlab))
+
+(defun org-babel-variable-assignments:octave (params)
+ "Return list of octave statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (format "%s=%s;"
+ (car pair)
+ (org-babel-octave-var-to-octave (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defalias 'org-babel-variable-assignments:matlab
+ 'org-babel-variable-assignments:octave)
+
+(defun org-babel-octave-var-to-octave (var)
+ "Convert an emacs-lisp value into an octave variable.
+Converts an emacs-lisp variable into a string of octave code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-octave-var-to-octave var
+ (if (listp (car var)) "; " ",")) "]")
+ (cond
+ ((stringp var)
+ (format "'%s'" var))
+ (t
+ (format "%s" var)))))
+
+(defun org-babel-prep-session:octave (session params &optional matlabp)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-octave-initiate-session session params matlabp))
+ (var-lines (org-babel-variable-assignments:octave params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-matlab-initiate-session (&optional session params)
+ "Create a matlab inferior process buffer.
+If there is not a current inferior-process-buffer in SESSION then
+create. Return the initialized session."
+ (org-babel-octave-initiate-session session params 'matlab))
+
+(defun org-babel-octave-initiate-session (&optional session _params matlabp)
+ "Create an octave inferior process buffer.
+If there is not a current inferior-process-buffer in SESSION then
+create. Return the initialized session."
+ (if matlabp (require 'matlab) (or (require 'octave-inf nil 'noerror)
+ (require 'octave)))
+ (unless (string= session "none")
+ (let ((session (or session
+ (if matlabp "*Inferior Matlab*" "*Inferior Octave*"))))
+ (if (org-babel-comint-buffer-livep session) session
+ (save-window-excursion
+ (if matlabp (unless org-babel-matlab-with-emacs-link (matlab-shell))
+ (run-octave))
+ (rename-buffer (if (bufferp session) (buffer-name session)
+ (if (stringp session) session (buffer-name))))
+ (current-buffer))))))
+
+(defun org-babel-octave-evaluate
+ (session body result-type &optional matlabp)
+ "Pass BODY to the octave process in SESSION.
+If RESULT-TYPE equals `output' then return the outputs of the
+statements in BODY, if RESULT-TYPE equals `value' then return the
+value of the last statement in BODY, as elisp."
+ (if session
+ (org-babel-octave-evaluate-session session body result-type matlabp)
+ (org-babel-octave-evaluate-external-process body result-type matlabp)))
+
+(defun org-babel-octave-evaluate-external-process (body result-type matlabp)
+ "Evaluate BODY in an external octave process."
+ (let ((cmd (if matlabp
+ org-babel-matlab-shell-command
+ org-babel-octave-shell-command)))
+ (pcase result-type
+ (`output (org-babel-eval cmd body))
+ (`value (let ((tmp-file (org-babel-temp-file "octave-")))
+ (org-babel-eval
+ cmd
+ (format org-babel-octave-wrapper-method body
+ (org-babel-process-file-name tmp-file 'noquote)
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (org-babel-octave-import-elisp-from-file tmp-file))))))
+
+(defun org-babel-octave-evaluate-session
+ (session body result-type &optional matlabp)
+ "Evaluate BODY in SESSION."
+ (let* ((tmp-file (org-babel-temp-file (if matlabp "matlab-" "octave-")))
+ (wait-file (org-babel-temp-file "matlab-emacs-link-wait-signal-"))
+ (full-body
+ (pcase result-type
+ (`output
+ (mapconcat
+ #'org-babel-chomp
+ (list body org-babel-octave-eoe-indicator) "\n"))
+ (`value
+ (if (and matlabp org-babel-matlab-with-emacs-link)
+ (concat
+ (format org-babel-matlab-emacs-link-wrapper-method
+ body
+ (org-babel-process-file-name tmp-file 'noquote)
+ (org-babel-process-file-name tmp-file 'noquote) wait-file) "\n")
+ (mapconcat
+ #'org-babel-chomp
+ (list (format org-babel-octave-wrapper-method
+ body
+ (org-babel-process-file-name tmp-file 'noquote)
+ (org-babel-process-file-name tmp-file 'noquote))
+ org-babel-octave-eoe-indicator) "\n")))))
+ (raw (if (and matlabp org-babel-matlab-with-emacs-link)
+ (save-window-excursion
+ (with-temp-buffer
+ (insert full-body)
+ (write-region "" 'ignored wait-file nil nil nil 'excl)
+ (matlab-shell-run-region (point-min) (point-max))
+ (message "Waiting for Matlab Emacs Link")
+ (while (file-exists-p wait-file) (sit-for 0.01))
+ "")) ;; matlab-shell-run-region doesn't seem to
+ ;; make *matlab* buffer contents easily
+ ;; available, so :results output currently
+ ;; won't work
+ (org-babel-comint-with-output
+ (session
+ (if matlabp
+ org-babel-octave-eoe-indicator
+ org-babel-octave-eoe-output)
+ t full-body)
+ (insert full-body) (comint-send-input nil t)))) results)
+ (pcase result-type
+ (`value
+ (org-babel-octave-import-elisp-from-file tmp-file))
+ (`output
+ (setq results
+ (if matlabp
+ (cdr (reverse (delq "" (mapcar
+ #'org-babel-strip-quotes
+ (mapcar #'org-trim raw)))))
+ (cdr (member org-babel-octave-eoe-output
+ (reverse (mapcar
+ #'org-babel-strip-quotes
+ (mapcar #'org-trim raw)))))))
+ (mapconcat #'identity (reverse results) "\n")))))
+
+(defun org-babel-octave-import-elisp-from-file (file-name)
+ "Import data from FILE-NAME.
+This removes initial blank and comment lines and then calls
+`org-babel-import-elisp-from-file'."
+ (let ((temp-file (org-babel-temp-file "octave-matlab-")) beg end)
+ (with-temp-file temp-file
+ (insert-file-contents file-name)
+ (re-search-forward "^[ \t]*[^# \t]" nil t)
+ (if (< (setq beg (point-min))
+ (setq end (point-at-bol)))
+ (delete-region beg end)))
+ (org-babel-import-elisp-from-file temp-file '(16))))
+
+(provide 'ob-octave)
+
+
+
+;;; ob-octave.el ends here
diff --git a/lisp/ob-org.el b/lisp/ob-org.el
new file mode 100644
index 0000000..5683b96
--- /dev/null
+++ b/lisp/ob-org.el
@@ -0,0 +1,72 @@
+;;; ob-org.el --- Babel Functions for Org Code Blocks -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This is the simplest of code blocks, where upon evaluation the
+;; contents of the code block are returned in a raw result.
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-export-string-as "ox"
+ (string backend &optional body-only ext-plist))
+
+(defvar org-babel-default-header-args:org
+ '((:results . "raw silent") (:exports . "code"))
+ "Default arguments for evaluating a org source block.")
+
+(defvar org-babel-org-default-header
+ "#+TITLE: default empty header\n"
+ "Default header inserted during export of org blocks.")
+
+(defun org-babel-expand-body:org (body params)
+ (dolist (var (org-babel--get-vars params))
+ (setq body (replace-regexp-in-string
+ (regexp-quote (format "$%s" (car var)))
+ (format "%s" (cdr var))
+ body nil 'literal)))
+ body)
+
+(defun org-babel-execute:org (body params)
+ "Execute a block of Org code with.
+This function is called by `org-babel-execute-src-block'."
+ (let ((result-params (split-string (or (cdr (assq :results params)) "")))
+ (body (org-babel-expand-body:org
+ (replace-regexp-in-string "^," "" body) params)))
+ (cond
+ ((member "latex" result-params)
+ (org-export-string-as (concat "#+Title: \n" body) 'latex t))
+ ((member "html" result-params) (org-export-string-as body 'html t))
+ ((member "ascii" result-params) (org-export-string-as body 'ascii t))
+ (t body))))
+
+(defun org-babel-prep-session:org (_session _params)
+ "Return an error because org does not support sessions."
+ (error "Org does not support sessions"))
+
+(provide 'ob-org)
+
+
+
+;;; ob-org.el ends here
diff --git a/lisp/ob-perl.el b/lisp/ob-perl.el
new file mode 100644
index 0000000..62df8c5
--- /dev/null
+++ b/lisp/ob-perl.el
@@ -0,0 +1,157 @@
+;;; ob-perl.el --- Babel Functions for Perl -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Dan Davison
+;; Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating perl source code.
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("perl" . "pl"))
+
+(defvar org-babel-default-header-args:perl '())
+
+(defvar org-babel-perl-command "perl"
+ "Name of command to use for executing perl code.")
+
+(defun org-babel-execute:perl (body params)
+ "Execute a block of Perl code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((session (cdr (assq :session params)))
+ (result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:perl params)))
+ (session (org-babel-perl-initiate-session session)))
+ (org-babel-reassemble-table
+ (org-babel-perl-evaluate session full-body result-type result-params)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:perl (_session _params)
+ "Prepare SESSION according to the header arguments in PARAMS."
+ (error "Sessions are not supported for Perl"))
+
+(defun org-babel-variable-assignments:perl (params)
+ "Return list of perl statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (org-babel-perl--var-to-perl (cdr pair) (car pair)))
+ (org-babel--get-vars params)))
+
+;; helper functions
+
+(defvar org-babel-perl-var-wrap "q(%s)"
+ "Wrapper for variables inserted into Perl code.")
+
+(defvar org-babel-perl--lvl)
+(defun org-babel-perl--var-to-perl (var &optional varn)
+ "Convert an elisp value to a perl variable.
+The elisp value, VAR, is converted to a string of perl source code
+specifying a var of the same value."
+ (if varn
+ (let ((org-babel-perl--lvl 0) (lvar (listp var)))
+ (concat "my $" (symbol-name varn) "=" (when lvar "\n")
+ (org-babel-perl--var-to-perl var)
+ ";\n"))
+ (let ((prefix (make-string (* 2 org-babel-perl--lvl) ?\ )))
+ (concat prefix
+ (if (listp var)
+ (let ((org-babel-perl--lvl (1+ org-babel-perl--lvl)))
+ (concat "[\n"
+ (mapconcat #'org-babel-perl--var-to-perl var "")
+ prefix "]"))
+ (format "q(%s)" var))
+ (unless (zerop org-babel-perl--lvl) ",\n")))))
+
+(defvar org-babel-perl-buffers '(:default . nil))
+
+(defun org-babel-perl-initiate-session (&optional _session _params)
+ "Return nil because sessions are not supported by perl."
+ nil)
+
+(defvar org-babel-perl-wrapper-method "{
+ my $babel_sub = sub {
+ %s
+ };
+ open my $BOH, qq(>%s) or die qq(Perl: Could not open output file.$/);
+ my $rv = &$babel_sub();
+ my $rt = ref $rv;
+ select $BOH;
+ if (qq(ARRAY) eq $rt) {
+ local $\\=$/;
+ local $,=qq(\t);
+ foreach my $rv ( @$rv ) {
+ my $rt = ref $rv;
+ if (qq(ARRAY) eq $rt) {
+ print @$rv;
+ } else {
+ print $rv;
+ }
+ }
+ } else {
+ print $rv;
+ }
+}")
+
+(defvar org-babel-perl-preface nil)
+
+(defvar org-babel-perl-pp-wrapper-method
+ nil)
+
+(defun org-babel-perl-evaluate (session ibody &optional result-type result-params)
+ "Pass BODY to the Perl process in SESSION.
+If RESULT-TYPE equals `output' then return a list of the outputs
+of the statements in BODY, if RESULT-TYPE equals `value' then
+return the value of the last statement in BODY, as elisp."
+ (when session (error "Sessions are not supported for Perl"))
+ (let* ((body (concat org-babel-perl-preface ibody))
+ (tmp-file (org-babel-temp-file "perl-"))
+ (tmp-babel-file (org-babel-process-file-name
+ tmp-file 'noquote)))
+ (let ((results
+ (pcase result-type
+ (`output
+ (with-temp-file tmp-file
+ (insert
+ (org-babel-eval org-babel-perl-command body))
+ (buffer-string)))
+ (`value
+ (org-babel-eval org-babel-perl-command
+ (format org-babel-perl-wrapper-method
+ body tmp-babel-file))))))
+ (when results
+ (org-babel-result-cond result-params
+ (org-babel-eval-read-file tmp-file)
+ (org-babel-import-elisp-from-file tmp-file '(16)))))))
+
+(provide 'ob-perl)
+
+
+
+;;; ob-perl.el ends here
diff --git a/lisp/ob-picolisp.el b/lisp/ob-picolisp.el
new file mode 100644
index 0000000..f577381
--- /dev/null
+++ b/lisp/ob-picolisp.el
@@ -0,0 +1,187 @@
+;;; ob-picolisp.el --- Babel Functions for Picolisp -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Authors: Thorsten Jolitz
+;; Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library enables the use of PicoLisp in the multi-language
+;; programming framework Org-Babel. PicoLisp is a minimal yet
+;; fascinating lisp dialect and a highly productive application
+;; framework for web-based client-server applications on top of
+;; object-oriented databases. A good way to learn PicoLisp is to first
+;; read Paul Grahams essay "The hundred year language"
+;; (http://www.paulgraham.com/hundred.html) and then study the various
+;; documents and essays published in the PicoLisp wiki
+;; (http://picolisp.com/5000/-2.html). PicoLisp is included in some
+;; GNU/Linux Distributions, and can be downloaded here:
+;; http://software-lab.de/down.html. It ships with a picolisp-mode and
+;; a inferior-picolisp-mode for Emacs (to be found in the /lib/el/
+;; directory).
+
+;; Although it might seem more natural to use Emacs Lisp for most
+;; Lisp-based programming tasks inside Org-Mode, an Emacs library
+;; written in Emacs Lisp, PicoLisp has at least two outstanding
+;; features that make it a valuable addition to Org-Babel:
+
+;; PicoLisp _is_ an object-oriented database with a Prolog-based query
+;; language implemented in PicoLisp (Pilog). Database objects are
+;; first-class members of the language.
+
+;; PicoLisp is an extremely productive framework for the development
+;; of interactive web-applications (on top of a database).
+
+;;; Requirements:
+
+;;; Code:
+(require 'ob)
+(require 'comint)
+
+(declare-function run-picolisp "ext:inferior-picolisp" (cmd))
+(defvar org-babel-tangle-lang-exts) ;; Autoloaded
+
+;; optionally define a file extension for this language
+(add-to-list 'org-babel-tangle-lang-exts '("picolisp" . "l"))
+
+;;; interferes with settings in org-babel buffer?
+;; optionally declare default header arguments for this language
+;; (defvar org-babel-default-header-args:picolisp
+;; '((:colnames . "no"))
+;; "Default arguments for evaluating a picolisp source block.")
+
+(defvar org-babel-picolisp-eoe "org-babel-picolisp-eoe"
+ "String to indicate that evaluation has completed.")
+
+(defcustom org-babel-picolisp-cmd "pil"
+ "Name of command used to evaluate picolisp blocks."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defun org-babel-expand-body:picolisp (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params))
+ (print-level nil)
+ (print-length nil))
+ (if (> (length vars) 0)
+ (concat "(prog (let ("
+ (mapconcat
+ (lambda (var)
+ (format "%S '%S)"
+ (print (car var))
+ (print (cdr var))))
+ vars "\n ")
+ " \n" body ") )")
+ body)))
+
+(defun org-babel-execute:picolisp (body params)
+ "Execute a block of Picolisp code with org-babel. This function is
+ called by `org-babel-execute-src-block'"
+ (message "executing Picolisp source code block")
+ (let* (
+ ;; Name of the session or "none".
+ (session-name (cdr (assq :session params)))
+ ;; Set the session if the session variable is non-nil.
+ (session (org-babel-picolisp-initiate-session session-name))
+ ;; Either OUTPUT or VALUE which should behave as described above.
+ (result-params (cdr (assq :result-params params)))
+ ;; Expand the body with `org-babel-expand-body:picolisp'.
+ (full-body (org-babel-expand-body:picolisp body params))
+ ;; Wrap body appropriately for the type of evaluation and results.
+ (wrapped-body
+ (cond
+ ((or (member "code" result-params)
+ (member "pp" result-params))
+ (format "(pretty (out \"/dev/null\" %s))" full-body))
+ ((and (member "value" result-params) (not session))
+ (format "(print (out \"/dev/null\" %s))" full-body))
+ ((member "value" result-params)
+ (format "(out \"/dev/null\" %s)" full-body))
+ (t full-body)))
+ (result
+ (if (not (string= session-name "none"))
+ ;; Session based evaluation.
+ (mapconcat ;; <- joins the list back into a single string
+ #'identity
+ (butlast ;; <- remove the org-babel-picolisp-eoe line
+ (delq nil
+ (mapcar
+ (lambda (line)
+ (org-babel-chomp ;; Remove trailing newlines.
+ (when (> (length line) 0) ;; Remove empty lines.
+ (cond
+ ;; Remove leading "-> " from return values.
+ ((and (>= (length line) 3)
+ (string= "-> " (substring line 0 3)))
+ (substring line 3))
+ ;; Remove trailing "-> <<return-value>>" on the
+ ;; last line of output.
+ ((and (member "output" result-params)
+ (string-match-p "->" line))
+ (substring line 0 (string-match "->" line)))
+ (t line)
+ )
+ ;;(if (and (>= (length line) 3);Remove leading "<-"
+ ;; (string= "-> " (substring line 0 3)))
+ ;; (substring line 3)
+ ;; line)
+ )))
+ ;; Returns a list of the output of each evaluated exp.
+ (org-babel-comint-with-output
+ (session org-babel-picolisp-eoe)
+ (insert wrapped-body) (comint-send-input)
+ (insert "'" org-babel-picolisp-eoe)
+ (comint-send-input)))))
+ "\n")
+ ;; external evaluation
+ (let ((script-file (org-babel-temp-file "picolisp-script-")))
+ (with-temp-file script-file
+ (insert (concat wrapped-body "(bye)")))
+ (org-babel-eval
+ (format "%s %s"
+ org-babel-picolisp-cmd
+ (org-babel-process-file-name script-file))
+ "")))))
+ (org-babel-result-cond result-params
+ result
+ (read result))))
+
+(defun org-babel-picolisp-initiate-session (&optional session-name)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session."
+ (unless (string= session-name "none")
+ (require 'inferior-picolisp)
+ ;; provide a reasonable default session name
+ (let ((session (or session-name "*inferior-picolisp*")))
+ ;; check if we already have a live session by this name
+ (if (org-babel-comint-buffer-livep session)
+ (get-buffer session)
+ (save-window-excursion
+ (run-picolisp org-babel-picolisp-cmd)
+ (rename-buffer session-name)
+ (current-buffer))))))
+
+(provide 'ob-picolisp)
+
+
+
+;;; ob-picolisp.el ends here
diff --git a/lisp/ob-plantuml.el b/lisp/ob-plantuml.el
new file mode 100644
index 0000000..e90021a
--- /dev/null
+++ b/lisp/ob-plantuml.el
@@ -0,0 +1,100 @@
+;;; ob-plantuml.el --- Babel Functions for Plantuml -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Zhang Weize
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating plantuml script.
+;;
+;; Inspired by Ian Yang's org-export-blocks-format-plantuml
+;; http://www.emacswiki.org/emacs/org-export-blocks-format-plantuml.el
+
+;;; Requirements:
+
+;; plantuml | http://plantuml.sourceforge.net/
+;; plantuml.jar | `org-plantuml-jar-path' should point to the jar file
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:plantuml
+ '((:results . "file") (:exports . "results"))
+ "Default arguments for evaluating a plantuml source block.")
+
+(defcustom org-plantuml-jar-path ""
+ "Path to the plantuml.jar file."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defun org-babel-execute:plantuml (body params)
+ "Execute a block of plantuml code with org-babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((out-file (or (cdr (assq :file params))
+ (error "PlantUML requires a \":file\" header argument")))
+ (cmdline (cdr (assq :cmdline params)))
+ (in-file (org-babel-temp-file "plantuml-"))
+ (java (or (cdr (assq :java params)) ""))
+ (cmd (if (string= "" org-plantuml-jar-path)
+ (error "`org-plantuml-jar-path' is not set")
+ (concat "java " java " -jar "
+ (shell-quote-argument
+ (expand-file-name org-plantuml-jar-path))
+ (if (string= (file-name-extension out-file) "png")
+ " -tpng" "")
+ (if (string= (file-name-extension out-file) "svg")
+ " -tsvg" "")
+ (if (string= (file-name-extension out-file) "eps")
+ " -teps" "")
+ (if (string= (file-name-extension out-file) "pdf")
+ " -tpdf" "")
+ (if (string= (file-name-extension out-file) "vdx")
+ " -tvdx" "")
+ (if (string= (file-name-extension out-file) "xmi")
+ " -txmi" "")
+ (if (string= (file-name-extension out-file) "scxml")
+ " -tscxml" "")
+ (if (string= (file-name-extension out-file) "html")
+ " -thtml" "")
+ (if (string= (file-name-extension out-file) "txt")
+ " -ttxt" "")
+ (if (string= (file-name-extension out-file) "utxt")
+ " -utxt" "")
+ " -p " cmdline " < "
+ (org-babel-process-file-name in-file)
+ " > "
+ (org-babel-process-file-name out-file)))))
+ (unless (file-exists-p org-plantuml-jar-path)
+ (error "Could not find plantuml.jar at %s" org-plantuml-jar-path))
+ (with-temp-file in-file (insert (concat "@startuml\n" body "\n@enduml")))
+ (message "%s" cmd) (org-babel-eval cmd "")
+ nil)) ;; signal that output has already been written to file
+
+(defun org-babel-prep-session:plantuml (_session _params)
+ "Return an error because plantuml does not support sessions."
+ (error "Plantuml does not support sessions"))
+
+(provide 'ob-plantuml)
+
+
+
+;;; ob-plantuml.el ends here
diff --git a/lisp/ob-processing.el b/lisp/ob-processing.el
new file mode 100644
index 0000000..a18a53c
--- /dev/null
+++ b/lisp/ob-processing.el
@@ -0,0 +1,195 @@
+;;; ob-processing.el --- Babel functions for processing -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2015-2017 Free Software Foundation, Inc.
+
+;; Author: Jarmo Hurri (adapted from ob-asymptote.el written by Eric Schulte)
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Babel support for evaluating processing source code.
+;;
+;; This differs from most standard languages in that
+;;
+;; 1) there is no such thing as a "session" in processing
+;;
+;; 2) results can only be exported as html; in this case, the
+;; processing code is embedded via a file into a javascript block
+;; using the processing.js module; the script then draws the
+;; resulting output when the web page is viewed in a browser; note
+;; that the user is responsible for making sure that processing.js
+;; is available on the website
+;;
+;; 3) it is possible to interactively view the sketch of the
+;; Processing code block via Processing 2.0 Emacs mode, using
+;; `org-babel-processing-view-sketch'. You can bind this command
+;; to, e.g., C-c C-v C-k with
+;;
+;; (define-key org-babel-map (kbd "C-k") 'org-babel-processing-view-sketch)
+
+
+;;; Requirements:
+
+;; - processing2-emacs mode :: https://github.com/ptrv/processing2-emacs
+;; - Processing.js module :: http://processingjs.org/
+
+;;; Code:
+(require 'ob)
+(require 'sha1)
+
+(declare-function processing-sketch-run "ext:processing-mode" ())
+
+(defvar org-babel-temporary-directory)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("processing" . "pde"))
+
+;; Default header tags depend on whether exporting html or not; if not
+;; exporting html, then no results are produced; otherwise results are
+;; HTML.
+(defvar org-babel-default-header-args:processing
+ '((:results . "html") (:exports . "results"))
+ "Default arguments when evaluating a Processing source block.")
+
+(defvar org-babel-processing-processing-js-filename "processing.js"
+ "Filename of the processing.js file.")
+
+(defun org-babel-processing-view-sketch ()
+ "Show the sketch of the Processing block under point in an external viewer."
+ (interactive)
+ (require 'processing-mode)
+ (let ((info (org-babel-get-src-block-info)))
+ (if (string= (nth 0 info) "processing")
+ (let* ((body (nth 1 info))
+ (params (org-babel-process-params (nth 2 info)))
+ (sketch-code
+ (org-babel-expand-body:generic
+ body
+ params
+ (org-babel-variable-assignments:processing params))))
+ ;; Note: sketch filename can not contain a hyphen, since it
+ ;; has to be a valid java class name; for this reason
+ ;; make-temp-file is repeated until no hyphen is in the
+ ;; name; also sketch dir name must be the same as the
+ ;; basename of the sketch file.
+ (let* ((temporary-file-directory org-babel-temporary-directory)
+ (sketch-dir
+ (let (sketch-dir-candidate)
+ (while
+ (progn
+ (setq sketch-dir-candidate
+ (make-temp-file "processing" t))
+ (when (string-match-p
+ "-"
+ (file-name-nondirectory sketch-dir-candidate))
+ (delete-directory sketch-dir-candidate)
+ t)))
+ sketch-dir-candidate))
+ (sketch-filename
+ (concat sketch-dir
+ "/"
+ (file-name-nondirectory sketch-dir)
+ ".pde")))
+ (with-temp-file sketch-filename (insert sketch-code))
+ (find-file sketch-filename)
+ (processing-sketch-run)
+ (kill-buffer)))
+ (message "Not inside a Processing source block."))))
+
+(defun org-babel-execute:processing (body params)
+ "Execute a block of Processing code.
+This function is called by `org-babel-execute-src-block'."
+ (let ((sketch-code
+ (org-babel-expand-body:generic
+ body
+ params
+ (org-babel-variable-assignments:processing params))))
+ ;; Results are HTML.
+ (let ((sketch-canvas-id (concat "ob-" (sha1 sketch-code))))
+ (concat "<script src=\""
+ org-babel-processing-processing-js-filename
+ "\"></script>\n <script type=\"text/processing\""
+ " data-processing-target=\""
+ sketch-canvas-id
+ "\">\n"
+ sketch-code
+ "\n</script> <canvas id=\""
+ sketch-canvas-id
+ "\"></canvas>"))))
+
+(defun org-babel-prep-session:processing (_session _params)
+ "Return an error if the :session header argument is set.
+Processing does not support sessions"
+ (error "Processing does not support sessions"))
+
+(defun org-babel-variable-assignments:processing (params)
+ "Return list of processing statements assigning the block's variables."
+ (mapcar #'org-babel-processing-var-to-processing
+ (org-babel--get-vars params)))
+
+(defun org-babel-processing-var-to-processing (pair)
+ "Convert an elisp value into a Processing variable.
+The elisp value PAIR is converted into Processing code specifying
+a variable of the same value."
+ (let ((var (car pair))
+ (val (let ((v (cdr pair)))
+ (if (symbolp v) (symbol-name v) v))))
+ (cond
+ ((integerp val)
+ (format "int %S=%S;" var val))
+ ((floatp val)
+ (format "float %S=%S;" var val))
+ ((stringp val)
+ (format "String %S=\"%s\";" var val))
+ ((and (listp val) (not (listp (car val))))
+ (let* ((type (org-babel-processing-define-type val))
+ (fmt (if (eq 'String type) "\"%s\"" "%s"))
+ (vect (mapconcat (lambda (e) (format fmt e)) val ", ")))
+ (format "%s[] %S={%s};" type var vect)))
+ ((listp val)
+ (let* ((type (org-babel-processing-define-type val))
+ (fmt (if (eq 'String type) "\"%s\"" "%s"))
+ (array (mapconcat (lambda (row)
+ (concat "{"
+ (mapconcat (lambda (e) (format fmt e))
+ row ", ")
+ "}"))
+ val ",")))
+ (format "%S[][] %S={%s};" type var array))))))
+
+(defun org-babel-processing-define-type (data)
+ "Determine type of DATA.
+
+DATA is a list. Return type as a symbol.
+
+The type is `String' if any element in DATA is a string.
+Otherwise, it is either `float', if some elements are floats, or
+`int'."
+ (letrec ((type 'int)
+ (find-type
+ (lambda (row)
+ (dolist (e row type)
+ (cond ((listp e) (setq type (funcall find-type e)))
+ ((stringp e) (throw 'exit 'String))
+ ((floatp e) (setq type 'float)))))))
+ (catch 'exit (funcall find-type data))))
+
+(provide 'ob-processing)
+
+;;; ob-processing.el ends here
diff --git a/lisp/ob-python.el b/lisp/ob-python.el
new file mode 100644
index 0000000..302f8bd
--- /dev/null
+++ b/lisp/ob-python.el
@@ -0,0 +1,347 @@
+;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating python source code.
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-remove-indentation "org" )
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function py-shell "ext:python-mode" (&optional argprompt))
+(declare-function py-toggle-shells "ext:python-mode" (arg))
+(declare-function run-python "ext:python" (&optional cmd dedicated show))
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
+
+(defvar org-babel-default-header-args:python '())
+
+(defcustom org-babel-python-command "python"
+ "Name of the command for executing Python code."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-babel
+ :type 'string)
+
+(defcustom org-babel-python-mode
+ (if (featurep 'python-mode) 'python-mode 'python)
+ "Preferred python mode for use in running python interactively.
+This will typically be either `python' or `python-mode'."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'symbol)
+
+(defcustom org-babel-python-hline-to "None"
+ "Replace hlines in incoming tables with this when translating to python."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-babel-python-None-to 'hline
+ "Replace `None' in python tables with this before returning."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'symbol)
+
+(defun org-babel-execute:python (body params)
+ "Execute a block of Python code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((org-babel-python-command
+ (or (cdr (assq :python params))
+ org-babel-python-command))
+ (session (org-babel-python-initiate-session
+ (cdr (assq :session params))))
+ (result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (return-val (when (and (eq result-type 'value) (not session))
+ (cdr (assq :return params))))
+ (preamble (cdr (assq :preamble params)))
+ (full-body
+ (org-babel-expand-body:generic
+ (concat body (if return-val (format "\nreturn %s" return-val) ""))
+ params (org-babel-variable-assignments:python params)))
+ (result (org-babel-python-evaluate
+ session full-body result-type result-params preamble)))
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:python (session params)
+ "Prepare SESSION according to the header arguments in PARAMS.
+VARS contains resolved variable references"
+ (let* ((session (org-babel-python-initiate-session session))
+ (var-lines
+ (org-babel-variable-assignments:python params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (end-of-line 1) (insert var) (comint-send-input)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:python (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:python session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:python (params)
+ "Return a list of Python statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (format "%s=%s"
+ (car pair)
+ (org-babel-python-var-to-python (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-python-var-to-python (var)
+ "Convert an elisp value to a python variable.
+Convert an elisp value, VAR, into a string of python source code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
+ (if (eq var 'hline)
+ org-babel-python-hline-to
+ (format
+ (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
+ (if (stringp var) (substring-no-properties var) var)))))
+
+(defun org-babel-python-table-or-string (results)
+ "Convert RESULTS into an appropriate elisp value.
+If the results look like a list or tuple, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (let ((res (org-babel-script-escape results)))
+ (if (listp res)
+ (mapcar (lambda (el) (if (eq el 'None)
+ org-babel-python-None-to el))
+ res)
+ res)))
+
+(defvar org-babel-python-buffers '((:default . "*Python*")))
+
+(defun org-babel-python-session-buffer (session)
+ "Return the buffer associated with SESSION."
+ (cdr (assoc session org-babel-python-buffers)))
+
+(defun org-babel-python-with-earmuffs (session)
+ (let ((name (if (stringp session) session (format "%s" session))))
+ (if (and (string= "*" (substring name 0 1))
+ (string= "*" (substring name (- (length name) 1))))
+ name
+ (format "*%s*" name))))
+
+(defun org-babel-python-without-earmuffs (session)
+ (let ((name (if (stringp session) session (format "%s" session))))
+ (if (and (string= "*" (substring name 0 1))
+ (string= "*" (substring name (- (length name) 1))))
+ (substring name 1 (- (length name) 1))
+ name)))
+
+(defvar py-default-interpreter)
+(defvar py-which-bufname)
+(defvar python-shell-buffer-name)
+(defun org-babel-python-initiate-session-by-key (&optional session)
+ "Initiate a python session.
+If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session."
+ (require org-babel-python-mode)
+ (save-window-excursion
+ (let* ((session (if session (intern session) :default))
+ (python-buffer (org-babel-python-session-buffer session))
+ (cmd (if (member system-type '(cygwin windows-nt ms-dos))
+ (concat org-babel-python-command " -i")
+ org-babel-python-command)))
+ (cond
+ ((and (eq 'python org-babel-python-mode)
+ (fboundp 'run-python)) ; python.el
+ (if (not (version< "24.1" emacs-version))
+ (run-python cmd)
+ (unless python-buffer
+ (setq python-buffer (org-babel-python-with-earmuffs session)))
+ (let ((python-shell-buffer-name
+ (org-babel-python-without-earmuffs python-buffer)))
+ (run-python cmd))))
+ ((and (eq 'python-mode org-babel-python-mode)
+ (fboundp 'py-shell)) ; python-mode.el
+ ;; Make sure that py-which-bufname is initialized, as otherwise
+ ;; it will be overwritten the first time a Python buffer is
+ ;; created.
+ (py-toggle-shells py-default-interpreter)
+ ;; `py-shell' creates a buffer whose name is the value of
+ ;; `py-which-bufname' with '*'s at the beginning and end
+ (let* ((bufname (if (and python-buffer (buffer-live-p python-buffer))
+ (replace-regexp-in-string ;; zap surrounding *
+ "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
+ (concat "Python-" (symbol-name session))))
+ (py-which-bufname bufname))
+ (py-shell)
+ (setq python-buffer (org-babel-python-with-earmuffs bufname))))
+ (t
+ (error "No function available for running an inferior Python")))
+ (setq org-babel-python-buffers
+ (cons (cons session python-buffer)
+ (assq-delete-all session org-babel-python-buffers)))
+ session)))
+
+(defun org-babel-python-initiate-session (&optional session _params)
+ "Create a session named SESSION according to PARAMS."
+ (unless (string= session "none")
+ (org-babel-python-session-buffer
+ (org-babel-python-initiate-session-by-key session))))
+
+(defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
+ "A string to indicate that evaluation has completed.")
+(defconst org-babel-python-wrapper-method
+ "
+def main():
+%s
+
+open('%s', 'w').write( str(main()) )")
+(defconst org-babel-python-pp-wrapper-method
+ "
+import pprint
+def main():
+%s
+
+open('%s', 'w').write( pprint.pformat(main()) )")
+
+(defun org-babel-python-evaluate
+ (session body &optional result-type result-params preamble)
+ "Evaluate BODY as Python code."
+ (if session
+ (org-babel-python-evaluate-session
+ session body result-type result-params)
+ (org-babel-python-evaluate-external-process
+ body result-type result-params preamble)))
+
+(defun org-babel-python-evaluate-external-process
+ (body &optional result-type result-params preamble)
+ "Evaluate BODY in external python process.
+If RESULT-TYPE equals `output' then return standard output as a
+string. If RESULT-TYPE equals `value' then return the value of the
+last statement in BODY, as elisp."
+ (let ((raw
+ (pcase result-type
+ (`output (org-babel-eval org-babel-python-command
+ (concat (if preamble (concat preamble "\n"))
+ body)))
+ (`value (let ((tmp-file (org-babel-temp-file "python-")))
+ (org-babel-eval
+ org-babel-python-command
+ (concat
+ (if preamble (concat preamble "\n") "")
+ (format
+ (if (member "pp" result-params)
+ org-babel-python-pp-wrapper-method
+ org-babel-python-wrapper-method)
+ (mapconcat
+ (lambda (line) (format "\t%s" line))
+ (split-string (org-remove-indentation (org-trim body))
+ "[\r\n]")
+ "\n")
+ (org-babel-process-file-name tmp-file 'noquote))))
+ (org-babel-eval-read-file tmp-file))))))
+ (org-babel-result-cond result-params
+ raw
+ (org-babel-python-table-or-string (org-trim raw)))))
+
+(defun org-babel-python-evaluate-session
+ (session body &optional result-type result-params)
+ "Pass BODY to the Python process in SESSION.
+If RESULT-TYPE equals `output' then return standard output as a
+string. If RESULT-TYPE equals `value' then return the value of the
+last statement in BODY, as elisp."
+ (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
+ (dump-last-value
+ (lambda
+ (tmp-file pp)
+ (mapc
+ (lambda (statement) (insert statement) (funcall send-wait))
+ (if pp
+ (list
+ "import pprint"
+ (format "open('%s', 'w').write(pprint.pformat(_))"
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (list (format "open('%s', 'w').write(str(_))"
+ (org-babel-process-file-name tmp-file
+ 'noquote)))))))
+ (input-body (lambda (body)
+ (mapc (lambda (line) (insert line) (funcall send-wait))
+ (split-string body "[\r\n]"))
+ (funcall send-wait)))
+ (results
+ (pcase result-type
+ (`output
+ (mapconcat
+ #'org-trim
+ (butlast
+ (org-babel-comint-with-output
+ (session org-babel-python-eoe-indicator t body)
+ (funcall input-body body)
+ (funcall send-wait) (funcall send-wait)
+ (insert org-babel-python-eoe-indicator)
+ (funcall send-wait))
+ 2) "\n"))
+ (`value
+ (let ((tmp-file (org-babel-temp-file "python-")))
+ (org-babel-comint-with-output
+ (session org-babel-python-eoe-indicator nil body)
+ (let ((comint-process-echoes nil))
+ (funcall input-body body)
+ (funcall dump-last-value tmp-file
+ (member "pp" result-params))
+ (funcall send-wait) (funcall send-wait)
+ (insert org-babel-python-eoe-indicator)
+ (funcall send-wait)))
+ (org-babel-eval-read-file tmp-file))))))
+ (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
+ (org-babel-result-cond result-params
+ results
+ (org-babel-python-table-or-string results)))))
+
+(defun org-babel-python-read-string (string)
+ "Strip \\='s from around Python string."
+ (if (and (string-prefix-p "'" string)
+ (string-suffix-p "'" string))
+ (substring string 1 -1)
+ string))
+
+(provide 'ob-python)
+
+
+
+;;; ob-python.el ends here
diff --git a/lisp/ob-ref.el b/lisp/ob-ref.el
new file mode 100644
index 0000000..f8b9ea4
--- /dev/null
+++ b/lisp/ob-ref.el
@@ -0,0 +1,249 @@
+;;; ob-ref.el --- Babel Functions for Referencing External Data -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Dan Davison
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Functions for referencing data from the header arguments of a
+;; org-babel block. The syntax of such a reference should be
+
+;; #+VAR: variable-name=file:resource-id
+
+;; - variable-name :: the name of the variable to which the value
+;; will be assigned
+
+;; - file :: path to the file containing the resource, or omitted if
+;; resource is in the current file
+
+;; - resource-id :: the id or name of the resource
+
+;; So an example of a simple src block referencing table data in the
+;; same file would be
+
+;; #+NAME: sandbox
+;; | 1 | 2 | 3 |
+;; | 4 | org-babel | 6 |
+;;
+;; #+begin_src emacs-lisp :var table=sandbox
+;; (message table)
+;; #+end_src
+
+;;; Code:
+(require 'ob-core)
+(require 'cl-lib)
+
+(declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-end-of-meta-data "org" (&optional full))
+(declare-function org-find-property "org" (property &optional value))
+(declare-function org-id-find-id-file "org-id" (id))
+(declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
+(declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
+(declare-function org-narrow-to-subtree "org" ())
+(declare-function org-show-context "org" (&optional key))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-babel-ref-split-regexp
+ "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
+
+(defvar org-babel-update-intermediate nil
+ "Update the in-buffer results of code blocks executed to resolve references.")
+
+(defun org-babel-ref-parse (assignment)
+ "Parse a variable ASSIGNMENT in a header argument.
+If the right hand side of the assignment has a literal value
+return that value, otherwise interpret as a reference to an
+external resource and find its value using
+`org-babel-ref-resolve'. Return a list with two elements. The
+first element of the list will be the name of the variable, and
+the second will be an emacs-lisp representation of the value of
+the variable."
+ (when (string-match org-babel-ref-split-regexp assignment)
+ (let ((var (match-string 1 assignment))
+ (ref (match-string 2 assignment)))
+ (cons (intern var)
+ (let ((out (save-excursion
+ (when org-babel-current-src-block-location
+ (goto-char (if (markerp org-babel-current-src-block-location)
+ (marker-position org-babel-current-src-block-location)
+ org-babel-current-src-block-location)))
+ (org-babel-read ref))))
+ (if (equal out ref)
+ (if (and (string-prefix-p "\"" ref)
+ (string-suffix-p "\"" ref))
+ (read ref)
+ (org-babel-ref-resolve ref))
+ out))))))
+
+(defun org-babel-ref-goto-headline-id (id)
+ (or (let ((h (org-find-property "CUSTOM_ID" id)))
+ (when h (goto-char h)))
+ (let* ((file (org-id-find-id-file id))
+ (m (when file (org-id-find-id-in-file id file 'marker))))
+ (when (and file m)
+ (message "file:%S" file)
+ (pop-to-buffer-same-window (marker-buffer m))
+ (goto-char m)
+ (move-marker m nil)
+ (org-show-context)
+ t))))
+
+(defun org-babel-ref-headline-body ()
+ (save-restriction
+ (org-narrow-to-subtree)
+ (buffer-substring
+ (save-excursion (goto-char (point-min))
+ (org-end-of-meta-data)
+ (point))
+ (point-max))))
+
+(defvar org-babel-library-of-babel)
+(defun org-babel-ref-resolve (ref)
+ "Resolve the reference REF and return its value."
+ (save-window-excursion
+ (with-current-buffer (or org-babel-exp-reference-buffer (current-buffer))
+ (save-excursion
+ (let ((case-fold-search t)
+ args new-refere new-header-args new-referent split-file split-ref
+ index)
+ ;; if ref is indexed grab the indices -- beware nested indices
+ (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
+ (let ((str (substring ref 0 (match-beginning 0))))
+ (= (cl-count ?\( str) (cl-count ?\) str))))
+ (setq index (match-string 1 ref))
+ (setq ref (substring ref 0 (match-beginning 0))))
+ ;; assign any arguments to pass to source block
+ (when (string-match
+ "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\(.*\\))$" ref)
+ (setq new-refere (match-string 1 ref))
+ (setq new-header-args (match-string 3 ref))
+ (setq new-referent (match-string 5 ref))
+ (when (> (length new-refere) 0)
+ (when (> (length new-referent) 0)
+ (setq args (mapcar (lambda (ref) (cons :var ref))
+ (org-babel-ref-split-args new-referent))))
+ (when (> (length new-header-args) 0)
+ (setq args (append (org-babel-parse-header-arguments
+ new-header-args) args)))
+ (setq ref new-refere)))
+ (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
+ (setq split-file (match-string 1 ref))
+ (setq split-ref (match-string 2 ref))
+ (find-file split-file)
+ (setq ref split-ref))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let* ((params (append args '((:results . "silent"))))
+ (regexp (org-babel-named-data-regexp-for-name ref))
+ (result
+ (catch :found
+ ;; Check for code blocks or named data.
+ (while (re-search-forward regexp nil t)
+ ;; Ignore COMMENTed headings and orphaned
+ ;; affiliated keywords.
+ (unless (org-in-commented-heading-p)
+ (let ((e (org-element-at-point)))
+ (when (equal (org-element-property :name e) ref)
+ (goto-char
+ (org-element-property :post-affiliated e))
+ (pcase (org-element-type e)
+ (`babel-call
+ (throw :found
+ (org-babel-execute-src-block
+ nil (org-babel-lob-get-info e) params)))
+ (`src-block
+ (throw :found
+ (org-babel-execute-src-block
+ nil nil
+ (and
+ (not org-babel-update-intermediate)
+ params))))
+ ((and (let v (org-babel-read-element e))
+ (guard v))
+ (throw :found v))
+ (_ (error "Reference not found")))))))
+ ;; Check for local or global headlines by ID.
+ (when (org-babel-ref-goto-headline-id ref)
+ (throw :found (org-babel-ref-headline-body)))
+ ;; Check the Library of Babel.
+ (let ((info (cdr (assq (intern ref)
+ org-babel-library-of-babel))))
+ (when info
+ (throw :found
+ (org-babel-execute-src-block nil info params))))
+ (error "Reference `%s' not found in this buffer" ref))))
+ (cond
+ ((symbolp result) (format "%S" result))
+ ((and index (listp result))
+ (org-babel-ref-index-list index result))
+ (t result)))))))))
+
+(defun org-babel-ref-index-list (index lis)
+ "Return the subset of LIS indexed by INDEX.
+
+Indices are 0 based and negative indices count from the end of
+LIS, so 0 references the first element of LIS and -1 references
+the last. If INDEX is separated by \",\"s then each \"portion\"
+is assumed to index into the next deepest nesting or dimension.
+
+A valid \"portion\" can consist of either an integer index, two
+integers separated by a \":\" in which case the entire range is
+returned, or an empty string or \"*\" both of which are
+interpreted to mean the entire range and as such are equivalent
+to \"0:-1\"."
+ (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index))
+ (let* ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\\*\\)")
+ (lgth (length lis))
+ (portion (match-string 1 index))
+ (remainder (substring index (match-end 0)))
+ (wrap (lambda (num) (if (< num 0) (+ lgth num) num)))
+ (open (lambda (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls))))
+ (funcall
+ open
+ (mapcar
+ (lambda (sub-lis)
+ (if (listp sub-lis)
+ (org-babel-ref-index-list remainder sub-lis)
+ sub-lis))
+ (if (or (= 0 (length portion)) (string-match ind-re portion))
+ (mapcar
+ (lambda (n) (nth n lis))
+ (apply 'org-number-sequence
+ (if (and (> (length portion) 0) (match-string 2 portion))
+ (list
+ (funcall wrap (string-to-number (match-string 2 portion)))
+ (funcall wrap (string-to-number (match-string 3 portion))))
+ (list (funcall wrap 0) (funcall wrap -1)))))
+ (list (nth (funcall wrap (string-to-number portion)) lis))))))
+ lis))
+
+(defun org-babel-ref-split-args (arg-string)
+ "Split ARG-STRING into top-level arguments of balanced parenthesis."
+ (mapcar #'org-trim (org-babel-balanced-split arg-string 44)))
+
+
+(provide 'ob-ref)
+
+;;; ob-ref.el ends here
diff --git a/lisp/ob-ruby.el b/lisp/ob-ruby.el
new file mode 100644
index 0000000..d055783
--- /dev/null
+++ b/lisp/ob-ruby.el
@@ -0,0 +1,268 @@
+;;; ob-ruby.el --- Babel Functions for Ruby -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating ruby source code.
+
+;;; Requirements:
+
+;; - ruby and irb executables :: http://www.ruby-lang.org/
+;;
+;; - ruby-mode :: Can be installed through ELPA, or from
+;; http://github.com/eschulte/rinari/raw/master/util/ruby-mode.el
+;;
+;; - inf-ruby mode :: Can be installed through ELPA, or from
+;; http://github.com/eschulte/rinari/raw/master/util/inf-ruby.el
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function run-ruby "ext:inf-ruby" (&optional command name))
+(declare-function xmp "ext:rcodetools" (&optional option))
+
+(defvar inf-ruby-default-implementation)
+(defvar inf-ruby-implementations)
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("ruby" . "rb"))
+
+(defvar org-babel-default-header-args:ruby '())
+
+(defvar org-babel-ruby-command "ruby"
+ "Name of command to use for executing ruby code.")
+
+(defcustom org-babel-ruby-hline-to "nil"
+ "Replace hlines in incoming tables with this when translating to ruby."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-babel-ruby-nil-to 'hline
+ "Replace nil in ruby tables with this before returning."
+ :group 'org-babel
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'symbol)
+
+(defun org-babel-execute:ruby (body params)
+ "Execute a block of Ruby code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((session (org-babel-ruby-initiate-session
+ (cdr (assq :session params))))
+ (result-params (cdr (assq :result-params params)))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:ruby params)))
+ (result (if (member "xmp" result-params)
+ (with-temp-buffer
+ (require 'rcodetools)
+ (insert full-body)
+ (xmp (cdr (assq :xmp-option params)))
+ (buffer-string))
+ (org-babel-ruby-evaluate
+ session full-body result-type result-params))))
+ (org-babel-reassemble-table
+ (org-babel-result-cond result-params
+ result
+ (org-babel-ruby-table-or-string result))
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:ruby (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ ;; (message "params=%S" params) ;; debugging
+ (let* ((session (org-babel-ruby-initiate-session session))
+ (var-lines (org-babel-variable-assignments:ruby params)))
+ (org-babel-comint-in-buffer session
+ (sit-for .5) (goto-char (point-max))
+ (mapc (lambda (var)
+ (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)
+ (sit-for .1) (goto-char (point-max))) var-lines))
+ session))
+
+(defun org-babel-load-session:ruby (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:ruby session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+;; helper functions
+
+(defun org-babel-variable-assignments:ruby (params)
+ "Return list of ruby statements assigning the block's variables."
+ (mapcar
+ (lambda (pair)
+ (format "%s=%s"
+ (car pair)
+ (org-babel-ruby-var-to-ruby (cdr pair))))
+ (org-babel--get-vars params)))
+
+(defun org-babel-ruby-var-to-ruby (var)
+ "Convert VAR into a ruby variable.
+Convert an elisp value into a string of ruby source code
+specifying a variable of the same value."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-ruby-var-to-ruby var ", ") "]")
+ (if (eq var 'hline)
+ org-babel-ruby-hline-to
+ (format "%S" var))))
+
+(defun org-babel-ruby-table-or-string (results)
+ "Convert RESULTS into an appropriate elisp value.
+If RESULTS look like a table, then convert them into an
+Emacs-lisp table, otherwise return the results as a string."
+ (let ((res (org-babel-script-escape results)))
+ (if (listp res)
+ (mapcar (lambda (el) (if (not el)
+ org-babel-ruby-nil-to el))
+ res)
+ res)))
+
+(defun org-babel-ruby-initiate-session (&optional session _params)
+ "Initiate a ruby session.
+If there is not a current inferior-process-buffer in SESSION
+then create one. Return the initialized session."
+ (unless (string= session "none")
+ (require 'inf-ruby)
+ (let* ((cmd (cdr (assoc inf-ruby-default-implementation
+ inf-ruby-implementations)))
+ (buffer (get-buffer (format "*%s*" session)))
+ (session-buffer (or buffer (save-window-excursion
+ (run-ruby cmd session)
+ (current-buffer)))))
+ (if (org-babel-comint-buffer-livep session-buffer)
+ (progn (sit-for .25) session-buffer)
+ (sit-for .5)
+ (org-babel-ruby-initiate-session session)))))
+
+(defvar org-babel-ruby-eoe-indicator ":org_babel_ruby_eoe"
+ "String to indicate that evaluation has completed.")
+(defvar org-babel-ruby-f-write
+ "File.open('%s','w'){|f| f.write((_.class == String) ? _ : _.inspect)}")
+(defvar org-babel-ruby-pp-f-write
+ "File.open('%s','w'){|f| $stdout = f; pp(results); $stdout = orig_out}")
+(defvar org-babel-ruby-wrapper-method
+ "
+def main()
+%s
+end
+results = main()
+File.open('%s', 'w'){ |f| f.write((results.class == String) ? results : results.inspect) }
+")
+(defvar org-babel-ruby-pp-wrapper-method
+ "
+require 'pp'
+def main()
+%s
+end
+results = main()
+File.open('%s', 'w') do |f|
+ $stdout = f
+ pp results
+end
+")
+
+(defun org-babel-ruby-evaluate
+ (buffer body &optional result-type result-params)
+ "Pass BODY to the Ruby process in BUFFER.
+If RESULT-TYPE equals `output' then return a list of the outputs
+of the statements in BODY, if RESULT-TYPE equals `value' then
+return the value of the last statement in BODY, as elisp."
+ (if (not buffer)
+ ;; external process evaluation
+ (pcase result-type
+ (`output (org-babel-eval org-babel-ruby-command body))
+ (`value (let ((tmp-file (org-babel-temp-file "ruby-")))
+ (org-babel-eval
+ org-babel-ruby-command
+ (format (if (member "pp" result-params)
+ org-babel-ruby-pp-wrapper-method
+ org-babel-ruby-wrapper-method)
+ body (org-babel-process-file-name tmp-file 'noquote)))
+ (org-babel-eval-read-file tmp-file))))
+ ;; comint session evaluation
+ (pcase result-type
+ (`output
+ (let ((eoe-string (format "puts \"%s\"" org-babel-ruby-eoe-indicator)))
+ ;; Force the session to be ready before the actual session
+ ;; code is run. There is some problem in comint that will
+ ;; sometimes show the prompt after the the input has already
+ ;; been inserted and that throws off the extraction of the
+ ;; result for Babel.
+ (org-babel-comint-with-output
+ (buffer org-babel-ruby-eoe-indicator t eoe-string)
+ (insert eoe-string) (comint-send-input nil t))
+ ;; Now we can start the evaluation.
+ (mapconcat
+ #'identity
+ (butlast
+ (split-string
+ (mapconcat
+ #'org-trim
+ (org-babel-comint-with-output
+ (buffer org-babel-ruby-eoe-indicator t body)
+ (mapc
+ (lambda (line)
+ (insert (org-babel-chomp line)) (comint-send-input nil t))
+ (list "conf.echo=false;_org_prompt_mode=conf.prompt_mode;conf.prompt_mode=:NULL"
+ body
+ "conf.prompt_mode=_org_prompt_mode;conf.echo=true"
+ eoe-string)))
+ "\n") "[\r\n]") 4) "\n")))
+ (`value
+ (let* ((tmp-file (org-babel-temp-file "ruby-"))
+ (ppp (or (member "code" result-params)
+ (member "pp" result-params))))
+ (org-babel-comint-with-output
+ (buffer org-babel-ruby-eoe-indicator t body)
+ (when ppp (insert "require 'pp';") (comint-send-input nil t))
+ (mapc
+ (lambda (line)
+ (insert (org-babel-chomp line)) (comint-send-input nil t))
+ (append
+ (list body)
+ (if (not ppp)
+ (list (format org-babel-ruby-f-write
+ (org-babel-process-file-name tmp-file 'noquote)))
+ (list
+ "results=_" "require 'pp'" "orig_out = $stdout"
+ (format org-babel-ruby-pp-f-write
+ (org-babel-process-file-name tmp-file 'noquote))))
+ (list org-babel-ruby-eoe-indicator)))
+ (comint-send-input nil t))
+ (org-babel-eval-read-file tmp-file))))))
+
+(provide 'ob-ruby)
+
+
+
+;;; ob-ruby.el ends here
diff --git a/lisp/ob-sass.el b/lisp/ob-sass.el
new file mode 100644
index 0000000..a9a2a9f
--- /dev/null
+++ b/lisp/ob-sass.el
@@ -0,0 +1,70 @@
+;;; ob-sass.el --- Babel Functions for the Sass CSS generation language -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; For more information on sass see http://sass-lang.com/
+;;
+;; This accepts a 'file' header argument which is the target of the
+;; compiled sass. The default output type for sass evaluation is
+;; either file (if a 'file' header argument was given) or scalar if no
+;; such header argument was supplied.
+;;
+;; A 'cmdline' header argument can be supplied to pass arguments to
+;; the sass command line.
+
+;;; Requirements:
+
+;; - sass-mode :: http://github.com/nex3/haml/blob/master/extra/sass-mode.el
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-default-header-args:sass '())
+
+(defun org-babel-execute:sass (body params)
+ "Execute a block of Sass code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((file (cdr (assq :file params)))
+ (out-file (or file (org-babel-temp-file "sass-out-")))
+ (cmdline (cdr (assq :cmdline params)))
+ (in-file (org-babel-temp-file "sass-in-"))
+ (cmd (concat "sass " (or cmdline "")
+ " " (org-babel-process-file-name in-file)
+ " " (org-babel-process-file-name out-file))))
+ (with-temp-file in-file
+ (insert (org-babel-expand-body:generic body params)))
+ (org-babel-eval cmd "")
+ (if file
+ nil ;; signal that output has already been written to file
+ (with-temp-buffer (insert-file-contents out-file) (buffer-string)))))
+
+(defun org-babel-prep-session:sass (_session _params)
+ "Raise an error because sass does not support sessions."
+ (error "Sass does not support sessions"))
+
+(provide 'ob-sass)
+
+
+
+;;; ob-sass.el ends here
diff --git a/lisp/ob-scala.el b/lisp/ob-scala.el
new file mode 100644
index 0000000..7d5f299
--- /dev/null
+++ b/lisp/ob-scala.el
@@ -0,0 +1,114 @@
+;;; ob-scala.el --- Babel Functions for Scala -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Andrzej Lichnerowicz
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;; Currently only supports the external execution. No session support yet.
+
+;;; Requirements:
+;; - Scala language :: http://www.scala-lang.org/
+;; - Scala major mode :: Can be installed from Scala sources
+;; https://github.com/scala/scala-dist/blob/master/tool-support/src/emacs/scala-mode.el
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-tangle-lang-exts) ;; Autoloaded
+(add-to-list 'org-babel-tangle-lang-exts '("scala" . "scala"))
+(defvar org-babel-default-header-args:scala '())
+(defvar org-babel-scala-command "scala"
+ "Name of the command to use for executing Scala code.")
+
+(defun org-babel-execute:scala (body params)
+ "Execute a block of Scala code with org-babel. This function is
+called by `org-babel-execute-src-block'"
+ (message "executing Scala source code block")
+ (let* ((processed-params (org-babel-process-params params))
+ (session (org-babel-scala-initiate-session (nth 0 processed-params)))
+ (result-params (nth 2 processed-params))
+ (result-type (cdr (assq :result-type params)))
+ (full-body (org-babel-expand-body:generic
+ body params))
+ (result (org-babel-scala-evaluate
+ session full-body result-type result-params)))
+
+ (org-babel-reassemble-table
+ result
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defvar org-babel-scala-wrapper-method
+
+"var str_result :String = null;
+
+Console.withOut(new java.io.OutputStream() {def write(b: Int){
+}}) {
+ str_result = {
+%s
+ }.toString
+}
+
+print(str_result)
+")
+
+
+(defun org-babel-scala-evaluate
+ (session body &optional result-type result-params)
+ "Evaluate BODY in external Scala process.
+If RESULT-TYPE equals `output' then return standard output as a string.
+If RESULT-TYPE equals `value' then return the value of the last statement
+in BODY as elisp."
+ (when session (error "Sessions are not (yet) supported for Scala"))
+ (pcase result-type
+ (`output
+ (let ((src-file (org-babel-temp-file "scala-")))
+ (with-temp-file src-file (insert body))
+ (org-babel-eval
+ (concat org-babel-scala-command " " src-file) "")))
+ (`value
+ (let* ((src-file (org-babel-temp-file "scala-"))
+ (wrapper (format org-babel-scala-wrapper-method body)))
+ (with-temp-file src-file (insert wrapper))
+ (let ((raw (org-babel-eval
+ (concat org-babel-scala-command " " src-file) "")))
+ (org-babel-result-cond result-params
+ raw
+ (org-babel-script-escape raw)))))))
+
+
+(defun org-babel-prep-session:scala (_session _params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (error "Sessions are not (yet) supported for Scala"))
+
+(defun org-babel-scala-initiate-session (&optional _session)
+ "If there is not a current inferior-process-buffer in SESSION
+then create. Return the initialized session. Sessions are not
+supported in Scala."
+ nil)
+
+(provide 'ob-scala)
+
+
+
+;;; ob-scala.el ends here
diff --git a/lisp/ob-scheme.el b/lisp/ob-scheme.el
new file mode 100644
index 0000000..cd8c386
--- /dev/null
+++ b/lisp/ob-scheme.el
@@ -0,0 +1,208 @@
+;;; ob-scheme.el --- Babel Functions for Scheme -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Michael Gauland
+;; Keywords: literate programming, reproducible research, scheme
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Now working with SBCL for both session and external evaluation.
+;;
+;; This certainly isn't optimally robust, but it seems to be working
+;; for the basic use cases.
+
+;;; Requirements:
+
+;; - a working scheme implementation
+;; (e.g. guile http://www.gnu.org/software/guile/guile.html)
+;;
+;; - for session based evaluation geiser is required, which is available from
+;; ELPA.
+
+;;; Code:
+(require 'ob)
+(require 'geiser nil t)
+(defvar geiser-repl--repl) ; Defined in geiser-repl.el
+(defvar geiser-impl--implementation) ; Defined in geiser-impl.el
+(defvar geiser-default-implementation) ; Defined in geiser-impl.el
+(defvar geiser-active-implementations) ; Defined in geiser-impl.el
+
+(declare-function run-geiser "ext:geiser-repl" (impl))
+(declare-function geiser-mode "ext:geiser-mode" ())
+(declare-function geiser-eval-region "ext:geiser-mode"
+ (start end &optional and-go raw nomsg))
+(declare-function geiser-repl-exit "ext:geiser-repl" (&optional arg))
+
+(defvar org-babel-default-header-args:scheme '()
+ "Default header arguments for scheme code blocks.")
+
+(defun org-babel-expand-body:scheme (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (if (> (length vars) 0)
+ (concat "(let ("
+ (mapconcat
+ (lambda (var) (format "%S" (print `(,(car var) ',(cdr var)))))
+ vars "\n ")
+ ")\n" body ")")
+ body)))
+
+
+(defvar org-babel-scheme-repl-map (make-hash-table :test 'equal)
+ "Map of scheme sessions to session names.")
+
+(defun org-babel-scheme-cleanse-repl-map ()
+ "Remove dead buffers from the REPL map."
+ (maphash
+ (lambda (x y)
+ (when (not (buffer-name y))
+ (remhash x org-babel-scheme-repl-map)))
+ org-babel-scheme-repl-map))
+
+(defun org-babel-scheme-get-session-buffer (session-name)
+ "Look up the scheme buffer for a session; return nil if it doesn't exist."
+ (org-babel-scheme-cleanse-repl-map) ; Prune dead sessions
+ (gethash session-name org-babel-scheme-repl-map))
+
+(defun org-babel-scheme-set-session-buffer (session-name buffer)
+ "Record the scheme buffer used for a given session."
+ (puthash session-name buffer org-babel-scheme-repl-map))
+
+(defun org-babel-scheme-get-buffer-impl (buffer)
+ "Returns the scheme implementation geiser associates with the buffer."
+ (with-current-buffer (set-buffer buffer)
+ geiser-impl--implementation))
+
+(defun org-babel-scheme-get-repl (impl name)
+ "Switch to a scheme REPL, creating it if it doesn't exist:"
+ (let ((buffer (org-babel-scheme-get-session-buffer name)))
+ (or buffer
+ (progn
+ (run-geiser impl)
+ (if name
+ (progn
+ (rename-buffer name t)
+ (org-babel-scheme-set-session-buffer name (current-buffer))))
+ (current-buffer)))))
+
+(defun org-babel-scheme-make-session-name (buffer name impl)
+ "Generate a name for the session buffer.
+
+For a named session, the buffer name will be the session name.
+
+If the session is unnamed (nil), generate a name.
+
+If the session is `none', use nil for the session name, and
+org-babel-scheme-execute-with-geiser will use a temporary session."
+ (let ((result
+ (cond ((not name)
+ (concat buffer " " (symbol-name impl) " REPL"))
+ ((string= name "none") nil)
+ (name))))
+ result))
+
+(defmacro org-babel-scheme-capture-current-message (&rest body)
+ "Capture current message in both interactive and noninteractive mode"
+ `(if noninteractive
+ (let ((original-message (symbol-function 'message))
+ (current-message nil))
+ (unwind-protect
+ (progn
+ (defun message (&rest args)
+ (setq current-message (apply original-message args)))
+ ,@body
+ current-message)
+ (fset 'message original-message)))
+ (progn
+ ,@body
+ (current-message))))
+
+(defun org-babel-scheme-execute-with-geiser (code output impl repl)
+ "Execute code in specified REPL. If the REPL doesn't exist, create it
+using the given scheme implementation.
+
+Returns the output of executing the code if the output parameter
+is true; otherwise returns the last value."
+ (let ((result nil))
+ (with-temp-buffer
+ (insert (format ";; -*- geiser-scheme-implementation: %s -*-" impl))
+ (newline)
+ (insert (if output
+ (format "(with-output-to-string (lambda () %s))" code)
+ code))
+ (geiser-mode)
+ (let ((repl-buffer (save-current-buffer
+ (org-babel-scheme-get-repl impl repl))))
+ (when (not (eq impl (org-babel-scheme-get-buffer-impl
+ (current-buffer))))
+ (message "Implementation mismatch: %s (%s) %s (%s)" impl (symbolp impl)
+ (org-babel-scheme-get-buffer-impl (current-buffer))
+ (symbolp (org-babel-scheme-get-buffer-impl
+ (current-buffer)))))
+ (setq geiser-repl--repl repl-buffer)
+ (setq geiser-impl--implementation nil)
+ (setq result (org-babel-scheme-capture-current-message
+ (geiser-eval-region (point-min) (point-max))))
+ (setq result
+ (if (and (stringp result) (equal (substring result 0 3) "=> "))
+ (replace-regexp-in-string "^=> " "" result)
+ "\"An error occurred.\""))
+ (when (not repl)
+ (save-current-buffer (set-buffer repl-buffer)
+ (geiser-repl-exit))
+ (set-process-query-on-exit-flag (get-buffer-process repl-buffer) nil)
+ (kill-buffer repl-buffer))
+ (setq result (if (or (string= result "#<void>")
+ (string= result "#<unspecified>"))
+ nil
+ result))))
+ result))
+
+(defun org-babel-execute:scheme (body params)
+ "Execute a block of Scheme code with org-babel.
+This function is called by `org-babel-execute-src-block'"
+ (let* ((source-buffer (current-buffer))
+ (source-buffer-name (replace-regexp-in-string ;; zap surrounding *
+ "^ ?\\*\\([^*]+\\)\\*" "\\1"
+ (buffer-name source-buffer))))
+ (save-excursion
+ (org-babel-reassemble-table
+ (let* ((result-type (cdr (assq :result-type params)))
+ (impl (or (when (cdr (assq :scheme params))
+ (intern (cdr (assq :scheme params))))
+ geiser-default-implementation
+ (car geiser-active-implementations)))
+ (session (org-babel-scheme-make-session-name
+ source-buffer-name (cdr (assq :session params)) impl))
+ (full-body (org-babel-expand-body:scheme body params)))
+ (org-babel-scheme-execute-with-geiser
+ full-body ; code
+ (string= result-type "output") ; output?
+ impl ; implementation
+ (and (not (string= session "none")) session))) ; session
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params)))))))
+
+(provide 'ob-scheme)
+
+;;; ob-scheme.el ends here
diff --git a/lisp/ob-screen.el b/lisp/ob-screen.el
new file mode 100644
index 0000000..554f8c4
--- /dev/null
+++ b/lisp/ob-screen.el
@@ -0,0 +1,143 @@
+;;; ob-screen.el --- Babel Support for Interactive Terminal -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Benjamin Andresen
+;; Keywords: literate programming, interactive shell
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for interactive terminals. Mostly shell scripts.
+;; Heavily inspired by 'eev' from Eduardo Ochs
+;;
+;; Adding :cmd and :terminal as header arguments
+;; :terminal must support the -T (title) and -e (command) parameter
+;;
+;; You can test the default setup. (xterm + sh) with
+;; M-x org-babel-screen-test RET
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-screen-location "screen"
+ "The command location for screen.
+In case you want to use a different screen than one selected by your $PATH")
+
+(defvar org-babel-default-header-args:screen
+ '((:results . "silent") (:session . "default") (:cmd . "sh") (:terminal . "xterm"))
+ "Default arguments to use when running screen source blocks.")
+
+(defun org-babel-execute:screen (body params)
+ "Send a block of code via screen to a terminal using Babel.
+\"default\" session is used when none is specified."
+ (message "Sending source code block to interactive terminal session...")
+ (save-window-excursion
+ (let* ((session (cdr (assq :session params)))
+ (socket (org-babel-screen-session-socketname session)))
+ (unless socket (org-babel-prep-session:screen session params))
+ (org-babel-screen-session-execute-string
+ session (org-babel-expand-body:generic body params)))))
+
+(defun org-babel-prep-session:screen (_session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (cdr (assq :session params)))
+ (cmd (cdr (assq :cmd params)))
+ (terminal (cdr (assq :terminal params)))
+ (process-name (concat "org-babel: terminal (" session ")")))
+ (apply 'start-process process-name "*Messages*"
+ terminal `("-T" ,(concat "org-babel: " session) "-e" ,org-babel-screen-location
+ "-c" "/dev/null" "-mS" ,(concat "org-babel-session-" session)
+ ,cmd))
+ ;; XXX: Is there a better way than the following?
+ (while (not (org-babel-screen-session-socketname session))
+ ;; wait until screen session is available before returning
+ )))
+
+;; helper functions
+
+(defun org-babel-screen-session-execute-string (session body)
+ "If SESSION exists, send BODY to it."
+ (let ((socket (org-babel-screen-session-socketname session)))
+ (when socket
+ (let ((tmpfile (org-babel-screen-session-write-temp-file session body)))
+ (apply 'start-process (concat "org-babel: screen (" session ")") "*Messages*"
+ org-babel-screen-location
+ `("-S" ,socket "-X" "eval" "msgwait 0"
+ ,(concat "readreg z " tmpfile)
+ "paste z"))))))
+
+(defun org-babel-screen-session-socketname (session)
+ "Check if SESSION exists by parsing output of \"screen -ls\"."
+ (let* ((screen-ls (shell-command-to-string "screen -ls"))
+ (sockets (delq
+ nil
+ (mapcar
+ (lambda (x)
+ (when (string-match (rx (or "(Attached)" "(Detached)")) x)
+ x))
+ (split-string screen-ls "\n"))))
+ (match-socket (car
+ (delq
+ nil
+ (mapcar
+ (lambda (x)
+ (when (string-match
+ (concat "org-babel-session-" session) x)
+ x))
+ sockets)))))
+ (when match-socket (car (split-string match-socket)))))
+
+(defun org-babel-screen-session-write-temp-file (_session body)
+ "Save BODY in a temp file that is named after SESSION."
+ (let ((tmpfile (org-babel-temp-file "screen-")))
+ (with-temp-file tmpfile
+ (insert body)
+
+ ;; org-babel has superfluous spaces
+ (goto-char (point-min))
+ (delete-matching-lines "^ +$"))
+ tmpfile))
+
+(defun org-babel-screen-test ()
+ "Test if the default setup works.
+The terminal should shortly flicker."
+ (interactive)
+ (let* ((random-string (format "%s" (random 99999)))
+ (tmpfile (org-babel-temp-file "ob-screen-test-"))
+ (body (concat "echo '" random-string "' > " tmpfile "\nexit\n"))
+ tmp-string)
+ (org-babel-execute:screen body org-babel-default-header-args:screen)
+ ;; XXX: need to find a better way to do the following
+ (while (not (file-readable-p tmpfile))
+ ;; do something, otherwise this will be optimized away
+ (format "org-babel-screen: File not readable yet."))
+ (setq tmp-string (with-temp-buffer
+ (insert-file-contents-literally tmpfile)
+ (buffer-substring (point-min) (point-max))))
+ (delete-file tmpfile)
+ (message (concat "org-babel-screen: Setup "
+ (if (string-match random-string tmp-string)
+ "WORKS."
+ "DOESN'T work.")))))
+
+(provide 'ob-screen)
+
+
+
+;;; ob-screen.el ends here
diff --git a/lisp/ob-sed.el b/lisp/ob-sed.el
new file mode 100644
index 0000000..733c7e1
--- /dev/null
+++ b/lisp/ob-sed.el
@@ -0,0 +1,107 @@
+;;; ob-sed.el --- Babel Functions for Sed Scripts -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2015-2017 Free Software Foundation, Inc.
+
+;; Author: Bjarte Johansen
+;; Keywords: literate programming, reproducible research
+;; Version: 0.1.0
+
+;; This file is part of GNU Emacs.
+
+;;; License:
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+;;
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Provides a way to evaluate sed scripts in Org mode.
+
+;;; Usage:
+
+;; Add to your Emacs config:
+
+;; (org-babel-do-load-languages
+;; 'org-babel-load-languages
+;; '((sed . t)))
+
+;; In addition to the normal header arguments, ob-sed also provides
+;; :cmd-line and :in-file. :cmd-line allows one to pass other flags to
+;; the sed command like the "--in-place" flag which makes sed edit the
+;; file pass to it instead of outputting to standard out or to a
+;; different file. :in-file is a header arguments that allows one to
+;; tell Org Babel which file the sed script to act on.
+
+;;; Code:
+(require 'ob)
+
+(defvar org-babel-sed-command "sed"
+ "Name of the sed executable command.")
+
+(defvar org-babel-tangle-lang-exts)
+(add-to-list 'org-babel-tangle-lang-exts '("sed" . "sed"))
+
+(defconst org-babel-header-args:sed
+ '((:cmd-line . :any)
+ (:in-file . :any))
+ "Sed specific header arguments.")
+
+(defvar org-babel-default-header-args:sed '()
+ "Default arguments for evaluating a sed source block.")
+
+(defun org-babel-execute:sed (body params)
+ "Execute a block of sed code with Org Babel.
+BODY is the source inside a sed source block and PARAMS is an
+association list over the source block configurations. This
+function is called by `org-babel-execute-src-block'."
+ (message "executing sed source code block")
+ (let* ((result-params (cdr (assq :result-params params)))
+ (cmd-line (cdr (assq :cmd-line params)))
+ (in-file (cdr (assq :in-file params)))
+ (code-file (let ((file (org-babel-temp-file "sed-")))
+ (with-temp-file file
+ (insert body)) file))
+ (stdin (let ((stdin (cdr (assq :stdin params))))
+ (when stdin
+ (let ((tmp (org-babel-temp-file "sed-stdin-"))
+ (res (org-babel-ref-resolve stdin)))
+ (with-temp-file tmp
+ (insert res))
+ tmp))))
+ (cmd (mapconcat #'identity
+ (remq nil
+ (list org-babel-sed-command
+ (format "--file=\"%s\"" code-file)
+ cmd-line
+ in-file))
+ " ")))
+ (org-babel-reassemble-table
+ (let ((results
+ (cond
+ (stdin (with-temp-buffer
+ (call-process-shell-command cmd stdin (current-buffer))
+ (buffer-string)))
+ (t (org-babel-eval cmd "")))))
+ (when results
+ (org-babel-result-cond result-params
+ results
+ (let ((tmp (org-babel-temp-file "sed-results-")))
+ (with-temp-file tmp (insert results))
+ (org-babel-import-elisp-from-file tmp)))))
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(provide 'ob-sed)
+;;; ob-sed.el ends here
diff --git a/lisp/ob-shell.el b/lisp/ob-shell.el
new file mode 100644
index 0000000..3787c26
--- /dev/null
+++ b/lisp/ob-shell.el
@@ -0,0 +1,283 @@
+;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating shell source code.
+
+;;; Code:
+(require 'ob)
+(require 'shell)
+(require 'cl-lib)
+
+(declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body)
+ t)
+(declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
+(declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
+(declare-function org-babel-comint-with-output "ob-comint" (meta &rest body)
+ t)
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function orgtbl-to-generic "org-table" (table params))
+
+(defvar org-babel-default-header-args:shell '())
+(defvar org-babel-shell-names)
+
+(defun org-babel-shell-initialize ()
+ "Define execution functions associated to shell names.
+This function has to be called whenever `org-babel-shell-names'
+is modified outside the Customize interface."
+ (interactive)
+ (dolist (name org-babel-shell-names)
+ (eval `(defun ,(intern (concat "org-babel-execute:" name))
+ (body params)
+ ,(format "Execute a block of %s commands with Babel." name)
+ (let ((shell-file-name ,name))
+ (org-babel-execute:shell body params))))
+ (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name))
+ 'org-babel-variable-assignments:shell
+ ,(format "Return list of %s statements assigning to the block's \
+variables."
+ name)))))
+
+(defcustom org-babel-shell-names
+ '("sh" "bash" "csh" "ash" "dash" "ksh" "mksh" "posh")
+ "List of names of shell supported by babel shell code blocks.
+Call `org-babel-shell-initialize' when modifying this variable
+outside the Customize interface."
+ :group 'org-babel
+ :type '(repeat (string :tag "Shell name: "))
+ :set (lambda (symbol value)
+ (set-default symbol value)
+ (org-babel-shell-initialize)))
+
+(defun org-babel-execute:shell (body params)
+ "Execute a block of Shell commands with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((session (org-babel-sh-initiate-session
+ (cdr (assq :session params))))
+ (stdin (let ((stdin (cdr (assq :stdin params))))
+ (when stdin (org-babel-sh-var-to-string
+ (org-babel-ref-resolve stdin)))))
+ (cmdline (cdr (assq :cmdline params)))
+ (full-body (org-babel-expand-body:generic
+ body params (org-babel-variable-assignments:shell params))))
+ (org-babel-reassemble-table
+ (org-babel-sh-evaluate session full-body params stdin cmdline)
+ (org-babel-pick-name
+ (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
+ (org-babel-pick-name
+ (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
+
+(defun org-babel-prep-session:shell (session params)
+ "Prepare SESSION according to the header arguments specified in PARAMS."
+ (let* ((session (org-babel-sh-initiate-session session))
+ (var-lines (org-babel-variable-assignments:shell params)))
+ (org-babel-comint-in-buffer session
+ (mapc (lambda (var)
+ (insert var) (comint-send-input nil t)
+ (org-babel-comint-wait-for-output session)) var-lines))
+ session))
+
+(defun org-babel-load-session:shell (session body params)
+ "Load BODY into SESSION."
+ (save-window-excursion
+ (let ((buffer (org-babel-prep-session:shell session params)))
+ (with-current-buffer buffer
+ (goto-char (process-mark (get-buffer-process (current-buffer))))
+ (insert (org-babel-chomp body)))
+ buffer)))
+
+
+;;; Helper functions
+(defun org-babel--variable-assignments:sh-generic
+ (varname values &optional sep hline)
+ "Returns a list of statements declaring the values as a generic variable."
+ (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
+
+(defun org-babel--variable-assignments:bash_array
+ (varname values &optional sep hline)
+ "Returns a list of statements declaring the values as a bash array."
+ (format "unset %s\ndeclare -a %s=( %s )"
+ varname varname
+ (mapconcat
+ (lambda (value) (org-babel-sh-var-to-sh value sep hline))
+ values
+ " ")))
+
+(defun org-babel--variable-assignments:bash_assoc
+ (varname values &optional sep hline)
+ "Returns a list of statements declaring the values as bash associative array."
+ (format "unset %s\ndeclare -A %s\n%s"
+ varname varname
+ (mapconcat
+ (lambda (items)
+ (format "%s[%s]=%s"
+ varname
+ (org-babel-sh-var-to-sh (car items) sep hline)
+ (org-babel-sh-var-to-sh (cdr items) sep hline)))
+ values
+ "\n")))
+
+(defun org-babel--variable-assignments:bash (varname values &optional sep hline)
+ "Represents the parameters as useful Bash shell variables."
+ (pcase values
+ (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
+ (org-babel--variable-assignments:bash_assoc varname values sep hline))
+ (`(,_ . ,_) ;simple list
+ (org-babel--variable-assignments:bash_array varname values sep hline))
+ (_ ;scalar value
+ (org-babel--variable-assignments:sh-generic varname values sep hline))))
+
+(defun org-babel-variable-assignments:shell (params)
+ "Return list of shell statements assigning the block's variables."
+ (let ((sep (cdr (assq :separator params)))
+ (hline (when (string= "yes" (cdr (assq :hlines params)))
+ (or (cdr (assq :hline-string params))
+ "hline"))))
+ (mapcar
+ (lambda (pair)
+ (if (string-suffix-p "bash" shell-file-name)
+ (org-babel--variable-assignments:bash
+ (car pair) (cdr pair) sep hline)
+ (org-babel--variable-assignments:sh-generic
+ (car pair) (cdr pair) sep hline)))
+ (org-babel--get-vars params))))
+
+(defun org-babel-sh-var-to-sh (var &optional sep hline)
+ "Convert an elisp value to a shell variable.
+Convert an elisp var into a string of shell commands specifying a
+var of the same value."
+ (concat "'" (replace-regexp-in-string
+ "'" "'\"'\"'"
+ (org-babel-sh-var-to-string var sep hline))
+ "'"))
+
+(defun org-babel-sh-var-to-string (var &optional sep hline)
+ "Convert an elisp value to a string."
+ (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
+ (cond
+ ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
+ (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
+ :hline hline)))
+ ((listp var)
+ (mapconcat echo-var var "\n"))
+ (t (funcall echo-var var)))))
+
+(defun org-babel-sh-initiate-session (&optional session _params)
+ "Initiate a session named SESSION according to PARAMS."
+ (when (and session (not (string= session "none")))
+ (save-window-excursion
+ (or (org-babel-comint-buffer-livep session)
+ (progn
+ (shell session)
+ ;; Needed for Emacs 23 since the marker is initially
+ ;; undefined and the filter functions try to use it without
+ ;; checking.
+ (set-marker comint-last-output-start (point))
+ (get-buffer (current-buffer)))))))
+
+(defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
+ "String to indicate that evaluation has completed.")
+(defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
+ "String to indicate that evaluation has completed.")
+
+(defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
+ "Pass BODY to the Shell process in BUFFER.
+If RESULT-TYPE equals `output' then return a list of the outputs
+of the statements in BODY, if RESULT-TYPE equals `value' then
+return the value of the last statement in BODY."
+ (let ((results
+ (cond
+ ((or stdin cmdline) ; external shell script w/STDIN
+ (let ((script-file (org-babel-temp-file "sh-script-"))
+ (stdin-file (org-babel-temp-file "sh-stdin-"))
+ (shebang (cdr (assq :shebang params)))
+ (padline (not (string= "no" (cdr (assq :padline params))))))
+ (with-temp-file script-file
+ (when shebang (insert (concat shebang "\n")))
+ (when padline (insert "\n"))
+ (insert body))
+ (set-file-modes script-file #o755)
+ (with-temp-file stdin-file (insert (or stdin "")))
+ (with-temp-buffer
+ (call-process-shell-command
+ (concat (if shebang script-file
+ (format "%s %s" shell-file-name script-file))
+ (and cmdline (concat " " cmdline)))
+ stdin-file
+ (current-buffer))
+ (buffer-string))))
+ (session ; session evaluation
+ (mapconcat
+ #'org-babel-sh-strip-weird-long-prompt
+ (mapcar
+ #'org-trim
+ (butlast
+ (org-babel-comint-with-output
+ (session org-babel-sh-eoe-output t body)
+ (mapc
+ (lambda (line)
+ (insert line)
+ (comint-send-input nil t)
+ (while (save-excursion
+ (goto-char comint-last-input-end)
+ (not (re-search-forward
+ comint-prompt-regexp nil t)))
+ (accept-process-output
+ (get-buffer-process (current-buffer)))))
+ (append
+ (split-string (org-trim body) "\n")
+ (list org-babel-sh-eoe-indicator))))
+ 2)) "\n"))
+ ('otherwise ; external shell script
+ (if (and (cdr (assq :shebang params))
+ (> (length (cdr (assq :shebang params))) 0))
+ (let ((script-file (org-babel-temp-file "sh-script-"))
+ (shebang (cdr (assq :shebang params)))
+ (padline (not (equal "no" (cdr (assq :padline params))))))
+ (with-temp-file script-file
+ (when shebang (insert (concat shebang "\n")))
+ (when padline (insert "\n"))
+ (insert body))
+ (set-file-modes script-file #o755)
+ (org-babel-eval script-file ""))
+ (org-babel-eval shell-file-name (org-trim body)))))))
+ (when results
+ (let ((result-params (cdr (assq :result-params params))))
+ (org-babel-result-cond result-params
+ results
+ (let ((tmp-file (org-babel-temp-file "sh-")))
+ (with-temp-file tmp-file (insert results))
+ (org-babel-import-elisp-from-file tmp-file)))))))
+
+(defun org-babel-sh-strip-weird-long-prompt (string)
+ "Remove prompt cruft from a string of shell output."
+ (while (string-match "^% +[\r\n$]+ *" string)
+ (setq string (substring string (match-end 0))))
+ string)
+
+(provide 'ob-shell)
+
+
+
+;;; ob-shell.el ends here
diff --git a/lisp/ob-shen.el b/lisp/ob-shen.el
new file mode 100644
index 0000000..6bf36c6
--- /dev/null
+++ b/lisp/ob-shen.el
@@ -0,0 +1,78 @@
+;;; ob-shen.el --- Babel Functions for Shen -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research, shen
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Currently this only works using session evaluation as there is no
+;; defined method for executing shen code outside of a session.
+
+;;; Requirements:
+
+;; - shen-mode and inf-shen will soon be available through the GNU
+;; elpa, however in the interim they are available at
+;; https://github.com/eschulte/shen-mode
+
+;;; Code:
+(require 'ob)
+
+(declare-function shen-eval-defun "ext:inf-shen" (&optional and-go))
+(declare-function org-babel-ruby-var-to-ruby "ob-ruby" (var))
+
+(defvar org-babel-default-header-args:shen '()
+ "Default header arguments for shen code blocks.")
+
+(defun org-babel-expand-body:shen (body params)
+ "Expand BODY according to PARAMS, return the expanded body."
+ (let ((vars (org-babel--get-vars params)))
+ (if (> (length vars) 0)
+ (concat "(let "
+ (mapconcat (lambda (var)
+ (format "%s %s" (car var)
+ (org-babel-shen-var-to-shen (cdr var))))
+ vars " ")
+ body ")")
+ body)))
+
+(defun org-babel-shen-var-to-shen (var)
+ "Convert VAR into a shen variable."
+ (if (listp var)
+ (concat "[" (mapconcat #'org-babel-ruby-var-to-ruby var " ") "]")
+ (format "%S" var)))
+
+(defun org-babel-execute:shen (body params)
+ "Execute a block of Shen code with org-babel.
+This function is called by `org-babel-execute-src-block'"
+ (require 'inf-shen)
+ (let* ((result-params (cdr (assq :result-params params)))
+ (full-body (org-babel-expand-body:shen body params)))
+ (let ((results
+ (with-temp-buffer
+ (insert full-body)
+ (call-interactively #'shen-eval-defun))))
+ (org-babel-result-cond result-params
+ results
+ (condition-case nil (org-babel-script-escape results)
+ (error results))))))
+
+(provide 'ob-shen)
+;;; ob-shen.el ends here
diff --git a/lisp/ob-sql.el b/lisp/ob-sql.el
new file mode 100644
index 0000000..06477d3
--- /dev/null
+++ b/lisp/ob-sql.el
@@ -0,0 +1,283 @@
+;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating sql source code.
+;; (see also ob-sqlite.el)
+;;
+;; SQL is somewhat unique in that there are many different engines for
+;; the evaluation of sql (Mysql, PostgreSQL, etc...), so much of this
+;; file will have to be implemented engine by engine.
+;;
+;; Also SQL evaluation generally takes place inside of a database.
+;;
+;; Header args used:
+;; - engine
+;; - cmdline
+;; - dbhost
+;; - dbport
+;; - dbuser
+;; - dbpassword
+;; - database
+;; - colnames (default, nil, means "yes")
+;; - result-params
+;; - out-file
+;; The following are used but not really implemented for SQL:
+;; - colname-names
+;; - rownames
+;; - rowname-names
+;;
+;; TODO:
+;;
+;; - support for sessions
+;; - support for more engines (currently only supports mysql)
+;; - what's a reasonable way to drop table data into SQL?
+;;
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-table-import "org-table" (file arg))
+(declare-function orgtbl-to-csv "org-table" (table params))
+(declare-function org-table-to-lisp "org-table" (&optional txt))
+(declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
+
+(defvar org-babel-default-header-args:sql '())
+
+(defconst org-babel-header-args:sql
+ '((engine . :any)
+ (out-file . :any)
+ (dbhost . :any)
+ (dbport . :any)
+ (dbuser . :any)
+ (dbpassword . :any)
+ (database . :any))
+ "SQL-specific header arguments.")
+
+(defun org-babel-expand-body:sql (body params)
+ "Expand BODY according to the values of PARAMS."
+ (org-babel-sql-expand-vars
+ body (org-babel--get-vars params)))
+
+(defun org-babel-sql-dbstring-mysql (host port user password database)
+ "Make MySQL cmd line args for database connection. Pass nil to omit that arg."
+ (combine-and-quote-strings
+ (delq nil
+ (list (when host (concat "-h" host))
+ (when port (format "-P%d" port))
+ (when user (concat "-u" user))
+ (when password (concat "-p" password))
+ (when database (concat "-D" database))))))
+
+(defun org-babel-sql-dbstring-postgresql (host port user database)
+ "Make PostgreSQL command line args for database connection.
+Pass nil to omit that arg."
+ (combine-and-quote-strings
+ (delq nil
+ (list (when host (concat "-h" host))
+ (when port (format "-p%d" port))
+ (when user (concat "-U" user))
+ (when database (concat "-d" database))))))
+
+(defun org-babel-sql-dbstring-oracle (host port user password database)
+ "Make Oracle command line args for database connection."
+ (format "%s/%s@%s:%s/%s" user password host port database))
+
+(defun org-babel-sql-dbstring-mssql (host user password database)
+ "Make sqlcmd commmand line args for database connection.
+`sqlcmd' is the preferred command line tool to access Microsoft
+SQL Server on Windows and Linux platform."
+ (mapconcat #'identity
+ (delq nil
+ (list (when host (format "-S \"%s\"" host))
+ (when user (format "-U \"%s\"" user))
+ (when password (format "-P \"%s\"" password))
+ (when database (format "-d \"%s\"" database))))
+ " "))
+
+(defun org-babel-sql-convert-standard-filename (file)
+ "Convert FILE to OS standard file name.
+If in Cygwin environment, uses Cygwin specific function to
+convert the file name. In a Windows-NT environment, do nothing.
+Otherwise, use Emacs' standard conversion function."
+ (cond ((fboundp 'cygwin-convert-file-name-to-windows)
+ (format "%S" (cygwin-convert-file-name-to-windows file)))
+ ((string= "windows-nt" system-type) file)
+ (t (format "%S" (convert-standard-filename file)))))
+
+(defun org-babel-execute:sql (body params)
+ "Execute a block of Sql code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let* ((result-params (cdr (assq :result-params params)))
+ (cmdline (cdr (assq :cmdline params)))
+ (dbhost (cdr (assq :dbhost params)))
+ (dbport (cdr (assq :dbport params)))
+ (dbuser (cdr (assq :dbuser params)))
+ (dbpassword (cdr (assq :dbpassword params)))
+ (database (cdr (assq :database params)))
+ (engine (cdr (assq :engine params)))
+ (colnames-p (not (equal "no" (cdr (assq :colnames params)))))
+ (in-file (org-babel-temp-file "sql-in-"))
+ (out-file (or (cdr (assq :out-file params))
+ (org-babel-temp-file "sql-out-")))
+ (header-delim "")
+ (command (pcase (intern engine)
+ (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
+ (or cmdline "")
+ (org-babel-process-file-name in-file)
+ "/^+/d;s/^|//;s/(NULL)/ /g;$d"
+ (org-babel-process-file-name out-file)))
+ (`monetdb (format "mclient -f tab %s < %s > %s"
+ (or cmdline "")
+ (org-babel-process-file-name in-file)
+ (org-babel-process-file-name out-file)))
+ (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
+ (or cmdline "")
+ (org-babel-sql-dbstring-mssql
+ dbhost dbuser dbpassword database)
+ (org-babel-sql-convert-standard-filename
+ (org-babel-process-file-name in-file))
+ (org-babel-sql-convert-standard-filename
+ (org-babel-process-file-name out-file))))
+ (`mysql (format "mysql %s %s %s < %s > %s"
+ (org-babel-sql-dbstring-mysql
+ dbhost dbport dbuser dbpassword database)
+ (if colnames-p "" "-N")
+ (or cmdline "")
+ (org-babel-process-file-name in-file)
+ (org-babel-process-file-name out-file)))
+ (`postgresql (format
+ "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \
+footer=off -F \"\t\" %s -f %s -o %s %s"
+ (if dbpassword
+ (format "PGPASSWORD=%s " dbpassword)
+ "")
+ (if colnames-p "" "-t")
+ (org-babel-sql-dbstring-postgresql
+ dbhost dbport dbuser database)
+ (org-babel-process-file-name in-file)
+ (org-babel-process-file-name out-file)
+ (or cmdline "")))
+ (`oracle (format
+ "sqlplus -s %s < %s > %s"
+ (org-babel-sql-dbstring-oracle
+ dbhost dbport dbuser dbpassword database)
+ (org-babel-process-file-name in-file)
+ (org-babel-process-file-name out-file)))
+ (_ (error "No support for the %s SQL engine" engine)))))
+ (with-temp-file in-file
+ (insert
+ (pcase (intern engine)
+ (`dbi "/format partbox\n")
+ (`oracle "SET PAGESIZE 50000
+SET NEWPAGE 0
+SET TAB OFF
+SET SPACE 0
+SET LINESIZE 9999
+SET ECHO OFF
+SET FEEDBACK OFF
+SET VERIFY OFF
+SET HEADING ON
+SET MARKUP HTML OFF SPOOL OFF
+SET COLSEP '|'
+
+")
+ (`mssql "SET NOCOUNT ON
+
+")
+ (_ ""))
+ (org-babel-expand-body:sql body params)))
+ (org-babel-eval command "")
+ (org-babel-result-cond result-params
+ (with-temp-buffer
+ (progn (insert-file-contents-literally out-file) (buffer-string)))
+ (with-temp-buffer
+ (cond
+ ((memq (intern engine) '(dbi mysql postgresql))
+ ;; Add header row delimiter after column-names header in first line
+ (cond
+ (colnames-p
+ (with-temp-buffer
+ (insert-file-contents out-file)
+ (goto-char (point-min))
+ (forward-line 1)
+ (insert "-\n")
+ (setq header-delim "-")
+ (write-file out-file)))))
+ (t
+ ;; Need to figure out the delimiter for the header row
+ (with-temp-buffer
+ (insert-file-contents out-file)
+ (goto-char (point-min))
+ (when (re-search-forward "^\\(-+\\)[^-]" nil t)
+ (setq header-delim (match-string-no-properties 1)))
+ (goto-char (point-max))
+ (forward-char -1)
+ (while (looking-at "\n")
+ (delete-char 1)
+ (goto-char (point-max))
+ (forward-char -1))
+ (write-file out-file))))
+ (org-table-import out-file '(16))
+ (org-babel-reassemble-table
+ (mapcar (lambda (x)
+ (if (string= (car x) header-delim)
+ 'hline
+ x))
+ (org-table-to-lisp))
+ (org-babel-pick-name (cdr (assq :colname-names params))
+ (cdr (assq :colnames params)))
+ (org-babel-pick-name (cdr (assq :rowname-names params))
+ (cdr (assq :rownames params))))))))
+
+(defun org-babel-sql-expand-vars (body vars)
+ "Expand the variables held in VARS in BODY."
+ (mapc
+ (lambda (pair)
+ (setq body
+ (replace-regexp-in-string
+ (format "$%s" (car pair))
+ (let ((val (cdr pair)))
+ (if (listp val)
+ (let ((data-file (org-babel-temp-file "sql-data-")))
+ (with-temp-file data-file
+ (insert (orgtbl-to-csv
+ val '(:fmt (lambda (el) (if (stringp el)
+ el
+ (format "%S" el)))))))
+ data-file)
+ (if (stringp val) val (format "%S" val))))
+ body)))
+ vars)
+ body)
+
+(defun org-babel-prep-session:sql (_session _params)
+ "Raise an error because Sql sessions aren't implemented."
+ (error "SQL sessions not yet implemented"))
+
+(provide 'ob-sql)
+
+
+
+;;; ob-sql.el ends here
diff --git a/lisp/ob-sqlite.el b/lisp/ob-sqlite.el
new file mode 100644
index 0000000..8094019
--- /dev/null
+++ b/lisp/ob-sqlite.el
@@ -0,0 +1,161 @@
+;;; ob-sqlite.el --- Babel Functions for SQLite Databases -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating sqlite source code.
+
+;;; Code:
+(require 'ob)
+
+(declare-function org-fill-template "org" (template alist))
+(declare-function org-table-convert-region "org-table"
+ (beg0 end0 &optional separator))
+(declare-function orgtbl-to-csv "org-table" (table params))
+(declare-function org-table-to-lisp "org-table" (&optional txt))
+
+(defvar org-babel-default-header-args:sqlite '())
+
+(defvar org-babel-header-args:sqlite
+ '((db . :any)
+ (header . :any)
+ (echo . :any)
+ (bail . :any)
+ (csv . :any)
+ (column . :any)
+ (html . :any)
+ (line . :any)
+ (list . :any)
+ (separator . :any)
+ (nullvalue . :any))
+ "Sqlite specific header args.")
+
+(defun org-babel-expand-body:sqlite (body params)
+ "Expand BODY according to the values of PARAMS."
+ (org-babel-sqlite-expand-vars
+ body (org-babel--get-vars params)))
+
+(defvar org-babel-sqlite3-command "sqlite3")
+
+(defun org-babel-execute:sqlite (body params)
+ "Execute a block of Sqlite code with Babel.
+This function is called by `org-babel-execute-src-block'."
+ (let ((result-params (split-string (or (cdr (assq :results params)) "")))
+ (db (cdr (assq :db params)))
+ (separator (cdr (assq :separator params)))
+ (nullvalue (cdr (assq :nullvalue params)))
+ (headers-p (equal "yes" (cdr (assq :colnames params))))
+ (others (delq nil (mapcar
+ (lambda (arg) (car (assq arg params)))
+ (list :header :echo :bail :column
+ :csv :html :line :list)))))
+ (unless db (error "ob-sqlite: can't evaluate without a database"))
+ (with-temp-buffer
+ (insert
+ (org-babel-eval
+ (org-fill-template
+ "%cmd %header %separator %nullvalue %others %csv %db "
+ (list
+ (cons "cmd" org-babel-sqlite3-command)
+ (cons "header" (if headers-p "-header" "-noheader"))
+ (cons "separator"
+ (if separator (format "-separator %s" separator) ""))
+ (cons "nullvalue"
+ (if nullvalue (format "-nullvalue %s" nullvalue) ""))
+ (cons "others"
+ (mapconcat
+ (lambda (arg) (format "-%s" (substring (symbol-name arg) 1)))
+ others " "))
+ ;; for easy table parsing, default header type should be -csv
+ (cons "csv" (if (or (member :csv others) (member :column others)
+ (member :line others) (member :list others)
+ (member :html others) separator)
+ ""
+ "-csv"))
+ (cons "db " db)))
+ ;; body of the code block
+ (org-babel-expand-body:sqlite body params)))
+ (org-babel-result-cond result-params
+ (buffer-string)
+ (if (equal (point-min) (point-max))
+ ""
+ (org-table-convert-region (point-min) (point-max)
+ (if (or (member :csv others)
+ (member :column others)
+ (member :line others)
+ (member :list others)
+ (member :html others) separator)
+ nil
+ '(4)))
+ (org-babel-sqlite-table-or-scalar
+ (org-babel-sqlite-offset-colnames
+ (org-table-to-lisp) headers-p)))))))
+
+(defun org-babel-sqlite-expand-vars (body vars)
+ "Expand the variables held in VARS in BODY."
+ ;; FIXME: Redundancy with org-babel-sql-expand-vars!
+ (mapc
+ (lambda (pair)
+ (setq body
+ (replace-regexp-in-string
+ (format "$%s" (car pair))
+ (let ((val (cdr pair)))
+ (if (listp val)
+ (let ((data-file (org-babel-temp-file "sqlite-data-")))
+ (with-temp-file data-file
+ (insert (orgtbl-to-csv
+ val '(:fmt (lambda (el) (if (stringp el)
+ el
+ (format "%S" el)))))))
+ data-file)
+ (if (stringp val) val (format "%S" val))))
+ body)))
+ vars)
+ body)
+
+(defun org-babel-sqlite-table-or-scalar (result)
+ "If RESULT looks like a trivial table, then unwrap it."
+ (if (and (equal 1 (length result))
+ (equal 1 (length (car result))))
+ (org-babel-read (caar result))
+ (mapcar (lambda (row)
+ (if (eq 'hline row)
+ 'hline
+ (mapcar #'org-babel-string-read row))) result)))
+
+(defun org-babel-sqlite-offset-colnames (table headers-p)
+ "If HEADERS-P is non-nil then offset the first row as column names."
+ (if headers-p
+ (cons (car table) (cons 'hline (cdr table)))
+ table))
+
+(defun org-babel-prep-session:sqlite (_session _params)
+ "Raise an error because support for SQLite sessions isn't implemented.
+Prepare SESSION according to the header arguments specified in PARAMS."
+ (error "SQLite sessions not yet implemented"))
+
+(provide 'ob-sqlite)
+
+
+
+;;; ob-sqlite.el ends here
diff --git a/lisp/ob-stan.el b/lisp/ob-stan.el
new file mode 100644
index 0000000..40dd0ef
--- /dev/null
+++ b/lisp/ob-stan.el
@@ -0,0 +1,84 @@
+;;; ob-stan.el --- Babel Functions for Stan -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2015-2017 Free Software Foundation, Inc.
+
+;; Author: Kyle Meyer
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Org-Babel support for evaluating Stan [1] source code.
+;;
+;; Evaluating a Stan block can produce two different results.
+;;
+;; 1) Dump the source code contents to a file.
+;;
+;; This file can then be used as a variable in other blocks, which
+;; allows interfaces like RStan to use the model.
+;;
+;; 2) Compile the contents to a model file.
+;;
+;; This provides access to the CmdStan interface. To use this, set
+;; `org-babel-stan-cmdstan-directory' and provide a :file argument
+;; that does not end in ".stan".
+;;
+;; For more information and usage examples, visit
+;; http://orgmode.org/worg/org-contrib/babel/languages/ob-doc-stan.html
+;;
+;; [1] http://mc-stan.org/
+
+;;; Code:
+(require 'ob)
+(require 'org-compat)
+
+(defcustom org-babel-stan-cmdstan-directory nil
+ "CmdStan source directory.
+'make' will be called from this directory to compile the Stan
+block. When nil, executing Stan blocks dumps the content to a
+plain text file."
+ :group 'org-babel
+ :type 'string)
+
+(defvar org-babel-default-header-args:stan
+ '((:results . "file")))
+
+(defun org-babel-execute:stan (body params)
+ "Generate Stan file from BODY according to PARAMS.
+A :file header argument must be given. If
+`org-babel-stan-cmdstan-directory' is non-nil and the file name
+does not have a \".stan\" extension, save an intermediate
+\".stan\" file and compile the block to the named file.
+Otherwise, write the Stan code directly to the named file."
+ (let ((file (expand-file-name
+ (or (cdr (assq :file params))
+ (user-error "Set :file argument to execute Stan blocks")))))
+ (if (or (not org-babel-stan-cmdstan-directory)
+ (string-match-p "\\.stan\\'" file))
+ (with-temp-file file (insert body))
+ (with-temp-file (concat file ".stan") (insert body))
+ (let ((default-directory org-babel-stan-cmdstan-directory))
+ (call-process-shell-command (concat "make " file))))
+ nil)) ; Signal that output has been written to file.
+
+(defun org-babel-prep-session:stan (_session _params)
+ "Return an error because Stan does not support sessions."
+ (user-error "Stan does not support sessions"))
+
+(provide 'ob-stan)
+;;; ob-stan.el ends here
diff --git a/lisp/ob-table.el b/lisp/ob-table.el
new file mode 100644
index 0000000..4de8936
--- /dev/null
+++ b/lisp/ob-table.el
@@ -0,0 +1,153 @@
+;;; ob-table.el --- Support for Calling Babel Functions from Tables -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Should allow calling functions from Org tables using the function
+;; `org-sbe' as so...
+
+;; #+begin_src emacs-lisp :results silent
+;; (defun fibbd (n) (if (< n 2) 1 (+ (fibbd (- n 1)) (fibbd (- n 2)))))
+;; #+end_src
+
+;; #+name: fibbd
+;; #+begin_src emacs-lisp :var n=2 :results silent
+;; (fibbd n)
+;; #+end_src
+
+;; | original | fibbd |
+;; |----------+--------|
+;; | 0 | |
+;; | 1 | |
+;; | 2 | |
+;; | 3 | |
+;; | 4 | |
+;; | 5 | |
+;; | 6 | |
+;; | 7 | |
+;; | 8 | |
+;; | 9 | |
+;; #+TBLFM: $2='(org-sbe "fibbd" (n $1))
+
+;; NOTE: The quotation marks around the function name, 'fibbd' here,
+;; are optional.
+
+;;; Code:
+(require 'ob-core)
+
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defun org-babel-table-truncate-at-newline (string)
+ "Replace newline character with ellipses.
+If STRING ends in a newline character, then remove the newline
+character and replace it with ellipses."
+ (if (and (stringp string) (string-match "[\n\r]\\(.\\)?" string))
+ (concat (substring string 0 (match-beginning 0))
+ (when (match-string 1 string) "...")) string))
+
+(defmacro org-sbe (source-block &rest variables)
+ "Return the results of calling SOURCE-BLOCK with VARIABLES.
+
+Each element of VARIABLES should be a list of two elements: the
+first element is the name of the variable and second element is a
+string of its value.
+
+So this `org-sbe' construct
+
+ (org-sbe \"source-block\" (n $2) (m 3))
+
+is the equivalent of the following source code block:
+
+ #+begin_src emacs-lisp :var results=source-block(n=val_at_col_2, m=3) :results silent
+ results
+ #+end_src
+
+NOTE: The quotation marks around the function name,
+'source-block', are optional.
+
+NOTE: By default, string variable names are interpreted as
+references to source-code blocks, to force interpretation of a
+cell's value as a string, prefix the identifier a \"$\" (e.g.,
+\"$$2\" instead of \"$2\" or \"$@2$2\" instead of \"@2$2\").
+
+NOTE: It is also possible to pass header arguments to the code
+block. In this case a table cell should hold the string value of
+the header argument which can then be passed before all variables
+as shown in the example below.
+
+| 1 | 2 | :file nothing.png | nothing.png |
+#+TBLFM: @1$4=\\='(org-sbe test-sbe $3 (x $1) (y $2))"
+ (declare (debug (form form)))
+ (let* ((header-args (if (stringp (car variables)) (car variables) ""))
+ (variables (if (stringp (car variables)) (cdr variables) variables)))
+ (let* (quote
+ (variables
+ (mapcar
+ (lambda (var)
+ ;; ensure that all cells prefixed with $'s are strings
+ (cons (car var)
+ (delq nil (mapcar
+ (lambda (el)
+ (if (eq '$ el)
+ (prog1 nil (setq quote t))
+ (prog1
+ (cond
+ (quote (format "\"%s\"" el))
+ ((stringp el) (org-no-properties el))
+ (t el))
+ (setq quote nil))))
+ (cdr var)))))
+ variables)))
+ (unless (stringp source-block)
+ (setq source-block (symbol-name source-block)))
+ (let ((result
+ (if (and source-block (> (length source-block) 0))
+ (let ((params
+ ;; FIXME: Why `eval'?!?!?
+ (eval `(org-babel-parse-header-arguments
+ (concat
+ ":var results="
+ ,source-block
+ "[" ,header-args "]"
+ "("
+ (mapconcat
+ (lambda (var-spec)
+ (if (> (length (cdr var-spec)) 1)
+ (format "%S='%S"
+ (car var-spec)
+ (mapcar #'read (cdr var-spec)))
+ (format "%S=%s"
+ (car var-spec) (cadr var-spec))))
+ ',variables ", ")
+ ")")))))
+ (org-babel-execute-src-block
+ nil (list "emacs-lisp" "results" params)
+ '((:results . "silent"))))
+ "")))
+ (org-trim (if (stringp result) result (format "%S" result)))))))
+
+(provide 'ob-table)
+
+
+
+;;; ob-table.el ends here
diff --git a/lisp/ob-tangle.el b/lisp/ob-tangle.el
new file mode 100644
index 0000000..3b05332
--- /dev/null
+++ b/lisp/ob-tangle.el
@@ -0,0 +1,602 @@
+;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Extract the code from source blocks out into raw source-code files.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-src)
+
+(declare-function make-directory "files" (dir &optional parents))
+(declare-function org-at-heading-p "org" (&optional ignored))
+(declare-function org-babel-update-block-body "ob-core" (new-body))
+(declare-function org-back-to-heading "org" (&optional invisible-ok))
+(declare-function org-before-first-heading-p "org" ())
+(declare-function org-edit-special "org" (&optional arg))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-type "org-element" (element))
+(declare-function org-fill-template "org" (template alist))
+(declare-function org-heading-components "org" ())
+(declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
+(declare-function org-link-escape "org" (text &optional table merge))
+(declare-function org-open-link-from-string "org" (s &optional arg reference-buffer))
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-store-link "org" (arg))
+(declare-function org-string-nw-p "org-macs" (s))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function outline-previous-heading "outline" ())
+(declare-function org-id-find "org-id" (id &optional markerp))
+
+(defvar org-link-types-re)
+
+(defcustom org-babel-tangle-lang-exts
+ '(("emacs-lisp" . "el")
+ ("elisp" . "el"))
+ "Alist mapping languages to their file extensions.
+The key is the language name, the value is the string that should
+be inserted as the extension commonly used to identify files
+written in this language. If no entry is found in this list,
+then the name of the language is used."
+ :group 'org-babel-tangle
+ :version "24.1"
+ :type '(repeat
+ (cons
+ (string "Language name")
+ (string "File Extension"))))
+
+(defcustom org-babel-tangle-use-relative-file-links t
+ "Use relative path names in links from tangled source back the Org file."
+ :group 'org-babel-tangle
+ :type 'boolean)
+
+(defcustom org-babel-post-tangle-hook nil
+ "Hook run in code files tangled by `org-babel-tangle'."
+ :group 'org-babel
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-babel-pre-tangle-hook '(save-buffer)
+ "Hook run at the beginning of `org-babel-tangle'."
+ :group 'org-babel
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-babel-tangle-body-hook nil
+ "Hook run over the contents of each code block body."
+ :group 'org-babel
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]"
+ "Format of inserted comments in tangled code files.
+The following format strings can be used to insert special
+information into the output using `org-fill-template'.
+%start-line --- the line number at the start of the code block
+%file --------- the file from which the code block was tangled
+%link --------- Org style link to the code block
+%source-name -- name of the code block
+
+Upon insertion the formatted comment will be commented out, and
+followed by a newline. To inhibit this post-insertion processing
+set the `org-babel-tangle-uncomment-comments' variable to a
+non-nil value.
+
+Whether or not comments are inserted during tangling is
+controlled by the :comments header argument."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-babel-tangle-comment-format-end "%source-name ends here"
+ "Format of inserted comments in tangled code files.
+The following format strings can be used to insert special
+information into the output using `org-fill-template'.
+%start-line --- the line number at the start of the code block
+%file --------- the file from which the code block was tangled
+%link --------- Org style link to the code block
+%source-name -- name of the code block
+
+Upon insertion the formatted comment will be commented out, and
+followed by a newline. To inhibit this post-insertion processing
+set the `org-babel-tangle-uncomment-comments' variable to a
+non-nil value.
+
+Whether or not comments are inserted during tangling is
+controlled by the :comments header argument."
+ :group 'org-babel
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-babel-tangle-uncomment-comments nil
+ "Inhibits automatic commenting and addition of trailing newline
+of tangle comments. Use `org-babel-tangle-comment-format-beg'
+and `org-babel-tangle-comment-format-end' to customize the format
+of tangled comments."
+ :group 'org-babel
+ :type 'boolean)
+
+(defcustom org-babel-process-comment-text 'org-remove-indentation
+ "Function called to process raw Org text collected to be
+inserted as comments in tangled source-code files. The function
+should take a single string argument and return a string
+result. The default value is `org-remove-indentation'."
+ :group 'org-babel
+ :version "24.1"
+ :type 'function)
+
+(defun org-babel-find-file-noselect-refresh (file)
+ "Find file ensuring that the latest changes on disk are
+represented in the file."
+ (find-file-noselect file 'nowarn)
+ (with-current-buffer (get-file-buffer file)
+ (revert-buffer t t t)))
+
+(defmacro org-babel-with-temp-filebuffer (file &rest body)
+ "Open FILE into a temporary buffer execute BODY there like
+`progn', then kill the FILE buffer returning the result of
+evaluating BODY."
+ (declare (indent 1))
+ (let ((temp-path (make-symbol "temp-path"))
+ (temp-result (make-symbol "temp-result"))
+ (temp-file (make-symbol "temp-file"))
+ (visited-p (make-symbol "visited-p")))
+ `(let* ((,temp-path ,file)
+ (,visited-p (get-file-buffer ,temp-path))
+ ,temp-result ,temp-file)
+ (org-babel-find-file-noselect-refresh ,temp-path)
+ (setf ,temp-file (get-file-buffer ,temp-path))
+ (with-current-buffer ,temp-file
+ (setf ,temp-result (progn ,@body)))
+ (unless ,visited-p (kill-buffer ,temp-file))
+ ,temp-result)))
+(def-edebug-spec org-babel-with-temp-filebuffer (form body))
+
+;;;###autoload
+(defun org-babel-tangle-file (file &optional target-file lang)
+ "Extract the bodies of source code blocks in FILE.
+Source code blocks are extracted with `org-babel-tangle'.
+Optional argument TARGET-FILE can be used to specify a default
+export file for all source blocks. Optional argument LANG can be
+used to limit the exported source code blocks by language.
+Return a list whose CAR is the tangled file name."
+ (interactive "fFile to tangle: \nP")
+ (let ((visited-p (get-file-buffer (expand-file-name file)))
+ to-be-removed)
+ (prog1
+ (save-window-excursion
+ (find-file file)
+ (setq to-be-removed (current-buffer))
+ (mapcar #'expand-file-name (org-babel-tangle nil target-file lang)))
+ (unless visited-p
+ (kill-buffer to-be-removed)))))
+
+(defun org-babel-tangle-publish (_ filename pub-dir)
+ "Tangle FILENAME and place the results in PUB-DIR."
+ (unless (file-exists-p pub-dir)
+ (make-directory pub-dir t))
+ (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
+
+;;;###autoload
+(defun org-babel-tangle (&optional arg target-file lang)
+ "Write code blocks to source-specific files.
+Extract the bodies of all source code blocks from the current
+file into their own source-specific files.
+With one universal prefix argument, only tangle the block at point.
+When two universal prefix arguments, only tangle blocks for the
+tangle file of the block at point.
+Optional argument TARGET-FILE can be used to specify a default
+export file for all source blocks. Optional argument LANG can be
+used to limit the exported source code blocks by language."
+ (interactive "P")
+ (run-hooks 'org-babel-pre-tangle-hook)
+ ;; Possibly Restrict the buffer to the current code block
+ (save-restriction
+ (save-excursion
+ (when (equal arg '(4))
+ (let ((head (org-babel-where-is-src-block-head)))
+ (if head
+ (goto-char head)
+ (user-error "Point is not in a source code block"))))
+ (let ((block-counter 0)
+ (org-babel-default-header-args
+ (if target-file
+ (org-babel-merge-params org-babel-default-header-args
+ (list (cons :tangle target-file)))
+ org-babel-default-header-args))
+ (tangle-file
+ (when (equal arg '(16))
+ (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'light))))
+ (user-error "Point is not in a source code block"))))
+ path-collector)
+ (mapc ;; map over all languages
+ (lambda (by-lang)
+ (let* ((lang (car by-lang))
+ (specs (cdr by-lang))
+ (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
+ (lang-f (intern
+ (concat
+ (or (and (cdr (assoc lang org-src-lang-modes))
+ (symbol-name
+ (cdr (assoc lang org-src-lang-modes))))
+ lang)
+ "-mode")))
+ she-banged)
+ (mapc
+ (lambda (spec)
+ (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
+ (let* ((tangle (funcall get-spec :tangle))
+ (she-bang (let ((sheb (funcall get-spec :shebang)))
+ (when (> (length sheb) 0) sheb)))
+ (tangle-mode (funcall get-spec :tangle-mode))
+ (base-name (cond
+ ((string= "yes" tangle)
+ (file-name-sans-extension
+ (nth 1 spec)))
+ ((string= "no" tangle) nil)
+ ((> (length tangle) 0) tangle)))
+ (file-name (when base-name
+ ;; decide if we want to add ext to base-name
+ (if (and ext (string= "yes" tangle))
+ (concat base-name "." ext) base-name))))
+ (when file-name
+ ;; Possibly create the parent directories for file.
+ (let ((m (funcall get-spec :mkdirp))
+ (fnd (file-name-directory file-name)))
+ (and m fnd (not (string= m "no"))
+ (make-directory fnd 'parents)))
+ ;; delete any old versions of file
+ (and (file-exists-p file-name)
+ (not (member file-name (mapcar #'car path-collector)))
+ (delete-file file-name))
+ ;; drop source-block to file
+ (with-temp-buffer
+ (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
+ (when (and she-bang (not (member file-name she-banged)))
+ (insert (concat she-bang "\n"))
+ (setq she-banged (cons file-name she-banged)))
+ (org-babel-spec-to-string spec)
+ ;; We avoid append-to-file as it does not work with tramp.
+ (let ((content (buffer-string)))
+ (with-temp-buffer
+ (when (file-exists-p file-name)
+ (insert-file-contents file-name))
+ (goto-char (point-max))
+ ;; Handle :padlines unless first line in file
+ (unless (or (string= "no" (cdr (assq :padline (nth 4 spec))))
+ (= (point) (point-min)))
+ (insert "\n"))
+ (insert content)
+ (write-region nil nil file-name))))
+ ;; if files contain she-bangs, then make the executable
+ (when she-bang
+ (unless tangle-mode (setq tangle-mode #o755)))
+ ;; update counter
+ (setq block-counter (+ 1 block-counter))
+ (unless (assoc file-name path-collector)
+ (push (cons file-name tangle-mode) path-collector))))))
+ specs)))
+ (if (equal arg '(4))
+ (org-babel-tangle-single-block 1 t)
+ (org-babel-tangle-collect-blocks lang tangle-file)))
+ (message "Tangled %d code block%s from %s" block-counter
+ (if (= block-counter 1) "" "s")
+ (file-name-nondirectory
+ (buffer-file-name
+ (or (buffer-base-buffer) (current-buffer)))))
+ ;; run `org-babel-post-tangle-hook' in all tangled files
+ (when org-babel-post-tangle-hook
+ (mapc
+ (lambda (file)
+ (org-babel-with-temp-filebuffer file
+ (run-hooks 'org-babel-post-tangle-hook)))
+ (mapcar #'car path-collector)))
+ ;; set permissions on tangled files
+ (mapc (lambda (pair)
+ (when (cdr pair) (set-file-modes (car pair) (cdr pair))))
+ path-collector)
+ (mapcar #'car path-collector)))))
+
+(defun org-babel-tangle-clean ()
+ "Remove comments inserted by `org-babel-tangle'.
+Call this function inside of a source-code file generated by
+`org-babel-tangle' to remove all comments inserted automatically
+by `org-babel-tangle'. Warning, this comment removes any lines
+containing constructs which resemble Org file links or noweb
+references."
+ (interactive)
+ (goto-char (point-min))
+ (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
+ (re-search-forward (org-babel-noweb-wrap) nil t))
+ (delete-region (save-excursion (beginning-of-line 1) (point))
+ (save-excursion (end-of-line 1) (forward-char 1) (point)))))
+
+(defvar org-stored-links)
+(defvar org-bracket-link-regexp)
+(defun org-babel-spec-to-string (spec)
+ "Insert SPEC into the current file.
+
+Insert the source-code specified by SPEC into the current source
+code file. This function uses `comment-region' which assumes
+that the appropriate major-mode is set. SPEC has the form:
+
+ (start-line file link source-name params body comment)"
+ (pcase-let*
+ ((`(,start ,file ,link ,source ,info ,body ,comment) spec)
+ (comments (cdr (assq :comments info)))
+ (link? (or (string= comments "both") (string= comments "link")
+ (string= comments "yes") (string= comments "noweb")))
+ (link-data `(("start-line" . ,(number-to-string start))
+ ("file" . ,file)
+ ("link" . ,link)
+ ("source-name" . ,source)))
+ (insert-comment (lambda (text)
+ (when (and comments
+ (not (string= comments "no"))
+ (org-string-nw-p text))
+ (if org-babel-tangle-uncomment-comments
+ ;; Plain comments: no processing.
+ (insert text)
+ ;; Ensure comments are made to be
+ ;; comments, and add a trailing newline.
+ ;; Also ignore invisible characters when
+ ;; commenting.
+ (comment-region
+ (point)
+ (progn (insert (org-no-properties text))
+ (point)))
+ (end-of-line)
+ (insert "\n"))))))
+ (when comment (funcall insert-comment comment))
+ (when link?
+ (funcall insert-comment
+ (org-fill-template
+ org-babel-tangle-comment-format-beg link-data)))
+ (insert body "\n")
+ (when link?
+ (funcall insert-comment
+ (org-fill-template
+ org-babel-tangle-comment-format-end link-data)))))
+
+(defun org-babel-tangle-collect-blocks (&optional language tangle-file)
+ "Collect source blocks in the current Org file.
+Return an association list of source-code block specifications of
+the form used by `org-babel-spec-to-string' grouped by language.
+Optional argument LANGUAGE can be used to limit the collected
+source code blocks by language. Optional argument TANGLE-FILE
+can be used to limit the collected code blocks by target file."
+ (let ((counter 0) last-heading-pos blocks)
+ (org-babel-map-src-blocks (buffer-file-name)
+ (let ((current-heading-pos
+ (org-with-wide-buffer
+ (org-with-limited-levels (outline-previous-heading)))))
+ (if (eq last-heading-pos current-heading-pos) (cl-incf counter)
+ (setq counter 1)
+ (setq last-heading-pos current-heading-pos)))
+ (unless (org-in-commented-heading-p)
+ (let* ((info (org-babel-get-src-block-info 'light))
+ (src-lang (nth 0 info))
+ (src-tfile (cdr (assq :tangle (nth 2 info)))))
+ (unless (or (string= src-tfile "no")
+ (and tangle-file (not (equal tangle-file src-tfile)))
+ (and language (not (string= language src-lang))))
+ ;; Add the spec for this block to blocks under its
+ ;; language.
+ (let ((by-lang (assoc src-lang blocks))
+ (block (org-babel-tangle-single-block counter)))
+ (if by-lang (setcdr by-lang (cons block (cdr by-lang)))
+ (push (cons src-lang (list block)) blocks)))))))
+ ;; Ensure blocks are in the correct order.
+ (mapcar (lambda (b) (cons (car b) (nreverse (cdr b)))) blocks)))
+
+(defun org-babel-tangle-single-block (block-counter &optional only-this-block)
+ "Collect the tangled source for current block.
+Return the list of block attributes needed by
+`org-babel-tangle-collect-blocks'. When ONLY-THIS-BLOCK is
+non-nil, return the full association list to be used by
+`org-babel-tangle' directly."
+ (let* ((info (org-babel-get-src-block-info))
+ (start-line
+ (save-restriction (widen)
+ (+ 1 (line-number-at-pos (point)))))
+ (file (buffer-file-name (buffer-base-buffer)))
+ (src-lang (nth 0 info))
+ (params (nth 2 info))
+ (extra (nth 3 info))
+ (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra)
+ (match-string 1 extra))
+ org-coderef-label-format))
+ (link (let ((l (org-no-properties (org-store-link nil))))
+ (and (string-match org-bracket-link-regexp l)
+ (match-string 1 l))))
+ (source-name
+ (or (nth 4 info)
+ (format "%s:%d"
+ (or (ignore-errors (nth 4 (org-heading-components)))
+ "No heading")
+ block-counter)))
+ (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
+ (assignments-cmd
+ (intern (concat "org-babel-variable-assignments:" src-lang)))
+ (body
+ ;; Run the tangle-body-hook.
+ (let ((body (if (org-babel-noweb-p params :tangle)
+ (org-babel-expand-noweb-references info)
+ (nth 1 info))))
+ (with-temp-buffer
+ (insert
+ ;; Expand body in language specific manner.
+ (cond ((assq :no-expand params) body)
+ ((fboundp expand-cmd) (funcall expand-cmd body params))
+ (t
+ (org-babel-expand-body:generic
+ body params (and (fboundp assignments-cmd)
+ (funcall assignments-cmd params))))))
+ (when (string-match "-r" extra)
+ (goto-char (point-min))
+ (while (re-search-forward
+ (replace-regexp-in-string "%s" ".+" cref-fmt) nil t)
+ (replace-match "")))
+ (run-hooks 'org-babel-tangle-body-hook)
+ (buffer-string))))
+ (comment
+ (when (or (string= "both" (cdr (assq :comments params)))
+ (string= "org" (cdr (assq :comments params))))
+ ;; From the previous heading or code-block end
+ (funcall
+ org-babel-process-comment-text
+ (buffer-substring
+ (max (condition-case nil
+ (save-excursion
+ (org-back-to-heading t) ; Sets match data
+ (match-end 0))
+ (error (point-min)))
+ (save-excursion
+ (if (re-search-backward
+ org-babel-src-block-regexp nil t)
+ (match-end 0)
+ (point-min))))
+ (point)))))
+ (result
+ (list start-line
+ (if org-babel-tangle-use-relative-file-links
+ (file-relative-name file)
+ file)
+ (if (and org-babel-tangle-use-relative-file-links
+ (string-match org-link-types-re link)
+ (string= (match-string 0 link) "file"))
+ (concat "file:"
+ (file-relative-name (match-string 1 link)
+ (file-name-directory
+ (cdr (assq :tangle params)))))
+ link)
+ source-name
+ params
+ (org-unescape-code-in-string
+ (if org-src-preserve-indentation
+ (org-trim body t)
+ (org-trim (org-remove-indentation body))))
+ comment)))
+ (if only-this-block
+ (list (cons src-lang (list result)))
+ result)))
+
+(defun org-babel-tangle-comment-links (&optional info)
+ "Return a list of begin and end link comments for the code block at point."
+ (let ((link-data
+ `(("start-line" . ,(number-to-string
+ (org-babel-where-is-src-block-head)))
+ ("file" . ,(buffer-file-name))
+ ("link" . ,(org-link-escape
+ (progn
+ (call-interactively #'org-store-link)
+ (org-no-properties (car (pop org-stored-links))))))
+ ("source-name" .
+ ,(nth 4 (or info (org-babel-get-src-block-info 'light)))))))
+ (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
+ (org-fill-template org-babel-tangle-comment-format-end link-data))))
+
+;; de-tangling functions
+(defvar org-bracket-link-analytic-regexp)
+(defun org-babel-detangle (&optional source-code-file)
+ "Propagate changes in source file back original to Org file.
+This requires that code blocks were tangled with link comments
+which enable the original code blocks to be found."
+ (interactive)
+ (save-excursion
+ (when source-code-file (find-file source-code-file))
+ (goto-char (point-min))
+ (let ((counter 0) new-body end)
+ (while (re-search-forward org-bracket-link-analytic-regexp nil t)
+ (when (re-search-forward
+ (concat " " (regexp-quote (match-string 5)) " ends here"))
+ (setq end (match-end 0))
+ (forward-line -1)
+ (save-excursion
+ (when (setq new-body (org-babel-tangle-jump-to-org))
+ (org-babel-update-block-body new-body)))
+ (setq counter (+ 1 counter)))
+ (goto-char end))
+ (prog1 counter (message "Detangled %d code blocks" counter)))))
+
+(defun org-babel-tangle-jump-to-org ()
+ "Jump from a tangled code file to the related Org mode file."
+ (interactive)
+ (let ((mid (point))
+ start body-start end
+ target-buffer target-char link path block-name body)
+ (save-window-excursion
+ (save-excursion
+ (while (and (re-search-backward org-bracket-link-analytic-regexp nil t)
+ (not ; ever wider searches until matching block comments
+ (and (setq start (line-beginning-position))
+ (setq body-start (line-beginning-position 2))
+ (setq link (match-string 0))
+ (setq path (match-string 3))
+ (setq block-name (match-string 5))
+ (save-excursion
+ (save-match-data
+ (re-search-forward
+ (concat " " (regexp-quote block-name)
+ " ends here") nil t)
+ (setq end (line-beginning-position))))))))
+ (unless (and start (< start mid) (< mid end))
+ (error "Not in tangled code"))
+ (setq body (buffer-substring body-start end)))
+ (when (string-match "::" path)
+ (setq path (substring path 0 (match-beginning 0))))
+ (find-file (or (car (org-id-find path)) path))
+ (setq target-buffer (current-buffer))
+ ;; Go to the beginning of the relative block in Org file.
+ (org-open-link-from-string link)
+ (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
+ (let ((n (string-to-number (match-string 1 block-name))))
+ (if (org-before-first-heading-p) (goto-char (point-min))
+ (org-back-to-heading t))
+ ;; Do not skip the first block if it begins at point min.
+ (cond ((or (org-at-heading-p)
+ (not (eq (org-element-type (org-element-at-point))
+ 'src-block)))
+ (org-babel-next-src-block n))
+ ((= n 1))
+ (t (org-babel-next-src-block (1- n)))))
+ (org-babel-goto-named-src-block block-name))
+ (goto-char (org-babel-where-is-src-block-head))
+ ;; Preserve location of point within the source code in tangled
+ ;; code file.
+ (forward-line 1)
+ (forward-char (- mid body-start))
+ (setq target-char (point)))
+ (org-src-switch-to-buffer target-buffer t)
+ (goto-char target-char)
+ body))
+
+(provide 'ob-tangle)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ob-tangle.el ends here
diff --git a/lisp/ob.el b/lisp/ob.el
new file mode 100644
index 0000000..736f588
--- /dev/null
+++ b/lisp/ob.el
@@ -0,0 +1,43 @@
+;;; ob.el --- Working with Code Blocks in Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Authors: Eric Schulte
+;; Keywords: literate programming, reproducible research
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Code:
+(require 'org-macs)
+(require 'org-compat)
+(require 'ob-eval)
+(require 'ob-core)
+(require 'ob-comint)
+(require 'ob-exp)
+(require 'ob-keys)
+(require 'ob-table)
+(require 'ob-lob)
+(require 'ob-ref)
+(require 'ob-tangle)
+
+(provide 'ob)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ob.el ends here
diff --git a/lisp/org-agenda.el b/lisp/org-agenda.el
new file mode 100644
index 0000000..f90dd53
--- /dev/null
+++ b/lisp/org-agenda.el
@@ -0,0 +1,10276 @@
+;;; org-agenda.el --- Dynamic task and appointment lists for Org
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code for creating and using the Agenda for Org.
+;;
+;; The functions `org-batch-agenda', `org-batch-agenda-csv', and
+;; `org-batch-store-agenda-views' are implemented as macros to provide
+;; a convenient way for extracting agenda information from the command
+;; line. The Lisp does not evaluate parameters of a macro call; thus
+;; it is not necessary to quote the parameters passed to one of those
+;; functions. E.g. you can write:
+;;
+;; emacs -batch -l ~/.emacs -eval '(org-batch-agenda "a" org-agenda-span 7)'
+;;
+;; To export an agenda spanning 7 days. If `org-batch-agenda' would
+;; have been implemented as a regular function you'd have to quote the
+;; symbol org-agenda-span. Moreover: To use a symbol as parameter
+;; value you would have to double quote the symbol.
+;;
+;; This is a hack, but it works even when running Org byte-compiled.
+;;
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+(require 'org-macs)
+
+(declare-function diary-add-to-list "diary-lib"
+ (date string specifier &optional marker globcolor literal))
+(declare-function calendar-iso-to-absolute "cal-iso" (date))
+(declare-function calendar-astro-date-string "cal-julian" (&optional date))
+(declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
+(declare-function calendar-chinese-date-string "cal-china" (&optional date))
+(declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
+(declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
+(declare-function calendar-french-date-string "cal-french" (&optional date))
+(declare-function calendar-goto-date "cal-move" (date))
+(declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
+(declare-function calendar-islamic-date-string "cal-islam" (&optional date))
+(declare-function calendar-iso-date-string "cal-iso" (&optional date))
+(declare-function calendar-iso-from-absolute "cal-iso" (date))
+(declare-function calendar-julian-date-string "cal-julian" (&optional date))
+(declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
+(declare-function calendar-persian-date-string "cal-persia" (&optional date))
+(declare-function calendar-check-holidays "holidays" (date))
+
+(declare-function org-columns-remove-overlays "org-colview" ())
+(declare-function org-datetree-find-date-create "org-datetree"
+ (date &optional keep-restriction))
+(declare-function org-columns-quit "org-colview" ())
+(declare-function diary-date-display-form "diary-lib" (&optional type))
+(declare-function org-mobile-write-agenda-for-mobile "org-mobile" (file))
+(declare-function org-habit-insert-consistency-graphs
+ "org-habit" (&optional line))
+(declare-function org-is-habit-p "org-habit" (&optional pom))
+(declare-function org-habit-parse-todo "org-habit" (&optional pom))
+(declare-function org-habit-get-priority "org-habit" (habit &optional moment))
+(declare-function org-agenda-columns "org-colview" ())
+(declare-function org-add-archive-files "org-archive" (files))
+(declare-function org-capture "org-capture" (&optional goto keys))
+
+(defvar calendar-mode-map)
+(defvar org-clock-current-task)
+(defvar org-current-tag-alist)
+(defvar org-mobile-force-id-on-agenda-items)
+(defvar org-habit-show-habits)
+(defvar org-habit-show-habits-only-for-today)
+(defvar org-habit-show-all-today)
+
+;; Defined somewhere in this file, but used before definition.
+(defvar org-agenda-buffer-name "*Org Agenda*")
+(defvar org-agenda-overriding-header nil)
+(defvar org-agenda-title-append nil)
+(with-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
+(with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
+(defvar original-date) ; dynamically scoped, calendar.el does scope this
+
+(defvar org-agenda-undo-list nil
+ "List of undoable operations in the agenda since last refresh.")
+(defvar org-agenda-pending-undo-list nil
+ "In a series of undo commands, this is the list of remaining undo items.")
+
+(defcustom org-agenda-confirm-kill 1
+ "When set, remote killing from the agenda buffer needs confirmation.
+When t, a confirmation is always needed. When a number N, confirmation is
+only needed when the text to be killed contains more than N non-white lines."
+ :group 'org-agenda
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (integer :tag "When more than N lines")))
+
+(defcustom org-agenda-compact-blocks nil
+ "Non-nil means make the block agenda more compact.
+This is done globally by leaving out lines like the agenda span
+name and week number or the separator lines."
+ :group 'org-agenda
+ :type 'boolean)
+
+(defcustom org-agenda-block-separator ?=
+ "The separator between blocks in the agenda.
+If this is a string, it will be used as the separator, with a newline added.
+If it is a character, it will be repeated to fill the window width.
+If nil the separator is disabled. In `org-agenda-custom-commands' this
+addresses the separator between the current and the previous block."
+ :group 'org-agenda
+ :type '(choice
+ (const :tag "Disabled" nil)
+ (character)
+ (string)))
+
+(defgroup org-agenda-export nil
+ "Options concerning exporting agenda views in Org mode."
+ :tag "Org Agenda Export"
+ :group 'org-agenda)
+
+(defcustom org-agenda-with-colors t
+ "Non-nil means use colors in agenda views."
+ :group 'org-agenda-export
+ :type 'boolean)
+
+(defcustom org-agenda-exporter-settings nil
+ "Alist of variable/value pairs that should be active during agenda export.
+This is a good place to set options for ps-print and for htmlize.
+Note that the way this is implemented, the values will be evaluated
+before assigned to the variables. So make sure to quote values you do
+*not* want evaluated, for example
+
+ (setq org-agenda-exporter-settings
+ \\='((ps-print-color-p \\='black-white)))"
+ :group 'org-agenda-export
+ :type '(repeat
+ (list
+ (variable)
+ (sexp :tag "Value"))))
+
+(defcustom org-agenda-before-write-hook '(org-agenda-add-entry-text)
+ "Hook run in a temporary buffer before writing the agenda to an export file.
+A useful function for this hook is `org-agenda-add-entry-text'."
+ :group 'org-agenda-export
+ :type 'hook
+ :options '(org-agenda-add-entry-text))
+
+(defcustom org-agenda-add-entry-text-maxlines 0
+ "Maximum number of entry text lines to be added to agenda.
+This is only relevant when `org-agenda-add-entry-text' is part of
+`org-agenda-before-write-hook', which is the default.
+When this is 0, nothing will happen. When it is greater than 0, it
+specifies the maximum number of lines that will be added for each entry
+that is listed in the agenda view.
+
+Note that this variable is not used during display, only when exporting
+the agenda. For agenda display, see the variables `org-agenda-entry-text-mode'
+and `org-agenda-entry-text-maxlines'."
+ :group 'org-agenda
+ :type 'integer)
+
+(defcustom org-agenda-add-entry-text-descriptive-links t
+ "Non-nil means export org-links as descriptive links in agenda added text.
+This variable applies to the text added to the agenda when
+`org-agenda-add-entry-text-maxlines' is larger than 0.
+When this variable nil, the URL will (also) be shown."
+ :group 'org-agenda
+ :type 'boolean)
+
+(defcustom org-agenda-export-html-style nil
+ "The style specification for exported HTML Agenda files.
+If this variable contains a string, it will replace the default <style>
+section as produced by `htmlize'.
+Since there are different ways of setting style information, this variable
+needs to contain the full HTML structure to provide a style, including the
+surrounding HTML tags. The style specifications should include definitions
+the fonts used by the agenda, here is an example:
+
+ <style type=\"text/css\">
+ p { font-weight: normal; color: gray; }
+ .org-agenda-structure {
+ font-size: 110%;
+ color: #003399;
+ font-weight: 600;
+ }
+ .org-todo {
+ color: #cc6666;
+ font-weight: bold;
+ }
+ .org-agenda-done {
+ color: #339933;
+ }
+ .org-done {
+ color: #339933;
+ }
+ .title { text-align: center; }
+ .todo, .deadline { color: red; }
+ .done { color: green; }
+ </style>
+
+or, if you want to keep the style in a file,
+
+ <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
+
+As the value of this option simply gets inserted into the HTML <head> header,
+you can \"misuse\" it to also add other text to the header."
+ :group 'org-agenda-export
+ :group 'org-export-html
+ :type '(choice
+ (const nil)
+ (string)))
+
+(defcustom org-agenda-persistent-filter nil
+ "When set, keep filters from one agenda view to the next."
+ :group 'org-agenda
+ :type 'boolean)
+
+(defgroup org-agenda-custom-commands nil
+ "Options concerning agenda views in Org mode."
+ :tag "Org Agenda Custom Commands"
+ :group 'org-agenda)
+
+(defconst org-sorting-choice
+ '(choice
+ (const time-up) (const time-down)
+ (const timestamp-up) (const timestamp-down)
+ (const scheduled-up) (const scheduled-down)
+ (const deadline-up) (const deadline-down)
+ (const ts-up) (const ts-down)
+ (const tsia-up) (const tsia-down)
+ (const category-keep) (const category-up) (const category-down)
+ (const tag-down) (const tag-up)
+ (const priority-up) (const priority-down)
+ (const todo-state-up) (const todo-state-down)
+ (const effort-up) (const effort-down)
+ (const habit-up) (const habit-down)
+ (const alpha-up) (const alpha-down)
+ (const user-defined-up) (const user-defined-down))
+ "Sorting choices.")
+
+;; Keep custom values for `org-agenda-filter-preset' compatible with
+;; the new variable `org-agenda-tag-filter-preset'.
+(defvaralias 'org-agenda-filter-preset 'org-agenda-tag-filter-preset)
+(defvaralias 'org-agenda-filter 'org-agenda-tag-filter)
+
+(defvar org-agenda-entry-types '(:deadline :scheduled :timestamp :sexp)
+ "List of types searched for when creating the daily/weekly agenda.
+This variable is a list of symbols that controls the types of
+items that appear in the daily/weekly agenda. Allowed symbols in this
+list are are
+
+ :timestamp List items containing a date stamp or date range matching
+ the selected date. This includes sexp entries in angular
+ brackets.
+
+ :sexp List entries resulting from plain diary-like sexps.
+
+ :deadline List deadline due on that date. When the date is today,
+ also list any deadlines past due, or due within
+ `org-deadline-warning-days'. `:deadline' must appear before
+ `:scheduled' if the setting of
+ `org-agenda-skip-scheduled-if-deadline-is-shown' is to have
+ any effect.
+
+ :deadline* Same as above, but only include the deadline if it has an
+ hour specification as [h]h:mm.
+
+ :scheduled List all items which are scheduled for the given date.
+ The diary for *today* also contains items which were
+ scheduled earlier and are not yet marked DONE.
+
+ :scheduled* Same as above, but only include the scheduled item if it
+ has an hour specification as [h]h:mm.
+
+By default, all four non-starred types are turned on.
+
+When :scheduled* or :deadline* are included, :schedule or :deadline
+will be ignored.
+
+Never set this variable globally using `setq', because then it
+will apply to all future agenda commands. Instead, bind it with
+`let' to scope it dynamically into the agenda-constructing
+command. A good way to set it is through options in
+`org-agenda-custom-commands'. For a more flexible (though
+somewhat less efficient) way of determining what is included in
+the daily/weekly agenda, see `org-agenda-skip-function'.")
+
+(defconst org-agenda-custom-commands-local-options
+ `(repeat :tag "Local settings for this command. Remember to quote values"
+ (choice :tag "Setting"
+ (list :tag "Heading for this block"
+ (const org-agenda-overriding-header)
+ (string :tag "Headline"))
+ (list :tag "Files to be searched"
+ (const org-agenda-files)
+ (list
+ (const :format "" quote)
+ (repeat (file))))
+ (list :tag "Sorting strategy"
+ (const org-agenda-sorting-strategy)
+ (list
+ (const :format "" quote)
+ (repeat
+ ,org-sorting-choice)))
+ (list :tag "Prefix format"
+ (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
+ (string))
+ (list :tag "Number of days in agenda"
+ (const org-agenda-span)
+ (choice (const :tag "Day" day)
+ (const :tag "Week" week)
+ (const :tag "Fortnight" fortnight)
+ (const :tag "Month" month)
+ (const :tag "Year" year)
+ (integer :tag "Custom")))
+ (list :tag "Fixed starting date"
+ (const org-agenda-start-day)
+ (string :value "2007-11-01"))
+ (list :tag "Start on day of week"
+ (const org-agenda-start-on-weekday)
+ (choice :value 1
+ (const :tag "Today" nil)
+ (integer :tag "Weekday No.")))
+ (list :tag "Include data from diary"
+ (const org-agenda-include-diary)
+ (boolean))
+ (list :tag "Deadline Warning days"
+ (const org-deadline-warning-days)
+ (integer :value 1))
+ (list :tag "Category filter preset"
+ (const org-agenda-category-filter-preset)
+ (list
+ (const :format "" quote)
+ (repeat
+ (string :tag "+category or -category"))))
+ (list :tag "Tags filter preset"
+ (const org-agenda-tag-filter-preset)
+ (list
+ (const :format "" quote)
+ (repeat
+ (string :tag "+tag or -tag"))))
+ (list :tag "Effort filter preset"
+ (const org-agenda-effort-filter-preset)
+ (list
+ (const :format "" quote)
+ (repeat
+ (string :tag "+=10 or -=10 or +<10 or ->10"))))
+ (list :tag "Regexp filter preset"
+ (const org-agenda-regexp-filter-preset)
+ (list
+ (const :format "" quote)
+ (repeat
+ (string :tag "+regexp or -regexp"))))
+ (list :tag "Set daily/weekly entry types"
+ (const org-agenda-entry-types)
+ (list
+ (const :format "" quote)
+ (set :greedy t :value ,org-agenda-entry-types
+ (const :deadline)
+ (const :scheduled)
+ (const :deadline*)
+ (const :scheduled*)
+ (const :timestamp)
+ (const :sexp))))
+ (list :tag "Standard skipping condition"
+ :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
+ (const org-agenda-skip-function)
+ (list
+ (const :format "" quote)
+ (list
+ (choice
+ :tag "Skipping range"
+ (const :tag "Skip entry" org-agenda-skip-entry-if)
+ (const :tag "Skip subtree" org-agenda-skip-subtree-if))
+ (repeat :inline t :tag "Conditions for skipping"
+ (choice
+ :tag "Condition type"
+ (list :tag "Regexp matches" :inline t
+ (const :format "" 'regexp)
+ (regexp))
+ (list :tag "Regexp does not match" :inline t
+ (const :format "" 'notregexp)
+ (regexp))
+ (list :tag "TODO state is" :inline t
+ (const 'todo)
+ (choice
+ (const :tag "Any not-done state" 'todo)
+ (const :tag "Any done state" 'done)
+ (const :tag "Any state" 'any)
+ (list :tag "Keyword list"
+ (const :format "" quote)
+ (repeat (string :tag "Keyword")))))
+ (list :tag "TODO state is not" :inline t
+ (const 'nottodo)
+ (choice
+ (const :tag "Any not-done state" 'todo)
+ (const :tag "Any done state" 'done)
+ (const :tag "Any state" 'any)
+ (list :tag "Keyword list"
+ (const :format "" quote)
+ (repeat (string :tag "Keyword")))))
+ (const :tag "scheduled" 'scheduled)
+ (const :tag "not scheduled" 'notscheduled)
+ (const :tag "deadline" 'deadline)
+ (const :tag "no deadline" 'notdeadline)
+ (const :tag "timestamp" 'timestamp)
+ (const :tag "no timestamp" 'nottimestamp))))))
+ (list :tag "Non-standard skipping condition"
+ :value (org-agenda-skip-function)
+ (const org-agenda-skip-function)
+ (sexp :tag "Function or form (quoted!)"))
+ (list :tag "Any variable"
+ (variable :tag "Variable")
+ (sexp :tag "Value (sexp)"))))
+ "Selection of examples for agenda command settings.
+This will be spliced into the custom type of
+`org-agenda-custom-commands'.")
+
+
+(defcustom org-agenda-custom-commands
+ '(("n" "Agenda and all TODOs" ((agenda "") (alltodo ""))))
+ "Custom commands for the agenda.
+\\<org-mode-map>
+These commands will be offered on the splash screen displayed by the
+agenda dispatcher `\\[org-agenda]'. Each entry is a list like this:
+
+ (key desc type match settings files)
+
+key The key (one or more characters as a string) to be associated
+ with the command.
+desc A description of the command, when omitted or nil, a default
+ description is built using MATCH.
+type The command type, any of the following symbols:
+ agenda The daily/weekly agenda.
+ todo Entries with a specific TODO keyword, in all agenda files.
+ search Entries containing search words entry or headline.
+ tags Tags/Property/TODO match in all agenda files.
+ tags-todo Tags/P/T match in all agenda files, TODO entries only.
+ todo-tree Sparse tree of specific TODO keyword in *current* file.
+ tags-tree Sparse tree with all tags matches in *current* file.
+ occur-tree Occur sparse tree for *current* file.
+ ... A user-defined function.
+match What to search for:
+ - a single keyword for TODO keyword searches
+ - a tags match expression for tags searches
+ - a word search expression for text searches.
+ - a regular expression for occur searches
+ For all other commands, this should be the empty string.
+settings A list of option settings, similar to that in a let form, so like
+ this: ((opt1 val1) (opt2 val2) ...). The values will be
+ evaluated at the moment of execution, so quote them when needed.
+files A list of files to write the produced agenda buffer to with
+ the command `org-store-agenda-views'.
+ If a file name ends in \".html\", an HTML version of the buffer
+ is written out. If it ends in \".ps\", a postscript version is
+ produced. Otherwise, only the plain text is written to the file.
+
+You can also define a set of commands, to create a composite agenda buffer.
+In this case, an entry looks like this:
+
+ (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
+
+where
+
+desc A description string to be displayed in the dispatcher menu.
+cmd An agenda command, similar to the above. However, tree commands
+ are not allowed, but instead you can get agenda and global todo list.
+ So valid commands for a set are:
+ (agenda \"\" settings)
+ (alltodo \"\" settings)
+ (stuck \"\" settings)
+ (todo \"match\" settings files)
+ (search \"match\" settings files)
+ (tags \"match\" settings files)
+ (tags-todo \"match\" settings files)
+
+Each command can carry a list of options, and another set of options can be
+given for the whole set of commands. Individual command options take
+precedence over the general options.
+
+When using several characters as key to a command, the first characters
+are prefix commands. For the dispatcher to display useful information, you
+should provide a description for the prefix, like
+
+ (setq org-agenda-custom-commands
+ \\='((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
+ (\"hl\" tags \"+HOME+Lisa\")
+ (\"hp\" tags \"+HOME+Peter\")
+ (\"hk\" tags \"+HOME+Kim\")))"
+ :group 'org-agenda-custom-commands
+ :type `(repeat
+ (choice :value ("x" "Describe command here" tags "" nil)
+ (list :tag "Single command"
+ (string :tag "Access Key(s) ")
+ (option (string :tag "Description"))
+ (choice
+ (const :tag "Agenda" agenda)
+ (const :tag "TODO list" alltodo)
+ (const :tag "Search words" search)
+ (const :tag "Stuck projects" stuck)
+ (const :tag "Tags/Property match (all agenda files)" tags)
+ (const :tag "Tags/Property match of TODO entries (all agenda files)" tags-todo)
+ (const :tag "TODO keyword search (all agenda files)" todo)
+ (const :tag "Tags sparse tree (current buffer)" tags-tree)
+ (const :tag "TODO keyword tree (current buffer)" todo-tree)
+ (const :tag "Occur tree (current buffer)" occur-tree)
+ (sexp :tag "Other, user-defined function"))
+ (string :tag "Match (only for some commands)")
+ ,org-agenda-custom-commands-local-options
+ (option (repeat :tag "Export" (file :tag "Export to"))))
+ (list :tag "Command series, all agenda files"
+ (string :tag "Access Key(s)")
+ (string :tag "Description ")
+ (repeat :tag "Component"
+ (choice
+ (list :tag "Agenda"
+ (const :format "" agenda)
+ (const :tag "" :format "" "")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "TODO list (all keywords)"
+ (const :format "" alltodo)
+ (const :tag "" :format "" "")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "Search words"
+ (const :format "" search)
+ (string :tag "Match")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "Stuck projects"
+ (const :format "" stuck)
+ (const :tag "" :format "" "")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "Tags search"
+ (const :format "" tags)
+ (string :tag "Match")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "Tags search, TODO entries only"
+ (const :format "" tags-todo)
+ (string :tag "Match")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "TODO keyword search"
+ (const :format "" todo)
+ (string :tag "Match")
+ ,org-agenda-custom-commands-local-options)
+ (list :tag "Other, user-defined function"
+ (symbol :tag "function")
+ (string :tag "Match")
+ ,org-agenda-custom-commands-local-options)))
+
+ (repeat :tag "Settings for entire command set"
+ (list (variable :tag "Any variable")
+ (sexp :tag "Value")))
+ (option (repeat :tag "Export" (file :tag "Export to"))))
+ (cons :tag "Prefix key documentation"
+ (string :tag "Access Key(s)")
+ (string :tag "Description ")))))
+
+(defcustom org-agenda-query-register ?o
+ "The register holding the current query string.
+The purpose of this is that if you construct a query string interactively,
+you can then use it to define a custom command."
+ :group 'org-agenda-custom-commands
+ :type 'character)
+
+(defcustom org-stuck-projects
+ '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
+ "How to identify stuck projects.
+This is a list of four items:
+1. A tags/todo/property matcher string that is used to identify a project.
+ See the manual for a description of tag and property searches.
+ The entire tree below a headline matched by this is considered one project.
+2. A list of TODO keywords identifying non-stuck projects.
+ If the project subtree contains any headline with one of these todo
+ keywords, the project is considered to be not stuck. If you specify
+ \"*\" as a keyword, any TODO keyword will mark the project unstuck.
+3. A list of tags identifying non-stuck projects.
+ If the project subtree contains any headline with one of these tags,
+ the project is considered to be not stuck. If you specify \"*\" as
+ a tag, any tag will mark the project unstuck. Note that this is about
+ the explicit presence of a tag somewhere in the subtree, inherited
+ tags do not count here. If inherited tags make a project not stuck,
+ use \"-TAG\" in the tags part of the matcher under (1.) above.
+4. An arbitrary regular expression matching non-stuck projects.
+
+If the project turns out to be not stuck, search continues also in the
+subtree to see if any of the subtasks have project status.
+
+See also the variable `org-tags-match-list-sublevels' which applies
+to projects matched by this search as well.
+
+After defining this variable, you may use `\\[org-agenda-list-stuck-projects]'
+\(bound to `C-c a #') to produce the list."
+ :group 'org-agenda-custom-commands
+ :type '(list
+ (string :tag "Tags/TODO match to identify a project")
+ (repeat :tag "Projects are *not* stuck if they have an entry with \
+TODO keyword any of" (string))
+ (repeat :tag "Projects are *not* stuck if they have an entry with \
+TAG being any of" (string))
+ (regexp :tag "Projects are *not* stuck if this regexp matches inside \
+the subtree")))
+
+(defgroup org-agenda-skip nil
+ "Options concerning skipping parts of agenda files."
+ :tag "Org Agenda Skip"
+ :group 'org-agenda)
+
+(defcustom org-agenda-skip-function-global nil
+ "Function to be called at each match during agenda construction.
+If this function returns nil, the current match should not be skipped.
+If the function decided to skip an agenda match, is must return the
+buffer position from which the search should be continued.
+This may also be a Lisp form, which will be evaluated.
+
+This variable will be applied to every agenda match, including
+tags/property searches and TODO lists. So try to make the test function
+do its checking as efficiently as possible. To implement a skipping
+condition just for specific agenda commands, use the variable
+`org-agenda-skip-function' which can be set in the options section
+of custom agenda commands."
+ :group 'org-agenda-skip
+ :type 'sexp)
+
+(defgroup org-agenda-daily/weekly nil
+ "Options concerning the daily/weekly agenda."
+ :tag "Org Agenda Daily/Weekly"
+ :group 'org-agenda)
+(defgroup org-agenda-todo-list nil
+ "Options concerning the global todo list agenda view."
+ :tag "Org Agenda Todo List"
+ :group 'org-agenda)
+(defgroup org-agenda-match-view nil
+ "Options concerning the general tags/property/todo match agenda view."
+ :tag "Org Agenda Match View"
+ :group 'org-agenda)
+(defgroup org-agenda-search-view nil
+ "Options concerning the search agenda view."
+ :tag "Org Agenda Search View"
+ :group 'org-agenda)
+
+(defvar org-agenda-archives-mode nil
+ "Non-nil means the agenda will include archived items.
+If this is the symbol `trees', trees in the selected agenda scope
+that are marked with the ARCHIVE tag will be included anyway. When this is
+t, also all archive files associated with the current selection of agenda
+files will be included.")
+
+(defcustom org-agenda-restriction-lock-highlight-subtree t
+ "Non-nil means highlight the whole subtree when restriction is active.
+Otherwise only highlight the headline. Highlighting the whole subtree is
+useful to ensure no edits happen beyond the restricted region."
+ :group 'org-agenda
+ :type 'boolean)
+
+(defcustom org-agenda-skip-comment-trees t
+ "Non-nil means skip trees that start with the COMMENT keyword.
+When nil, these trees are also scanned by agenda commands."
+ :group 'org-agenda-skip
+ :type 'boolean)
+
+(defcustom org-agenda-todo-list-sublevels t
+ "Non-nil means check also the sublevels of a TODO entry for TODO entries.
+When nil, the sublevels of a TODO entry are not checked, resulting in
+potentially much shorter TODO lists."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :type 'boolean)
+
+(defcustom org-agenda-todo-ignore-with-date nil
+ "Non-nil means don't show entries with a date in the global todo list.
+You can use this if you prefer to mark mere appointments with a TODO keyword,
+but don't want them to show up in the TODO list.
+When this is set, it also covers deadlines and scheduled items, the settings
+of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
+will be ignored.
+See also the variable `org-agenda-tags-todo-honor-ignore-options'."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :type 'boolean)
+
+(defcustom org-agenda-todo-ignore-timestamp nil
+ "Non-nil means don't show entries with a timestamp.
+This applies when creating the global todo list.
+Valid values are:
+
+past Don't show entries for today or in the past.
+
+future Don't show entries with a timestamp in the future.
+ The idea behind this is that if it has a future
+ timestamp, you don't want to think about it until the
+ date.
+
+all Don't show any entries with a timestamp in the global todo list.
+ The idea behind this is that by setting a timestamp, you
+ have already \"taken care\" of this item.
+
+This variable can also have an integer as a value. If positive (N),
+todos with a timestamp N or more days in the future will be ignored. If
+negative (-N), todos with a timestamp N or more days in the past will be
+ignored. If 0, todos with a timestamp either today or in the future will
+be ignored. For example, a value of -1 will exclude todos with a
+timestamp in the past (yesterday or earlier), while a value of 7 will
+exclude todos with a timestamp a week or more in the future.
+
+See also `org-agenda-todo-ignore-with-date'.
+See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want
+to make his option also apply to the tags-todo list."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :version "24.1"
+ :type '(choice
+ (const :tag "Ignore future timestamp todos" future)
+ (const :tag "Ignore past or present timestamp todos" past)
+ (const :tag "Ignore all timestamp todos" all)
+ (const :tag "Show timestamp todos" nil)
+ (integer :tag "Ignore if N or more days in past(-) or future(+).")))
+
+(defcustom org-agenda-todo-ignore-scheduled nil
+ "Non-nil means, ignore some scheduled TODO items when making TODO list.
+This applies when creating the global todo list.
+Valid values are:
+
+past Don't show entries scheduled today or in the past.
+
+future Don't show entries scheduled in the future.
+ The idea behind this is that by scheduling it, you don't want to
+ think about it until the scheduled date.
+
+all Don't show any scheduled entries in the global todo list.
+ The idea behind this is that by scheduling it, you have already
+ \"taken care\" of this item.
+
+t Same as `all', for backward compatibility.
+
+This variable can also have an integer as a value. See
+`org-agenda-todo-ignore-timestamp' for more details.
+
+See also `org-agenda-todo-ignore-with-date'.
+See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want
+to make his option also apply to the tags-todo list."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :type '(choice
+ (const :tag "Ignore future-scheduled todos" future)
+ (const :tag "Ignore past- or present-scheduled todos" past)
+ (const :tag "Ignore all scheduled todos" all)
+ (const :tag "Ignore all scheduled todos (compatibility)" t)
+ (const :tag "Show scheduled todos" nil)
+ (integer :tag "Ignore if N or more days in past(-) or future(+).")))
+
+(defcustom org-agenda-todo-ignore-deadlines nil
+ "Non-nil means ignore some deadline TODO items when making TODO list.
+
+There are different motivations for using different values, please think
+carefully when configuring this variable.
+
+This applies when creating the global TODO list.
+
+Valid values are:
+
+near Don't show near deadline entries. A deadline is near when it is
+ closer than `org-deadline-warning-days' days. The idea behind this
+ is that such items will appear in the agenda anyway.
+
+far Don't show TODO entries where a deadline has been defined, but
+ is not going to happen anytime soon. This is useful if you want to use
+ the TODO list to figure out what to do now.
+
+past Don't show entries with a deadline timestamp for today or in the past.
+
+future Don't show entries with a deadline timestamp in the future, not even
+ when they become `near' ones. Use it with caution.
+
+all Ignore all TODO entries that do have a deadline.
+
+t Same as `near', for backward compatibility.
+
+This variable can also have an integer as a value. See
+`org-agenda-todo-ignore-timestamp' for more details.
+
+See also `org-agenda-todo-ignore-with-date'.
+See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want
+to make his option also apply to the tags-todo list."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :type '(choice
+ (const :tag "Ignore near deadlines" near)
+ (const :tag "Ignore near deadlines (compatibility)" t)
+ (const :tag "Ignore far deadlines" far)
+ (const :tag "Ignore all TODOs with a deadlines" all)
+ (const :tag "Show all TODOs, even if they have a deadline" nil)
+ (integer :tag "Ignore if N or more days in past(-) or future(+).")))
+
+(defcustom org-agenda-todo-ignore-time-comparison-use-seconds nil
+ "Time unit to use when possibly ignoring an agenda item.
+
+See the docstring of various `org-agenda-todo-ignore-*' options.
+The default is to compare time stamps using days. An item is thus
+considered to be in the future if it is at least one day after today.
+Non-nil means to compare time stamps using seconds. An item is then
+considered future if it has a time value later than current time."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Compare time with days" nil)
+ (const :tag "Compare time with seconds" t)))
+
+(defcustom org-agenda-tags-todo-honor-ignore-options nil
+ "Non-nil means honor todo-list ignores options also in tags-todo search.
+The variables
+ `org-agenda-todo-ignore-with-date',
+ `org-agenda-todo-ignore-timestamp',
+ `org-agenda-todo-ignore-scheduled',
+ `org-agenda-todo-ignore-deadlines'
+make the global TODO list skip entries that have time stamps of certain
+kinds. If this option is set, the same options will also apply for the
+tags-todo search, which is the general tags/property matcher
+restricted to unfinished TODO entries only."
+ :group 'org-agenda-skip
+ :group 'org-agenda-todo-list
+ :group 'org-agenda-match-view
+ :type 'boolean)
+
+(defcustom org-agenda-skip-scheduled-if-done nil
+ "Non-nil means don't show scheduled items in agenda when they are done.
+This is relevant for the daily/weekly agenda, not for the TODO list. It
+applies only to the actual date of the scheduling. Warnings about an item
+with a past scheduling dates are always turned off when the item is DONE."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-skip-scheduled-if-deadline-is-shown nil
+ "Non-nil means skip scheduling line if same entry shows because of deadline.
+
+In the agenda of today, an entry can show up multiple times
+because it is both scheduled and has a nearby deadline, and maybe
+a plain time stamp as well.
+
+When this variable is nil, the entry will be shown several times.
+
+When set to t, then only the deadline is shown and the fact that
+the entry is scheduled today or was scheduled previously is not
+shown.
+
+When set to the symbol `not-today', skip scheduled previously,
+but not scheduled today.
+
+When set to the symbol `repeated-after-deadline', skip scheduled
+items if they are repeated beyond the current deadline."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (const :tag "Not when scheduled today" not-today)
+ (const :tag "When repeated past deadline" repeated-after-deadline)))
+
+(defcustom org-agenda-skip-timestamp-if-deadline-is-shown nil
+ "Non-nil means skip timestamp line if same entry shows because of deadline.
+In the agenda of today, an entry can show up multiple times
+because it has both a plain timestamp and has a nearby deadline.
+When this variable is t, then only the deadline is shown and the
+fact that the entry has a timestamp for or including today is not
+shown. When this variable is nil, the entry will be shown
+several times."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :version "24.1"
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Always" t)))
+
+(defcustom org-agenda-skip-deadline-if-done nil
+ "Non-nil means don't show deadlines when the corresponding item is done.
+When nil, the deadline is still shown and should give you a happy feeling.
+This is relevant for the daily/weekly agenda. It applies only to the
+actual date of the deadline. Warnings about approaching and past-due
+deadlines are always turned off when the item is DONE."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-skip-deadline-prewarning-if-scheduled nil
+ "Non-nil means skip deadline prewarning when entry is also scheduled.
+This will apply on all days where a prewarning for the deadline would
+be shown, but not at the day when the entry is actually due. On that day,
+the deadline will be shown anyway.
+This variable may be set to nil, t, the symbol `pre-scheduled',
+or a number which will then give the number of days before the actual
+deadline when the prewarnings should resume. The symbol `pre-scheduled'
+eliminates the deadline prewarning only prior to the scheduled date.
+This can be used in a workflow where the first showing of the deadline will
+trigger you to schedule it, and then you don't want to be reminded of it
+because you will take care of it on the day when scheduled."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :version "24.1"
+ :type '(choice
+ (const :tag "Always show prewarning" nil)
+ (const :tag "Remove prewarning prior to scheduled date" pre-scheduled)
+ (const :tag "Remove prewarning if entry is scheduled" t)
+ (integer :tag "Restart prewarning N days before deadline")))
+
+(defcustom org-agenda-skip-scheduled-delay-if-deadline nil
+ "Non-nil means skip scheduled delay when entry also has a deadline.
+This variable may be set to nil, t, the symbol `post-deadline',
+or a number which will then give the number of days after the actual
+scheduled date when the delay should expire. The symbol `post-deadline'
+eliminates the schedule delay when the date is posterior to the deadline."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Always honor delay" nil)
+ (const :tag "Ignore delay if posterior to the deadline" post-deadline)
+ (const :tag "Ignore delay if entry has a deadline" t)
+ (integer :tag "Honor delay up until N days after the scheduled date")))
+
+(defcustom org-agenda-skip-additional-timestamps-same-entry nil
+ "When nil, multiple same-day timestamps in entry make multiple agenda lines.
+When non-nil, after the search for timestamps has matched once in an
+entry, the rest of the entry will not be searched."
+ :group 'org-agenda-skip
+ :type 'boolean)
+
+(defcustom org-agenda-skip-timestamp-if-done nil
+ "Non-nil means don't select item by timestamp or -range if it is DONE."
+ :group 'org-agenda-skip
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-dim-blocked-tasks t
+ "Non-nil means dim blocked tasks in the agenda display.
+This causes some overhead during agenda construction, but if you
+have turned on `org-enforce-todo-dependencies',
+`org-enforce-todo-checkbox-dependencies', or any other blocking
+mechanism, this will create useful feedback in the agenda.
+
+Instead of t, this variable can also have the value `invisible'.
+Then blocked tasks will be invisible and only become visible when
+they become unblocked. An exemption to this behavior is when a task is
+blocked because of unchecked checkboxes below it. Since checkboxes do
+not show up in the agenda views, making this task invisible you remove any
+trace from agenda views that there is something to do. Therefore, a task
+that is blocked because of checkboxes will never be made invisible, it
+will only be dimmed."
+ :group 'org-agenda-daily/weekly
+ :group 'org-agenda-todo-list
+ :version "24.3"
+ :type '(choice
+ (const :tag "Do not dim" nil)
+ (const :tag "Dim to a gray face" t)
+ (const :tag "Make invisible" invisible)))
+
+(defcustom org-timeline-show-empty-dates 3
+ "Non-nil means `org-timeline' also shows dates without an entry.
+When nil, only the days which actually have entries are shown.
+When t, all days between the first and the last date are shown.
+When an integer, show also empty dates, but if there is a gap of more than
+N days, just insert a special line indicating the size of the gap."
+ :group 'org-agenda-skip
+ :type '(choice
+ (const :tag "None" nil)
+ (const :tag "All" t)
+ (integer :tag "at most")))
+
+(defgroup org-agenda-startup nil
+ "Options concerning initial settings in the Agenda in Org Mode."
+ :tag "Org Agenda Startup"
+ :group 'org-agenda)
+
+(defcustom org-agenda-menu-show-matcher t
+ "Non-nil means show the match string in the agenda dispatcher menu.
+When nil, the matcher string is not shown, but is put into the help-echo
+property so than moving the mouse over the command shows it.
+Setting it to nil is good if matcher strings are very long and/or if
+you want to use two-columns display (see `org-agenda-menu-two-columns')."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-menu-two-columns nil
+ "Non-nil means, use two columns to show custom commands in the dispatcher.
+If you use this, you probably want to set `org-agenda-menu-show-matcher'
+to nil."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-finalize-hook nil
+ "Hook run just before displaying an agenda buffer.
+The buffer is still writable when the hook is called.
+
+You can modify some of the buffer substrings but you should be
+extra careful not to modify the text properties of the agenda
+headlines as the agenda display heavily relies on them."
+ :group 'org-agenda-startup
+ :type 'hook)
+
+(defcustom org-agenda-mouse-1-follows-link nil
+ "Non-nil means mouse-1 on a link will follow the link in the agenda.
+A longer mouse click will still set point. Needs to be set
+before org.el is loaded."
+ :group 'org-agenda-startup
+ :type 'boolean)
+
+(defcustom org-agenda-start-with-follow-mode nil
+ "The initial value of follow mode in a newly created agenda window."
+ :group 'org-agenda-startup
+ :type 'boolean)
+
+(defcustom org-agenda-follow-indirect nil
+ "Non-nil means `org-agenda-follow-mode' displays only the
+current item's tree, in an indirect buffer."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-show-outline-path t
+ "Non-nil means show outline path in echo area after line motion."
+ :group 'org-agenda-startup
+ :type 'boolean)
+
+(defcustom org-agenda-start-with-entry-text-mode nil
+ "The initial value of entry-text-mode in a newly created agenda window."
+ :group 'org-agenda-startup
+ :type 'boolean)
+
+(defcustom org-agenda-entry-text-maxlines 5
+ "Number of text lines to be added when `E' is pressed in the agenda.
+
+Note that this variable only used during agenda display. To add entry text
+when exporting the agenda, configure the variable
+`org-agenda-add-entry-text-maxlines'."
+ :group 'org-agenda
+ :type 'integer)
+
+(defcustom org-agenda-entry-text-exclude-regexps nil
+ "List of regular expressions to clean up entry text.
+The complete matches of all regular expressions in this list will be
+removed from entry text before it is shown in the agenda."
+ :group 'org-agenda
+ :type '(repeat (regexp)))
+
+(defcustom org-agenda-entry-text-leaders " > "
+ "Text prepended to the entry text in agenda buffers."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-agenda
+ :type 'string)
+
+(defvar org-agenda-entry-text-cleanup-hook nil
+ "Hook that is run after basic cleanup of entry text to be shown in agenda.
+This cleanup is done in a temporary buffer, so the function may inspect and
+change the entire buffer.
+Some default stuff like drawers and scheduling/deadline dates will already
+have been removed when this is called, as will any matches for regular
+expressions listed in `org-agenda-entry-text-exclude-regexps'.")
+
+(defvar org-agenda-include-inactive-timestamps nil
+ "Non-nil means include inactive time stamps in agenda and timeline.
+Dynamically scoped.")
+
+(defgroup org-agenda-windows nil
+ "Options concerning the windows used by the Agenda in Org Mode."
+ :tag "Org Agenda Windows"
+ :group 'org-agenda)
+
+(defcustom org-agenda-window-setup 'reorganize-frame
+ "How the agenda buffer should be displayed.
+Possible values for this option are:
+
+current-window Show agenda in the current window, keeping all other windows.
+other-window Use `switch-to-buffer-other-window' to display agenda.
+only-window Show agenda, deleting all other windows.
+reorganize-frame Show only two windows on the current frame, the current
+ window and the agenda.
+other-frame Use `switch-to-buffer-other-frame' to display agenda.
+ Also, when exiting the agenda, kill that frame.
+See also the variable `org-agenda-restore-windows-after-quit'."
+ :group 'org-agenda-windows
+ :type '(choice
+ (const current-window)
+ (const other-frame)
+ (const other-window)
+ (const only-window)
+ (const reorganize-frame)))
+
+(defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
+ "The min and max height of the agenda window as a fraction of frame height.
+The value of the variable is a cons cell with two numbers between 0 and 1.
+It only matters if `org-agenda-window-setup' is `reorganize-frame'."
+ :group 'org-agenda-windows
+ :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
+
+(defcustom org-agenda-restore-windows-after-quit nil
+ "Non-nil means restore window configuration upon exiting agenda.
+Before the window configuration is changed for displaying the agenda,
+the current status is recorded. When the agenda is exited with
+`q' or `x' and this option is set, the old state is restored. If
+`org-agenda-window-setup' is `other-frame', the value of this
+option will be ignored."
+ :group 'org-agenda-windows
+ :type 'boolean)
+
+(defcustom org-agenda-span 'week
+ "Number of days to include in overview display.
+Can be day, week, month, year, or any number of days.
+Custom commands can set this variable in the options section."
+ :group 'org-agenda-daily/weekly
+ :type '(choice (const :tag "Day" day)
+ (const :tag "Week" week)
+ (const :tag "Fortnight" fortnight)
+ (const :tag "Month" month)
+ (const :tag "Year" year)
+ (integer :tag "Custom")))
+
+(defcustom org-agenda-start-on-weekday 1
+ "Non-nil means start the overview always on the specified weekday.
+0 denotes Sunday, 1 denotes Monday, etc.
+When nil, always start on the current day.
+Custom commands can set this variable in the options section."
+ :group 'org-agenda-daily/weekly
+ :type '(choice (const :tag "Today" nil)
+ (integer :tag "Weekday No.")))
+
+(defcustom org-agenda-show-all-dates t
+ "Non-nil means `org-agenda' shows every day in the selected range.
+When nil, only the days which actually have entries are shown."
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-format-date 'org-agenda-format-date-aligned
+ "Format string for displaying dates in the agenda.
+Used by the daily/weekly agenda and by the timeline. This should be
+a format string understood by `format-time-string', or a function returning
+the formatted date as a string. The function must take a single argument,
+a calendar-style date list like (month day year)."
+ :group 'org-agenda-daily/weekly
+ :type '(choice
+ (string :tag "Format string")
+ (function :tag "Function")))
+
+(defun org-agenda-format-date-aligned (date)
+ "Format a DATE string for display in the daily/weekly agenda, or timeline.
+This function makes sure that dates are aligned for easy reading."
+ (require 'cal-iso)
+ (let* ((dayname (calendar-day-name date))
+ (day (cadr date))
+ (day-of-week (calendar-day-of-week date))
+ (month (car date))
+ (monthname (calendar-month-name month))
+ (year (nth 2 date))
+ (iso-week (org-days-to-iso-week
+ (calendar-absolute-from-gregorian date)))
+ (weekyear (cond ((and (= month 1) (>= iso-week 52))
+ (1- year))
+ ((and (= month 12) (<= iso-week 1))
+ (1+ year))
+ (t year)))
+ (weekstring (if (= day-of-week 1)
+ (format " W%02d" iso-week)
+ "")))
+ (format "%-10s %2d %s %4d%s"
+ dayname day monthname year weekstring)))
+
+(defcustom org-agenda-time-leading-zero nil
+ "Non-nil means use leading zero for military times in agenda.
+For example, 9:30am would become 09:30 rather than 9:30."
+ :group 'org-agenda-daily/weekly
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-timegrid-use-ampm nil
+ "When set, show AM/PM style timestamps on the timegrid."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defun org-agenda-time-of-day-to-ampm (time)
+ "Convert TIME of a string like \"13:45\" to an AM/PM style time string."
+ (let* ((hour-number (string-to-number (substring time 0 -3)))
+ (minute (substring time -2))
+ (ampm "am"))
+ (cond
+ ((equal hour-number 12)
+ (setq ampm "pm"))
+ ((> hour-number 12)
+ (setq ampm "pm")
+ (setq hour-number (- hour-number 12))))
+ (concat
+ (if org-agenda-time-leading-zero
+ (format "%02d" hour-number)
+ (format "%02s" (number-to-string hour-number)))
+ ":" minute ampm)))
+
+(defun org-agenda-time-of-day-to-ampm-maybe (time)
+ "Conditionally convert TIME to AM/PM format based on `org-agenda-timegrid-use-ampm'."
+ (if org-agenda-timegrid-use-ampm
+ (org-agenda-time-of-day-to-ampm time)
+ time))
+
+(defcustom org-agenda-weekend-days '(6 0)
+ "Which days are weekend?
+These days get the special face `org-agenda-date-weekend' in the agenda
+and timeline buffers."
+ :group 'org-agenda-daily/weekly
+ :type '(set :greedy t
+ (const :tag "Monday" 1)
+ (const :tag "Tuesday" 2)
+ (const :tag "Wednesday" 3)
+ (const :tag "Thursday" 4)
+ (const :tag "Friday" 5)
+ (const :tag "Saturday" 6)
+ (const :tag "Sunday" 0)))
+
+(defcustom org-agenda-move-date-from-past-immediately-to-today t
+ "Non-nil means jump to today when moving a past date forward in time.
+When using S-right in the agenda to move a a date forward, and the date
+stamp currently points to the past, the first key press will move it
+to today. WHen nil, just move one day forward even if the date stays
+in the past."
+ :group 'org-agenda-daily/weekly
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-include-diary nil
+ "If non-nil, include in the agenda entries from the Emacs Calendar's diary.
+Custom commands can set this variable in the options section."
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-include-deadlines t
+ "If non-nil, include entries within their deadline warning period.
+Custom commands can set this variable in the options section."
+ :group 'org-agenda-daily/weekly
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-repeating-timestamp-show-all t
+ "Non-nil means show all occurrences of a repeating stamp in the agenda.
+When set to a list of strings, only show occurrences of repeating
+stamps for these TODO keywords. When nil, only one occurrence is
+shown, either today or the nearest into the future."
+ :group 'org-agenda-daily/weekly
+ :type '(choice
+ (const :tag "Show repeating stamps" t)
+ (repeat :tag "Show repeating stamps for these TODO keywords"
+ (string :tag "TODO Keyword"))
+ (const :tag "Don't show repeating stamps" nil)))
+
+(defcustom org-scheduled-past-days 10000
+ "Number of days to continue listing scheduled items not marked DONE.
+When an item is scheduled on a date, it shows up in the agenda on
+this day and will be listed until it is marked done or for the
+number of days given here."
+ :group 'org-agenda-daily/weekly
+ :type 'integer)
+
+(defcustom org-agenda-log-mode-items '(closed clock)
+ "List of items that should be shown in agenda log mode.
+\\<org-agenda-mode-map>\
+This list may contain the following symbols:
+
+ closed Show entries that have been closed on that day.
+ clock Show entries that have received clocked time on that day.
+ state Show all logged state changes.
+Note that instead of changing this variable, you can also press \
+`\\[universal-argument] \\[org-agenda-log-mode]' in
+the agenda to display all available LOG items temporarily."
+ :group 'org-agenda-daily/weekly
+ :type '(set :greedy t (const closed) (const clock) (const state)))
+
+(defcustom org-agenda-clock-consistency-checks
+ '(:max-duration "10:00" :min-duration 0 :max-gap "0:05"
+ :gap-ok-around ("4:00")
+ :default-face ((:background "DarkRed") (:foreground "white"))
+ :overlap-face nil :gap-face nil :no-end-time-face nil
+ :long-face nil :short-face nil)
+ "This is a property list, with the following keys:
+
+:max-duration Mark clocking chunks that are longer than this time.
+ This is a time string like \"HH:MM\", or the number
+ of minutes as an integer.
+
+:min-duration Mark clocking chunks that are shorter that this.
+ This is a time string like \"HH:MM\", or the number
+ of minutes as an integer.
+
+:max-gap Mark gaps between clocking chunks that are longer than
+ this duration. A number of minutes, or a string
+ like \"HH:MM\".
+
+:gap-ok-around List of times during the day which are usually not working
+ times. When a gap is detected, but the gap contains any
+ of these times, the gap is *not* reported. For example,
+ if this is (\"4:00\" \"13:00\") then gaps that contain
+ 4:00 in the morning (i.e. the night) and 13:00
+ (i.e. a typical lunch time) do not cause a warning.
+ You should have at least one time during the night in this
+ list, or otherwise the first task each morning will trigger
+ a warning because it follows a long gap.
+
+Furthermore, the following properties can be used to define faces for
+issue display.
+
+:default-face the default face, if the specific face is undefined
+:overlap-face face for overlapping clocks
+:gap-face face for gaps between clocks
+:no-end-time-face face for incomplete clocks
+:long-face face for clock intervals that are too long
+:short-face face for clock intervals that are too short"
+ :group 'org-agenda-daily/weekly
+ :group 'org-clock
+ :version "24.1"
+ :type 'plist)
+
+(defcustom org-agenda-log-mode-add-notes t
+ "Non-nil means add first line of notes to log entries in agenda views.
+If a log item like a state change or a clock entry is associated with
+notes, the first line of these notes will be added to the entry in the
+agenda display."
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-start-with-log-mode nil
+ "The initial value of log-mode in a newly created agenda window.
+See `org-agenda-log-mode' and `org-agenda-log-mode-items' for further
+explanations on the possible values."
+ :group 'org-agenda-startup
+ :group 'org-agenda-daily/weekly
+ :type '(choice (const :tag "Don't show log items" nil)
+ (const :tag "Show only log items" only)
+ (const :tag "Show all possible log items" clockcheck)
+ (repeat :tag "Choose among possible values for `org-agenda-log-mode-items'"
+ (choice (const :tag "Show closed log items" closed)
+ (const :tag "Show clocked log items" clock)
+ (const :tag "Show all logged state changes" state)))))
+
+(defcustom org-agenda-start-with-clockreport-mode nil
+ "The initial value of clockreport-mode in a newly created agenda window."
+ :group 'org-agenda-startup
+ :group 'org-agenda-daily/weekly
+ :type 'boolean)
+
+(defcustom org-agenda-clockreport-parameter-plist '(:link t :maxlevel 2)
+ "Property list with parameters for the clocktable in clockreport mode.
+This is the display mode that shows a clock table in the daily/weekly
+agenda, the properties for this dynamic block can be set here.
+The usual clocktable parameters are allowed here, but you cannot set
+the properties :name, :tstart, :tend, :block, and :scope - these will
+be overwritten to make sure the content accurately reflects the
+current display in the agenda."
+ :group 'org-agenda-daily/weekly
+ :type 'plist)
+
+(defcustom org-agenda-search-view-always-boolean nil
+ "Non-nil means the search string is interpreted as individual parts.
+
+The search string for search view can either be interpreted as a phrase,
+or as a list of snippets that define a boolean search for a number of
+strings.
+
+When this is non-nil, the string will be split on whitespace, and each
+snippet will be searched individually, and all must match in order to
+select an entry. A snippet is then a single string of non-white
+characters, or a string in double quotes, or a regexp in {} braces.
+If a snippet is preceded by \"-\", the snippet must *not* match.
+\"+\" is syntactic sugar for positive selection. Each snippet may
+be found as a full word or a partial word, but see the variable
+`org-agenda-search-view-force-full-words'.
+
+When this is nil, search will look for the entire search phrase as one,
+with each space character matching any amount of whitespace, including
+line breaks.
+
+Even when this is nil, you can still switch to Boolean search dynamically
+by preceding the first snippet with \"+\" or \"-\". If the first snippet
+is a regexp marked with braces like \"{abc}\", this will also switch to
+boolean search."
+ :group 'org-agenda-search-view
+ :version "24.1"
+ :type 'boolean)
+
+(defvaralias 'org-agenda-search-view-search-words-only
+ 'org-agenda-search-view-always-boolean)
+
+(defcustom org-agenda-search-view-force-full-words nil
+ "Non-nil means, search words must be matches as complete words.
+When nil, they may also match part of a word."
+ :group 'org-agenda-search-view
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-search-view-max-outline-level 0
+ "Maximum outline level to display in search view.
+E.g. when this is set to 1, the search view will only
+show headlines of level 1. When set to 0, the default
+value, don't limit agenda view by outline level."
+ :group 'org-agenda-search-view
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'integer)
+
+(defgroup org-agenda-time-grid nil
+ "Options concerning the time grid in the Org Agenda."
+ :tag "Org Agenda Time Grid"
+ :group 'org-agenda)
+
+(defcustom org-agenda-search-headline-for-time t
+ "Non-nil means search headline for a time-of-day.
+If the headline contains a time-of-day in one format or another, it will
+be used to sort the entry into the time sequence of items for a day.
+Some people have time stamps in the headline that refer to the creation
+time or so, and then this produces an unwanted side effect. If this is
+the case for your, use this variable to turn off searching the headline
+for a time."
+ :group 'org-agenda-time-grid
+ :type 'boolean)
+
+(defcustom org-agenda-use-time-grid t
+ "Non-nil means show a time grid in the agenda schedule.
+A time grid is a set of lines for specific times (like every two hours between
+8:00 and 20:00). The items scheduled for a day at specific times are
+sorted in between these lines.
+For details about when the grid will be shown, and what it will look like, see
+the variable `org-agenda-time-grid'."
+ :group 'org-agenda-time-grid
+ :type 'boolean)
+
+(defcustom org-agenda-time-grid
+ '((daily today require-timed)
+ "----------------"
+ (800 1000 1200 1400 1600 1800 2000))
+
+ "The settings for time grid for agenda display.
+This is a list of three items. The first item is again a list. It contains
+symbols specifying conditions when the grid should be displayed:
+
+ daily if the agenda shows a single day
+ weekly if the agenda shows an entire week
+ today show grid on current date, independent of daily/weekly display
+ require-timed show grid only if at least one item has a time specification
+ remove-match skip grid times already present in an entry
+
+The second item is a string which will be placed behind the grid time.
+
+The third item is a list of integers, indicating the times that should have
+a grid line."
+ :group 'org-agenda-time-grid
+ :type
+ '(list
+ (set :greedy t :tag "Grid Display Options"
+ (const :tag "Show grid in single day agenda display" daily)
+ (const :tag "Show grid in weekly agenda display" weekly)
+ (const :tag "Always show grid for today" today)
+ (const :tag "Show grid only if any timed entries are present"
+ require-timed)
+ (const :tag "Skip grid times already present in an entry"
+ remove-match))
+ (string :tag "Grid String")
+ (repeat :tag "Grid Times" (integer :tag "Time"))))
+
+(defcustom org-agenda-show-current-time-in-grid t
+ "Non-nil means show the current time in the time grid."
+ :group 'org-agenda-time-grid
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-current-time-string
+ "now - - - - - - - - - - - - - - - - - - - - - - - - -"
+ "The string for the current time marker in the agenda."
+ :group 'org-agenda-time-grid
+ :version "24.1"
+ :type 'string)
+
+(defgroup org-agenda-sorting nil
+ "Options concerning sorting in the Org Agenda."
+ :tag "Org Agenda Sorting"
+ :group 'org-agenda)
+
+(defcustom org-agenda-sorting-strategy
+ '((agenda habit-down time-up priority-down category-keep)
+ (todo priority-down category-keep)
+ (tags priority-down category-keep)
+ (search category-keep))
+ "Sorting structure for the agenda items of a single day.
+This is a list of symbols which will be used in sequence to determine
+if an entry should be listed before another entry. The following
+symbols are recognized:
+
+time-up Put entries with time-of-day indications first, early first
+time-down Put entries with time-of-day indications first, late first
+timestamp-up Sort by any timestamp, early first
+timestamp-down Sort by any timestamp, late first
+scheduled-up Sort by scheduled timestamp, early first
+scheduled-down Sort by scheduled timestamp, late first
+deadline-up Sort by deadline timestamp, early first
+deadline-down Sort by deadline timestamp, late first
+ts-up Sort by active timestamp, early first
+ts-down Sort by active timestamp, late first
+tsia-up Sort by inactive timestamp, early first
+tsia-down Sort by inactive timestamp, late first
+category-keep Keep the default order of categories, corresponding to the
+ sequence in `org-agenda-files'.
+category-up Sort alphabetically by category, A-Z.
+category-down Sort alphabetically by category, Z-A.
+tag-up Sort alphabetically by last tag, A-Z.
+tag-down Sort alphabetically by last tag, Z-A.
+priority-up Sort numerically by priority, high priority last.
+priority-down Sort numerically by priority, high priority first.
+todo-state-up Sort by todo state, tasks that are done last.
+todo-state-down Sort by todo state, tasks that are done first.
+effort-up Sort numerically by estimated effort, high effort last.
+effort-down Sort numerically by estimated effort, high effort first.
+user-defined-up Sort according to `org-agenda-cmp-user-defined', high last.
+user-defined-down Sort according to `org-agenda-cmp-user-defined', high first.
+habit-up Put entries that are habits first
+habit-down Put entries that are habits last
+alpha-up Sort headlines alphabetically
+alpha-down Sort headlines alphabetically, reversed
+
+The different possibilities will be tried in sequence, and testing stops
+if one comparison returns a \"not-equal\". For example, the default
+ '(time-up category-keep priority-down)
+means: Pull out all entries having a specified time of day and sort them,
+in order to make a time schedule for the current day the first thing in the
+agenda listing for the day. Of the entries without a time indication, keep
+the grouped in categories, don't sort the categories, but keep them in
+the sequence given in `org-agenda-files'. Within each category sort by
+priority.
+
+Leaving out `category-keep' would mean that items will be sorted across
+categories by priority.
+
+Instead of a single list, this can also be a set of list for specific
+contents, with a context symbol in the car of the list, any of
+`agenda', `todo', `tags', `search' for the corresponding agenda views.
+
+Custom commands can bind this variable in the options section."
+ :group 'org-agenda-sorting
+ :type `(choice
+ (repeat :tag "General" ,org-sorting-choice)
+ (list :tag "Individually"
+ (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
+ (repeat ,org-sorting-choice))
+ (cons (const :tag "Strategy for TODO lists" todo)
+ (repeat ,org-sorting-choice))
+ (cons (const :tag "Strategy for Tags matches" tags)
+ (repeat ,org-sorting-choice))
+ (cons (const :tag "Strategy for search matches" search)
+ (repeat ,org-sorting-choice)))))
+
+(defcustom org-agenda-cmp-user-defined nil
+ "A function to define the comparison `user-defined'.
+This function must receive two arguments, agenda entry a and b.
+If a>b, return +1. If a<b, return -1. If they are equal as seen by
+the user comparison, return nil.
+When this is defined, you can make `user-defined-up' and `user-defined-down'
+part of an agenda sorting strategy."
+ :group 'org-agenda-sorting
+ :type 'symbol)
+
+(defcustom org-sort-agenda-notime-is-late t
+ "Non-nil means items without time are considered late.
+This is only relevant for sorting. When t, items which have no explicit
+time like 15:30 will be considered as 99:01, i.e. later than any items which
+do have a time. When nil, the default time is before 0:00. You can use this
+option to decide if the schedule for today should come before or after timeless
+agenda entries."
+ :group 'org-agenda-sorting
+ :type 'boolean)
+
+(defcustom org-sort-agenda-noeffort-is-high t
+ "Non-nil means items without effort estimate are sorted as high effort.
+This also applies when filtering an agenda view with respect to the
+< or > effort operator. Then, tasks with no effort defined will be treated
+as tasks with high effort.
+When nil, such items are sorted as 0 minutes effort."
+ :group 'org-agenda-sorting
+ :type 'boolean)
+
+(defgroup org-agenda-line-format nil
+ "Options concerning the entry prefix in the Org agenda display."
+ :tag "Org Agenda Line Format"
+ :group 'org-agenda)
+
+(defcustom org-agenda-prefix-format
+ '((agenda . " %i %-12:c%?-12t% s")
+ (timeline . " % s")
+ (todo . " %i %-12:c")
+ (tags . " %i %-12:c")
+ (search . " %i %-12:c"))
+ "Format specifications for the prefix of items in the agenda views.
+An alist with five entries, each for the different agenda types. The
+keys of the sublists are `agenda', `timeline', `todo', `search' and `tags'.
+The values are format strings.
+
+This format works similar to a printf format, with the following meaning:
+
+ %c the category of the item, \"Diary\" for entries from the diary,
+ or as given by the CATEGORY keyword or derived from the file name
+ %e the effort required by the item
+ %l the level of the item (insert X space(s) if item is of level X)
+ %i the icon category of the item, see `org-agenda-category-icon-alist'
+ %T the last tag of the item (ignore inherited tags, which come first)
+ %t the HH:MM time-of-day specification if one applies to the entry
+ %s Scheduling/Deadline information, a short string
+ %b show breadcrumbs, i.e., the names of the higher levels
+ %(expression) Eval EXPRESSION and replace the control string
+ by the result
+
+All specifiers work basically like the standard `%s' of printf, but may
+contain two additional characters: a question mark just after the `%'
+and a whitespace/punctuation character just before the final letter.
+
+If the first character after `%' is a question mark, the entire field
+will only be included if the corresponding value applies to the current
+entry. This is useful for fields which should have fixed width when
+present, but zero width when absent. For example, \"%?-12t\" will
+result in a 12 character time field if a time of the day is specified,
+but will completely disappear in entries which do not contain a time.
+
+If there is punctuation or whitespace character just before the
+final format letter, this character will be appended to the field
+value if the value is not empty. For example, the format
+\"%-12:c\" leads to \"Diary: \" if the category is \"Diary\". If
+the category is empty, no additional colon is inserted.
+
+The default value for the agenda sublist is \" %-12:c%?-12t% s\",
+which means:
+
+- Indent the line with two space characters
+- Give the category a 12 chars wide field, padded with whitespace on
+ the right (because of `-'). Append a colon if there is a category
+ (because of `:').
+- If there is a time-of-day, put it into a 12 chars wide field. If no
+ time, don't put in an empty field, just skip it (because of '?').
+- Finally, put the scheduling information.
+
+See also the variables `org-agenda-remove-times-when-in-prefix' and
+`org-agenda-remove-tags'.
+
+Custom commands can set this variable in the options section."
+ :type '(choice
+ (string :tag "General format")
+ (list :greedy t :tag "View dependent"
+ (cons (const agenda) (string :tag "Format"))
+ (cons (const timeline) (string :tag "Format"))
+ (cons (const todo) (string :tag "Format"))
+ (cons (const tags) (string :tag "Format"))
+ (cons (const search) (string :tag "Format"))))
+ :group 'org-agenda-line-format)
+
+(defvar org-prefix-format-compiled nil
+ "The compiled prefix format and associated variables.
+This is a list where first element is a list of variable bindings, and second
+element is the compiled format expression. See the variable
+`org-agenda-prefix-format'.")
+
+(defcustom org-agenda-todo-keyword-format "%-1s"
+ "Format for the TODO keyword in agenda lines.
+Set this to something like \"%-12s\" if you want all TODO keywords
+to occupy a fixed space in the agenda display."
+ :group 'org-agenda-line-format
+ :type 'string)
+
+(defcustom org-agenda-diary-sexp-prefix nil
+ "A regexp that matches part of a diary sexp entry
+which should be treated as scheduling/deadline information in
+`org-agenda'.
+
+For example, you can use this to extract the `diary-remind-message' from
+`diary-remind' entries."
+ :group 'org-agenda-line-format
+ :type '(choice (const :tag "None" nil) (regexp :tag "Regexp")))
+
+(defcustom org-agenda-timerange-leaders '("" "(%d/%d): ")
+ "Text preceding timerange entries in the agenda view.
+This is a list with two strings. The first applies when the range
+is entirely on one day. The second applies if the range spans several days.
+The strings may have two \"%d\" format specifiers which will be filled
+with the sequence number of the days, and the total number of days in the
+range, respectively."
+ :group 'org-agenda-line-format
+ :type '(list
+ (string :tag "Deadline today ")
+ (choice :tag "Deadline relative"
+ (string :tag "Format string")
+ (function))))
+
+(defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
+ "Text preceding scheduled items in the agenda view.
+This is a list with two strings. The first applies when the item is
+scheduled on the current day. The second applies when it has been scheduled
+previously, it may contain a %d indicating that this is the nth time that
+this item is scheduled, due to automatic rescheduling of unfinished items
+for the following day. So this number is one larger than the number of days
+that passed since this item was scheduled first."
+ :group 'org-agenda-line-format
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(list
+ (string :tag "Scheduled today ")
+ (string :tag "Scheduled previously")))
+
+(defcustom org-agenda-inactive-leader "["
+ "Text preceding item pulled into the agenda by inactive time stamps.
+These entries are added to the agenda when pressing \"[\"."
+ :group 'org-agenda-line-format
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: " "%2d d. ago: ")
+ "Text preceding deadline items in the agenda view.
+This is a list with three strings. The first applies when the item has its
+deadline on the current day. The second applies when the deadline is in the
+future, the third one when it is in the past. The strings may contain %d
+to capture the number of days."
+ :group 'org-agenda-line-format
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(list
+ (string :tag "Deadline today ")
+ (string :tag "Deadline in the future ")
+ (string :tag "Deadline in the past ")))
+
+(defcustom org-agenda-remove-times-when-in-prefix t
+ "Non-nil means remove duplicate time specifications in agenda items.
+When the format `org-agenda-prefix-format' contains a `%t' specifier, a
+time-of-day specification in a headline or diary entry is extracted and
+placed into the prefix. If this option is non-nil, the original specification
+\(a timestamp or -range, or just a plain time(range) specification like
+11:30-4pm) will be removed for agenda display. This makes the agenda less
+cluttered.
+The option can be t or nil. It may also be the symbol `beg', indicating
+that the time should only be removed when it is located at the beginning of
+the headline/diary entry."
+ :group 'org-agenda-line-format
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (const :tag "When at beginning of entry" beg)))
+
+(defcustom org-agenda-remove-timeranges-from-blocks nil
+ "Non-nil means remove time ranges specifications in agenda
+items that span on several days."
+ :group 'org-agenda-line-format
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-default-appointment-duration nil
+ "Default duration for appointments that only have a starting time.
+When nil, no duration is specified in such cases.
+When non-nil, this must be the number of minutes, e.g. 60 for one hour."
+ :group 'org-agenda-line-format
+ :type '(choice
+ (integer :tag "Minutes")
+ (const :tag "No default duration")))
+
+(defcustom org-agenda-show-inherited-tags t
+ "Non-nil means show inherited tags in each agenda line.
+
+When this option is set to `always', it takes precedence over
+`org-agenda-use-tag-inheritance' and inherited tags are shown
+in every agenda.
+
+When this option is set to t (the default), inherited tags are
+shown when they are available, i.e. when the value of
+`org-agenda-use-tag-inheritance' enables tag inheritance for the
+given agenda type.
+
+This can be set to a list of agenda types in which the agenda
+must display the inherited tags. Available types are `todo',
+`agenda', `search' and `timeline'.
+
+When set to nil, never show inherited tags in agenda lines."
+ :group 'org-agenda-line-format
+ :group 'org-agenda
+ :version "24.3"
+ :type '(choice
+ (const :tag "Show inherited tags when available" t)
+ (const :tag "Always show inherited tags" always)
+ (repeat :tag "Show inherited tags only in selected agenda types"
+ (symbol :tag "Agenda type"))))
+
+(defcustom org-agenda-use-tag-inheritance '(todo search timeline agenda)
+ "List of agenda view types where to use tag inheritance.
+
+In tags/tags-todo/tags-tree agenda views, tag inheritance is
+controlled by `org-use-tag-inheritance'. In other agenda types,
+`org-use-tag-inheritance' is not used for the selection of the
+agenda entries. Still, you may want the agenda to be aware of
+the inherited tags anyway, e.g. for later tag filtering.
+
+Allowed value are `todo', `search', `timeline' and `agenda'.
+
+This variable has no effect if `org-agenda-show-inherited-tags'
+is set to `always'. In that case, the agenda is aware of those
+tags.
+
+The default value sets tags in every agenda type. Setting this
+option to nil will speed up non-tags agenda view a lot."
+ :group 'org-agenda
+ :version "24.3"
+ :type '(choice
+ (const :tag "Use tag inheritance in all agenda types" t)
+ (repeat :tag "Use tag inheritance in selected agenda types"
+ (symbol :tag "Agenda type"))))
+
+(defcustom org-agenda-hide-tags-regexp nil
+ "Regular expression used to filter away specific tags in agenda views.
+This means that these tags will be present, but not be shown in the agenda
+line. Secondary filtering will still work on the hidden tags.
+Nil means don't hide any tags."
+ :group 'org-agenda-line-format
+ :type '(choice
+ (const :tag "Hide none" nil)
+ (string :tag "Regexp ")))
+
+(defcustom org-agenda-remove-tags nil
+ "Non-nil means remove the tags from the headline copy in the agenda.
+When this is the symbol `prefix', only remove tags when
+`org-agenda-prefix-format' contains a `%T' specifier."
+ :group 'org-agenda-line-format
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (const :tag "When prefix format contains %T" prefix)))
+
+(defvaralias 'org-agenda-remove-tags-when-in-prefix
+ 'org-agenda-remove-tags)
+
+(defcustom org-agenda-tags-column -80
+ "Shift tags in agenda items to this column.
+If this number is positive, it specifies the column. If it is negative,
+it means that the tags should be flushright to that column. For example,
+-80 works well for a normal 80 character screen."
+ :group 'org-agenda-line-format
+ :type 'integer)
+
+(defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column)
+
+(defcustom org-agenda-fontify-priorities 'cookies
+ "Non-nil means highlight low and high priorities in agenda.
+When t, the highest priority entries are bold, lowest priority italic.
+However, settings in `org-priority-faces' will overrule these faces.
+When this variable is the symbol `cookies', only fontify the
+cookies, not the entire task.
+This may also be an association list of priority faces, whose
+keys are the character values of `org-highest-priority',
+`org-default-priority', and `org-lowest-priority' (the default values
+are ?A, ?B, and ?C, respectively). The face may be a named face, a
+color as a string, or a list like `(:background \"Red\")'.
+If it is a color, the variable `org-faces-easy-properties'
+determines if it is a foreground or a background color."
+ :group 'org-agenda-line-format
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Defaults" t)
+ (const :tag "Cookies only" cookies)
+ (repeat :tag "Specify"
+ (list (character :tag "Priority" :value ?A)
+ (choice :tag "Face "
+ (string :tag "Color")
+ (sexp :tag "Face"))))))
+
+(defcustom org-agenda-day-face-function nil
+ "Function called to determine what face should be used to display a day.
+The only argument passed to that function is the day. It should
+returns a face, or nil if does not want to specify a face and let
+the normal rules apply."
+ :group 'org-agenda-line-format
+ :version "24.1"
+ :type '(choice (const nil) (function)))
+
+(defcustom org-agenda-category-icon-alist nil
+ "Alist of category icon to be displayed in agenda views.
+
+Each entry should have the following format:
+
+ (CATEGORY-REGEXP FILE-OR-DATA TYPE DATA-P PROPS)
+
+Where CATEGORY-REGEXP is a regexp matching the categories where
+the icon should be displayed.
+FILE-OR-DATA either a file path or a string containing image data.
+
+The other fields can be omitted safely if not needed:
+TYPE indicates the image type.
+DATA-P is a boolean indicating whether the FILE-OR-DATA string is
+image data.
+PROPS are additional image attributes to assign to the image,
+like, e.g. `:ascent center'.
+
+ (\"Org\" \"/path/to/icon.png\" nil nil :ascent center)
+
+If you want to set the display properties yourself, just put a
+list as second element:
+
+ (CATEGORY-REGEXP (MY PROPERTY LIST))
+
+For example, to display a 16px horizontal space for Emacs
+category, you can use:
+
+ (\"Emacs\" \\='(space . (:width (16))))"
+ :group 'org-agenda-line-format
+ :version "24.1"
+ :type '(alist :key-type (string :tag "Regexp matching category")
+ :value-type (choice (list :tag "Icon"
+ (string :tag "File or data")
+ (symbol :tag "Type")
+ (boolean :tag "Data?")
+ (repeat :tag "Extra image properties" :inline t symbol))
+ (list :tag "Display properties" sexp))))
+
+(defgroup org-agenda-column-view nil
+ "Options concerning column view in the agenda."
+ :tag "Org Agenda Column View"
+ :group 'org-agenda)
+
+(defcustom org-agenda-view-columns-initially nil
+ "When non-nil, switch to columns view right after creating the agenda."
+ :group 'org-agenda-column-view
+ :type 'boolean
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :safe #'booleanp)
+
+(defcustom org-agenda-columns-show-summaries t
+ "Non-nil means show summaries for columns displayed in the agenda view."
+ :group 'org-agenda-column-view
+ :type 'boolean)
+
+(defcustom org-agenda-columns-compute-summary-properties t
+ "Non-nil means recompute all summary properties before column view.
+When column view in the agenda is listing properties that have a summary
+operator, it can go to all relevant buffers and recompute the summaries
+there. This can mean overhead for the agenda column view, but is necessary
+to have thing up to date.
+As a special case, a CLOCKSUM property also makes sure that the clock
+computations are current."
+ :group 'org-agenda-column-view
+ :type 'boolean)
+
+(defcustom org-agenda-columns-add-appointments-to-effort-sum nil
+ "Non-nil means the duration of an appointment will add to day effort.
+The property to which appointment durations will be added is the one given
+in the option `org-effort-property'. If an appointment does not have
+an end time, `org-agenda-default-appointment-duration' will be used. If that
+is not set, an appointment without end time will not contribute to the time
+estimate."
+ :group 'org-agenda-column-view
+ :type 'boolean)
+
+(defcustom org-agenda-auto-exclude-function nil
+ "A function called with a tag to decide if it is filtered on \
+\\<org-agenda-mode-map>`\\[org-agenda-filter-by-tag] RET'.
+The sole argument to the function, which is called once for each
+possible tag, is a string giving the name of the tag. The
+function should return either nil if the tag should be included
+as normal, or \"-<TAG>\" to exclude the tag.
+Note that for the purpose of tag filtering, only the lower-case version of
+all tags will be considered, so that this function will only ever see
+the lower-case version of all tags."
+ :group 'org-agenda
+ :type '(choice (const nil) (function)))
+
+(defcustom org-agenda-bulk-custom-functions nil
+ "Alist of characters and custom functions for bulk actions.
+For example, this value makes those two functions available:
+
+ \\='((?R set-category)
+ (?C bulk-cut))
+
+With selected entries in an agenda buffer, `B R' will call
+the custom function `set-category' on the selected entries.
+Note that functions in this alist don't need to be quoted."
+ :type '(alist :key-type character :value-type (group function))
+ :version "24.1"
+ :group 'org-agenda)
+
+(defmacro org-agenda-with-point-at-orig-entry (string &rest body)
+ "Execute BODY with point at location given by `org-hd-marker' property.
+If STRING is non-nil, the text property will be fetched from position 0
+in that string. If STRING is nil, it will be fetched from the beginning
+of the current line."
+ (org-with-gensyms (marker)
+ `(let ((,marker (get-text-property (if ,string 0 (point-at-bol))
+ 'org-hd-marker ,string)))
+ (with-current-buffer (marker-buffer ,marker)
+ (save-excursion
+ (goto-char ,marker)
+ ,@body)))))
+(def-edebug-spec org-agenda-with-point-at-orig-entry (form body))
+
+(defun org-add-agenda-custom-command (entry)
+ "Replace or add a command in `org-agenda-custom-commands'.
+This is mostly for hacking and trying a new command - once the command
+works you probably want to add it to `org-agenda-custom-commands' for good."
+ (let ((ass (assoc (car entry) org-agenda-custom-commands)))
+ (if ass
+ (setcdr ass (cdr entry))
+ (push entry org-agenda-custom-commands))))
+
+;;; Define the org-agenda-mode
+
+(defvar org-agenda-mode-map (make-sparse-keymap)
+ "Keymap for `org-agenda-mode'.")
+(defvaralias 'org-agenda-keymap 'org-agenda-mode-map)
+
+(defvar org-agenda-menu) ; defined later in this file.
+(defvar org-agenda-restrict nil) ; defined later in this file.
+(defvar org-agenda-follow-mode nil)
+(defvar org-agenda-entry-text-mode nil)
+(defvar org-agenda-clockreport-mode nil)
+(defvar org-agenda-show-log nil)
+(defvar org-agenda-redo-command nil)
+(defvar org-agenda-query-string nil)
+(defvar org-agenda-mode-hook nil
+ "Hook run after `org-agenda-mode' is turned on.
+The buffer is still writable when this hook is called.")
+(defvar org-agenda-type nil)
+(defvar org-agenda-force-single-file nil)
+(defvar org-agenda-bulk-marked-entries nil
+ "List of markers that refer to marked entries in the agenda.")
+(defvar org-agenda-current-date nil
+ "Active date when building the agenda.")
+
+;;; Multiple agenda buffers support
+
+(defcustom org-agenda-sticky nil
+ "Non-nil means agenda q key will bury agenda buffers.
+Agenda commands will then show existing buffer instead of generating new ones.
+When nil, `q' will kill the single agenda buffer."
+ :group 'org-agenda
+ :version "24.3"
+ :type 'boolean)
+
+
+;;;###autoload
+(defun org-toggle-sticky-agenda (&optional arg)
+ "Toggle `org-agenda-sticky'."
+ (interactive "P")
+ (let ((new-value (if arg
+ (> (prefix-numeric-value arg) 0)
+ (not org-agenda-sticky))))
+ (if (equal new-value org-agenda-sticky)
+ (and (called-interactively-p 'interactive)
+ (message "Sticky agenda was already %s"
+ (if org-agenda-sticky "enabled" "disabled")))
+ (setq org-agenda-sticky new-value)
+ (org-agenda-kill-all-agenda-buffers)
+ (and (called-interactively-p 'interactive)
+ (message "Sticky agenda %s"
+ (if org-agenda-sticky "enabled" "disabled"))))))
+
+(defvar org-agenda-buffer nil
+ "Agenda buffer currently being generated.")
+
+(defvar org-agenda-last-prefix-arg nil)
+(defvar org-agenda-this-buffer-name nil)
+(defvar org-agenda-doing-sticky-redo nil)
+(defvar org-agenda-this-buffer-is-sticky nil)
+(defvar org-agenda-last-indirect-buffer nil
+ "Last buffer loaded by `org-agenda-tree-to-indirect-buffer'.")
+
+(defconst org-agenda-local-vars
+ '(org-agenda-this-buffer-name
+ org-agenda-undo-list
+ org-agenda-pending-undo-list
+ org-agenda-follow-mode
+ org-agenda-entry-text-mode
+ org-agenda-clockreport-mode
+ org-agenda-show-log
+ org-agenda-redo-command
+ org-agenda-query-string
+ org-agenda-type
+ org-agenda-bulk-marked-entries
+ org-agenda-undo-has-started-in
+ org-agenda-info
+ org-agenda-pre-window-conf
+ org-agenda-columns-active
+ org-agenda-tag-filter
+ org-agenda-category-filter
+ org-agenda-top-headline-filter
+ org-agenda-regexp-filter
+ org-agenda-effort-filter
+ org-agenda-markers
+ org-agenda-last-search-view-search-was-boolean
+ org-agenda-last-indirect-buffer
+ org-agenda-filtered-by-category
+ org-agenda-filter-form
+ org-agenda-cycle-counter
+ org-agenda-last-prefix-arg)
+ "Variables that must be local in agenda buffers to allow multiple buffers.")
+
+(defun org-agenda-mode ()
+ "Mode for time-sorted view on action items in Org files.
+
+The following commands are available:
+
+\\{org-agenda-mode-map}"
+ (interactive)
+ (cond (org-agenda-doing-sticky-redo
+ ;; Refreshing sticky agenda-buffer
+ ;;
+ ;; Preserve the value of `org-agenda-local-vars' variables,
+ ;; while letting `kill-all-local-variables' kill the rest
+ (let ((save (buffer-local-variables)))
+ (kill-all-local-variables)
+ (mapc #'make-local-variable org-agenda-local-vars)
+ (dolist (elem save)
+ (pcase elem
+ (`(,var . ,val) ;ignore unbound variables
+ (when (and val (memq var org-agenda-local-vars))
+ (set var val))))))
+ (setq-local org-agenda-this-buffer-is-sticky t))
+ (org-agenda-sticky
+ ;; Creating a sticky Agenda buffer for the first time
+ (kill-all-local-variables)
+ (mapc 'make-local-variable org-agenda-local-vars)
+ (setq-local org-agenda-this-buffer-is-sticky t))
+ (t
+ ;; Creating a non-sticky agenda buffer
+ (kill-all-local-variables)
+ (setq-local org-agenda-this-buffer-is-sticky nil)))
+ (setq org-agenda-undo-list nil
+ org-agenda-pending-undo-list nil
+ org-agenda-bulk-marked-entries nil)
+ (setq major-mode 'org-agenda-mode)
+ ;; Keep global-font-lock-mode from turning on font-lock-mode
+ (setq-local font-lock-global-modes (list 'not major-mode))
+ (setq mode-name "Org-Agenda")
+ (setq indent-tabs-mode nil)
+ (use-local-map org-agenda-mode-map)
+ (easy-menu-add org-agenda-menu)
+ (if org-startup-truncated (setq truncate-lines t))
+ (setq-local line-move-visual nil)
+ (add-hook 'post-command-hook 'org-agenda-update-agenda-type nil 'local)
+ (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
+ ;; Make sure properties are removed when copying text
+ (add-hook 'filter-buffer-substring-functions
+ (lambda (fun start end delete)
+ (substring-no-properties (funcall fun start end delete)))
+ nil t)
+ (unless org-agenda-keep-modes
+ (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
+ org-agenda-entry-text-mode org-agenda-start-with-entry-text-mode))
+ (setq org-agenda-show-log org-agenda-start-with-log-mode)
+ (setq org-agenda-clockreport-mode org-agenda-start-with-clockreport-mode)
+ (add-to-invisibility-spec '(org-filtered))
+ (add-to-invisibility-spec '(org-link))
+ (easy-menu-change
+ '("Agenda") "Agenda Files"
+ (append
+ (list
+ (vector
+ (if (get 'org-agenda-files 'org-restrict)
+ "Restricted to single file"
+ "Edit File List")
+ '(org-edit-agenda-file-list)
+ (not (get 'org-agenda-files 'org-restrict)))
+ "--")
+ (mapcar 'org-file-menu-entry (org-agenda-files))))
+ (org-agenda-set-mode-name)
+ (apply
+ (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
+ (list 'org-agenda-mode-hook)))
+
+(substitute-key-definition 'undo 'org-agenda-undo
+ org-agenda-mode-map global-map)
+(org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
+(org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
+(org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
+(org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
+(org-defkey org-agenda-mode-map "\C-c\C-w" 'org-agenda-refile)
+(org-defkey org-agenda-mode-map [(meta down)] 'org-agenda-drag-line-forward)
+(org-defkey org-agenda-mode-map [(meta up)] 'org-agenda-drag-line-backward)
+(org-defkey org-agenda-mode-map "m" 'org-agenda-bulk-mark)
+(org-defkey org-agenda-mode-map "\M-m" 'org-agenda-bulk-toggle)
+(org-defkey org-agenda-mode-map "*" 'org-agenda-bulk-mark-all)
+(org-defkey org-agenda-mode-map "\M-*" 'org-agenda-bulk-toggle-all)
+(org-defkey org-agenda-mode-map "#" 'org-agenda-dim-blocked-tasks)
+(org-defkey org-agenda-mode-map "%" 'org-agenda-bulk-mark-regexp)
+(org-defkey org-agenda-mode-map "u" 'org-agenda-bulk-unmark)
+(org-defkey org-agenda-mode-map "U" 'org-agenda-bulk-unmark-all)
+(org-defkey org-agenda-mode-map "B" 'org-agenda-bulk-action)
+(org-defkey org-agenda-mode-map "k" 'org-agenda-capture)
+(org-defkey org-agenda-mode-map "A" 'org-agenda-append-agenda)
+(org-defkey org-agenda-mode-map "\C-c\C-x!" 'org-reload)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-a" 'org-agenda-archive-default)
+(org-defkey org-agenda-mode-map "\C-c\C-xa" 'org-agenda-toggle-archive-tag)
+(org-defkey org-agenda-mode-map "\C-c\C-xA" 'org-agenda-archive-to-archive-sibling)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
+(org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
+(org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
+(org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
+(org-defkey org-agenda-mode-map " " 'org-agenda-show-and-scroll-up)
+(org-defkey org-agenda-mode-map [backspace] 'org-agenda-show-scroll-down)
+(org-defkey org-agenda-mode-map "\d" 'org-agenda-show-scroll-down)
+(org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
+(org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
+(org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
+(org-defkey org-agenda-mode-map "o" 'delete-other-windows)
+(org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
+(org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
+(org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
+(org-defkey org-agenda-mode-map "a" 'org-agenda-archive-default-with-confirmation)
+(org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
+(org-defkey org-agenda-mode-map "\C-c\C-q" 'org-agenda-set-tags)
+(org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
+(org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
+(org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
+(org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
+(org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
+(org-defkey org-agenda-mode-map "\C-c\C-z" 'org-agenda-add-note)
+(org-defkey org-agenda-mode-map "z" 'org-agenda-add-note)
+(org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-do-date-later)
+(org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-do-date-earlier)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-do-date-later)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-do-date-earlier)
+
+(org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
+(org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
+(org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
+(let ((l '(1 2 3 4 5 6 7 8 9 0)))
+ (while l (org-defkey org-agenda-mode-map
+ (int-to-string (pop l)) 'digit-argument)))
+
+(org-defkey org-agenda-mode-map "F" 'org-agenda-follow-mode)
+(org-defkey org-agenda-mode-map "R" 'org-agenda-clockreport-mode)
+(org-defkey org-agenda-mode-map "E" 'org-agenda-entry-text-mode)
+(org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
+(org-defkey org-agenda-mode-map "v" 'org-agenda-view-mode-dispatch)
+(org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
+(org-defkey org-agenda-mode-map "!" 'org-agenda-toggle-deadlines)
+(org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
+(org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
+(org-defkey org-agenda-mode-map "g" (lambda () (interactive) (org-agenda-redo t)))
+(org-defkey org-agenda-mode-map "e" 'org-agenda-set-effort)
+(org-defkey org-agenda-mode-map "\C-c\C-xe" 'org-agenda-set-effort)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-e"
+ 'org-clock-modify-effort-estimate)
+(org-defkey org-agenda-mode-map "\C-c\C-xp" 'org-agenda-set-property)
+(org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
+(org-defkey org-agenda-mode-map "Q" 'org-agenda-Quit)
+(org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
+(org-defkey org-agenda-mode-map "\C-x\C-w" 'org-agenda-write)
+(org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
+(org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
+(org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
+(org-defkey org-agenda-mode-map "n" 'org-agenda-next-line)
+(org-defkey org-agenda-mode-map "p" 'org-agenda-previous-line)
+(org-defkey org-agenda-mode-map "N" 'org-agenda-next-item)
+(org-defkey org-agenda-mode-map "P" 'org-agenda-previous-item)
+(substitute-key-definition 'next-line 'org-agenda-next-line
+ org-agenda-mode-map global-map)
+(substitute-key-definition 'previous-line 'org-agenda-previous-line
+ org-agenda-mode-map global-map)
+(org-defkey org-agenda-mode-map "\C-c\C-a" 'org-attach)
+(org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
+(org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
+(org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
+(org-defkey org-agenda-mode-map "," 'org-agenda-priority)
+(org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
+(org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
+(org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
+(org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
+(org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
+(org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
+(org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
+(org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
+(org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
+(org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
+(org-defkey org-agenda-mode-map "J" 'org-agenda-clock-goto)
+(org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
+(org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
+(org-defkey org-agenda-mode-map "f" 'org-agenda-later)
+(org-defkey org-agenda-mode-map "b" 'org-agenda-earlier)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
+(org-defkey org-agenda-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
+
+(org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
+(org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
+(org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
+(org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
+(org-defkey org-agenda-mode-map "/" 'org-agenda-filter-by-tag)
+(org-defkey org-agenda-mode-map "_" 'org-agenda-filter-by-effort)
+(org-defkey org-agenda-mode-map "=" 'org-agenda-filter-by-regexp)
+(org-defkey org-agenda-mode-map "|" 'org-agenda-filter-remove-all)
+(org-defkey org-agenda-mode-map "~" 'org-agenda-limit-interactively)
+(org-defkey org-agenda-mode-map "<" 'org-agenda-filter-by-category)
+(org-defkey org-agenda-mode-map "^" 'org-agenda-filter-by-top-headline)
+(org-defkey org-agenda-mode-map ";" 'org-timer-set-timer)
+(define-key org-agenda-mode-map "?" 'org-agenda-show-the-flagging-note)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
+(org-defkey org-agenda-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
+
+(org-defkey org-agenda-mode-map [mouse-2] 'org-agenda-goto-mouse)
+(org-defkey org-agenda-mode-map [mouse-3] 'org-agenda-show-mouse)
+
+(define-key org-agenda-mode-map [remap forward-paragraph] 'org-agenda-forward-block)
+(define-key org-agenda-mode-map [remap backward-paragraph] 'org-agenda-backward-block)
+
+(when org-agenda-mouse-1-follows-link
+ (org-defkey org-agenda-mode-map [follow-link] 'mouse-face))
+(easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
+ '("Agenda"
+ ("Agenda Files")
+ "--"
+ ("Agenda Dates"
+ ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
+ ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
+ ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)])
+ "--"
+ ("View"
+ ["Day View" org-agenda-day-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'day)
+ :keys "v d (or just d)"]
+ ["Week View" org-agenda-week-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'week)
+ :keys "v w"]
+ ["Fortnight View" org-agenda-fortnight-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'fortnight)
+ :keys "v t"]
+ ["Month View" org-agenda-month-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'month)
+ :keys "v m"]
+ ["Year View" org-agenda-year-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'year)
+ :keys "v y"]
+ "--"
+ ["Include Diary" org-agenda-toggle-diary
+ :style toggle :selected org-agenda-include-diary
+ :active (org-agenda-check-type nil 'agenda)]
+ ["Include Deadlines" org-agenda-toggle-deadlines
+ :style toggle :selected org-agenda-include-deadlines
+ :active (org-agenda-check-type nil 'agenda)]
+ ["Use Time Grid" org-agenda-toggle-time-grid
+ :style toggle :selected org-agenda-use-time-grid
+ :active (org-agenda-check-type nil 'agenda)]
+ "--"
+ ["Show clock report" org-agenda-clockreport-mode
+ :style toggle :selected org-agenda-clockreport-mode
+ :active (org-agenda-check-type nil 'agenda)]
+ ["Show some entry text" org-agenda-entry-text-mode
+ :style toggle :selected org-agenda-entry-text-mode
+ :active t]
+ "--"
+ ["Show Logbook entries" org-agenda-log-mode
+ :style toggle :selected org-agenda-show-log
+ :active (org-agenda-check-type nil 'agenda 'timeline)
+ :keys "v l (or just l)"]
+ ["Include archived trees" org-agenda-archives-mode
+ :style toggle :selected org-agenda-archives-mode :active t
+ :keys "v a"]
+ ["Include archive files" (org-agenda-archives-mode t)
+ :style toggle :selected (eq org-agenda-archives-mode t) :active t
+ :keys "v A"]
+ "--"
+ ["Remove Restriction" org-agenda-remove-restriction-lock org-agenda-restrict])
+ ["Write view to file" org-agenda-write t]
+ ["Rebuild buffer" org-agenda-redo t]
+ ["Save all Org buffers" org-save-all-org-buffers t]
+ "--"
+ ["Show original entry" org-agenda-show t]
+ ["Go To (other window)" org-agenda-goto t]
+ ["Go To (this window)" org-agenda-switch-to t]
+ ["Capture with cursor date" org-agenda-capture t]
+ ["Follow Mode" org-agenda-follow-mode
+ :style toggle :selected org-agenda-follow-mode :active t]
+ ;; ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
+ "--"
+ ("TODO"
+ ["Cycle TODO" org-agenda-todo t]
+ ["Next TODO set" org-agenda-todo-nextset t]
+ ["Previous TODO set" org-agenda-todo-previousset t]
+ ["Add note" org-agenda-add-note t])
+ ("Archive/Refile/Delete"
+ ["Archive default" org-agenda-archive-default t]
+ ["Archive default" org-agenda-archive-default-with-confirmation t]
+ ["Toggle ARCHIVE tag" org-agenda-toggle-archive-tag t]
+ ["Move to archive sibling" org-agenda-archive-to-archive-sibling t]
+ ["Archive subtree" org-agenda-archive t]
+ "--"
+ ["Refile" org-agenda-refile t]
+ "--"
+ ["Delete subtree" org-agenda-kill t])
+ ("Bulk action"
+ ["Mark entry" org-agenda-bulk-mark t]
+ ["Mark all" org-agenda-bulk-mark-all t]
+ ["Unmark entry" org-agenda-bulk-unmark t]
+ ["Unmark all" org-agenda-bulk-unmark-all :active t :keys "U"]
+ ["Toggle mark" org-agenda-bulk-toggle t]
+ ["Toggle all" org-agenda-bulk-toggle-all t]
+ ["Mark regexp" org-agenda-bulk-mark-regexp t])
+ ["Act on all marked" org-agenda-bulk-action t]
+ "--"
+ ("Tags and Properties"
+ ["Show all Tags" org-agenda-show-tags t]
+ ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
+ ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
+ "--"
+ ["Column View" org-columns t])
+ ("Deadline/Schedule"
+ ["Schedule" org-agenda-schedule t]
+ ["Set Deadline" org-agenda-deadline t]
+ "--"
+ ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Change Time +1 hour" org-agenda-do-date-later :active (org-agenda-check-type nil 'agenda 'timeline) :keys "C-u S-right"]
+ ["Change Time -1 hour" org-agenda-do-date-earlier :active (org-agenda-check-type nil 'agenda 'timeline) :keys "C-u S-left"]
+ ["Change Time + min" org-agenda-date-later :active (org-agenda-check-type nil 'agenda 'timeline) :keys "C-u C-u S-right"]
+ ["Change Time - min" org-agenda-date-earlier :active (org-agenda-check-type nil 'agenda 'timeline) :keys "C-u C-u S-left"]
+ ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
+ ("Clock and Effort"
+ ["Clock in" org-agenda-clock-in t]
+ ["Clock out" org-agenda-clock-out t]
+ ["Clock cancel" org-agenda-clock-cancel t]
+ ["Goto running clock" org-clock-goto t]
+ "--"
+ ["Set Effort" org-agenda-set-effort t]
+ ["Change clocked effort" org-clock-modify-effort-estimate
+ (org-clock-is-active)])
+ ("Priority"
+ ["Set Priority" org-agenda-priority t]
+ ["Increase Priority" org-agenda-priority-up t]
+ ["Decrease Priority" org-agenda-priority-down t]
+ ["Show Priority" org-show-priority t])
+ ("Calendar/Diary"
+ ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
+ "--"
+ ["Create iCalendar File" org-icalendar-combine-agenda-files t])
+ "--"
+ ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
+ "--"
+ ("MobileOrg"
+ ["Push Files and Views" org-mobile-push t]
+ ["Get Captured and Flagged" org-mobile-pull t]
+ ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
+ ["Show note / unflag" org-agenda-show-the-flagging-note t]
+ "--"
+ ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
+ "--"
+ ["Quit" org-agenda-quit t]
+ ["Exit and Release Buffers" org-agenda-exit t]
+ ))
+
+;;; Agenda undo
+
+(defvar org-agenda-allow-remote-undo t
+ "Non-nil means allow remote undo from the agenda buffer.")
+(defvar org-agenda-undo-has-started-in nil
+ "Buffers that have already seen `undo-start' in the current undo sequence.")
+
+(defun org-agenda-undo ()
+ "Undo a remote editing step in the agenda.
+This undoes changes both in the agenda buffer and in the remote buffer
+that have been changed along."
+ (interactive)
+ (or org-agenda-allow-remote-undo
+ (user-error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo"))
+ (if (not (eq this-command last-command))
+ (setq org-agenda-undo-has-started-in nil
+ org-agenda-pending-undo-list org-agenda-undo-list))
+ (if (not org-agenda-pending-undo-list)
+ (user-error "No further undo information"))
+ (let* ((entry (pop org-agenda-pending-undo-list))
+ buf line cmd rembuf)
+ (setq cmd (pop entry) line (pop entry))
+ (setq rembuf (nth 2 entry))
+ (org-with-remote-undo rembuf
+ (while (bufferp (setq buf (pop entry)))
+ (if (pop entry)
+ (with-current-buffer buf
+ (let ((last-undo-buffer buf)
+ (inhibit-read-only t))
+ (unless (memq buf org-agenda-undo-has-started-in)
+ (push buf org-agenda-undo-has-started-in)
+ (make-local-variable 'pending-undo-list)
+ (undo-start))
+ (while (and pending-undo-list
+ (listp pending-undo-list)
+ (not (car pending-undo-list)))
+ (pop pending-undo-list))
+ (undo-more 1))))))
+ (org-goto-line line)
+ (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
+
+(defun org-verify-change-for-undo (l1 l2)
+ "Verify that a real change occurred between the undo lists L1 and L2."
+ (while (and l1 (listp l1) (null (car l1))) (pop l1))
+ (while (and l2 (listp l2) (null (car l2))) (pop l2))
+ (not (eq l1 l2)))
+
+;;; Agenda dispatch
+
+(defvar org-agenda-restrict-begin (make-marker))
+(defvar org-agenda-restrict-end (make-marker))
+(defvar org-agenda-last-dispatch-buffer nil)
+(defvar org-agenda-overriding-restriction nil)
+
+(defcustom org-agenda-custom-commands-contexts nil
+ "Alist of custom agenda keys and contextual rules.
+
+For example, if you have a custom agenda command \"p\" and you
+want this command to be accessible only from plain text files,
+use this:
+
+ \\='((\"p\" ((in-file . \"\\\\.txt\\\\'\"))))
+
+Here are the available contexts definitions:
+
+ in-file: command displayed only in matching files
+ in-mode: command displayed only in matching modes
+ not-in-file: command not displayed in matching files
+ not-in-mode: command not displayed in matching modes
+ in-buffer: command displayed only in matching buffers
+not-in-buffer: command not displayed in matching buffers
+ [function]: a custom function taking no argument
+
+If you define several checks, the agenda command will be
+accessible if there is at least one valid check.
+
+You can also bind a key to another agenda custom command
+depending on contextual rules.
+
+ \\='((\"p\" \"q\" ((in-file . \"\\\\.txt\\\\'\"))))
+
+Here it means: in .txt files, use \"p\" as the key for the
+agenda command otherwise associated with \"q\". (The command
+originally associated with \"q\" is not displayed to avoid
+duplicates.)"
+ :version "24.3"
+ :group 'org-agenda-custom-commands
+ :type '(repeat (list :tag "Rule"
+ (string :tag " Agenda key")
+ (string :tag "Replace by command")
+ (repeat :tag "Available when"
+ (choice
+ (cons :tag "Condition"
+ (choice
+ (const :tag "In file" in-file)
+ (const :tag "Not in file" not-in-file)
+ (const :tag "In buffer" in-buffer)
+ (const :tag "Not in buffer" not-in-buffer)
+ (const :tag "In mode" in-mode)
+ (const :tag "Not in mode" not-in-mode))
+ (regexp))
+ (function :tag "Custom function"))))))
+
+(defcustom org-agenda-max-entries nil
+ "Maximum number of entries to display in an agenda.
+This can be nil (no limit) or an integer or an alist of agenda
+types with an associated number of entries to display in this
+type."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-agenda-custom-commands
+ :type '(choice (symbol :tag "No limit" nil)
+ (integer :tag "Max number of entries")
+ (repeat
+ (cons (choice :tag "Agenda type"
+ (const agenda)
+ (const todo)
+ (const tags)
+ (const search)
+ (const timeline))
+ (integer :tag "Max number of entries")))))
+
+(defcustom org-agenda-max-todos nil
+ "Maximum number of TODOs to display in an agenda.
+This can be nil (no limit) or an integer or an alist of agenda
+types with an associated number of entries to display in this
+type."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-agenda-custom-commands
+ :type '(choice (symbol :tag "No limit" nil)
+ (integer :tag "Max number of TODOs")
+ (repeat
+ (cons (choice :tag "Agenda type"
+ (const agenda)
+ (const todo)
+ (const tags)
+ (const search)
+ (const timeline))
+ (integer :tag "Max number of TODOs")))))
+
+(defcustom org-agenda-max-tags nil
+ "Maximum number of tagged entries to display in an agenda.
+This can be nil (no limit) or an integer or an alist of agenda
+types with an associated number of entries to display in this
+type."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-agenda-custom-commands
+ :type '(choice (symbol :tag "No limit" nil)
+ (integer :tag "Max number of tagged entries")
+ (repeat
+ (cons (choice :tag "Agenda type"
+ (const agenda)
+ (const todo)
+ (const tags)
+ (const search)
+ (const timeline))
+ (integer :tag "Max number of tagged entries")))))
+
+(defcustom org-agenda-max-effort nil
+ "Maximum cumulated effort duration for the agenda.
+This can be nil (no limit) or a number of minutes (as an integer)
+or an alist of agenda types with an associated number of minutes
+to limit entries to in this type."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-agenda-custom-commands
+ :type '(choice (symbol :tag "No limit" nil)
+ (integer :tag "Max number of minutes")
+ (repeat
+ (cons (choice :tag "Agenda type"
+ (const agenda)
+ (const todo)
+ (const tags)
+ (const search)
+ (const timeline))
+ (integer :tag "Max number of minutes")))))
+
+(defvar org-agenda-keep-restricted-file-list nil)
+(defvar org-keys nil)
+(defvar org-match nil)
+;;;###autoload
+(defun org-agenda (&optional arg org-keys restriction)
+ "Dispatch agenda commands to collect entries to the agenda buffer.
+Prompts for a command to execute. Any prefix arg will be passed
+on to the selected command. The default selections are:
+
+a Call `org-agenda-list' to display the agenda for current day or week.
+t Call `org-todo-list' to display the global todo list.
+T Call `org-todo-list' to display the global todo list, select only
+ entries with a specific TODO keyword (the user gets a prompt).
+m Call `org-tags-view' to display headlines with tags matching
+ a condition (the user is prompted for the condition).
+M Like `m', but select only TODO entries, no ordinary headlines.
+L Create a timeline for the current buffer.
+e Export views to associated files.
+s Search entries for keywords.
+S Search entries for keywords, only with TODO keywords.
+/ Multi occur across all agenda files and also files listed
+ in `org-agenda-text-search-extra-files'.
+< Restrict agenda commands to buffer, subtree, or region.
+ Press several times to get the desired effect.
+> Remove a previous restriction.
+# List \"stuck\" projects.
+! Configure what \"stuck\" means.
+C Configure custom agenda commands.
+
+More commands can be added by configuring the variable
+`org-agenda-custom-commands'. In particular, specific tags and TODO keyword
+searches can be pre-defined in this way.
+
+If the current buffer is in Org mode and visiting a file, you can also
+first press `<' once to indicate that the agenda should be temporarily
+\(until the next use of `\\[org-agenda]') restricted to the current file.
+Pressing `<' twice means to restrict to the current subtree or region
+\(if active)."
+ (interactive "P")
+ (catch 'exit
+ (let* ((prefix-descriptions nil)
+ (org-agenda-buffer-name org-agenda-buffer-name)
+ (org-agenda-window-setup (if (equal (buffer-name)
+ org-agenda-buffer-name)
+ 'current-window
+ org-agenda-window-setup))
+ (org-agenda-custom-commands-orig org-agenda-custom-commands)
+ (org-agenda-custom-commands
+ ;; normalize different versions
+ (delq nil
+ (mapcar
+ (lambda (x)
+ (cond ((stringp (cdr x))
+ (push x prefix-descriptions)
+ nil)
+ ((stringp (nth 1 x)) x)
+ ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
+ (t (cons (car x) (cons "" (cdr x))))))
+ org-agenda-custom-commands)))
+ (org-agenda-custom-commands
+ (org-contextualize-keys
+ org-agenda-custom-commands org-agenda-custom-commands-contexts))
+ (buf (current-buffer))
+ (bfn (buffer-file-name (buffer-base-buffer)))
+ entry key type org-match lprops ans)
+ ;; Turn off restriction unless there is an overriding one,
+ (unless org-agenda-overriding-restriction
+ (unless org-agenda-keep-restricted-file-list
+ ;; There is a request to keep the file list in place
+ (put 'org-agenda-files 'org-restrict nil))
+ (setq org-agenda-restrict nil)
+ (move-marker org-agenda-restrict-begin nil)
+ (move-marker org-agenda-restrict-end nil))
+ ;; Delete old local properties
+ (put 'org-agenda-redo-command 'org-lprops nil)
+ ;; Delete previously set last-arguments
+ (put 'org-agenda-redo-command 'last-args nil)
+ ;; Remember where this call originated
+ (setq org-agenda-last-dispatch-buffer (current-buffer))
+ (unless org-keys
+ (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
+ org-keys (car ans)
+ restriction (cdr ans)))
+ ;; If we have sticky agenda buffers, set a name for the buffer,
+ ;; depending on the invoking keys. The user may still set this
+ ;; as a command option, which will overwrite what we do here.
+ (if org-agenda-sticky
+ (setq org-agenda-buffer-name
+ (format "*Org Agenda(%s)*" org-keys)))
+ ;; Establish the restriction, if any
+ (when (and (not org-agenda-overriding-restriction) restriction)
+ (put 'org-agenda-files 'org-restrict (list bfn))
+ (cond
+ ((eq restriction 'region)
+ (setq org-agenda-restrict (current-buffer))
+ (move-marker org-agenda-restrict-begin (region-beginning))
+ (move-marker org-agenda-restrict-end (region-end)))
+ ((eq restriction 'subtree)
+ (save-excursion
+ (setq org-agenda-restrict (current-buffer))
+ (org-back-to-heading t)
+ (move-marker org-agenda-restrict-begin (point))
+ (move-marker org-agenda-restrict-end
+ (progn (org-end-of-subtree t)))))))
+
+ ;; For example the todo list should not need it (but does...)
+ (cond
+ ((setq entry (assoc org-keys org-agenda-custom-commands))
+ (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
+ (progn
+ (setq type (nth 2 entry) org-match (eval (nth 3 entry))
+ lprops (nth 4 entry))
+ (if org-agenda-sticky
+ (setq org-agenda-buffer-name
+ (or (and (stringp org-match) (format "*Org Agenda(%s:%s)*" org-keys org-match))
+ (format "*Org Agenda(%s)*" org-keys))))
+ (put 'org-agenda-redo-command 'org-lprops lprops)
+ (cond
+ ((eq type 'agenda)
+ (org-let lprops '(org-agenda-list current-prefix-arg)))
+ ((eq type 'agenda*)
+ (org-let lprops '(org-agenda-list current-prefix-arg nil nil t)))
+ ((eq type 'alltodo)
+ (org-let lprops '(org-todo-list current-prefix-arg)))
+ ((eq type 'search)
+ (org-let lprops '(org-search-view current-prefix-arg org-match nil)))
+ ((eq type 'stuck)
+ (org-let lprops '(org-agenda-list-stuck-projects
+ current-prefix-arg)))
+ ((eq type 'tags)
+ (org-let lprops '(org-tags-view current-prefix-arg org-match)))
+ ((eq type 'tags-todo)
+ (org-let lprops '(org-tags-view '(4) org-match)))
+ ((eq type 'todo)
+ (org-let lprops '(org-todo-list org-match)))
+ ((eq type 'tags-tree)
+ (org-check-for-org-mode)
+ (org-let lprops '(org-match-sparse-tree current-prefix-arg org-match)))
+ ((eq type 'todo-tree)
+ (org-check-for-org-mode)
+ (org-let lprops
+ '(org-occur (concat "^" org-outline-regexp "[ \t]*"
+ (regexp-quote org-match) "\\>"))))
+ ((eq type 'occur-tree)
+ (org-check-for-org-mode)
+ (org-let lprops '(org-occur org-match)))
+ ((functionp type)
+ (org-let lprops '(funcall type org-match)))
+ ((fboundp type)
+ (org-let lprops '(funcall type org-match)))
+ (t (user-error "Invalid custom agenda command type %s" type))))
+ (org-agenda-run-series (nth 1 entry) (cddr entry))))
+ ((equal org-keys "C")
+ (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
+ (customize-variable 'org-agenda-custom-commands))
+ ((equal org-keys "a") (call-interactively 'org-agenda-list))
+ ((equal org-keys "s") (call-interactively 'org-search-view))
+ ((equal org-keys "S") (org-call-with-arg 'org-search-view (or arg '(4))))
+ ((equal org-keys "t") (call-interactively 'org-todo-list))
+ ((equal org-keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
+ ((equal org-keys "m") (call-interactively 'org-tags-view))
+ ((equal org-keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
+ ((equal org-keys "e") (call-interactively 'org-store-agenda-views))
+ ((equal org-keys "?") (org-tags-view nil "+FLAGGED")
+ (add-hook
+ 'post-command-hook
+ (lambda ()
+ (unless (current-message)
+ (let* ((m (org-agenda-get-any-marker))
+ (note (and m (org-entry-get m "THEFLAGGINGNOTE"))))
+ (when note
+ (message (concat
+ "FLAGGING-NOTE ([?] for more info): "
+ (org-add-props
+ (replace-regexp-in-string
+ "\\\\n" "//"
+ (copy-sequence note))
+ nil 'face 'org-warning)))))))
+ t t))
+ ((equal org-keys "L")
+ (unless (derived-mode-p 'org-mode)
+ (user-error "This is not an Org file"))
+ (unless restriction
+ (put 'org-agenda-files 'org-restrict (list bfn))
+ (org-call-with-arg 'org-timeline arg)))
+ ((equal org-keys "#") (call-interactively 'org-agenda-list-stuck-projects))
+ ((equal org-keys "/") (call-interactively 'org-occur-in-agenda-files))
+ ((equal org-keys "!") (customize-variable 'org-stuck-projects))
+ (t (user-error "Invalid agenda key"))))))
+
+(defvar org-agenda-multi)
+
+(defun org-agenda-append-agenda ()
+ "Append another agenda view to the current one.
+This function allows interactive building of block agendas.
+Agenda views are separated by `org-agenda-block-separator'."
+ (interactive)
+ (unless (derived-mode-p 'org-agenda-mode)
+ (user-error "Can only append from within agenda buffer"))
+ (let ((org-agenda-multi t))
+ (org-agenda)
+ (widen)
+ (org-agenda-finalize)
+ (setq buffer-read-only t)
+ (org-agenda-fit-window-to-buffer)))
+
+(defun org-agenda-normalize-custom-commands (cmds)
+ "Normalize custom commands CMDS."
+ (delq nil
+ (mapcar
+ (lambda (x)
+ (cond ((stringp (cdr x)) nil)
+ ((stringp (nth 1 x)) x)
+ ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
+ (t (cons (car x) (cons "" (cdr x))))))
+ cmds)))
+
+(defun org-agenda-get-restriction-and-command (prefix-descriptions)
+ "The user interface for selecting an agenda command."
+ (catch 'exit
+ (let* ((bfn (buffer-file-name (buffer-base-buffer)))
+ (restrict-ok (and bfn (derived-mode-p 'org-mode)))
+ (region-p (org-region-active-p))
+ (custom org-agenda-custom-commands)
+ (selstring "")
+ restriction second-time
+ c entry key type match prefixes rmheader header-end custom1 desc
+ line lines left right n n1)
+ (save-window-excursion
+ (delete-other-windows)
+ (org-switch-to-buffer-other-window " *Agenda Commands*")
+ (erase-buffer)
+ (insert (eval-when-compile
+ (let ((header
+ "Press key for an agenda command: < Buffer, subtree/region restriction
+-------------------------------- > Remove restriction
+a Agenda for current week or day e Export agenda views
+t List of all TODO entries T Entries with special TODO kwd
+m Match a TAGS/PROP/TODO query M Like m, but only TODO entries
+s Search for keywords S Like s, but only TODO entries
+L Timeline for current buffer # List stuck projects (!=configure)
+/ Multi-occur C Configure custom agenda commands
+? Find :FLAGGED: entries * Toggle sticky agenda views
+")
+ (start 0))
+ (while (string-match
+ "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
+ header start)
+ (setq start (match-end 0))
+ (add-text-properties (match-beginning 2) (match-end 2)
+ '(face bold) header))
+ header)))
+ (setq header-end (point-marker))
+ (while t
+ (setq custom1 custom)
+ (when (eq rmheader t)
+ (org-goto-line 1)
+ (re-search-forward ":" nil t)
+ (delete-region (match-end 0) (point-at-eol))
+ (forward-char 1)
+ (looking-at "-+")
+ (delete-region (match-end 0) (point-at-eol))
+ (move-marker header-end (match-end 0)))
+ (goto-char header-end)
+ (delete-region (point) (point-max))
+
+ ;; Produce all the lines that describe custom commands and prefixes
+ (setq lines nil)
+ (while (setq entry (pop custom1))
+ (setq key (car entry) desc (nth 1 entry)
+ type (nth 2 entry)
+ match (nth 3 entry))
+ (if (> (length key) 1)
+ (cl-pushnew (string-to-char key) prefixes :test #'equal)
+ (setq line
+ (format
+ "%-4s%-14s"
+ (org-add-props (copy-sequence key)
+ '(face bold))
+ (cond
+ ((string-match "\\S-" desc) desc)
+ ((eq type 'agenda) "Agenda for current week or day")
+ ((eq type 'agenda*) "Appointments for current week or day")
+ ((eq type 'alltodo) "List of all TODO entries")
+ ((eq type 'search) "Word search")
+ ((eq type 'stuck) "List of stuck projects")
+ ((eq type 'todo) "TODO keyword")
+ ((eq type 'tags) "Tags query")
+ ((eq type 'tags-todo) "Tags (TODO)")
+ ((eq type 'tags-tree) "Tags tree")
+ ((eq type 'todo-tree) "TODO kwd tree")
+ ((eq type 'occur-tree) "Occur tree")
+ ((functionp type) (if (symbolp type)
+ (symbol-name type)
+ "Lambda expression"))
+ (t "???"))))
+ (if org-agenda-menu-show-matcher
+ (setq line
+ (concat line ": "
+ (cond
+ ((stringp match)
+ (setq match (copy-sequence match))
+ (org-add-props match nil 'face 'org-warning))
+ ((listp type)
+ (format "set of %d commands" (length type))))))
+ (if (org-string-nw-p match)
+ (add-text-properties
+ 0 (length line) (list 'help-echo
+ (concat "Matcher: " match)) line)))
+ (push line lines)))
+ (setq lines (nreverse lines))
+ (when prefixes
+ (mapc (lambda (x)
+ (push
+ (format "%s %s"
+ (org-add-props (char-to-string x)
+ nil 'face 'bold)
+ (or (cdr (assoc (concat selstring
+ (char-to-string x))
+ prefix-descriptions))
+ "Prefix key"))
+ lines))
+ prefixes))
+
+ ;; Check if we should display in two columns
+ (if org-agenda-menu-two-columns
+ (progn
+ (setq n (length lines)
+ n1 (+ (/ n 2) (mod n 2))
+ right (nthcdr n1 lines)
+ left (copy-sequence lines))
+ (setcdr (nthcdr (1- n1) left) nil))
+ (setq left lines right nil))
+ (while left
+ (insert "\n" (pop left))
+ (when right
+ (if (< (current-column) 40)
+ (move-to-column 40 t)
+ (insert " "))
+ (insert (pop right))))
+
+ ;; Make the window the right size
+ (goto-char (point-min))
+ (if second-time
+ (if (not (pos-visible-in-window-p (point-max)))
+ (org-fit-window-to-buffer))
+ (setq second-time t)
+ (org-fit-window-to-buffer))
+
+ ;; Ask for selection
+ (message "Press key for agenda command%s:"
+ (if (or restrict-ok org-agenda-overriding-restriction)
+ (if org-agenda-overriding-restriction
+ " (restriction lock active)"
+ (if restriction
+ (format " (restricted to %s)" restriction)
+ " (unrestricted)"))
+ ""))
+ (setq c (read-char-exclusive))
+ (message "")
+ (cond
+ ((assoc (char-to-string c) custom)
+ (setq selstring (concat selstring (char-to-string c)))
+ (throw 'exit (cons selstring restriction)))
+ ((memq c prefixes)
+ (setq selstring (concat selstring (char-to-string c))
+ prefixes nil
+ rmheader (or rmheader t)
+ custom (delq nil (mapcar
+ (lambda (x)
+ (if (or (= (length (car x)) 1)
+ (/= (string-to-char (car x)) c))
+ nil
+ (cons (substring (car x) 1) (cdr x))))
+ custom))))
+ ((eq c ?*)
+ (call-interactively 'org-toggle-sticky-agenda)
+ (sit-for 2))
+ ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
+ (message "Restriction is only possible in Org buffers")
+ (ding) (sit-for 1))
+ ((eq c ?1)
+ (org-agenda-remove-restriction-lock 'noupdate)
+ (setq restriction 'buffer))
+ ((eq c ?0)
+ (org-agenda-remove-restriction-lock 'noupdate)
+ (setq restriction (if region-p 'region 'subtree)))
+ ((eq c ?<)
+ (org-agenda-remove-restriction-lock 'noupdate)
+ (setq restriction
+ (cond
+ ((eq restriction 'buffer)
+ (if region-p 'region 'subtree))
+ ((memq restriction '(subtree region))
+ nil)
+ (t 'buffer))))
+ ((eq c ?>)
+ (org-agenda-remove-restriction-lock 'noupdate)
+ (setq restriction nil))
+ ((and (equal selstring "") (memq c '(?s ?S ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/ ??)))
+ (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
+ ((and (> (length selstring) 0) (eq c ?\d))
+ (delete-window)
+ (org-agenda-get-restriction-and-command prefix-descriptions))
+
+ ((equal c ?q) (error "Abort"))
+ (t (user-error "Invalid key %c" c))))))))
+
+(defun org-agenda-fit-window-to-buffer ()
+ "Fit the window to the buffer size."
+ (and (memq org-agenda-window-setup '(reorganize-frame))
+ (fboundp 'fit-window-to-buffer)
+ (if (and (= (cdr org-agenda-window-frame-fractions) 1.0)
+ (= (car org-agenda-window-frame-fractions) 1.0))
+ (delete-other-windows)
+ (org-fit-window-to-buffer
+ nil
+ (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
+ (floor (* (frame-height) (car org-agenda-window-frame-fractions)))))))
+
+(defvar org-cmd nil)
+(defvar org-agenda-overriding-cmd nil)
+(defvar org-agenda-overriding-arguments nil)
+(defvar org-agenda-overriding-cmd-arguments nil)
+(defun org-agenda-run-series (name series)
+ "Run agenda NAME as a SERIES of agenda commands."
+ (org-let (nth 1 series) '(org-agenda-prepare name))
+ ;; We need to reset agenda markers here, because when constructing a
+ ;; block agenda, the individual blocks do not do that.
+ (org-agenda-reset-markers)
+ (let* ((org-agenda-multi t)
+ (redo (list 'org-agenda-run-series name (list 'quote series)))
+ (cmds (car series))
+ (gprops (nth 1 series))
+ match ;; The byte compiler incorrectly complains about this. Keep it!
+ org-cmd type lprops)
+ (while (setq org-cmd (pop cmds))
+ (setq type (car org-cmd))
+ (setq match (eval (nth 1 org-cmd)))
+ (setq lprops (nth 2 org-cmd))
+ (let ((org-agenda-overriding-arguments
+ (if (eq org-agenda-overriding-cmd org-cmd)
+ (or org-agenda-overriding-arguments
+ org-agenda-overriding-cmd-arguments))))
+ (cond
+ ((eq type 'agenda)
+ (org-let2 gprops lprops
+ '(call-interactively 'org-agenda-list)))
+ ((eq type 'agenda*)
+ (org-let2 gprops lprops
+ '(funcall 'org-agenda-list nil nil t)))
+ ((eq type 'alltodo)
+ (org-let2 gprops lprops
+ '(call-interactively 'org-todo-list)))
+ ((eq type 'search)
+ (org-let2 gprops lprops
+ '(org-search-view current-prefix-arg match nil)))
+ ((eq type 'stuck)
+ (org-let2 gprops lprops
+ '(call-interactively 'org-agenda-list-stuck-projects)))
+ ((eq type 'tags)
+ (org-let2 gprops lprops
+ '(org-tags-view current-prefix-arg match)))
+ ((eq type 'tags-todo)
+ (org-let2 gprops lprops
+ '(org-tags-view '(4) match)))
+ ((eq type 'todo)
+ (org-let2 gprops lprops
+ '(org-todo-list match)))
+ ((fboundp type)
+ (org-let2 gprops lprops
+ '(funcall type match)))
+ (t (error "Invalid type in command series")))))
+ (widen)
+ (let ((inhibit-read-only t))
+ (add-text-properties (point-min) (point-max)
+ `(org-series t org-series-redo-cmd ,redo)))
+ (setq org-agenda-redo-command redo)
+ (goto-char (point-min)))
+ (org-agenda-fit-window-to-buffer)
+ (org-let (nth 1 series) '(org-agenda-finalize)))
+
+;;;###autoload
+(defmacro org-batch-agenda (cmd-key &rest parameters)
+ "Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command. If it is a
+longer string it is used as a tags/todo match string.
+Parameters are alternating variable names and values that will be bound
+before running the agenda command."
+ (org-eval-in-environment (org-make-parameter-alist parameters)
+ (let (org-agenda-sticky)
+ (if (> (length cmd-key) 1)
+ (org-tags-view nil cmd-key)
+ (org-agenda nil cmd-key))))
+ (set-buffer org-agenda-buffer-name)
+ (princ (buffer-string)))
+
+(defvar org-agenda-info nil)
+
+;;;###autoload
+(defmacro org-batch-agenda-csv (cmd-key &rest parameters)
+ "Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command. If it is a
+longer string it is used as a tags/todo match string.
+Parameters are alternating variable names and values that will be bound
+before running the agenda command.
+
+The output gives a line for each selected agenda item. Each
+item is a list of comma-separated values, like this:
+
+category,head,type,todo,tags,date,time,extra,priority-l,priority-n
+
+category The category of the item
+head The headline, without TODO kwd, TAGS and PRIORITY
+type The type of the agenda entry, can be
+ todo selected in TODO match
+ tagsmatch selected in tags match
+ diary imported from diary
+ deadline a deadline on given date
+ scheduled scheduled on given date
+ timestamp entry has timestamp on given date
+ closed entry was closed on given date
+ upcoming-deadline warning about deadline
+ past-scheduled forwarded scheduled item
+ block entry has date block including g. date
+todo The todo keyword, if any
+tags All tags including inherited ones, separated by colons
+date The relevant date, like 2007-2-14
+time The time, like 15:00-16:50
+extra Sting with extra planning info
+priority-l The priority letter if any was given
+priority-n The computed numerical priority
+agenda-day The day in the agenda where this is listed"
+ (org-eval-in-environment (append '((org-agenda-remove-tags t))
+ (org-make-parameter-alist parameters))
+ (if (> (length cmd-key) 2)
+ (org-tags-view nil cmd-key)
+ (org-agenda nil cmd-key)))
+ (set-buffer org-agenda-buffer-name)
+ (let* ((lines (org-split-string (buffer-string) "\n"))
+ line)
+ (while (setq line (pop lines))
+ (catch 'next
+ (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
+ (setq org-agenda-info
+ (org-fix-agenda-info (text-properties-at 0 line)))
+ (princ
+ (mapconcat 'org-agenda-export-csv-mapper
+ '(org-category txt type todo tags date time extra
+ priority-letter priority agenda-day)
+ ","))
+ (princ "\n")))))
+
+(defun org-fix-agenda-info (props)
+ "Make sure all properties on an agenda item have a canonical form.
+This ensures the export commands can easily use it."
+ (let (tmp re)
+ (when (setq tmp (plist-get props 'tags))
+ (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
+ (when (setq tmp (plist-get props 'date))
+ (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
+ (let ((calendar-date-display-form '(year "-" month "-" day)))
+ '((format "%4d, %9s %2s, %4s" dayname monthname day year))
+
+ (setq tmp (calendar-date-string tmp)))
+ (setq props (plist-put props 'date tmp)))
+ (when (setq tmp (plist-get props 'day))
+ (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
+ (let ((calendar-date-display-form '(year "-" month "-" day)))
+ (setq tmp (calendar-date-string tmp)))
+ (setq props (plist-put props 'day tmp))
+ (setq props (plist-put props 'agenda-day tmp)))
+ (when (setq tmp (plist-get props 'txt))
+ (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
+ (plist-put props 'priority-letter (match-string 1 tmp))
+ (setq tmp (replace-match "" t t tmp)))
+ (when (and (setq re (plist-get props 'org-todo-regexp))
+ (setq re (concat "\\`\\.*" re " ?"))
+ (let ((case-fold-search nil)) (string-match re tmp)))
+ (plist-put props 'todo (match-string 1 tmp))
+ (setq tmp (replace-match "" t t tmp)))
+ (plist-put props 'txt tmp)))
+ props)
+
+(defun org-agenda-export-csv-mapper (prop)
+ (let ((res (plist-get org-agenda-info prop)))
+ (setq res
+ (cond
+ ((not res) "")
+ ((stringp res) res)
+ (t (prin1-to-string res))))
+ (org-trim (replace-regexp-in-string "," ";" res nil t))))
+
+;;;###autoload
+(defun org-store-agenda-views (&rest parameters)
+ "Store agenda views."
+ (interactive)
+ (eval (list 'org-batch-store-agenda-views)))
+
+;;;###autoload
+(defmacro org-batch-store-agenda-views (&rest parameters)
+ "Run all custom agenda commands that have a file argument."
+ (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
+ (pop-up-frames nil)
+ (dir default-directory)
+ (pars (org-make-parameter-alist parameters))
+ cmd thiscmdkey thiscmdcmd match files opts cmd-or-set bufname)
+ (save-window-excursion
+ (while cmds
+ (setq cmd (pop cmds)
+ thiscmdkey (car cmd)
+ thiscmdcmd (cdr cmd)
+ match (nth 2 thiscmdcmd)
+ bufname (if org-agenda-sticky
+ (or (and (stringp match)
+ (format "*Org Agenda(%s:%s)*" thiscmdkey match))
+ (format "*Org Agenda(%s)*" thiscmdkey))
+ org-agenda-buffer-name)
+ cmd-or-set (nth 2 cmd)
+ opts (nth (if (listp cmd-or-set) 3 4) cmd)
+ files (nth (if (listp cmd-or-set) 4 5) cmd))
+ (if (stringp files) (setq files (list files)))
+ (when files
+ (org-eval-in-environment (append org-agenda-exporter-settings
+ opts pars)
+ (org-agenda nil thiscmdkey))
+ (set-buffer bufname)
+ (while files
+ (org-eval-in-environment (append org-agenda-exporter-settings
+ opts pars)
+ (org-agenda-write (expand-file-name (pop files) dir) nil t bufname)))
+ (and (get-buffer bufname)
+ (kill-buffer bufname)))))))
+
+(defvar org-agenda-current-span nil
+ "The current span used in the agenda view.") ; local variable in the agenda buffer
+(defun org-agenda-mark-header-line (pos)
+ "Mark the line at POS as an agenda structure header."
+ (save-excursion
+ (goto-char pos)
+ (put-text-property (point-at-bol) (point-at-eol)
+ 'org-agenda-structural-header t)
+ (when org-agenda-title-append
+ (put-text-property (point-at-bol) (point-at-eol)
+ 'org-agenda-title-append org-agenda-title-append))))
+
+(defvar org-mobile-creating-agendas) ; defined in org-mobile.el
+(defvar org-agenda-write-buffer-name "Agenda View")
+(defun org-agenda-write (file &optional open nosettings agenda-bufname)
+ "Write the current buffer (an agenda view) as a file.
+
+Depending on the extension of the file name, plain text (.txt),
+HTML (.html or .htm), PDF (.pdf) or Postscript (.ps) is produced.
+If the extension is .ics, translate visible agenda into iCalendar
+format. If the extension is .org, collect all subtrees
+corresponding to the agenda entries and add them in an .org file.
+
+With prefix argument OPEN, open the new file immediately. If
+NOSETTINGS is given, do not scope the settings of
+`org-agenda-exporter-settings' into the export commands. This is
+used when the settings have already been scoped and we do not
+wish to overrule other, higher priority settings. If
+AGENDA-BUFFER-NAME is provided, use this as the buffer name for
+the agenda to write."
+ (interactive "FWrite agenda to file: \nP")
+ (if (or (not (file-writable-p file))
+ (and (file-exists-p file)
+ (if (called-interactively-p 'any)
+ (not (y-or-n-p (format "Overwrite existing file %s? " file))))))
+ (user-error "Cannot write agenda to file %s" file))
+ (org-let (if nosettings nil org-agenda-exporter-settings)
+ '(save-excursion
+ (save-window-excursion
+ (let ((bs (copy-sequence (buffer-string)))
+ (extension (file-name-extension file))
+ beg content)
+ (with-temp-buffer
+ (rename-buffer org-agenda-write-buffer-name t)
+ (set-buffer-modified-p nil)
+ (insert bs)
+ (org-agenda-remove-marked-text 'invisible 'org-filtered)
+ (run-hooks 'org-agenda-before-write-hook)
+ (cond
+ ((bound-and-true-p org-mobile-creating-agendas)
+ (org-mobile-write-agenda-for-mobile file))
+ ((string= "org" extension)
+ (let (content p m message-log-max)
+ (goto-char (point-min))
+ (while (setq p (next-single-property-change (point) 'org-hd-marker nil))
+ (goto-char p)
+ (setq m (get-text-property (point) 'org-hd-marker))
+ (when m
+ (push (save-excursion
+ (set-buffer (marker-buffer m))
+ (goto-char m)
+ (org-copy-subtree 1 nil t t)
+ org-subtree-clip)
+ content)))
+ (find-file file)
+ (erase-buffer)
+ (dolist (s content) (org-paste-subtree 1 s))
+ (write-file file)
+ (kill-buffer (current-buffer))
+ (message "Org file written to %s" file)))
+ ((member extension '("html" "htm"))
+ (require 'htmlize)
+ (set-buffer (htmlize-buffer (current-buffer)))
+ (when org-agenda-export-html-style
+ ;; replace <style> section with org-agenda-export-html-style
+ (goto-char (point-min))
+ (kill-region (- (search-forward "<style") 6)
+ (search-forward "</style>"))
+ (insert org-agenda-export-html-style))
+ (write-file file)
+ (kill-buffer (current-buffer))
+ (message "HTML written to %s" file))
+ ((string= "ps" extension)
+ (require 'ps-print)
+ (ps-print-buffer-with-faces file)
+ (message "Postscript written to %s" file))
+ ((string= "pdf" extension)
+ (require 'ps-print)
+ (ps-print-buffer-with-faces
+ (concat (file-name-sans-extension file) ".ps"))
+ (call-process "ps2pdf" nil nil nil
+ (expand-file-name
+ (concat (file-name-sans-extension file) ".ps"))
+ (expand-file-name file))
+ (delete-file (concat (file-name-sans-extension file) ".ps"))
+ (message "PDF written to %s" file))
+ ((string= "ics" extension)
+ (require 'ox-icalendar)
+ (org-icalendar-export-current-agenda (expand-file-name file)))
+ (t
+ (let ((bs (buffer-string)))
+ (find-file file)
+ (erase-buffer)
+ (insert bs)
+ (save-buffer 0)
+ (kill-buffer (current-buffer))
+ (message "Plain text written to %s" file))))))))
+ (set-buffer (or agenda-bufname
+ (and (called-interactively-p 'any) (buffer-name))
+ org-agenda-buffer-name)))
+ (when open (org-open-file file)))
+
+(defun org-agenda-remove-marked-text (property &optional value)
+ "Delete all text marked with VALUE of PROPERTY.
+VALUE defaults to t."
+ (let (beg)
+ (setq value (or value t))
+ (while (setq beg (text-property-any (point-min) (point-max)
+ property value))
+ (delete-region
+ beg (or (next-single-property-change beg property)
+ (point-max))))))
+
+(defun org-agenda-add-entry-text ()
+ "Add entry text to agenda lines.
+This will add a maximum of `org-agenda-add-entry-text-maxlines' lines of the
+entry text following headings shown in the agenda.
+Drawers will be excluded, also the line with scheduling/deadline info."
+ (when (and (> org-agenda-add-entry-text-maxlines 0)
+ (not (bound-and-true-p org-mobile-creating-agendas)))
+ (let (m txt)
+ (goto-char (point-min))
+ (while (not (eobp))
+ (if (not (setq m (org-get-at-bol 'org-hd-marker)))
+ (beginning-of-line 2)
+ (setq txt (org-agenda-get-some-entry-text
+ m org-agenda-add-entry-text-maxlines " > "))
+ (end-of-line 1)
+ (if (string-match "\\S-" txt)
+ (insert "\n" txt)
+ (or (eobp) (forward-char 1))))))))
+
+(defun org-agenda-get-some-entry-text (marker n-lines &optional indent
+ &rest keep)
+ "Extract entry text from MARKER, at most N-LINES lines.
+This will ignore drawers etc, just get the text.
+If INDENT is given, prefix every line with this string. If KEEP is
+given, it is a list of symbols, defining stuff that should not be
+removed from the entry content. Currently only `planning' is allowed here."
+ (let (txt drawer-re kwd-time-re ind)
+ (save-excursion
+ (with-current-buffer (marker-buffer marker)
+ (if (not (derived-mode-p 'org-mode))
+ (setq txt "")
+ (org-with-wide-buffer
+ (goto-char marker)
+ (end-of-line 1)
+ (setq txt (buffer-substring
+ (min (1+ (point)) (point-max))
+ (progn (outline-next-heading) (point)))
+ drawer-re org-drawer-regexp
+ kwd-time-re (concat "^[ \t]*" org-keyword-time-regexp
+ ".*\n?"))
+ (with-temp-buffer
+ (insert txt)
+ (when org-agenda-add-entry-text-descriptive-links
+ (goto-char (point-min))
+ (while (org-activate-links (point-max))
+ (add-text-properties (match-beginning 0) (match-end 0)
+ '(face org-link))))
+ (goto-char (point-min))
+ (while (re-search-forward org-bracket-link-regexp (point-max) t)
+ (set-text-properties (match-beginning 0) (match-end 0)
+ nil))
+ (goto-char (point-min))
+ (while (re-search-forward drawer-re nil t)
+ (delete-region
+ (match-beginning 0)
+ (progn (re-search-forward
+ "^[ \t]*:END:.*\n?" nil 'move)
+ (point))))
+ (unless (member 'planning keep)
+ (goto-char (point-min))
+ (while (re-search-forward kwd-time-re nil t)
+ (replace-match "")))
+ (goto-char (point-min))
+ (when org-agenda-entry-text-exclude-regexps
+ (let ((re-list org-agenda-entry-text-exclude-regexps) re)
+ (while (setq re (pop re-list))
+ (goto-char (point-min))
+ (while (re-search-forward re nil t)
+ (replace-match "")))))
+ (goto-char (point-max))
+ (skip-chars-backward " \t\n")
+ (if (looking-at "[ \t\n]+\\'") (replace-match ""))
+
+ ;; find and remove min common indentation
+ (goto-char (point-min))
+ (untabify (point-min) (point-max))
+ (setq ind (org-get-indentation))
+ (while (not (eobp))
+ (unless (looking-at "[ \t]*$")
+ (setq ind (min ind (org-get-indentation))))
+ (beginning-of-line 2))
+ (goto-char (point-min))
+ (while (not (eobp))
+ (unless (looking-at "[ \t]*$")
+ (move-to-column ind)
+ (delete-region (point-at-bol) (point)))
+ (beginning-of-line 2))
+
+ (run-hooks 'org-agenda-entry-text-cleanup-hook)
+
+ (goto-char (point-min))
+ (when indent
+ (while (and (not (eobp)) (re-search-forward "^" nil t))
+ (replace-match indent t t)))
+ (goto-char (point-min))
+ (while (looking-at "[ \t]*\n") (replace-match ""))
+ (goto-char (point-max))
+ (when (> (org-current-line)
+ n-lines)
+ (org-goto-line (1+ n-lines))
+ (backward-char 1))
+ (setq txt (buffer-substring (point-min) (point))))))))
+ txt))
+
+(defun org-check-for-org-mode ()
+ "Make sure current buffer is in org-mode. Error if not."
+ (or (derived-mode-p 'org-mode)
+ (error "Cannot execute Org agenda command on buffer in %s"
+ major-mode)))
+
+;;; Agenda prepare and finalize
+
+(defvar org-agenda-multi nil) ; dynamically scoped
+(defvar org-agenda-pre-window-conf nil)
+(defvar org-agenda-columns-active nil)
+(defvar org-agenda-name nil)
+(defvar org-agenda-tag-filter nil)
+(defvar org-agenda-category-filter nil)
+(defvar org-agenda-regexp-filter nil)
+(defvar org-agenda-effort-filter nil)
+(defvar org-agenda-top-headline-filter nil)
+(defvar org-agenda-tag-filter-preset nil
+ "A preset of the tags filter used for secondary agenda filtering.
+This must be a list of strings, each string must be a single tag preceded
+by \"+\" or \"-\".
+This variable should not be set directly, but agenda custom commands can
+bind it in the options section. The preset filter is a global property of
+the entire agenda view. In a block agenda, it will not work reliably to
+define a filter for one of the individual blocks. You need to set it in
+the global options and expect it to be applied to the entire view.")
+
+(defvar org-agenda-category-filter-preset nil
+ "A preset of the category filter used for secondary agenda filtering.
+This must be a list of strings, each string must be a single category
+preceded by \"+\" or \"-\".
+This variable should not be set directly, but agenda custom commands can
+bind it in the options section. The preset filter is a global property of
+the entire agenda view. In a block agenda, it will not work reliably to
+define a filter for one of the individual blocks. You need to set it in
+the global options and expect it to be applied to the entire view.")
+
+(defvar org-agenda-regexp-filter-preset nil
+ "A preset of the regexp filter used for secondary agenda filtering.
+This must be a list of strings, each string must be a single regexp
+preceded by \"+\" or \"-\".
+This variable should not be set directly, but agenda custom commands can
+bind it in the options section. The preset filter is a global property of
+the entire agenda view. In a block agenda, it will not work reliably to
+define a filter for one of the individual blocks. You need to set it in
+the global options and expect it to be applied to the entire view.")
+
+(defvar org-agenda-effort-filter-preset nil
+ "A preset of the effort condition used for secondary agenda filtering.
+This must be a list of strings, each string must be a single regexp
+preceded by \"+\" or \"-\".
+This variable should not be set directly, but agenda custom commands can
+bind it in the options section. The preset filter is a global property of
+the entire agenda view. In a block agenda, it will not work reliably to
+define a filter for one of the individual blocks. You need to set it in
+the global options and expect it to be applied to the entire view.")
+
+(defun org-agenda-use-sticky-p ()
+ "Return non-nil if an agenda buffer named
+`org-agenda-buffer-name' exists and should be shown instead of
+generating a new one."
+ (and
+ ;; turned off by user
+ org-agenda-sticky
+ ;; For multi-agenda buffer already exists
+ (not org-agenda-multi)
+ ;; buffer found
+ (get-buffer org-agenda-buffer-name)
+ ;; C-u parameter is same as last call
+ (with-current-buffer (get-buffer org-agenda-buffer-name)
+ (and
+ (equal current-prefix-arg
+ org-agenda-last-prefix-arg)
+ ;; In case user turned stickiness on, while having existing
+ ;; Agenda buffer active, don't reuse that buffer, because it
+ ;; does not have org variables local
+ org-agenda-this-buffer-is-sticky))))
+
+(defun org-agenda-prepare-window (abuf filter-alist)
+ "Setup agenda buffer in the window.
+ABUF is the buffer for the agenda window.
+FILTER-ALIST is an alist of filters we need to apply when
+`org-agenda-persistent-filter' is non-nil."
+ (let* ((awin (get-buffer-window abuf)) wconf)
+ (cond
+ ((equal (current-buffer) abuf) nil)
+ (awin (select-window awin))
+ ((not (setq wconf (current-window-configuration))))
+ ((eq org-agenda-window-setup 'current-window)
+ (pop-to-buffer-same-window abuf))
+ ((eq org-agenda-window-setup 'other-window)
+ (org-switch-to-buffer-other-window abuf))
+ ((eq org-agenda-window-setup 'other-frame)
+ (switch-to-buffer-other-frame abuf))
+ ((eq org-agenda-window-setup 'only-window)
+ (delete-other-windows)
+ (pop-to-buffer-same-window abuf))
+ ((eq org-agenda-window-setup 'reorganize-frame)
+ (delete-other-windows)
+ (org-switch-to-buffer-other-window abuf)))
+ (setq org-agenda-tag-filter (cdr (assq 'tag filter-alist)))
+ (setq org-agenda-category-filter (cdr (assq 'cat filter-alist)))
+ (setq org-agenda-effort-filter (cdr (assq 'effort filter-alist)))
+ (setq org-agenda-regexp-filter (cdr (assq 're filter-alist)))
+ ;; Additional test in case agenda is invoked from within agenda
+ ;; buffer via elisp link.
+ (unless (equal (current-buffer) abuf)
+ (pop-to-buffer-same-window abuf))
+ (setq org-agenda-pre-window-conf
+ (or wconf org-agenda-pre-window-conf))))
+
+(defun org-agenda-prepare (&optional name)
+ (let ((filter-alist (if org-agenda-persistent-filter
+ (with-current-buffer
+ (get-buffer-create org-agenda-buffer-name)
+ (list `(tag . ,org-agenda-tag-filter)
+ `(re . ,org-agenda-regexp-filter)
+ `(effort . ,org-agenda-effort-filter)
+ `(cat . ,org-agenda-category-filter))))))
+ (if (org-agenda-use-sticky-p)
+ (progn
+ (put 'org-agenda-tag-filter :preset-filter nil)
+ (put 'org-agenda-category-filter :preset-filter nil)
+ (put 'org-agenda-regexp-filter :preset-filter nil)
+ ;; Popup existing buffer
+ (org-agenda-prepare-window (get-buffer org-agenda-buffer-name)
+ filter-alist)
+ (message "Sticky Agenda buffer, use `r' to refresh")
+ (or org-agenda-multi (org-agenda-fit-window-to-buffer))
+ (throw 'exit "Sticky Agenda buffer, use `r' to refresh"))
+ (setq org-todo-keywords-for-agenda nil)
+ (put 'org-agenda-tag-filter :preset-filter
+ org-agenda-tag-filter-preset)
+ (put 'org-agenda-category-filter :preset-filter
+ org-agenda-category-filter-preset)
+ (put 'org-agenda-regexp-filter :preset-filter
+ org-agenda-regexp-filter-preset)
+ (put 'org-agenda-effort-filter :preset-filter
+ org-agenda-effort-filter-preset)
+ (if org-agenda-multi
+ (progn
+ (setq buffer-read-only nil)
+ (goto-char (point-max))
+ (unless (or (bobp) org-agenda-compact-blocks
+ (not org-agenda-block-separator))
+ (insert "\n"
+ (if (stringp org-agenda-block-separator)
+ org-agenda-block-separator
+ (make-string (window-width) org-agenda-block-separator))
+ "\n"))
+ (narrow-to-region (point) (point-max)))
+ (setq org-done-keywords-for-agenda nil)
+ ;; Setting any org variables that are in org-agenda-local-vars
+ ;; list need to be done after the prepare call
+ (org-agenda-prepare-window
+ (get-buffer-create org-agenda-buffer-name) filter-alist)
+ (setq buffer-read-only nil)
+ (org-agenda-reset-markers)
+ (let ((inhibit-read-only t)) (erase-buffer))
+ (org-agenda-mode)
+ (setq org-agenda-buffer (current-buffer))
+ (setq org-agenda-contributing-files nil)
+ (setq org-agenda-columns-active nil)
+ (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode))
+ (setq org-todo-keywords-for-agenda
+ (org-uniquify org-todo-keywords-for-agenda))
+ (setq org-done-keywords-for-agenda
+ (org-uniquify org-done-keywords-for-agenda))
+ (setq org-agenda-last-prefix-arg current-prefix-arg)
+ (setq org-agenda-this-buffer-name org-agenda-buffer-name)
+ (and name (not org-agenda-name)
+ (setq-local org-agenda-name name)))
+ (setq buffer-read-only nil))))
+
+(defvar org-agenda-overriding-columns-format) ; From org-colview.el
+(defun org-agenda-finalize ()
+ "Finishing touch for the agenda buffer, called just before displaying it."
+ (unless org-agenda-multi
+ (save-excursion
+ (let ((inhibit-read-only t))
+ (goto-char (point-min))
+ (save-excursion
+ (while (org-activate-links (point-max))
+ (add-text-properties (match-beginning 0) (match-end 0)
+ '(face org-link))))
+ (unless (eq org-agenda-remove-tags t)
+ (org-agenda-align-tags))
+ (unless org-agenda-with-colors
+ (remove-text-properties (point-min) (point-max) '(face nil)))
+ (if (and (boundp 'org-agenda-overriding-columns-format)
+ org-agenda-overriding-columns-format)
+ (setq-local org-agenda-overriding-columns-format
+ org-agenda-overriding-columns-format))
+ (if (and (boundp 'org-agenda-view-columns-initially)
+ org-agenda-view-columns-initially)
+ (org-agenda-columns))
+ (when org-agenda-fontify-priorities
+ (org-agenda-fontify-priorities))
+ (when (and org-agenda-dim-blocked-tasks org-blocker-hook)
+ (org-agenda-dim-blocked-tasks))
+ (org-agenda-mark-clocking-task)
+ (when org-agenda-entry-text-mode
+ (org-agenda-entry-text-hide)
+ (org-agenda-entry-text-show))
+ (if (and (functionp 'org-habit-insert-consistency-graphs)
+ (save-excursion (next-single-property-change (point-min) 'org-habit-p)))
+ (org-habit-insert-consistency-graphs))
+ (setq org-agenda-type (org-get-at-bol 'org-agenda-type))
+ (unless (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq org-agenda-type org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (and (listp org-agenda-use-tag-inheritance)
+ (not (memq org-agenda-type
+ org-agenda-use-tag-inheritance))))))
+ (let (mrk)
+ (save-excursion
+ (goto-char (point-min))
+ (while (equal (forward-line) 0)
+ (when (setq mrk (get-text-property (point) 'org-hd-marker))
+ (put-text-property (point-at-bol) (point-at-eol)
+ 'tags (org-with-point-at mrk
+ (delete-dups
+ (mapcar 'downcase (org-get-tags-at))))))))))
+ (run-hooks 'org-agenda-finalize-hook)
+ (when org-agenda-top-headline-filter
+ (org-agenda-filter-top-headline-apply
+ org-agenda-top-headline-filter))
+ (when org-agenda-tag-filter
+ (org-agenda-filter-apply org-agenda-tag-filter 'tag t))
+ (when (get 'org-agenda-tag-filter :preset-filter)
+ (org-agenda-filter-apply
+ (get 'org-agenda-tag-filter :preset-filter) 'tag t))
+ (when org-agenda-category-filter
+ (org-agenda-filter-apply org-agenda-category-filter 'category))
+ (when (get 'org-agenda-category-filter :preset-filter)
+ (org-agenda-filter-apply
+ (get 'org-agenda-category-filter :preset-filter) 'category))
+ (when org-agenda-regexp-filter
+ (org-agenda-filter-apply org-agenda-regexp-filter 'regexp))
+ (when (get 'org-agenda-regexp-filter :preset-filter)
+ (org-agenda-filter-apply
+ (get 'org-agenda-regexp-filter :preset-filter) 'regexp))
+ (when org-agenda-effort-filter
+ (org-agenda-filter-apply org-agenda-effort-filter 'effort))
+ (when (get 'org-agenda-effort-filter :preset-filter)
+ (org-agenda-filter-apply
+ (get 'org-agenda-effort-filter :preset-filter) 'effort))
+ (add-hook 'kill-buffer-hook 'org-agenda-reset-markers 'append 'local)))))
+
+(defun org-agenda-mark-clocking-task ()
+ "Mark the current clock entry in the agenda if it is present."
+ ;; We need to widen when `org-agenda-finalize' is called from
+ ;; `org-agenda-change-all-lines' (e.g. in `org-agenda-clock-in')
+ (when (bound-and-true-p org-clock-current-task)
+ (save-restriction
+ (widen)
+ (org-agenda-unmark-clocking-task)
+ (when (marker-buffer org-clock-hd-marker)
+ (save-excursion
+ (goto-char (point-min))
+ (let (s ov)
+ (while (setq s (next-single-property-change (point) 'org-hd-marker))
+ (goto-char s)
+ (when (equal (org-get-at-bol 'org-hd-marker)
+ org-clock-hd-marker)
+ (setq ov (make-overlay (point-at-bol) (1+ (point-at-eol))))
+ (overlay-put ov 'type 'org-agenda-clocking)
+ (overlay-put ov 'face 'org-agenda-clocking)
+ (overlay-put ov 'help-echo
+ "The clock is running in this item")))))))))
+
+(defun org-agenda-unmark-clocking-task ()
+ "Unmark the current clocking task."
+ (mapc (lambda (o)
+ (if (eq (overlay-get o 'type) 'org-agenda-clocking)
+ (delete-overlay o)))
+ (overlays-in (point-min) (point-max))))
+
+(defun org-agenda-fontify-priorities ()
+ "Make highest priority lines bold, and lowest italic."
+ (interactive)
+ (mapc (lambda (o) (if (eq (overlay-get o 'org-type) 'org-priority)
+ (delete-overlay o)))
+ (overlays-in (point-min) (point-max)))
+ (save-excursion
+ (let (b e p ov h l)
+ (goto-char (point-min))
+ (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
+ (setq h (or (get-char-property (point) 'org-highest-priority)
+ org-highest-priority)
+ l (or (get-char-property (point) 'org-lowest-priority)
+ org-lowest-priority)
+ p (string-to-char (match-string 1))
+ b (match-beginning 0)
+ e (if (eq org-agenda-fontify-priorities 'cookies)
+ (match-end 0)
+ (point-at-eol))
+ ov (make-overlay b e))
+ (overlay-put
+ ov 'face
+ (let ((special-face
+ (cond ((org-face-from-face-or-color
+ 'priority 'org-priority
+ (cdr (assoc p org-priority-faces))))
+ ((and (listp org-agenda-fontify-priorities)
+ (org-face-from-face-or-color
+ 'priority 'org-priority
+ (cdr (assoc p org-agenda-fontify-priorities)))))
+ ((equal p l) 'italic)
+ ((equal p h) 'bold))))
+ (if special-face (list special-face 'org-priority) 'org-priority)))
+ (overlay-put ov 'org-type 'org-priority)))))
+
+(defvar org-depend-tag-blocked)
+
+(defun org-agenda-dim-blocked-tasks (&optional invisible)
+ "Dim currently blocked TODOs in the agenda display.
+When INVISIBLE is non-nil, hide currently blocked TODO instead of
+dimming them."
+ (interactive "P")
+ (when (called-interactively-p 'interactive)
+ (message "Dim or hide blocked tasks..."))
+ (dolist (o (overlays-in (point-min) (point-max)))
+ (when (eq (overlay-get o 'org-type) 'org-blocked-todo)
+ (delete-overlay o)))
+ (save-excursion
+ (let ((inhibit-read-only t)
+ (org-depend-tag-blocked nil)
+ org-blocked-by-checkboxes)
+ (goto-char (point-min))
+ (while (let ((pos (text-property-not-all
+ (point) (point-max) 'todo-state nil)))
+ (when pos (goto-char pos)))
+ (setq org-blocked-by-checkboxes nil)
+ (let ((marker (org-get-at-bol 'org-hd-marker)))
+ (when (and (markerp marker)
+ (with-current-buffer (marker-buffer marker)
+ (save-excursion (goto-char marker)
+ (org-entry-blocked-p))))
+ ;; Entries blocked by checkboxes cannot be made invisible.
+ ;; See `org-agenda-dim-blocked-tasks' for details.
+ (let* ((really-invisible
+ (and (not org-blocked-by-checkboxes)
+ (or invisible (eq org-agenda-dim-blocked-tasks
+ 'invisible))))
+ (ov (make-overlay (if really-invisible (line-end-position 0)
+ (line-beginning-position))
+ (line-end-position))))
+ (if really-invisible (overlay-put ov 'invisible t)
+ (overlay-put ov 'face 'org-agenda-dimmed-todo-face))
+ (overlay-put ov 'org-type 'org-blocked-todo))))
+ (forward-line))))
+ (when (called-interactively-p 'interactive)
+ (message "Dim or hide blocked tasks...done")))
+
+(defvar org-agenda-skip-function nil
+ "Function to be called at each match during agenda construction.
+If this function returns nil, the current match should not be skipped.
+Otherwise, the function must return a position from where the search
+should be continued.
+This may also be a Lisp form, it will be evaluated.
+Never set this variable using `setq' or so, because then it will apply
+to all future agenda commands. If you do want a global skipping condition,
+use the option `org-agenda-skip-function-global' instead.
+The correct usage for `org-agenda-skip-function' is to bind it with
+`let' to scope it dynamically into the agenda-constructing command.
+A good way to set it is through options in `org-agenda-custom-commands'.")
+
+(defun org-agenda-skip ()
+ "Throw to `:skip' in places that should be skipped.
+Also moves point to the end of the skipped region, so that search can
+continue from there."
+ (let ((p (point-at-bol)) to)
+ (when (or
+ (save-excursion (goto-char p) (looking-at comment-start-skip))
+ (and org-agenda-skip-archived-trees (not org-agenda-archives-mode)
+ (get-text-property p :org-archived)
+ (org-end-of-subtree t))
+ (and org-agenda-skip-comment-trees
+ (get-text-property p :org-comment)
+ (org-end-of-subtree t))
+ (and (setq to (or (org-agenda-skip-eval org-agenda-skip-function-global)
+ (org-agenda-skip-eval org-agenda-skip-function)))
+ (goto-char to))
+ (org-in-src-block-p t))
+ (throw :skip t))))
+
+(defun org-agenda-skip-eval (form)
+ "If FORM is a function or a list, call (or eval) it and return the result.
+`save-excursion' and `save-match-data' are wrapped around the call, so point
+and match data are returned to the previous state no matter what these
+functions do."
+ (let (fp)
+ (and form
+ (or (setq fp (functionp form))
+ (consp form))
+ (save-excursion
+ (save-match-data
+ (if fp
+ (funcall form)
+ (eval form)))))))
+
+(defvar org-agenda-markers nil
+ "List of all currently active markers created by `org-agenda'.")
+(defvar org-agenda-last-marker-time (float-time)
+ "Creation time of the last agenda marker.")
+
+(defun org-agenda-new-marker (&optional pos)
+ "Return a new agenda marker.
+Maker is at point, or at POS if non-nil. Org mode keeps a list of
+these markers and resets them when they are no longer in use."
+ (let ((m (copy-marker (or pos (point)) t)))
+ (setq org-agenda-last-marker-time (float-time))
+ (if org-agenda-buffer
+ (with-current-buffer org-agenda-buffer
+ (push m org-agenda-markers))
+ (push m org-agenda-markers))
+ m))
+
+(defun org-agenda-reset-markers ()
+ "Reset markers created by `org-agenda'."
+ (while org-agenda-markers
+ (move-marker (pop org-agenda-markers) nil)))
+
+(defun org-agenda-save-markers-for-cut-and-paste (beg end)
+ "Save relative positions of markers in region.
+This check for agenda markers in all agenda buffers currently active."
+ (dolist (buf (buffer-list))
+ (with-current-buffer buf
+ (when (eq major-mode 'org-agenda-mode)
+ (mapc (lambda (m) (org-check-and-save-marker m beg end))
+ org-agenda-markers)))))
+
+;;; Entry text mode
+
+(defun org-agenda-entry-text-show-here ()
+ "Add some text from the entry as context to the current line."
+ (let (m txt o)
+ (setq m (org-get-at-bol 'org-hd-marker))
+ (unless (marker-buffer m)
+ (error "No marker points to an entry here"))
+ (setq txt (concat "\n" (org-no-properties
+ (org-agenda-get-some-entry-text
+ m org-agenda-entry-text-maxlines
+ org-agenda-entry-text-leaders))))
+ (when (string-match "\\S-" txt)
+ (setq o (make-overlay (point-at-bol) (point-at-eol)))
+ (overlay-put o 'evaporate t)
+ (overlay-put o 'org-overlay-type 'agenda-entry-content)
+ (overlay-put o 'after-string txt))))
+
+(defun org-agenda-entry-text-show ()
+ "Add entry context for all agenda lines."
+ (interactive)
+ (save-excursion
+ (goto-char (point-max))
+ (beginning-of-line 1)
+ (while (not (bobp))
+ (when (org-get-at-bol 'org-hd-marker)
+ (org-agenda-entry-text-show-here))
+ (beginning-of-line 0))))
+
+(defun org-agenda-entry-text-hide ()
+ "Remove any shown entry context."
+ (delq nil
+ (mapcar (lambda (o)
+ (if (eq (overlay-get o 'org-overlay-type)
+ 'agenda-entry-content)
+ (progn (delete-overlay o) t)))
+ (overlays-in (point-min) (point-max)))))
+
+(defun org-agenda-get-day-face (date)
+ "Return the face DATE should be displayed with."
+ (cond ((and (functionp org-agenda-day-face-function)
+ (funcall org-agenda-day-face-function date)))
+ ((org-agenda-today-p date) 'org-agenda-date-today)
+ ((memq (calendar-day-of-week date) org-agenda-weekend-days)
+ 'org-agenda-date-weekend)
+ (t 'org-agenda-date)))
+
+;;; Agenda timeline
+
+(defvar org-agenda-only-exact-dates nil) ; dynamically scoped
+(defvar org-agenda-show-log-scoped) ;; dynamically scope in `org-timeline' or `org-agenda-list'
+
+(defun org-timeline (&optional dotodo)
+ "Show a time-sorted view of the entries in the current Org file.
+
+Only entries with a time stamp of today or later will be listed.
+
+With `\\[universal-argument]' prefix, all unfinished TODO items will also be \
+shown,
+under the current date.
+
+If the buffer contains an active region, only check the region
+for dates."
+ (interactive "P")
+ (let* ((dopast t)
+ (org-agenda-show-log-scoped org-agenda-show-log)
+ (org-agenda-show-log org-agenda-show-log-scoped)
+ (entry (buffer-file-name (or (buffer-base-buffer (current-buffer))
+ (current-buffer))))
+ (date (calendar-current-date))
+ (beg (if (org-region-active-p) (region-beginning) (point-min)))
+ (end (if (org-region-active-p) (region-end) (point-max)))
+ (day-numbers (org-get-all-dates
+ beg end 'no-ranges
+ t org-agenda-show-log-scoped ; always include today
+ org-timeline-show-empty-dates))
+ (org-deadline-warning-days 0)
+ (org-agenda-only-exact-dates t)
+ (today (org-today))
+ (past t)
+ args
+ s e rtn d emptyp)
+ (setq org-agenda-redo-command
+ (list 'let
+ (list (list 'org-agenda-show-log 'org-agenda-show-log))
+ (list 'org-switch-to-buffer-other-window (current-buffer))
+ (list 'org-timeline (list 'quote dotodo))))
+ (put 'org-agenda-redo-command 'org-lprops nil)
+ (if (not dopast)
+ ;; Remove past dates from the list of dates.
+ (setq day-numbers (delq nil (mapcar (lambda(x)
+ (if (>= x today) x nil))
+ day-numbers))))
+ (org-agenda-prepare (concat "Timeline " (file-name-nondirectory entry)))
+ (org-compile-prefix-format 'timeline)
+ (org-set-sorting-strategy 'timeline)
+ (if org-agenda-show-log-scoped (push :closed args))
+ (push :timestamp args)
+ (push :deadline args)
+ (push :scheduled args)
+ (push :sexp args)
+ (if dotodo (push :todo args))
+ (insert "Timeline of file " entry "\n")
+ (add-text-properties (point-min) (point)
+ (list 'face 'org-agenda-structure))
+ (org-agenda-mark-header-line (point-min))
+ (while (setq d (pop day-numbers))
+ (if (and (listp d) (eq (car d) :omitted))
+ (progn
+ (setq s (point))
+ (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
+ (put-text-property s (1- (point)) 'face 'org-agenda-structure))
+ (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
+ (if (and (>= d today)
+ dopast
+ past)
+ (progn
+ (setq past nil)
+ (insert (make-string 79 ?-) "\n")))
+ (setq date (calendar-gregorian-from-absolute d))
+ (setq s (point))
+ (setq rtn (and (not emptyp)
+ (apply 'org-agenda-get-day-entries entry
+ date args)))
+ (if (or rtn (equal d today) org-timeline-show-empty-dates)
+ (progn
+ (insert
+ (if (stringp org-agenda-format-date)
+ (format-time-string org-agenda-format-date
+ (org-time-from-absolute date))
+ (funcall org-agenda-format-date date))
+ "\n")
+ (put-text-property s (1- (point)) 'face
+ (org-agenda-get-day-face date))
+ (put-text-property s (1- (point)) 'org-date-line t)
+ (put-text-property s (1- (point)) 'org-agenda-date-header t)
+ (if (equal d today)
+ (put-text-property s (1- (point)) 'org-today t))
+ (and rtn (insert (org-agenda-finalize-entries rtn 'timeline) "\n"))
+ (put-text-property s (1- (point)) 'day d)))))
+ (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
+ (point-min)))
+ (add-text-properties
+ (point-min) (point-max)
+ `(org-agenda-type timeline org-redo-cmd ,org-agenda-redo-command))
+ (org-agenda-finalize)
+ (setq buffer-read-only t)))
+
+(defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
+ "Return a list of all relevant day numbers from BEG to END buffer positions.
+If NO-RANGES is non-nil, include only the start and end dates of a range,
+not every single day in the range. If FORCE-TODAY is non-nil, make
+sure that TODAY is included in the list. If INACTIVE is non-nil, also
+inactive time stamps (those in square brackets) are included.
+When EMPTY is non-nil, also include days without any entries."
+ (let ((re (concat
+ (if pre-re pre-re "")
+ (if inactive org-ts-regexp-both org-ts-regexp)))
+ dates dates1 date day day1 day2 ts1 ts2 pos)
+ (if force-today
+ (setq dates (list (org-today))))
+ (save-excursion
+ (goto-char beg)
+ (while (re-search-forward re end t)
+ (setq day (time-to-days (org-time-string-to-time
+ (substring (match-string 1) 0 10)
+ (current-buffer) (match-beginning 0))))
+ (or (memq day dates) (push day dates)))
+ (unless no-ranges
+ (goto-char beg)
+ (while (re-search-forward org-tr-regexp end t)
+ (setq pos (match-beginning 0))
+ (setq ts1 (substring (match-string 1) 0 10)
+ ts2 (substring (match-string 2) 0 10)
+ day1 (time-to-days (org-time-string-to-time
+ ts1 (current-buffer) pos))
+ day2 (time-to-days (org-time-string-to-time
+ ts2 (current-buffer) pos)))
+ (while (< (setq day1 (1+ day1)) day2)
+ (or (memq day1 dates) (push day1 dates)))))
+ (setq dates (sort dates '<))
+ (when empty
+ (while (setq day (pop dates))
+ (setq day2 (car dates))
+ (push day dates1)
+ (when (and day2 empty)
+ (if (or (eq empty t)
+ (and (numberp empty) (<= (- day2 day) empty)))
+ (while (< (setq day (1+ day)) day2)
+ (push (list day) dates1))
+ (push (cons :omitted (- day2 day)) dates1))))
+ (setq dates (nreverse dates1)))
+ dates)))
+
+;;; Agenda Daily/Weekly
+
+(defvar org-agenda-start-day nil ; dynamically scoped parameter
+ "Start day for the agenda view.
+Custom commands can set this variable in the options section.
+This is usually a string like \"2007-11-01\", \"+2d\" or any other
+input allowed when reading a date through the Org calendar.
+See the docstring of `org-read-date' for details.")
+(defvar org-starting-day nil) ; local variable in the agenda buffer
+(defvar org-arg-loc nil) ; local variable
+
+(defvar org-agenda-buffer-tmp-name nil)
+;;;###autoload
+(defun org-agenda-list (&optional arg start-day span with-hour)
+ "Produce a daily/weekly view from all files in variable `org-agenda-files'.
+The view will be for the current day or week, but from the overview buffer
+you will be able to go to other days/weeks.
+
+With a numeric prefix argument in an interactive call, the agenda will
+span ARG days. Lisp programs should instead specify SPAN to change
+the number of days. SPAN defaults to `org-agenda-span'.
+
+START-DAY defaults to TODAY, or to the most recent match for the weekday
+given in `org-agenda-start-on-weekday'.
+
+When WITH-HOUR is non-nil, only include scheduled and deadline
+items if they have an hour specification like [h]h:mm."
+ (interactive "P")
+ (if org-agenda-overriding-arguments
+ (setq arg (car org-agenda-overriding-arguments)
+ start-day (nth 1 org-agenda-overriding-arguments)
+ span (nth 2 org-agenda-overriding-arguments)))
+ (if (and (integerp arg) (> arg 0))
+ (setq span arg arg nil))
+ (catch 'exit
+ (setq org-agenda-buffer-name
+ (or org-agenda-buffer-tmp-name
+ (and org-agenda-doing-sticky-redo org-agenda-buffer-name)
+ (if org-agenda-sticky
+ (cond ((and org-keys (stringp org-match))
+ (format "*Org Agenda(%s:%s)*" org-keys org-match))
+ (org-keys
+ (format "*Org Agenda(%s)*" org-keys))
+ (t "*Org Agenda(a)*")))
+ "*Org Agenda*"))
+ (org-agenda-prepare "Day/Week")
+ (setq start-day (or start-day org-agenda-start-day))
+ (if (stringp start-day)
+ ;; Convert to an absolute day number
+ (setq start-day (time-to-days (org-read-date nil t start-day))))
+ (org-compile-prefix-format 'agenda)
+ (org-set-sorting-strategy 'agenda)
+ (let* ((span (org-agenda-ndays-to-span (or span org-agenda-span)))
+ (today (org-today))
+ (sd (or start-day today))
+ (ndays (org-agenda-span-to-ndays span sd))
+ (org-agenda-start-on-weekday
+ (if (or (eq ndays 7) (eq ndays 14))
+ org-agenda-start-on-weekday))
+ (thefiles (org-agenda-files nil 'ifmode))
+ (files thefiles)
+ (start (if (or (null org-agenda-start-on-weekday)
+ (< ndays 7))
+ sd
+ (let* ((nt (calendar-day-of-week
+ (calendar-gregorian-from-absolute sd)))
+ (n1 org-agenda-start-on-weekday)
+ (d (- nt n1)))
+ (- sd (+ (if (< d 0) 7 0) d)))))
+ (day-numbers (list start))
+ (day-cnt 0)
+ (inhibit-redisplay (not debug-on-error))
+ (org-agenda-show-log-scoped org-agenda-show-log)
+ s e rtn rtnall file date d start-pos end-pos todayp
+ clocktable-start clocktable-end filter)
+ (setq org-agenda-redo-command
+ (list 'org-agenda-list (list 'quote arg) start-day (list 'quote span) with-hour))
+ (dotimes (n (1- ndays))
+ (push (1+ (car day-numbers)) day-numbers))
+ (setq day-numbers (nreverse day-numbers))
+ (setq clocktable-start (car day-numbers)
+ clocktable-end (1+ (or (org-last day-numbers) 0)))
+ (setq-local org-starting-day (car day-numbers))
+ (setq-local org-arg-loc arg)
+ (setq-local org-agenda-current-span (org-agenda-ndays-to-span span))
+ (unless org-agenda-compact-blocks
+ (let* ((d1 (car day-numbers))
+ (d2 (org-last day-numbers))
+ (w1 (org-days-to-iso-week d1))
+ (w2 (org-days-to-iso-week d2)))
+ (setq s (point))
+ (if org-agenda-overriding-header
+ (insert (org-add-props (copy-sequence org-agenda-overriding-header)
+ nil 'face 'org-agenda-structure) "\n")
+ (insert (org-agenda-span-name span)
+ "-agenda"
+ (if (< (- d2 d1) 350)
+ (if (= w1 w2)
+ (format " (W%02d)" w1)
+ (format " (W%02d-W%02d)" w1 w2))
+ "")
+ ":\n")))
+ (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
+ 'org-date-line t))
+ (org-agenda-mark-header-line s))
+ (while (setq d (pop day-numbers))
+ (setq date (calendar-gregorian-from-absolute d)
+ s (point))
+ (if (or (setq todayp (= d today))
+ (and (not start-pos) (= d sd)))
+ (setq start-pos (point))
+ (if (and start-pos (not end-pos))
+ (setq end-pos (point))))
+ (setq files thefiles
+ rtnall nil)
+ (while (setq file (pop files))
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (let ((org-agenda-entry-types org-agenda-entry-types))
+ ;; Starred types override non-starred equivalents
+ (when (member :deadline* org-agenda-entry-types)
+ (setq org-agenda-entry-types
+ (delq :deadline org-agenda-entry-types)))
+ (when (member :scheduled* org-agenda-entry-types)
+ (setq org-agenda-entry-types
+ (delq :scheduled org-agenda-entry-types)))
+ ;; Honor with-hour
+ (when with-hour
+ (when (member :deadline org-agenda-entry-types)
+ (setq org-agenda-entry-types
+ (delq :deadline org-agenda-entry-types))
+ (push :deadline* org-agenda-entry-types))
+ (when (member :scheduled org-agenda-entry-types)
+ (setq org-agenda-entry-types
+ (delq :scheduled org-agenda-entry-types))
+ (push :scheduled* org-agenda-entry-types)))
+ (unless org-agenda-include-deadlines
+ (setq org-agenda-entry-types
+ (delq :deadline* (delq :deadline org-agenda-entry-types))))
+ (cond
+ ((memq org-agenda-show-log-scoped '(only clockcheck))
+ (setq rtn (org-agenda-get-day-entries
+ file date :closed)))
+ (org-agenda-show-log-scoped
+ (setq rtn (apply 'org-agenda-get-day-entries
+ file date
+ (append '(:closed) org-agenda-entry-types))))
+ (t
+ (setq rtn (apply 'org-agenda-get-day-entries
+ file date
+ org-agenda-entry-types)))))
+ (setq rtnall (append rtnall rtn)))) ;; all entries
+ (if org-agenda-include-diary
+ (let ((org-agenda-search-headline-for-time t))
+ (require 'diary-lib)
+ (setq rtn (org-get-entries-from-diary date))
+ (setq rtnall (append rtnall rtn))))
+ (if (or rtnall org-agenda-show-all-dates)
+ (progn
+ (setq day-cnt (1+ day-cnt))
+ (insert
+ (if (stringp org-agenda-format-date)
+ (format-time-string org-agenda-format-date
+ (org-time-from-absolute date))
+ (funcall org-agenda-format-date date))
+ "\n")
+ (put-text-property s (1- (point)) 'face
+ (org-agenda-get-day-face date))
+ (put-text-property s (1- (point)) 'org-date-line t)
+ (put-text-property s (1- (point)) 'org-agenda-date-header t)
+ (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
+ (when todayp
+ (put-text-property s (1- (point)) 'org-today t))
+ (setq rtnall
+ (org-agenda-add-time-grid-maybe rtnall ndays todayp))
+ (if rtnall (insert ;; all entries
+ (org-agenda-finalize-entries rtnall 'agenda)
+ "\n"))
+ (put-text-property s (1- (point)) 'day d)
+ (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
+ (when (and org-agenda-clockreport-mode clocktable-start)
+ (let ((org-agenda-files (org-agenda-files nil 'ifmode))
+ ;; the above line is to ensure the restricted range!
+ (p (copy-sequence org-agenda-clockreport-parameter-plist))
+ tbl)
+ (setq p (org-plist-delete p :block))
+ (setq p (plist-put p :tstart clocktable-start))
+ (setq p (plist-put p :tend clocktable-end))
+ (setq p (plist-put p :scope 'agenda))
+ (setq tbl (apply 'org-clock-get-clocktable p))
+ (insert tbl)))
+ (goto-char (point-min))
+ (or org-agenda-multi (org-agenda-fit-window-to-buffer))
+ (unless (and (pos-visible-in-window-p (point-min))
+ (pos-visible-in-window-p (point-max)))
+ (goto-char (1- (point-max)))
+ (recenter -1)
+ (if (not (pos-visible-in-window-p (or start-pos 1)))
+ (progn
+ (goto-char (or start-pos 1))
+ (recenter 1))))
+ (goto-char (or start-pos 1))
+ (add-text-properties (point-min) (point-max)
+ `(org-agenda-type agenda
+ org-last-args (,arg ,start-day ,span)
+ org-redo-cmd ,org-agenda-redo-command
+ org-series-cmd ,org-cmd))
+ (if (eq org-agenda-show-log-scoped 'clockcheck)
+ (org-agenda-show-clocking-issues))
+ (org-agenda-finalize)
+ (setq buffer-read-only t)
+ (message ""))))
+
+(defun org-agenda-ndays-to-span (n)
+ "Return a span symbol for a span of N days, or N if none matches."
+ (cond ((symbolp n) n)
+ ((= n 1) 'day)
+ ((= n 7) 'week)
+ ((= n 14) 'fortnight)
+ (t n)))
+
+(defun org-agenda-span-to-ndays (span &optional start-day)
+ "Return ndays from SPAN, possibly starting at START-DAY.
+START-DAY is an absolute time value."
+ (cond ((numberp span) span)
+ ((eq span 'day) 1)
+ ((eq span 'week) 7)
+ ((eq span 'fortnight) 14)
+ ((eq span 'month)
+ (let ((date (calendar-gregorian-from-absolute start-day)))
+ (calendar-last-day-of-month (car date) (cl-caddr date))))
+ ((eq span 'year)
+ (let ((date (calendar-gregorian-from-absolute start-day)))
+ (if (calendar-leap-year-p (cl-caddr date)) 366 365)))))
+
+(defun org-agenda-span-name (span)
+ "Return a SPAN name."
+ (if (null span)
+ ""
+ (if (symbolp span)
+ (capitalize (symbol-name span))
+ (format "%d days" span))))
+
+;;; Agenda word search
+
+(defvar org-agenda-search-history nil)
+
+(defvar org-search-syntax-table nil
+ "Special syntax table for Org search.
+In this table, we have single quotes not as word constituents, to
+that when \"+Ameli\" is searched as a work, it will also match \"Ameli's\"")
+
+(defvar org-mode-syntax-table) ; From org.el
+(defun org-search-syntax-table ()
+ (unless org-search-syntax-table
+ (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table))
+ (modify-syntax-entry ?' "." org-search-syntax-table)
+ (modify-syntax-entry ?` "." org-search-syntax-table))
+ org-search-syntax-table)
+
+(defvar org-agenda-last-search-view-search-was-boolean nil)
+
+;;;###autoload
+(defun org-search-view (&optional todo-only string edit-at)
+ "Show all entries that contain a phrase or words or regular expressions.
+
+With optional prefix argument TODO-ONLY, only consider entries that are
+TODO entries. The argument STRING can be used to pass a default search
+string into this function. If EDIT-AT is non-nil, it means that the
+user should get a chance to edit this string, with cursor at position
+EDIT-AT.
+
+The search string can be viewed either as a phrase that should be found as
+is, or it can be broken into a number of snippets, each of which must match
+in a Boolean way to select an entry. The default depends on the variable
+`org-agenda-search-view-always-boolean'.
+Even if this is turned off (the default) you can always switch to
+Boolean search dynamically by preceding the first word with \"+\" or \"-\".
+
+The default is a direct search of the whole phrase, where each space in
+the search string can expand to an arbitrary amount of whitespace,
+including newlines.
+
+If using a Boolean search, the search string is split on whitespace and
+each snippet is searched separately, with logical AND to select an entry.
+Words prefixed with a minus must *not* occur in the entry. Words without
+a prefix or prefixed with a plus must occur in the entry. Matching is
+case-insensitive. Words are enclosed by word delimiters (i.e. they must
+match whole words, not parts of a word) if
+`org-agenda-search-view-force-full-words' is set (default is nil).
+
+Boolean search snippets enclosed by curly braces are interpreted as
+regular expressions that must or (when preceded with \"-\") must not
+match in the entry. Snippets enclosed into double quotes will be taken
+as a whole, to include whitespace.
+
+- If the search string starts with an asterisk, search only in headlines.
+- If (possibly after the leading star) the search string starts with an
+ exclamation mark, this also means to look at TODO entries only, an effect
+ that can also be achieved with a prefix argument.
+- If (possibly after star and exclamation mark) the search string starts
+ with a colon, this will mean that the (non-regexp) snippets of the
+ Boolean search must match as full words.
+
+This command searches the agenda files, and in addition the files listed
+in `org-agenda-text-search-extra-files'."
+ (interactive "P")
+ (if org-agenda-overriding-arguments
+ (setq todo-only (car org-agenda-overriding-arguments)
+ string (nth 1 org-agenda-overriding-arguments)
+ edit-at (nth 2 org-agenda-overriding-arguments)))
+ (let* ((props (list 'face nil
+ 'done-face 'org-agenda-done
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'mouse-face 'highlight
+ 'help-echo (format "mouse-2 or RET jump to location")))
+ (full-words org-agenda-search-view-force-full-words)
+ (org-agenda-text-search-extra-files org-agenda-text-search-extra-files)
+ regexp rtn rtnall files file pos inherited-tags
+ marker category level tags c neg re boolean
+ ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
+ (unless (and (not edit-at)
+ (stringp string)
+ (string-match "\\S-" string))
+ (setq string (read-string
+ (if org-agenda-search-view-always-boolean
+ "[+-]Word/{Regexp} ...: "
+ "Phrase or [+-]Word/{Regexp} ...: ")
+ (cond
+ ((integerp edit-at) (cons string edit-at))
+ (edit-at string))
+ 'org-agenda-search-history)))
+ (catch 'exit
+ (if org-agenda-sticky
+ (setq org-agenda-buffer-name
+ (if (stringp string)
+ (format "*Org Agenda(%s:%s)*"
+ (or org-keys (or (and todo-only "S") "s")) string)
+ (format "*Org Agenda(%s)*" (or (and todo-only "S") "s")))))
+ (org-agenda-prepare "SEARCH")
+ (org-compile-prefix-format 'search)
+ (org-set-sorting-strategy 'search)
+ (setq org-agenda-redo-command
+ (list 'org-search-view (if todo-only t nil)
+ (list 'if 'current-prefix-arg nil string)))
+ (setq org-agenda-query-string string)
+ (if (equal (string-to-char string) ?*)
+ (setq hdl-only t
+ words (substring string 1))
+ (setq words string))
+ (when (equal (string-to-char words) ?!)
+ (setq todo-only t
+ words (substring words 1)))
+ (when (equal (string-to-char words) ?:)
+ (setq full-words t
+ words (substring words 1)))
+ (if (or org-agenda-search-view-always-boolean
+ (member (string-to-char words) '(?- ?+ ?\{)))
+ (setq boolean t))
+ (setq words (org-split-string words))
+ (let (www w)
+ (while (setq w (pop words))
+ (while (and (string-match "\\\\\\'" w) words)
+ (setq w (concat (substring w 0 -1) " " (pop words))))
+ (push w www))
+ (setq words (nreverse www) www nil)
+ (while (setq w (pop words))
+ (when (and (string-match "\\`[-+]?{" w)
+ (not (string-match "}\\'" w)))
+ (while (and words (not (string-match "}\\'" (car words))))
+ (setq w (concat w " " (pop words))))
+ (setq w (concat w " " (pop words))))
+ (push w www))
+ (setq words (nreverse www)))
+ (setq org-agenda-last-search-view-search-was-boolean boolean)
+ (when boolean
+ (let (wds w)
+ (while (setq w (pop words))
+ (if (or (equal (substring w 0 1) "\"")
+ (and (> (length w) 1)
+ (member (substring w 0 1) '("+" "-"))
+ (equal (substring w 1 2) "\"")))
+ (while (and words (not (equal (substring w -1) "\"")))
+ (setq w (concat w " " (pop words)))))
+ (and (string-match "\\`\\([-+]?\\)\"" w)
+ (setq w (replace-match "\\1" nil nil w)))
+ (and (equal (substring w -1) "\"") (setq w (substring w 0 -1)))
+ (push w wds))
+ (setq words (nreverse wds))))
+ (if boolean
+ (mapc (lambda (w)
+ (setq c (string-to-char w))
+ (if (equal c ?-)
+ (setq neg t w (substring w 1))
+ (if (equal c ?+)
+ (setq neg nil w (substring w 1))
+ (setq neg nil)))
+ (if (string-match "\\`{.*}\\'" w)
+ (setq re (substring w 1 -1))
+ (if full-words
+ (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>"))
+ (setq re (regexp-quote (downcase w)))))
+ (if neg (push re regexps-) (push re regexps+)))
+ words)
+ (push (mapconcat (lambda (w) (regexp-quote w)) words "\\s-+")
+ regexps+))
+ (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
+ (if (not regexps+)
+ (setq regexp org-outline-regexp-bol)
+ (setq regexp (pop regexps+))
+ (if hdl-only (setq regexp (concat org-outline-regexp-bol ".*?"
+ regexp))))
+ (setq files (org-agenda-files nil 'ifmode))
+ (when (eq (car org-agenda-text-search-extra-files) 'agenda-archives)
+ (pop org-agenda-text-search-extra-files)
+ (setq files (org-add-archive-files files)))
+ (setq files (append files org-agenda-text-search-extra-files)
+ rtnall nil)
+ (while (setq file (pop files))
+ (setq ee nil)
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (setq buffer (if (file-exists-p file)
+ (org-get-agenda-file-buffer file)
+ (error "No such file %s" file)))
+ (if (not buffer)
+ ;; If file does not exist, make sure an error message is sent
+ (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
+ file))))
+ (with-current-buffer buffer
+ (with-syntax-table (org-search-syntax-table)
+ (unless (derived-mode-p 'org-mode)
+ (error "Agenda file %s is not in `org-mode'" file))
+ (let ((case-fold-search t))
+ (save-excursion
+ (save-restriction
+ (if (eq buffer org-agenda-restrict)
+ (narrow-to-region org-agenda-restrict-begin
+ org-agenda-restrict-end)
+ (widen))
+ (goto-char (point-min))
+ (unless (or (org-at-heading-p)
+ (outline-next-heading))
+ (throw 'nextfile t))
+ (goto-char (max (point-min) (1- (point))))
+ (while (re-search-forward regexp nil t)
+ (org-back-to-heading t)
+ (while (and (not (zerop org-agenda-search-view-max-outline-level))
+ (> (org-reduced-level (org-outline-level))
+ org-agenda-search-view-max-outline-level)
+ (forward-line -1)
+ (org-back-to-heading t)))
+ (skip-chars-forward "* ")
+ (setq beg (point-at-bol)
+ beg1 (point)
+ end (progn
+ (outline-next-heading)
+ (while (and (not (zerop org-agenda-search-view-max-outline-level))
+ (> (org-reduced-level (org-outline-level))
+ org-agenda-search-view-max-outline-level)
+ (forward-line 1)
+ (outline-next-heading)))
+ (point)))
+
+ (catch :skip
+ (goto-char beg)
+ (org-agenda-skip)
+ (setq str (buffer-substring-no-properties
+ (point-at-bol)
+ (if hdl-only (point-at-eol) end)))
+ (mapc (lambda (wr) (when (string-match wr str)
+ (goto-char (1- end))
+ (throw :skip t)))
+ regexps-)
+ (mapc (lambda (wr) (unless (string-match wr str)
+ (goto-char (1- end))
+ (throw :skip t)))
+ (if todo-only
+ (cons (concat "^\\*+[ \t]+"
+ org-not-done-regexp)
+ regexps+)
+ regexps+))
+ (goto-char beg)
+ (setq marker (org-agenda-new-marker (point))
+ category (org-get-category)
+ level (make-string (org-reduced-level (org-outline-level)) ? )
+ inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'todo org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'todo org-agenda-use-tag-inheritance))))
+ tags (org-get-tags-at nil (not inherited-tags))
+ txt (org-agenda-format-item
+ ""
+ (buffer-substring-no-properties
+ beg1 (point-at-eol))
+ level category tags t))
+ (org-add-props txt props
+ 'org-marker marker 'org-hd-marker marker
+ 'org-todo-regexp org-todo-regexp
+ 'level level
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'priority 1000
+ 'type "search")
+ (push txt ee)
+ (goto-char (1- end))))))))))
+ (setq rtn (nreverse ee))
+ (setq rtnall (append rtnall rtn)))
+ (if org-agenda-overriding-header
+ (insert (org-add-props (copy-sequence org-agenda-overriding-header)
+ nil 'face 'org-agenda-structure) "\n")
+ (insert "Search words: ")
+ (add-text-properties (point-min) (1- (point))
+ (list 'face 'org-agenda-structure))
+ (setq pos (point))
+ (insert string "\n")
+ (add-text-properties pos (1- (point)) (list 'face 'org-warning))
+ (setq pos (point))
+ (unless org-agenda-multi
+ (insert (substitute-command-keys "\
+Press `\\[org-agenda-manipulate-query-add]', \
+`\\[org-agenda-manipulate-query-subtract]' to add/sub word, \
+`\\[org-agenda-manipulate-query-add-re]', \
+`\\[org-agenda-manipulate-query-subtract-re]' to add/sub regexp, \
+`\\[universal-argument] \\[org-agenda-redo]' to edit\n"))
+ (add-text-properties pos (1- (point))
+ (list 'face 'org-agenda-structure))))
+ (org-agenda-mark-header-line (point-min))
+ (when rtnall
+ (insert (org-agenda-finalize-entries rtnall 'search) "\n"))
+ (goto-char (point-min))
+ (or org-agenda-multi (org-agenda-fit-window-to-buffer))
+ (add-text-properties (point-min) (point-max)
+ `(org-agenda-type search
+ org-last-args (,todo-only ,string ,edit-at)
+ org-redo-cmd ,org-agenda-redo-command
+ org-series-cmd ,org-cmd))
+ (org-agenda-finalize)
+ (setq buffer-read-only t))))
+
+;;; Agenda TODO list
+
+(defun org-agenda-propertize-selected-todo-keywords (keywords)
+ "Use `org-todo-keyword-faces' for the selected todo KEYWORDS."
+ (concat
+ (if (or (equal keywords "ALL") (not keywords))
+ (propertize "ALL" 'face 'warning)
+ (mapconcat
+ (lambda (kw)
+ (propertize kw 'face (org-get-todo-face kw)))
+ (org-split-string keywords "|")
+ "|"))
+ "\n"))
+
+(defvar org-select-this-todo-keyword nil)
+(defvar org-last-arg nil)
+
+;;;###autoload
+(defun org-todo-list (&optional arg)
+ "Show all (not done) TODO entries from all agenda file in a single list.
+The prefix arg can be used to select a specific TODO keyword and limit
+the list to these. When using `\\[universal-argument]', you will be prompted
+for a keyword. A numeric prefix directly selects the Nth keyword in
+`org-todo-keywords-1'."
+ (interactive "P")
+ (if org-agenda-overriding-arguments
+ (setq arg org-agenda-overriding-arguments))
+ (if (and (stringp arg) (not (string-match "\\S-" arg))) (setq arg nil))
+ (let* ((today (org-today))
+ (date (calendar-gregorian-from-absolute today))
+ (kwds org-todo-keywords-for-agenda)
+ (completion-ignore-case t)
+ (org-select-this-todo-keyword
+ (if (stringp arg) arg
+ (and arg (integerp arg) (> arg 0)
+ (nth (1- arg) kwds))))
+ rtn rtnall files file pos)
+ (when (equal arg '(4))
+ (setq org-select-this-todo-keyword
+ (completing-read "Keyword (or KWD1|K2D2|...): "
+ (mapcar #'list kwds) nil nil)))
+ (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
+ (catch 'exit
+ (if org-agenda-sticky
+ (setq org-agenda-buffer-name
+ (if (stringp org-select-this-todo-keyword)
+ (format "*Org Agenda(%s:%s)*" (or org-keys "t")
+ org-select-this-todo-keyword)
+ (format "*Org Agenda(%s)*" (or org-keys "t")))))
+ (org-agenda-prepare "TODO")
+ (org-compile-prefix-format 'todo)
+ (org-set-sorting-strategy 'todo)
+ (setq org-agenda-redo-command
+ `(org-todo-list (or (and (numberp current-prefix-arg)
+ current-prefix-arg)
+ ,org-select-this-todo-keyword
+ current-prefix-arg ,arg)))
+ (setq files (org-agenda-files nil 'ifmode)
+ rtnall nil)
+ (while (setq file (pop files))
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (setq rtn (org-agenda-get-day-entries file date :todo))
+ (setq rtnall (append rtnall rtn))))
+ (if org-agenda-overriding-header
+ (insert (org-add-props (copy-sequence org-agenda-overriding-header)
+ nil 'face 'org-agenda-structure) "\n")
+ (insert "Global list of TODO items of type: ")
+ (add-text-properties (point-min) (1- (point))
+ (list 'face 'org-agenda-structure
+ 'short-heading
+ (concat "ToDo: "
+ (or org-select-this-todo-keyword "ALL"))))
+ (org-agenda-mark-header-line (point-min))
+ (insert (org-agenda-propertize-selected-todo-keywords
+ org-select-this-todo-keyword))
+ (setq pos (point))
+ (unless org-agenda-multi
+ (insert (substitute-command-keys "Available with \
+`N \\[org-agenda-redo]': (0)[ALL]"))
+ (let ((n 0) s)
+ (mapc (lambda (x)
+ (setq s (format "(%d)%s" (setq n (1+ n)) x))
+ (if (> (+ (current-column) (string-width s) 1) (frame-width))
+ (insert "\n "))
+ (insert " " s))
+ kwds))
+ (insert "\n"))
+ (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
+ (org-agenda-mark-header-line (point-min))
+ (when rtnall
+ (insert (org-agenda-finalize-entries rtnall 'todo) "\n"))
+ (goto-char (point-min))
+ (or org-agenda-multi (org-agenda-fit-window-to-buffer))
+ (add-text-properties (point-min) (point-max)
+ `(org-agenda-type todo
+ org-last-args ,arg
+ org-redo-cmd ,org-agenda-redo-command
+ org-series-cmd ,org-cmd))
+ (org-agenda-finalize)
+ (setq buffer-read-only t))))
+
+;;; Agenda tags match
+
+;;;###autoload
+(defun org-tags-view (&optional todo-only match)
+ "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
+The prefix arg TODO-ONLY limits the search to TODO entries."
+ (interactive "P")
+ (if org-agenda-overriding-arguments
+ (setq todo-only (car org-agenda-overriding-arguments)
+ match (nth 1 org-agenda-overriding-arguments)))
+ (let* ((org-tags-match-list-sublevels
+ org-tags-match-list-sublevels)
+ (completion-ignore-case t)
+ (org--matcher-tags-todo-only todo-only)
+ rtn rtnall files file pos matcher
+ buffer)
+ (when (and (stringp match) (not (string-match "\\S-" match)))
+ (setq match nil))
+ (catch 'exit
+ (if org-agenda-sticky
+ (setq org-agenda-buffer-name
+ (if (stringp match)
+ (format "*Org Agenda(%s:%s)*"
+ (or org-keys (or (and todo-only "M") "m")) match)
+ (format "*Org Agenda(%s)*" (or (and todo-only "M") "m")))))
+ ;; Prepare agendas (and `org-tag-alist-for-agenda') before
+ ;; expanding tags within `org-make-tags-matcher'
+ (org-agenda-prepare (concat "TAGS " match))
+ (setq matcher (org-make-tags-matcher match)
+ match (car matcher)
+ matcher (cdr matcher))
+ (org-compile-prefix-format 'tags)
+ (org-set-sorting-strategy 'tags)
+ (setq org-agenda-query-string match)
+ (setq org-agenda-redo-command
+ (list 'org-tags-view
+ `(quote ,org--matcher-tags-todo-only)
+ `(if current-prefix-arg nil ,org-agenda-query-string)))
+ (setq files (org-agenda-files nil 'ifmode)
+ rtnall nil)
+ (while (setq file (pop files))
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (setq buffer (if (file-exists-p file)
+ (org-get-agenda-file-buffer file)
+ (error "No such file %s" file)))
+ (if (not buffer)
+ ;; If file does not exist, error message to agenda
+ (setq rtn (list
+ (format "ORG-AGENDA-ERROR: No such org-file %s" file))
+ rtnall (append rtnall rtn))
+ (with-current-buffer buffer
+ (unless (derived-mode-p 'org-mode)
+ (error "Agenda file %s is not in `org-mode'" file))
+ (save-excursion
+ (save-restriction
+ (if (eq buffer org-agenda-restrict)
+ (narrow-to-region org-agenda-restrict-begin
+ org-agenda-restrict-end)
+ (widen))
+ (setq rtn (org-scan-tags 'agenda
+ matcher
+ org--matcher-tags-todo-only))
+ (setq rtnall (append rtnall rtn))))))))
+ (if org-agenda-overriding-header
+ (insert (org-add-props (copy-sequence org-agenda-overriding-header)
+ nil 'face 'org-agenda-structure) "\n")
+ (insert "Headlines with TAGS match: ")
+ (add-text-properties (point-min) (1- (point))
+ (list 'face 'org-agenda-structure
+ 'short-heading
+ (concat "Match: " match)))
+ (setq pos (point))
+ (insert match "\n")
+ (add-text-properties pos (1- (point)) (list 'face 'org-warning))
+ (setq pos (point))
+ (unless org-agenda-multi
+ (insert (substitute-command-keys
+ "Press `\\[universal-argument] \\[org-agenda-redo]' \
+to search again with new search string\n")))
+ (add-text-properties pos (1- (point))
+ (list 'face 'org-agenda-structure)))
+ (org-agenda-mark-header-line (point-min))
+ (when rtnall
+ (insert (org-agenda-finalize-entries rtnall 'tags) "\n"))
+ (goto-char (point-min))
+ (or org-agenda-multi (org-agenda-fit-window-to-buffer))
+ (add-text-properties
+ (point-min) (point-max)
+ `(org-agenda-type tags
+ org-last-args (,org--matcher-tags-todo-only ,match)
+ org-redo-cmd ,org-agenda-redo-command
+ org-series-cmd ,org-cmd))
+ (org-agenda-finalize)
+ (setq buffer-read-only t))))
+
+;;; Agenda Finding stuck projects
+
+(defvar org-agenda-skip-regexp nil
+ "Regular expression used in skipping subtrees for the agenda.
+This is basically a temporary global variable that can be set and then
+used by user-defined selections using `org-agenda-skip-function'.")
+
+(defvar org-agenda-overriding-header nil
+ "When set during agenda, todo and tags searches it replaces the header.
+This variable should not be set directly, but custom commands can bind it
+in the options section.")
+
+(defun org-agenda-skip-entry-when-regexp-matches ()
+ "Check if the current entry contains match for `org-agenda-skip-regexp'.
+If yes, it returns the end position of this entry, causing agenda commands
+to skip the entry but continuing the search in the subtree. This is a
+function that can be put into `org-agenda-skip-function' for the duration
+of a command."
+ (let ((end (save-excursion (org-end-of-subtree t)))
+ skip)
+ (save-excursion
+ (setq skip (re-search-forward org-agenda-skip-regexp end t)))
+ (and skip end)))
+
+(defun org-agenda-skip-subtree-when-regexp-matches ()
+ "Check if the current subtree contains match for `org-agenda-skip-regexp'.
+If yes, it returns the end position of this tree, causing agenda commands
+to skip this subtree. This is a function that can be put into
+`org-agenda-skip-function' for the duration of a command."
+ (let ((end (save-excursion (org-end-of-subtree t)))
+ skip)
+ (save-excursion
+ (setq skip (re-search-forward org-agenda-skip-regexp end t)))
+ (and skip end)))
+
+(defun org-agenda-skip-entry-when-regexp-matches-in-subtree ()
+ "Check if the current subtree contains match for `org-agenda-skip-regexp'.
+If yes, it returns the end position of the current entry (NOT the tree),
+causing agenda commands to skip the entry but continuing the search in
+the subtree. This is a function that can be put into
+`org-agenda-skip-function' for the duration of a command. An important
+use of this function is for the stuck project list."
+ (let ((end (save-excursion (org-end-of-subtree t)))
+ (entry-end (save-excursion (outline-next-heading) (1- (point))))
+ skip)
+ (save-excursion
+ (setq skip (re-search-forward org-agenda-skip-regexp end t)))
+ (and skip entry-end)))
+
+(defun org-agenda-skip-entry-if (&rest conditions)
+ "Skip entry if any of CONDITIONS is true.
+See `org-agenda-skip-if' for details."
+ (org-agenda-skip-if nil conditions))
+
+(defun org-agenda-skip-subtree-if (&rest conditions)
+ "Skip subtree if any of CONDITIONS is true.
+See `org-agenda-skip-if' for details."
+ (org-agenda-skip-if t conditions))
+
+(defun org-agenda-skip-if (subtree conditions)
+ "Checks current entity for CONDITIONS.
+If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
+the entry (i.e. the text before the next heading) is checked.
+
+CONDITIONS is a list of symbols, boolean OR is used to combine the results
+from different tests. Valid conditions are:
+
+scheduled Check if there is a scheduled cookie
+notscheduled Check if there is no scheduled cookie
+deadline Check if there is a deadline
+notdeadline Check if there is no deadline
+timestamp Check if there is a timestamp (also deadline or scheduled)
+nottimestamp Check if there is no timestamp (also deadline or scheduled)
+regexp Check if regexp matches
+notregexp Check if regexp does not match.
+todo Check if TODO keyword matches
+nottodo Check if TODO keyword does not match
+
+The regexp is taken from the conditions list, it must come right after
+the `regexp' or `notregexp' element.
+
+`todo' and `nottodo' accept as an argument a list of todo
+keywords, which may include \"*\" to match any todo keyword.
+
+ (org-agenda-skip-entry-if \\='todo \\='(\"TODO\" \"WAITING\"))
+
+would skip all entries with \"TODO\" or \"WAITING\" keywords.
+
+Instead of a list, a keyword class may be given. For example:
+
+ (org-agenda-skip-entry-if \\='nottodo \\='done)
+
+would skip entries that haven't been marked with any of \"DONE\"
+keywords. Possible classes are: `todo', `done', `any'.
+
+If any of these conditions is met, this function returns the end point of
+the entity, causing the search to continue from there. This is a function
+that can be put into `org-agenda-skip-function' for the duration of a command."
+ (let (beg end m)
+ (org-back-to-heading t)
+ (setq beg (point)
+ end (if subtree
+ (progn (org-end-of-subtree t) (point))
+ (progn (outline-next-heading) (1- (point)))))
+ (goto-char beg)
+ (and
+ (or
+ (and (memq 'scheduled conditions)
+ (re-search-forward org-scheduled-time-regexp end t))
+ (and (memq 'notscheduled conditions)
+ (not (re-search-forward org-scheduled-time-regexp end t)))
+ (and (memq 'deadline conditions)
+ (re-search-forward org-deadline-time-regexp end t))
+ (and (memq 'notdeadline conditions)
+ (not (re-search-forward org-deadline-time-regexp end t)))
+ (and (memq 'timestamp conditions)
+ (re-search-forward org-ts-regexp end t))
+ (and (memq 'nottimestamp conditions)
+ (not (re-search-forward org-ts-regexp end t)))
+ (and (setq m (memq 'regexp conditions))
+ (stringp (nth 1 m))
+ (re-search-forward (nth 1 m) end t))
+ (and (setq m (memq 'notregexp conditions))
+ (stringp (nth 1 m))
+ (not (re-search-forward (nth 1 m) end t)))
+ (and (or
+ (setq m (memq 'nottodo conditions))
+ (setq m (memq 'todo-unblocked conditions))
+ (setq m (memq 'nottodo-unblocked conditions))
+ (setq m (memq 'todo conditions)))
+ (org-agenda-skip-if-todo m end)))
+ end)))
+
+(defun org-agenda-skip-if-todo (args end)
+ "Helper function for `org-agenda-skip-if', do not use it directly.
+ARGS is a list with first element either `todo', `nottodo',
+`todo-unblocked' or `nottodo-unblocked'. The remainder is either
+a list of TODO keywords, or a state symbol `todo' or `done' or
+`any'."
+ (let ((kw (car args))
+ (arg (cadr args))
+ todo-wds todo-re)
+ (setq todo-wds
+ (org-uniquify
+ (cond
+ ((listp arg) ;; list of keywords
+ (if (member "*" arg)
+ (mapcar 'substring-no-properties org-todo-keywords-1)
+ arg))
+ ((symbolp arg) ;; keyword class name
+ (cond
+ ((eq arg 'todo)
+ (org-delete-all org-done-keywords
+ (mapcar 'substring-no-properties
+ org-todo-keywords-1)))
+ ((eq arg 'done) org-done-keywords)
+ ((eq arg 'any)
+ (mapcar 'substring-no-properties org-todo-keywords-1)))))))
+ (setq todo-re
+ (concat "^\\*+[ \t]+\\<\\("
+ (mapconcat 'identity todo-wds "\\|")
+ "\\)\\>"))
+ (cond
+ ((eq kw 'todo) (re-search-forward todo-re end t))
+ ((eq kw 'nottodo) (not (re-search-forward todo-re end t)))
+ ((eq kw 'todo-unblocked)
+ (catch 'unblocked
+ (while (re-search-forward todo-re end t)
+ (or (org-entry-blocked-p) (throw 'unblocked t)))
+ nil))
+ ((eq kw 'nottodo-unblocked)
+ (catch 'unblocked
+ (while (re-search-forward todo-re end t)
+ (or (org-entry-blocked-p) (throw 'unblocked nil)))
+ t))
+ )))
+
+;;;###autoload
+(defun org-agenda-list-stuck-projects (&rest ignore)
+ "Create agenda view for projects that are stuck.
+Stuck projects are project that have no next actions. For the definitions
+of what a project is and how to check if it stuck, customize the variable
+`org-stuck-projects'."
+ (interactive)
+ (let* ((org-agenda-overriding-header
+ (or org-agenda-overriding-header "List of stuck projects: "))
+ (matcher (nth 0 org-stuck-projects))
+ (todo (nth 1 org-stuck-projects))
+ (tags (nth 2 org-stuck-projects))
+ (gen-re (org-string-nw-p (nth 3 org-stuck-projects)))
+ (todo-wds
+ (if (not (member "*" todo)) todo
+ (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode))
+ (org-delete-all org-done-keywords-for-agenda
+ (copy-sequence org-todo-keywords-for-agenda))))
+ (todo-re (and todo
+ (format "^\\*+[ \t]+\\(%s\\)\\>"
+ (mapconcat #'identity todo-wds "\\|"))))
+ (tags-re (cond ((null tags) nil)
+ ((member "*" tags)
+ (eval-when-compile
+ (concat org-outline-regexp-bol
+ ".*:[[:alnum:]_@#%]+:[ \t]*$")))
+ (tags (concat org-outline-regexp-bol
+ ".*:\\("
+ (mapconcat #'identity tags "\\|")
+ "\\):[[:alnum:]_@#%:]*[ \t]*$"))
+ (t nil)))
+ (re-list (delq nil (list todo-re tags-re gen-re)))
+ (skip-re
+ (if (null re-list)
+ (error "Missing information to identify unstuck projects")
+ (mapconcat #'identity re-list "\\|")))
+ (org-agenda-skip-function
+ ;; Skip entry if `org-agenda-skip-regexp' matches anywhere
+ ;; in the subtree.
+ `(lambda ()
+ (and (save-excursion
+ (let ((case-fold-search nil))
+ (re-search-forward
+ ,skip-re (save-excursion (org-end-of-subtree t)) t)))
+ (progn (outline-next-heading) (point))))))
+ (org-tags-view nil matcher)
+ (setq org-agenda-buffer-name (buffer-name))
+ (with-current-buffer org-agenda-buffer-name
+ (setq org-agenda-redo-command
+ `(org-agenda-list-stuck-projects ,current-prefix-arg))
+ (let ((inhibit-read-only t))
+ (add-text-properties
+ (point-min) (point-max)
+ `(org-redo-cmd ,org-agenda-redo-command))))))
+
+;;; Diary integration
+
+(defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
+(defvar diary-list-entries-hook)
+(defvar diary-time-regexp)
+(defun org-get-entries-from-diary (date)
+ "Get the (Emacs Calendar) diary entries for DATE."
+ (require 'diary-lib)
+ (let* ((diary-fancy-buffer "*temporary-fancy-diary-buffer*")
+ (diary-display-function 'diary-fancy-display)
+ (pop-up-frames nil)
+ (diary-list-entries-hook
+ (cons 'org-diary-default-entry diary-list-entries-hook))
+ (diary-file-name-prefix nil) ; turn this feature off
+ (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
+ entries
+ (org-disable-agenda-to-diary t))
+ (save-excursion
+ (save-window-excursion
+ (funcall (if (fboundp 'diary-list-entries)
+ 'diary-list-entries 'list-diary-entries)
+ date 1)))
+ (if (not (get-buffer diary-fancy-buffer))
+ (setq entries nil)
+ (with-current-buffer diary-fancy-buffer
+ (setq buffer-read-only nil)
+ (if (zerop (buffer-size))
+ ;; No entries
+ (setq entries nil)
+ ;; Omit the date and other unnecessary stuff
+ (org-agenda-cleanup-fancy-diary)
+ ;; Add prefix to each line and extend the text properties
+ (if (zerop (buffer-size))
+ (setq entries nil)
+ (setq entries (buffer-substring (point-min) (- (point-max) 1)))
+ (setq entries
+ (with-temp-buffer
+ (insert entries) (goto-char (point-min))
+ (while (re-search-forward "\n[ \t]+\\(.+\\)$" nil t)
+ (unless (save-match-data (string-match diary-time-regexp (match-string 1)))
+ (replace-match (concat "; " (match-string 1)))))
+ (buffer-string)))))
+ (set-buffer-modified-p nil)
+ (kill-buffer diary-fancy-buffer)))
+ (when entries
+ (setq entries (org-split-string entries "\n"))
+ (setq entries
+ (mapcar
+ (lambda (x)
+ (setq x (org-agenda-format-item "" x nil "Diary" nil 'time))
+ ;; Extend the text properties to the beginning of the line
+ (org-add-props x (text-properties-at (1- (length x)) x)
+ 'type "diary" 'date date 'face 'org-agenda-diary))
+ entries)))))
+
+(defvar org-agenda-cleanup-fancy-diary-hook nil
+ "Hook run when the fancy diary buffer is cleaned up.")
+
+(defun org-agenda-cleanup-fancy-diary ()
+ "Remove unwanted stuff in buffer created by `fancy-diary-display'.
+This gets rid of the date, the underline under the date, and
+the dummy entry installed by `org-mode' to ensure non-empty diary for each
+date. It also removes lines that contain only whitespace."
+ (goto-char (point-min))
+ (if (looking-at ".*?:[ \t]*")
+ (progn
+ (replace-match "")
+ (re-search-forward "\n=+$" nil t)
+ (replace-match "")
+ (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
+ (re-search-forward "\n=+$" nil t)
+ (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
+ (goto-char (point-min))
+ (while (re-search-forward "^ +\n" nil t)
+ (replace-match ""))
+ (goto-char (point-min))
+ (if (re-search-forward "^Org mode dummy\n?" nil t)
+ (replace-match ""))
+ (run-hooks 'org-agenda-cleanup-fancy-diary-hook))
+
+;; Make sure entries from the diary have the right text properties.
+(eval-after-load "diary-lib"
+ '(if (boundp 'diary-modify-entry-list-string-function)
+ ;; We can rely on the hook, nothing to do
+ nil
+ ;; Hook not available, must use advice to make this work
+ (defadvice add-to-diary-list (before org-mark-diary-entry activate)
+ "Make the position visible."
+ (if (and org-disable-agenda-to-diary ;; called from org-agenda
+ (stringp string)
+ buffer-file-name)
+ (setq string (org-modify-diary-entry-string string))))))
+
+(defun org-modify-diary-entry-string (string)
+ "Add text properties to string, allowing Org to act on it."
+ (org-add-props string nil
+ 'mouse-face 'highlight
+ 'help-echo (if buffer-file-name
+ (format "mouse-2 or RET jump to diary file %s"
+ (abbreviate-file-name buffer-file-name))
+ "")
+ 'org-agenda-diary-link t
+ 'org-marker (org-agenda-new-marker (point-at-bol))))
+
+(defun org-diary-default-entry ()
+ "Add a dummy entry to the diary.
+Needed to avoid empty dates which mess up holiday display."
+ ;; Catch the error if dealing with the new add-to-diary-alist
+ (when org-disable-agenda-to-diary
+ (condition-case nil
+ (org-add-to-diary-list original-date "Org mode dummy" "")
+ (error
+ (org-add-to-diary-list original-date "Org mode dummy" "" nil)))))
+
+(defun org-add-to-diary-list (&rest args)
+ (if (fboundp 'diary-add-to-list)
+ (apply 'diary-add-to-list args)
+ (apply 'add-to-diary-list args)))
+
+(defvar org-diary-last-run-time nil)
+
+;;;###autoload
+(defun org-diary (&rest args)
+ "Return diary information from org files.
+This function can be used in a \"sexp\" diary entry in the Emacs calendar.
+It accesses org files and extracts information from those files to be
+listed in the diary. The function accepts arguments specifying what
+items should be listed. For a list of arguments allowed here, see the
+variable `org-agenda-entry-types'.
+
+The call in the diary file should look like this:
+
+ &%%(org-diary) ~/path/to/some/orgfile.org
+
+Use a separate line for each org file to check. Or, if you omit the file name,
+all files listed in `org-agenda-files' will be checked automatically:
+
+ &%%(org-diary)
+
+If you don't give any arguments (as in the example above), the default value
+of `org-agenda-entry-types' is used: (:deadline :scheduled :timestamp :sexp).
+So the example above may also be written as
+
+ &%%(org-diary :deadline :timestamp :sexp :scheduled)
+
+The function expects the lisp variables `entry' and `date' to be provided
+by the caller, because this is how the calendar works. Don't use this
+function from a program - use `org-agenda-get-day-entries' instead."
+ (when (> (- (float-time)
+ org-agenda-last-marker-time)
+ 5)
+ ;; I am not sure if this works with sticky agendas, because the marker
+ ;; list is then no longer a global variable.
+ (org-agenda-reset-markers))
+ (org-compile-prefix-format 'agenda)
+ (org-set-sorting-strategy 'agenda)
+ (setq args (or args org-agenda-entry-types))
+ (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
+ (list entry)
+ (org-agenda-files t)))
+ (time (float-time))
+ file rtn results)
+ (when (or (not org-diary-last-run-time)
+ (> (- time
+ org-diary-last-run-time)
+ 3))
+ (org-agenda-prepare-buffers files))
+ (setq org-diary-last-run-time time)
+ ;; If this is called during org-agenda, don't return any entries to
+ ;; the calendar. Org Agenda will list these entries itself.
+ (if org-disable-agenda-to-diary (setq files nil))
+ (while (setq file (pop files))
+ (setq rtn (apply 'org-agenda-get-day-entries file date args))
+ (setq results (append results rtn)))
+ (when results
+ (setq results
+ (mapcar (lambda (i) (replace-regexp-in-string
+ org-bracket-link-regexp "\\3" i)) results))
+ (concat (org-agenda-finalize-entries results) "\n"))))
+
+;;; Agenda entry finders
+
+(defun org-agenda--timestamp-to-absolute (&rest args)
+ "Call `org-time-string-to-absolute' with ARGS.
+However, throw `:skip' whenever an error is raised."
+ (condition-case e
+ (apply #'org-time-string-to-absolute args)
+ (org-diary-sexp-no-match (throw :skip nil))
+ (error
+ (message "%s; Skipping entry" (error-message-string e))
+ (throw :skip nil))))
+
+(defun org-agenda-get-day-entries (file date &rest args)
+ "Does the work for `org-diary' and `org-agenda'.
+FILE is the path to a file to be checked for entries. DATE is date like
+the one returned by `calendar-current-date'. ARGS are symbols indicating
+which kind of entries should be extracted. For details about these, see
+the documentation of `org-diary'."
+ (let* ((org-startup-folded nil)
+ (org-startup-align-all-tables nil)
+ (buffer (if (file-exists-p file) (org-get-agenda-file-buffer file)
+ (error "No such file %s" file))))
+ (if (not buffer)
+ ;; If file does not exist, signal it in diary nonetheless.
+ (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
+ (with-current-buffer buffer
+ (unless (derived-mode-p 'org-mode)
+ (error "Agenda file %s is not in `org-mode'" file))
+ (setq org-agenda-buffer (or org-agenda-buffer buffer))
+ (setf org-agenda-current-date date)
+ (save-excursion
+ (save-restriction
+ (if (eq buffer org-agenda-restrict)
+ (narrow-to-region org-agenda-restrict-begin
+ org-agenda-restrict-end)
+ (widen))
+ ;; Rationalize ARGS. Also make sure `:deadline' comes
+ ;; first in order to populate DEADLINES before passing it.
+ ;;
+ ;; We use `delq' since `org-uniquify' duplicates ARGS,
+ ;; guarding us from modifying `org-agenda-entry-types'.
+ (setf args (org-uniquify (or args org-agenda-entry-types)))
+ (when (and (memq :scheduled args) (memq :scheduled* args))
+ (setf args (delq :scheduled* args)))
+ (cond
+ ((memq :deadline args)
+ (setf args (cons :deadline
+ (delq :deadline (delq :deadline* args)))))
+ ((memq :deadline* args)
+ (setf args (cons :deadline* (delq :deadline* args)))))
+ ;; Collect list of headlines. Return them flattened.
+ (let ((case-fold-search nil) results deadlines)
+ (dolist (arg args (apply #'nconc (nreverse results)))
+ (pcase arg
+ ((and :todo (guard (org-agenda-today-p date)))
+ (push (org-agenda-get-todos) results))
+ (:timestamp
+ (push (org-agenda-get-blocks) results)
+ (push (org-agenda-get-timestamps deadlines) results))
+ (:sexp
+ (push (org-agenda-get-sexps) results))
+ (:scheduled
+ (push (org-agenda-get-scheduled deadlines) results))
+ (:scheduled*
+ (push (org-agenda-get-scheduled deadlines t) results))
+ (:closed
+ (push (org-agenda-get-progress) results))
+ (:deadline
+ (setf deadlines (org-agenda-get-deadlines))
+ (push deadlines results))
+ (:deadline*
+ (setf deadlines (org-agenda-get-deadlines t))
+ (push deadlines results)))))))))))
+
+(defsubst org-em (x y list)
+ "Is X or Y a member of LIST?"
+ (or (memq x list) (memq y list)))
+
+(defvar org-heading-keyword-regexp-format) ; defined in org.el
+(defvar org-agenda-sorting-strategy-selected nil)
+
+(defun org-agenda-entry-get-agenda-timestamp (pom)
+ "Retrieve timestamp information for sorting agenda views.
+Given a point or marker POM, returns a cons cell of the timestamp
+and the timestamp type relevant for the sorting strategy in
+`org-agenda-sorting-strategy-selected'."
+ (let (ts ts-date-type)
+ (save-match-data
+ (cond ((org-em 'scheduled-up 'scheduled-down
+ org-agenda-sorting-strategy-selected)
+ (setq ts (org-entry-get pom "SCHEDULED")
+ ts-date-type " scheduled"))
+ ((org-em 'deadline-up 'deadline-down
+ org-agenda-sorting-strategy-selected)
+ (setq ts (org-entry-get pom "DEADLINE")
+ ts-date-type " deadline"))
+ ((org-em 'ts-up 'ts-down
+ org-agenda-sorting-strategy-selected)
+ (setq ts (org-entry-get pom "TIMESTAMP")
+ ts-date-type " timestamp"))
+ ((org-em 'tsia-up 'tsia-down
+ org-agenda-sorting-strategy-selected)
+ (setq ts (org-entry-get pom "TIMESTAMP_IA")
+ ts-date-type " timestamp_ia"))
+ ((org-em 'timestamp-up 'timestamp-down
+ org-agenda-sorting-strategy-selected)
+ (setq ts (or (org-entry-get pom "SCHEDULED")
+ (org-entry-get pom "DEADLINE")
+ (org-entry-get pom "TIMESTAMP")
+ (org-entry-get pom "TIMESTAMP_IA"))
+ ts-date-type ""))
+ (t (setq ts-date-type "")))
+ (cons (when ts (ignore-errors (org-time-string-to-absolute ts)))
+ ts-date-type))))
+
+(defun org-agenda-get-todos ()
+ "Return the TODO information for agenda display."
+ (let* ((props (list 'face nil
+ 'done-face 'org-agenda-done
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'mouse-face 'highlight
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (case-fold-search nil)
+ (regexp (format org-heading-keyword-regexp-format
+ (cond
+ ((and org-select-this-todo-keyword
+ (equal org-select-this-todo-keyword "*"))
+ org-todo-regexp)
+ (org-select-this-todo-keyword
+ (concat "\\("
+ (mapconcat 'identity
+ (org-split-string
+ org-select-this-todo-keyword
+ "|")
+ "\\|") "\\)"))
+ (t org-not-done-regexp))))
+ marker priority category level tags todo-state
+ ts-date ts-date-type ts-date-pair
+ ee txt beg end inherited-tags todo-state-end-pos)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (save-match-data
+ (beginning-of-line)
+ (org-agenda-skip)
+ (setq beg (point) end (save-excursion (outline-next-heading) (point)))
+ (unless (and (setq todo-state (org-get-todo-state))
+ (setq todo-state-end-pos (match-end 2)))
+ (goto-char end)
+ (throw :skip nil))
+ (when (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item end)
+ (goto-char (1+ beg))
+ (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
+ (throw :skip nil)))
+ (goto-char (match-beginning 2))
+ (setq marker (org-agenda-new-marker (match-beginning 0))
+ category (org-get-category)
+ ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
+ ts-date (car ts-date-pair)
+ ts-date-type (cdr ts-date-pair)
+ txt (org-trim (buffer-substring (match-beginning 2) (match-end 0)))
+ inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'todo org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'todo org-agenda-use-tag-inheritance))))
+ tags (org-get-tags-at nil (not inherited-tags))
+ level (make-string (org-reduced-level (org-outline-level)) ? )
+ txt (org-agenda-format-item "" txt level category tags t)
+ priority (1+ (org-get-priority txt)))
+ (org-add-props txt props
+ 'org-marker marker 'org-hd-marker marker
+ 'priority priority
+ 'level level
+ 'ts-date ts-date
+ 'type (concat "todo" ts-date-type) 'todo-state todo-state)
+ (push txt ee)
+ (if org-agenda-todo-list-sublevels
+ (goto-char todo-state-end-pos)
+ (org-end-of-subtree 'invisible))))
+ (nreverse ee)))
+
+(defun org-agenda-todo-custom-ignore-p (time n)
+ "Check whether timestamp is farther away than n number of days.
+This function is invoked if `org-agenda-todo-ignore-deadlines',
+`org-agenda-todo-ignore-scheduled' or
+`org-agenda-todo-ignore-timestamp' is set to an integer."
+ (let ((days (org-time-stamp-to-now
+ time org-agenda-todo-ignore-time-comparison-use-seconds)))
+ (if (>= n 0)
+ (>= days n)
+ (<= days n))))
+
+;;;###autoload
+(defun org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
+ (&optional end)
+ "Do we have a reason to ignore this TODO entry because it has a time stamp?"
+ (when (or org-agenda-todo-ignore-with-date
+ org-agenda-todo-ignore-scheduled
+ org-agenda-todo-ignore-deadlines
+ org-agenda-todo-ignore-timestamp)
+ (setq end (or end (save-excursion (outline-next-heading) (point))))
+ (save-excursion
+ (or (and org-agenda-todo-ignore-with-date
+ (re-search-forward org-ts-regexp end t))
+ (and org-agenda-todo-ignore-scheduled
+ (re-search-forward org-scheduled-time-regexp end t)
+ (cond
+ ((eq org-agenda-todo-ignore-scheduled 'future)
+ (> (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((eq org-agenda-todo-ignore-scheduled 'past)
+ (<= (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((numberp org-agenda-todo-ignore-scheduled)
+ (org-agenda-todo-custom-ignore-p
+ (match-string 1) org-agenda-todo-ignore-scheduled))
+ (t)))
+ (and org-agenda-todo-ignore-deadlines
+ (re-search-forward org-deadline-time-regexp end t)
+ (cond
+ ((memq org-agenda-todo-ignore-deadlines '(t all)) t)
+ ((eq org-agenda-todo-ignore-deadlines 'far)
+ (not (org-deadline-close-p (match-string 1))))
+ ((eq org-agenda-todo-ignore-deadlines 'future)
+ (> (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((eq org-agenda-todo-ignore-deadlines 'past)
+ (<= (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((numberp org-agenda-todo-ignore-deadlines)
+ (org-agenda-todo-custom-ignore-p
+ (match-string 1) org-agenda-todo-ignore-deadlines))
+ (t (org-deadline-close-p (match-string 1)))))
+ (and org-agenda-todo-ignore-timestamp
+ (let ((buffer (current-buffer))
+ (regexp
+ (concat
+ org-scheduled-time-regexp "\\|" org-deadline-time-regexp))
+ (start (point)))
+ ;; Copy current buffer into a temporary one
+ (with-temp-buffer
+ (insert-buffer-substring buffer start end)
+ (goto-char (point-min))
+ ;; Delete SCHEDULED and DEADLINE items
+ (while (re-search-forward regexp end t)
+ (delete-region (match-beginning 0) (match-end 0)))
+ (goto-char (point-min))
+ ;; No search for timestamp left
+ (when (re-search-forward org-ts-regexp nil t)
+ (cond
+ ((eq org-agenda-todo-ignore-timestamp 'future)
+ (> (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((eq org-agenda-todo-ignore-timestamp 'past)
+ (<= (org-time-stamp-to-now
+ (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0))
+ ((numberp org-agenda-todo-ignore-timestamp)
+ (org-agenda-todo-custom-ignore-p
+ (match-string 1) org-agenda-todo-ignore-timestamp))
+ (t))))))))))
+
+(defun org-agenda-get-timestamps (&optional deadlines)
+ "Return the date stamp information for agenda display.
+Optional argument DEADLINES is a list of deadline items to be
+displayed in agenda view."
+ (let* ((props (list 'face 'org-agenda-calendar-event
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'mouse-face 'highlight
+ 'help-echo
+ (format "mouse-2 or RET jump to Org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (current (calendar-absolute-from-gregorian date))
+ (today (org-today))
+ (deadline-position-alist
+ (mapcar (lambda (d)
+ (let ((m (get-text-property 0 'org-hd-marker d)))
+ (and m (marker-position m))))
+ deadlines))
+ ;; Match time-stamps set to current date, time-stamps with
+ ;; a repeater, and S-exp time-stamps.
+ (regexp
+ (concat
+ (if org-agenda-include-inactive-timestamps "[[<]" "<")
+ (regexp-quote
+ (substring
+ (format-time-string
+ (car org-time-stamp-formats)
+ (apply #'encode-time ; DATE bound by calendar
+ (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
+ 1 11))
+ "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[hdwmy]>\\)"
+ "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
+ timestamp-items)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ ;; Skip date ranges, scheduled and deadlines, which are handled
+ ;; specially. Also skip time-stamps before first headline as
+ ;; there would be no entry to add to the agenda. Eventually,
+ ;; ignore clock entries.
+ (catch :skip
+ (save-match-data
+ (when (or (org-at-date-range-p)
+ (org-at-planning-p)
+ (org-before-first-heading-p)
+ (and org-agenda-include-inactive-timestamps
+ (org-at-clock-log-p)))
+ (throw :skip nil))
+ (org-agenda-skip))
+ (let* ((pos (match-beginning 0))
+ (repeat (match-string 1))
+ (sexp-entry (match-string 3))
+ (time-stamp (if (or repeat sexp-entry) (match-string 0)
+ (save-excursion
+ (goto-char pos)
+ (looking-at org-ts-regexp-both)
+ (match-string 0))))
+ (todo-state (org-get-todo-state))
+ (show-all (or (eq org-agenda-repeating-timestamp-show-all t)
+ (member todo-state
+ org-agenda-repeating-timestamp-show-all)))
+ (warntime (get-text-property (point) 'org-appt-warntime))
+ (done? (member todo-state org-done-keywords)))
+ ;; Possibly skip done tasks.
+ (when (and done? org-agenda-skip-timestamp-if-done)
+ (throw :skip t))
+ ;; S-exp entry doesn't match current day: skip it.
+ (when (and sexp-entry (not (org-diary-sexp-entry sexp-entry "" date)))
+ (throw :skip nil))
+ ;; When time-stamp doesn't match CURRENT but has a repeater,
+ ;; make sure it repeats on CURRENT. Furthermore, if
+ ;; SHOW-ALL is nil, ensure that repeats are only the first
+ ;; before and the first after today.
+ (when (and repeat
+ (if show-all
+ (/= current
+ (org-agenda--timestamp-to-absolute
+ repeat current 'future (current-buffer) pos))
+ (and (/= current
+ (org-agenda--timestamp-to-absolute
+ repeat today 'past (current-buffer) pos))
+ (/= current
+ (org-agenda--timestamp-to-absolute
+ repeat today 'future (current-buffer) pos)))))
+ (throw :skip nil))
+ (save-excursion
+ (re-search-backward org-outline-regexp-bol nil t)
+ ;; Possibly skip time-stamp when a deadline is set.
+ (when (and org-agenda-skip-timestamp-if-deadline-is-shown
+ (assq (point) deadline-position-alist))
+ (throw :skip nil))
+ (let* ((category (org-get-category pos))
+ (inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (consp org-agenda-show-inherited-tags)
+ (memq 'agenda org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'agenda
+ org-agenda-use-tag-inheritance)))))
+ (tags (org-get-tags-at nil (not inherited-tags)))
+ (level (make-string (org-reduced-level (org-outline-level))
+ ?\s))
+ (head (and (looking-at "\\*+[ \t]+\\(.*\\)")
+ (match-string 1)))
+ (inactive? (= (char-after pos) ?\[))
+ (habit? (and (fboundp 'org-is-habit-p) (org-is-habit-p)))
+ (item
+ (org-agenda-format-item
+ (and inactive? org-agenda-inactive-leader)
+ head level category tags time-stamp org-ts-regexp habit?)))
+ (org-add-props item props
+ 'priority (if habit?
+ (org-habit-get-priority (org-habit-parse-todo))
+ (org-get-priority item))
+ 'org-marker (org-agenda-new-marker pos)
+ 'org-hd-marker (org-agenda-new-marker)
+ 'date date
+ 'level level
+ 'ts-date (if repeat (org-agenda--timestamp-to-absolute repeat)
+ current)
+ 'todo-state todo-state
+ 'warntime warntime
+ 'type "timestamp")
+ (push item timestamp-items))))
+ (when org-agenda-skip-additional-timestamps-same-entry
+ (outline-next-heading))))
+ (nreverse timestamp-items)))
+
+(defun org-agenda-get-sexps ()
+ "Return the sexp information for agenda display."
+ (require 'diary-lib)
+ (let* ((props (list 'face 'org-agenda-calendar-sexp
+ 'mouse-face 'highlight
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (regexp "^&?%%(")
+ marker category extra level ee txt tags entry
+ result beg b sexp sexp-entry todo-state warntime inherited-tags)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (org-agenda-skip)
+ (setq beg (match-beginning 0))
+ (goto-char (1- (match-end 0)))
+ (setq b (point))
+ (forward-sexp 1)
+ (setq sexp (buffer-substring b (point)))
+ (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
+ (org-trim (match-string 1))
+ ""))
+ (setq result (org-diary-sexp-entry sexp sexp-entry date))
+ (when result
+ (setq marker (org-agenda-new-marker beg)
+ level (make-string (org-reduced-level (org-outline-level)) ? )
+ category (org-get-category beg)
+ inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'agenda org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'agenda org-agenda-use-tag-inheritance))))
+ tags (org-get-tags-at nil (not inherited-tags))
+ todo-state (org-get-todo-state)
+ warntime (get-text-property (point) 'org-appt-warntime)
+ extra nil)
+
+ (dolist (r (if (stringp result)
+ (list result)
+ result)) ;; we expect a list here
+ (when (and org-agenda-diary-sexp-prefix
+ (string-match org-agenda-diary-sexp-prefix r))
+ (setq extra (match-string 0 r)
+ r (replace-match "" nil nil r)))
+ (if (string-match "\\S-" r)
+ (setq txt r)
+ (setq txt "SEXP entry returned empty string"))
+ (setq txt (org-agenda-format-item extra txt level category tags 'time))
+ (org-add-props txt props 'org-marker marker
+ 'date date 'todo-state todo-state
+ 'level level 'type "sexp" 'warntime warntime)
+ (push txt ee)))))
+ (nreverse ee)))
+
+;; Calendar sanity: define some functions that are independent of
+;; `calendar-date-style'.
+(defun org-anniversary (year month day &optional mark)
+ "Like `diary-anniversary', but with fixed (ISO) order of arguments."
+ (with-no-warnings
+ (let ((calendar-date-style 'iso))
+ (diary-anniversary year month day mark))))
+(defun org-cyclic (N year month day &optional mark)
+ "Like `diary-cyclic', but with fixed (ISO) order of arguments."
+ (with-no-warnings
+ (let ((calendar-date-style 'iso))
+ (diary-cyclic N year month day mark))))
+(defun org-block (Y1 M1 D1 Y2 M2 D2 &optional mark)
+ "Like `diary-block', but with fixed (ISO) order of arguments."
+ (with-no-warnings
+ (let ((calendar-date-style 'iso))
+ (diary-block Y1 M1 D1 Y2 M2 D2 mark))))
+(defun org-date (year month day &optional mark)
+ "Like `diary-date', but with fixed (ISO) order of arguments."
+ (with-no-warnings
+ (let ((calendar-date-style 'iso))
+ (diary-date year month day mark))))
+
+;; Define the `org-class' function
+(defun org-class (y1 m1 d1 y2 m2 d2 dayname &rest skip-weeks)
+ "Entry applies if date is between dates on DAYNAME, but skips SKIP-WEEKS.
+DAYNAME is a number between 0 (Sunday) and 6 (Saturday).
+SKIP-WEEKS is any number of ISO weeks in the block period for which the
+item should be skipped. If any of the SKIP-WEEKS arguments is the symbol
+`holidays', then any date that is known by the Emacs calendar to be a
+holiday will also be skipped. If SKIP-WEEKS arguments are holiday strings,
+then those holidays will be skipped."
+ (let* ((date1 (calendar-absolute-from-gregorian (list m1 d1 y1)))
+ (date2 (calendar-absolute-from-gregorian (list m2 d2 y2)))
+ (d (calendar-absolute-from-gregorian date))
+ (h (when skip-weeks (calendar-check-holidays date))))
+ (and
+ (<= date1 d)
+ (<= d date2)
+ (= (calendar-day-of-week date) dayname)
+ (or (not skip-weeks)
+ (progn
+ (require 'cal-iso)
+ (not (member (car (calendar-iso-from-absolute d)) skip-weeks))))
+ (not (or (and h (memq 'holidays skip-weeks))
+ (delq nil (mapcar (lambda(g) (member g skip-weeks)) h))))
+ entry)))
+
+(defalias 'org-get-closed 'org-agenda-get-progress)
+(defun org-agenda-get-progress ()
+ "Return the logged TODO entries for agenda display."
+ (let* ((props (list 'mouse-face 'highlight
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (items (if (consp org-agenda-show-log-scoped)
+ org-agenda-show-log-scoped
+ (if (eq org-agenda-show-log-scoped 'clockcheck)
+ '(clock)
+ org-agenda-log-mode-items)))
+ (parts
+ (delq nil
+ (list
+ (if (memq 'closed items) (concat "\\<" org-closed-string))
+ (if (memq 'clock items) (concat "\\<" org-clock-string))
+ (if (memq 'state items) "- State \"\\([a-zA-Z0-9]+\\)\".*?"))))
+ (parts-re (if parts (mapconcat 'identity parts "\\|")
+ (error "`org-agenda-log-mode-items' is empty")))
+ (regexp (concat
+ "\\(" parts-re "\\)"
+ " *\\["
+ (regexp-quote
+ (substring
+ (format-time-string
+ (car org-time-stamp-formats)
+ (apply 'encode-time ; DATE bound by calendar
+ (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
+ 1 11))))
+ (org-agenda-search-headline-for-time nil)
+ marker hdmarker priority category level tags closedp
+ statep clockp state ee txt extra timestr rest clocked inherited-tags)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (org-agenda-skip)
+ (setq marker (org-agenda-new-marker (match-beginning 0))
+ closedp (equal (match-string 1) org-closed-string)
+ statep (equal (string-to-char (match-string 1)) ?-)
+ clockp (not (or closedp statep))
+ state (and statep (match-string 2))
+ category (org-get-category (match-beginning 0))
+ timestr (buffer-substring (match-beginning 0) (point-at-eol)))
+ (when (string-match "\\]" timestr)
+ ;; substring should only run to end of time stamp
+ (setq rest (substring timestr (match-end 0))
+ timestr (substring timestr 0 (match-end 0)))
+ (if (and (not closedp) (not statep)
+ (string-match "\\([0-9]\\{1,2\\}:[0-9]\\{2\\}\\)\\].*?\\([0-9]\\{1,2\\}:[0-9]\\{2\\}\\)"
+ rest))
+ (progn (setq timestr (concat (substring timestr 0 -1)
+ "-" (match-string 1 rest) "]"))
+ (setq clocked (match-string 2 rest)))
+ (setq clocked "-")))
+ (save-excursion
+ (setq extra
+ (cond
+ ((not org-agenda-log-mode-add-notes) nil)
+ (statep
+ (and (looking-at ".*\\\\\n[ \t]*\\([^-\n \t].*?\\)[ \t]*$")
+ (match-string 1)))
+ (clockp
+ (and (looking-at ".*\n[ \t]*-[ \t]+\\([^-\n \t].*?\\)[ \t]*$")
+ (match-string 1)))))
+ (if (not (re-search-backward org-outline-regexp-bol nil t))
+ (throw :skip nil)
+ (goto-char (match-beginning 0))
+ (setq hdmarker (org-agenda-new-marker)
+ inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'todo org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'todo org-agenda-use-tag-inheritance))))
+ tags (org-get-tags-at nil (not inherited-tags))
+ level (make-string (org-reduced-level (org-outline-level)) ? ))
+ (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
+ (setq txt (match-string 1))
+ (when extra
+ (if (string-match "\\([ \t]+\\)\\(:[^ \n\t]*?:\\)[ \t]*$" txt)
+ (setq txt (concat (substring txt 0 (match-beginning 1))
+ " - " extra " " (match-string 2 txt)))
+ (setq txt (concat txt " - " extra))))
+ (setq txt (org-agenda-format-item
+ (cond
+ (closedp "Closed: ")
+ (statep (concat "State: (" state ")"))
+ (t (concat "Clocked: (" clocked ")")))
+ txt level category tags timestr)))
+ (setq priority 100000)
+ (org-add-props txt props
+ 'org-marker marker 'org-hd-marker hdmarker 'face 'org-agenda-done
+ 'priority priority 'level level
+ 'type "closed" 'date date
+ 'undone-face 'org-warning 'done-face 'org-agenda-done)
+ (push txt ee))
+ (goto-char (point-at-eol))))
+ (nreverse ee)))
+
+(defun org-agenda-show-clocking-issues ()
+ "Add overlays, showing issues with clocking.
+See also the user option `org-agenda-clock-consistency-checks'."
+ (interactive)
+ (let* ((org-time-clocksum-use-effort-durations nil)
+ (pl org-agenda-clock-consistency-checks)
+ (re (concat "^[ \t]*"
+ org-clock-string
+ "[ \t]+"
+ "\\(\\[.*?\\]\\)" ; group 1 is first stamp
+ "\\(-\\{1,3\\}\\(\\[.*?\\]\\)\\)?")) ; group 3 is second
+ (tlstart 0.)
+ (tlend 0.)
+ (maxtime (org-hh:mm-string-to-minutes
+ (or (plist-get pl :max-duration) "24:00")))
+ (mintime (org-hh:mm-string-to-minutes
+ (or (plist-get pl :min-duration) 0)))
+ (maxgap (org-hh:mm-string-to-minutes
+ ;; default 30:00 means never complain
+ (or (plist-get pl :max-gap) "30:00")))
+ (gapok (mapcar 'org-hh:mm-string-to-minutes
+ (plist-get pl :gap-ok-around)))
+ (def-face (or (plist-get pl :default-face)
+ '((:background "DarkRed") (:foreground "white"))))
+ issue face m te ts dt ov)
+ (goto-char (point-min))
+ (while (re-search-forward " Clocked: +(-\\|\\([0-9]+:[0-9]+\\))" nil t)
+ (setq issue nil face def-face)
+ (catch 'next
+ (setq m (org-get-at-bol 'org-marker)
+ te nil ts nil)
+ (unless (and m (markerp m))
+ (setq issue "No valid clock line") (throw 'next t))
+ (org-with-point-at m
+ (save-excursion
+ (goto-char (point-at-bol))
+ (unless (looking-at re)
+ (error "No valid Clock line")
+ (throw 'next t))
+ (unless (match-end 3)
+ (setq issue "No end time"
+ face (or (plist-get pl :no-end-time-face) face))
+ (throw 'next t))
+ (setq ts (match-string 1)
+ te (match-string 3)
+ ts (float-time
+ (apply #'encode-time (org-parse-time-string ts)))
+ te (float-time
+ (apply #'encode-time (org-parse-time-string te)))
+ dt (- te ts))))
+ (cond
+ ((> dt (* 60 maxtime))
+ ;; a very long clocking chunk
+ (setq issue (format "Clocking interval is very long: %s"
+ (org-minutes-to-clocksum-string
+ (floor (/ (float dt) 60.))))
+ face (or (plist-get pl :long-face) face)))
+ ((< dt (* 60 mintime))
+ ;; a very short clocking chunk
+ (setq issue (format "Clocking interval is very short: %s"
+ (org-minutes-to-clocksum-string
+ (floor (/ (float dt) 60.))))
+ face (or (plist-get pl :short-face) face)))
+ ((and (> tlend 0) (< ts tlend))
+ ;; Two clock entries are overlapping
+ (setq issue (format "Clocking overlap: %d minutes"
+ (/ (- tlend ts) 60))
+ face (or (plist-get pl :overlap-face) face)))
+ ((and (> tlend 0) (> ts (+ tlend (* 60 maxgap))))
+ ;; There is a gap, lets see if we need to report it
+ (unless (org-agenda-check-clock-gap tlend ts gapok)
+ (setq issue (format "Clocking gap: %d minutes"
+ (/ (- ts tlend) 60))
+ face (or (plist-get pl :gap-face) face))))
+ (t nil)))
+ (setq tlend (or te tlend) tlstart (or ts tlstart))
+ (when issue
+ ;; OK, there was some issue, add an overlay to show the issue
+ (setq ov (make-overlay (point-at-bol) (point-at-eol)))
+ (overlay-put ov 'before-string
+ (concat
+ (org-add-props
+ (format "%-43s" (concat " " issue))
+ nil
+ 'face face)
+ "\n"))
+ (overlay-put ov 'evaporate t)))))
+
+(defun org-agenda-check-clock-gap (t1 t2 ok-list)
+ "Check if gap T1 -> T2 contains one of the OK-LIST time-of-day values."
+ (catch 'exit
+ (unless ok-list
+ ;; there are no OK times for gaps...
+ (throw 'exit nil))
+ (if (> (- (/ t2 36000) (/ t1 36000)) 24)
+ ;; This is more than 24 hours, so it is OK.
+ ;; because we have at least one OK time, that must be in the
+ ;; 24 hour interval.
+ (throw 'exit t))
+ ;; We have a shorter gap.
+ ;; Now we have to get the minute of the day when these times are
+ (let* ((t1dec (decode-time (seconds-to-time t1)))
+ (t2dec (decode-time (seconds-to-time t2)))
+ ;; compute the minute on the day
+ (min1 (+ (nth 1 t1dec) (* 60 (nth 2 t1dec))))
+ (min2 (+ (nth 1 t2dec) (* 60 (nth 2 t2dec)))))
+ (when (< min2 min1)
+ ;; if min2 is smaller than min1, this means it is on the next day.
+ ;; Wrap it to after midnight.
+ (setq min2 (+ min2 1440)))
+ ;; Now check if any of the OK times is in the gap
+ (mapc (lambda (x)
+ ;; Wrap the time to after midnight if necessary
+ (if (< x min1) (setq x (+ x 1440)))
+ ;; Check if in interval
+ (and (<= min1 x) (>= min2 x) (throw 'exit t)))
+ ok-list)
+ ;; Nope, this gap is not OK
+ nil)))
+
+(defun org-agenda-get-deadlines (&optional with-hour)
+ "Return the deadline information for agenda display.
+When WITH-HOUR is non-nil, only return deadlines with an hour
+specification like [h]h:mm."
+ (let* ((props (list 'mouse-face 'highlight
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (regexp (if with-hour
+ org-deadline-time-hour-regexp
+ org-deadline-time-regexp))
+ (today (org-today))
+ (today? (org-agenda-today-p date)) ; DATE bound by calendar.
+ (current (calendar-absolute-from-gregorian date))
+ deadline-items)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
+ (org-agenda-skip)
+ (let* ((s (match-string 1))
+ (pos (1- (match-beginning 1)))
+ (todo-state (save-match-data (org-get-todo-state)))
+ (done? (member todo-state org-done-keywords))
+ (show-all (or (eq org-agenda-repeating-timestamp-show-all t)
+ (member todo-state
+ org-agenda-repeating-timestamp-show-all)))
+ (sexp? (string-prefix-p "%%" s))
+ ;; DEADLINE is the bare deadline date, i.e., without
+ ;; any repeater, or the last repeat if SHOW-ALL is
+ ;; non-nil. REPEAT is closest repeat after CURRENT, if
+ ;; all repeated time stamps are to be shown, or after
+ ;; TODAY otherwise. REPEAT only applies to future
+ ;; dates.
+ (deadline (cond
+ (sexp? (org-agenda--timestamp-to-absolute s current))
+ (show-all (org-agenda--timestamp-to-absolute s))
+ (t (org-agenda--timestamp-to-absolute
+ s today 'past (current-buffer) pos))))
+ (repeat (cond (sexp? deadline)
+ ((< current today) deadline)
+ (t
+ (org-agenda--timestamp-to-absolute
+ s (if show-all current today) 'future
+ (current-buffer) pos))))
+ (diff (- deadline current))
+ (suppress-prewarning
+ (let ((scheduled
+ (and org-agenda-skip-deadline-prewarning-if-scheduled
+ (org-entry-get nil "SCHEDULED"))))
+ (cond
+ ((not scheduled) nil)
+ ;; The current item has a scheduled date, so
+ ;; evaluate its prewarning lead time.
+ ((integerp org-agenda-skip-deadline-prewarning-if-scheduled)
+ ;; Use global prewarning-restart lead time.
+ org-agenda-skip-deadline-prewarning-if-scheduled)
+ ((eq org-agenda-skip-deadline-prewarning-if-scheduled
+ 'pre-scheduled)
+ ;; Set pre-warning to no earlier than SCHEDULED.
+ (min (- deadline
+ (org-agenda--timestamp-to-absolute scheduled))
+ org-deadline-warning-days))
+ ;; Set pre-warning to deadline.
+ (t 0))))
+ (wdays (if suppress-prewarning
+ (let ((org-deadline-warning-days suppress-prewarning))
+ (org-get-wdays s))
+ (org-get-wdays s))))
+ ;; When to show a deadline in the calendar: if the
+ ;; expiration is within WDAYS warning time. Past-due
+ ;; deadlines are only shown on today agenda.
+ (when (cond ((= current deadline) nil)
+ ((< deadline today)
+ (and (not today?)
+ (or (< current today) (/= repeat current))))
+ ((> deadline current)
+ (or (not today?) (> diff wdays)))
+ (t (/= repeat current)))
+ (throw :skip nil))
+ ;; Possibly skip done tasks.
+ (when (and done?
+ (or org-agenda-skip-deadline-if-done
+ (/= deadline current)))
+ (throw :skip nil))
+ (save-excursion
+ (re-search-backward "^\\*+[ \t]+" nil t)
+ (goto-char (match-end 0))
+ (let* ((category (org-get-category))
+ (level
+ (make-string (org-reduced-level (org-outline-level)) ?\s))
+ (head (buffer-substring (point) (line-end-position)))
+ (inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'agenda org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'agenda
+ org-agenda-use-tag-inheritance)))))
+ (tags (org-get-tags-at nil (not inherited-tags)))
+ (time
+ (cond
+ ;; No time of day designation if it is only
+ ;; a reminder.
+ ((and (/= current deadline) (/= current repeat)) nil)
+ ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
+ (concat (substring s (match-beginning 1)) " "))
+ (t 'time)))
+ (item
+ (org-agenda-format-item
+ ;; Insert appropriate suffixes before deadlines.
+ (pcase-let ((`(,now ,future ,past)
+ org-agenda-deadline-leaders))
+ (cond
+ ;; Future (i.e., repeated) deadlines are
+ ;; displayed as new headlines.
+ ((> current today) now)
+ ;; When SHOW-ALL is nil, prefer repeated
+ ;; deadlines over reminders of past deadlines.
+ ((and (not show-all) (= repeat today)) now)
+ ((= deadline current) now)
+ ((< deadline current) (format past (- diff)))
+ (t (format future diff))))
+ head level category tags
+ (and (or (= repeat current) (= deadline current))
+ time)))
+ (face (org-agenda-deadline-face
+ (- 1 (/ (float (- deadline current)) (max wdays 1)))))
+ (upcoming? (and today? (> deadline today)))
+ (warntime (get-text-property (point) 'org-appt-warntime)))
+ (org-add-props item props
+ 'org-marker (org-agenda-new-marker pos)
+ 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
+ 'warntime warntime
+ 'level level
+ 'ts-date deadline
+ 'priority
+ ;; Adjust priority to today reminders about deadlines.
+ ;; Overdue deadlines get the highest priority
+ ;; increase, then imminent deadlines and eventually
+ ;; more distant deadlines.
+ (let ((adjust (cond ((not today?) 0)
+ ((and (not show-all) (= repeat current)) 0)
+ (t (- diff)))))
+ (+ adjust (org-get-priority item)))
+ 'todo-state todo-state
+ 'type (if upcoming? "upcoming-deadline" "deadline")
+ 'date (if upcoming? date deadline)
+ 'face (if done? 'org-agenda-done face)
+ 'undone-face face
+ 'done-face 'org-agenda-done)
+ (push item deadline-items))))))
+ (nreverse deadline-items)))
+
+(defun org-agenda-deadline-face (fraction)
+ "Return the face to displaying a deadline item.
+FRACTION is what fraction of the head-warning time has passed."
+ (assoc-default fraction org-agenda-deadline-faces #'<=))
+
+(defun org-agenda-get-scheduled (&optional deadlines with-hour)
+ "Return the scheduled information for agenda display.
+Optional argument DEADLINES is a list of deadline items to be
+displayed in agenda view. When WITH-HOUR is non-nil, only return
+scheduled items with an hour specification like [h]h:mm."
+ (let* ((props (list 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'done-face 'org-agenda-done
+ 'mouse-face 'highlight
+ 'help-echo
+ (format "mouse-2 or RET jump to Org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (regexp (if with-hour
+ org-scheduled-time-hour-regexp
+ org-scheduled-time-regexp))
+ (today (org-today))
+ (todayp (org-agenda-today-p date)) ; DATE bound by calendar.
+ (current (calendar-absolute-from-gregorian date))
+ (deadline-pos
+ (mapcar (lambda (d)
+ (let ((m (get-text-property 0 'org-hd-marker d)))
+ (and m (marker-position m))))
+ deadlines))
+ scheduled-items)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (unless (save-match-data (org-at-planning-p)) (throw :skip nil))
+ (org-agenda-skip)
+ (let* ((s (match-string 1))
+ (pos (1- (match-beginning 1)))
+ (todo-state (save-match-data (org-get-todo-state)))
+ (donep (member todo-state org-done-keywords))
+ (show-all (or (eq org-agenda-repeating-timestamp-show-all t)
+ (member todo-state
+ org-agenda-repeating-timestamp-show-all)))
+ (sexp? (string-prefix-p "%%" s))
+ ;; SCHEDULE is the bare scheduled date, i.e., without
+ ;; any repeater if non-nil, or last repeat if SHOW-ALL
+ ;; is nil. REPEAT is the closest repeat after CURRENT,
+ ;; if all repeated time stamps are to be shown, or
+ ;; after TODAY otherwise. REPEAT only applies to
+ ;; future dates.
+ (schedule (cond
+ (sexp? (org-agenda--timestamp-to-absolute s current))
+ (show-all (org-agenda--timestamp-to-absolute s))
+ (t (org-agenda--timestamp-to-absolute
+ s today 'past (current-buffer) pos))))
+ (repeat (cond
+ (sexp? schedule)
+ ((< current today) schedule)
+ (t
+ (org-agenda--timestamp-to-absolute
+ s (if show-all current today) 'future
+ (current-buffer) pos))))
+ (diff (- current schedule))
+ (warntime (get-text-property (point) 'org-appt-warntime))
+ (pastschedp (< schedule today))
+ (habitp (and (fboundp 'org-is-habit-p) (org-is-habit-p)))
+ (suppress-delay
+ (let ((deadline (and org-agenda-skip-scheduled-delay-if-deadline
+ (org-entry-get nil "DEADLINE"))))
+ (cond
+ ((not deadline) nil)
+ ;; The current item has a deadline date, so
+ ;; evaluate its delay time.
+ ((integerp org-agenda-skip-scheduled-delay-if-deadline)
+ ;; Use global delay time.
+ (- org-agenda-skip-scheduled-delay-if-deadline))
+ ((eq org-agenda-skip-scheduled-delay-if-deadline
+ 'post-deadline)
+ ;; Set delay to no later than DEADLINE.
+ (min (- schedule
+ (org-agenda--timestamp-to-absolute deadline))
+ org-scheduled-delay-days))
+ (t 0))))
+ (ddays
+ (cond
+ ;; Nullify delay when a repeater triggered already
+ ;; and the delay is of the form --Xd.
+ ((and (string-match-p "--[0-9]+[hdwmy]" s)
+ (> current schedule))
+ 0)
+ (suppress-delay
+ (let ((org-scheduled-delay-days suppress-delay))
+ (org-get-wdays s t t)))
+ (t (org-get-wdays s t)))))
+ ;; Display scheduled items at base date (SCHEDULE), today if
+ ;; scheduled before the current date, and at any repeat past
+ ;; today. However, skip delayed items and items that have
+ ;; been displayed for more than `org-scheduled-past-days'.
+ (unless (and todayp
+ habitp
+ (bound-and-true-p org-habit-show-all-today))
+ (when (or (and (> ddays 0) (< diff ddays))
+ (> diff org-scheduled-past-days)
+ (> schedule current)
+ (and (< schedule current)
+ (not todayp)
+ (/= repeat current)))
+ (throw :skip nil)))
+ ;; Possibly skip done tasks.
+ (when (and donep
+ (or org-agenda-skip-scheduled-if-done
+ (/= schedule current)))
+ (throw :skip nil))
+ ;; Skip entry if it already appears as a deadline, per
+ ;; `org-agenda-skip-scheduled-if-deadline-is-shown'. This
+ ;; doesn't apply to habits.
+ (when (pcase org-agenda-skip-scheduled-if-deadline-is-shown
+ ((guard
+ (or (not (memq (line-beginning-position 0) deadline-pos))
+ habitp))
+ nil)
+ (`repeated-after-deadline
+ (>= repeat (time-to-days (org-get-deadline-time (point)))))
+ (`not-today pastschedp)
+ (`t t)
+ (_ nil))
+ (throw :skip nil))
+ ;; Skip habits if `org-habit-show-habits' is nil, or if we
+ ;; only show them for today. Also skip done habits.
+ (when (and habitp
+ (or donep
+ (not (bound-and-true-p org-habit-show-habits))
+ (and (not todayp)
+ (bound-and-true-p
+ org-habit-show-habits-only-for-today))))
+ (throw :skip nil))
+ (save-excursion
+ (re-search-backward "^\\*+[ \t]+" nil t)
+ (goto-char (match-end 0))
+ (let* ((category (org-get-category))
+ (inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'agenda org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'agenda
+ org-agenda-use-tag-inheritance)))))
+ (tags (org-get-tags-at nil (not inherited-tags)))
+ (level
+ (make-string (org-reduced-level (org-outline-level)) ?\s))
+ (head (buffer-substring (point) (line-end-position)))
+ (time
+ (cond
+ ;; No time of day designation if it is only
+ ;; a reminder.
+ ((and (/= current schedule) (/= current repeat)) nil)
+ ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
+ (concat (substring s (match-beginning 1)) " "))
+ (t 'time)))
+ (item
+ (org-agenda-format-item
+ (pcase-let ((`(,first ,next) org-agenda-scheduled-leaders))
+ (cond
+ ;; If CURRENT is in the future, don't use past
+ ;; scheduled prefix.
+ ((> current today) first)
+ ;; SHOW-ALL focuses on future repeats. If one
+ ;; such repeat happens today, ignore late
+ ;; schedule reminder. However, still report
+ ;; such reminders when repeat happens later.
+ ((and (not show-all) (= repeat today)) first)
+ ;; Initial report.
+ ((= schedule current) first)
+ ;; Subsequent reminders. Count from base
+ ;; schedule.
+ (t (format next diff))))
+ head level category tags time nil habitp))
+ (face (cond ((and (not habitp) pastschedp)
+ 'org-scheduled-previously)
+ (todayp 'org-scheduled-today)
+ (t 'org-scheduled)))
+ (habitp (and habitp (org-habit-parse-todo))))
+ (org-add-props item props
+ 'undone-face face
+ 'face (if donep 'org-agenda-done face)
+ 'org-marker (org-agenda-new-marker pos)
+ 'org-hd-marker (org-agenda-new-marker (line-beginning-position))
+ 'type (if pastschedp "past-scheduled" "scheduled")
+ 'date (if pastschedp schedule date)
+ 'ts-date schedule
+ 'warntime warntime
+ 'level level
+ 'priority (if habitp (org-habit-get-priority habitp)
+ (+ 99 diff (org-get-priority item)))
+ 'org-habit-p habitp
+ 'todo-state todo-state)
+ (push item scheduled-items))))))
+ (nreverse scheduled-items)))
+
+(defun org-agenda-get-blocks ()
+ "Return the date-range information for agenda display."
+ (let* ((props (list 'face nil
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'mouse-face 'highlight
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name buffer-file-name))))
+ (regexp org-tr-regexp)
+ (d0 (calendar-absolute-from-gregorian date))
+ marker hdmarker ee txt d1 d2 s1 s2 category
+ level todo-state tags pos head donep inherited-tags)
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (catch :skip
+ (org-agenda-skip)
+ (setq pos (point))
+ (let ((start-time (match-string 1))
+ (end-time (match-string 2)))
+ (setq s1 (match-string 1)
+ s2 (match-string 2)
+ d1 (time-to-days (org-time-string-to-time s1 (current-buffer) pos))
+ d2 (time-to-days (org-time-string-to-time s2 (current-buffer) pos)))
+ (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
+ ;; Only allow days between the limits, because the normal
+ ;; date stamps will catch the limits.
+ (save-excursion
+ (setq todo-state (org-get-todo-state))
+ (setq donep (member todo-state org-done-keywords))
+ (if (and donep org-agenda-skip-timestamp-if-done)
+ (throw :skip t))
+ (setq marker (org-agenda-new-marker (point))
+ category (org-get-category))
+ (if (not (re-search-backward org-outline-regexp-bol nil t))
+ (throw :skip nil)
+ (goto-char (match-beginning 0))
+ (setq hdmarker (org-agenda-new-marker (point))
+ inherited-tags
+ (or (eq org-agenda-show-inherited-tags 'always)
+ (and (listp org-agenda-show-inherited-tags)
+ (memq 'agenda org-agenda-show-inherited-tags))
+ (and (eq org-agenda-show-inherited-tags t)
+ (or (eq org-agenda-use-tag-inheritance t)
+ (memq 'agenda org-agenda-use-tag-inheritance))))
+
+ tags (org-get-tags-at nil (not inherited-tags)))
+ (setq level (make-string (org-reduced-level (org-outline-level)) ? ))
+ (looking-at "\\*+[ \t]+\\(.*\\)")
+ (setq head (match-string 1))
+ (let ((remove-re
+ (if org-agenda-remove-timeranges-from-blocks
+ (concat
+ "<" (regexp-quote s1) ".*?>"
+ "--"
+ "<" (regexp-quote s2) ".*?>")
+ nil)))
+ (setq txt (org-agenda-format-item
+ (format
+ (nth (if (= d1 d2) 0 1)
+ org-agenda-timerange-leaders)
+ (1+ (- d0 d1)) (1+ (- d2 d1)))
+ head level category tags
+ (cond ((and (= d1 d0) (= d2 d0))
+ (concat "<" start-time ">--<" end-time ">"))
+ ((= d1 d0)
+ (concat "<" start-time ">"))
+ ((= d2 d0)
+ (concat "<" end-time ">")))
+ remove-re))))
+ (org-add-props txt props
+ 'org-marker marker 'org-hd-marker hdmarker
+ 'type "block" 'date date
+ 'level level
+ 'todo-state todo-state
+ 'priority (org-get-priority txt))
+ (push txt ee))))
+ (goto-char pos)))
+ ;; Sort the entries by expiration date.
+ (nreverse ee)))
+
+;;; Agenda presentation and sorting
+
+(defvar org-prefix-has-time nil
+ "A flag, set by `org-compile-prefix-format'.
+The flag is set if the currently compiled format contains a `%t'.")
+(defvar org-prefix-has-tag nil
+ "A flag, set by `org-compile-prefix-format'.
+The flag is set if the currently compiled format contains a `%T'.")
+(defvar org-prefix-has-effort nil
+ "A flag, set by `org-compile-prefix-format'.
+The flag is set if the currently compiled format contains a `%e'.")
+(defvar org-prefix-has-breadcrumbs nil
+ "A flag, set by `org-compile-prefix-format'.
+The flag is set if the currently compiled format contains a `%b'.")
+(defvar org-prefix-category-length nil
+ "Used by `org-compile-prefix-format' to remember the category field width.")
+(defvar org-prefix-category-max-length nil
+ "Used by `org-compile-prefix-format' to remember the category field width.")
+
+(defun org-agenda-get-category-icon (category)
+ "Return an image for CATEGORY according to `org-agenda-category-icon-alist'."
+ (cl-dolist (entry org-agenda-category-icon-alist)
+ (when (string-match-p (car entry) category)
+ (if (listp (cadr entry))
+ (cl-return (cadr entry))
+ (cl-return (apply #'create-image (cdr entry)))))))
+
+(defun org-agenda-format-item (extra txt &optional level category tags dotime
+ remove-re habitp)
+ "Format TXT to be inserted into the agenda buffer.
+In particular, add the prefix and corresponding text properties.
+
+EXTRA must be a string to replace the `%s' specifier in the prefix format.
+LEVEL may be a string to replace the `%l' specifier.
+CATEGORY (a string, a symbol or nil) may be used to overrule the default
+category taken from local variable or file name. It will replace the `%c'
+specifier in the format.
+DOTIME, when non-nil, indicates that a time-of-day should be extracted from
+TXT for sorting of this entry, and for the `%t' specifier in the format.
+When DOTIME is a string, this string is searched for a time before TXT is.
+TAGS can be the tags of the headline.
+Any match of REMOVE-RE will be removed from TXT."
+ ;; We keep the org-prefix-* variable values along with a compiled
+ ;; formatter, so that multiple agendas existing at the same time do
+ ;; not step on each other toes.
+ ;;
+ ;; It was inconvenient to make these variables buffer local in
+ ;; Agenda buffers, because this function expects to be called with
+ ;; the buffer where item comes from being current, and not agenda
+ ;; buffer
+ (let* ((bindings (car org-prefix-format-compiled))
+ (formatter (cadr org-prefix-format-compiled)))
+ (cl-loop for (var value) in bindings
+ do (set var value))
+ (save-match-data
+ ;; Diary entries sometimes have extra whitespace at the beginning
+ (setq txt (org-trim txt))
+
+ ;; Fix the tags part in txt
+ (setq txt (org-agenda-fix-displayed-tags
+ txt tags
+ org-agenda-show-inherited-tags
+ org-agenda-hide-tags-regexp))
+
+ (let* ((category (or category
+ (if buffer-file-name
+ (file-name-sans-extension
+ (file-name-nondirectory buffer-file-name))
+ "")))
+ (category-icon (org-agenda-get-category-icon category))
+ (category-icon (if category-icon
+ (propertize " " 'display category-icon)
+ ""))
+ (effort (and (not (string= txt ""))
+ (get-text-property 1 'effort txt)))
+ ;; time, tag, effort are needed for the eval of the prefix format
+ (tag (if tags (nth (1- (length tags)) tags) ""))
+ time
+ (ts (if dotime (concat
+ (if (stringp dotime) dotime "")
+ (and org-agenda-search-headline-for-time txt))))
+ (time-of-day (and dotime (org-get-time-of-day ts)))
+ stamp plain s0 s1 s2 rtn srp l
+ duration breadcrumbs)
+ (and (derived-mode-p 'org-mode) buffer-file-name
+ (add-to-list 'org-agenda-contributing-files buffer-file-name))
+ (when (and dotime time-of-day)
+ ;; Extract starting and ending time and move them to prefix
+ (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
+ (setq plain (string-match org-plain-time-of-day-regexp ts)))
+ (setq s0 (match-string 0 ts)
+ srp (and stamp (match-end 3))
+ s1 (match-string (if plain 1 2) ts)
+ s2 (match-string (if plain 8 (if srp 4 6)) ts))
+
+ ;; If the times are in TXT (not in DOTIMES), and the prefix will list
+ ;; them, we might want to remove them there to avoid duplication.
+ ;; The user can turn this off with a variable.
+ (if (and org-prefix-has-time
+ org-agenda-remove-times-when-in-prefix (or stamp plain)
+ (string-match (concat (regexp-quote s0) " *") txt)
+ (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
+ (if (eq org-agenda-remove-times-when-in-prefix 'beg)
+ (= (match-beginning 0) 0)
+ t))
+ (setq txt (replace-match "" nil nil txt))))
+ ;; Normalize the time(s) to 24 hour
+ (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
+ (if s2 (setq s2 (org-get-time-of-day s2 'string t)))
+
+ ;; Try to set s2 if s1 and `org-agenda-default-appointment-duration' are set
+ (let (org-time-clocksum-use-effort-durations)
+ (when (and s1 (not s2) org-agenda-default-appointment-duration)
+ (setq s2
+ (org-minutes-to-clocksum-string
+ (+ (org-hh:mm-string-to-minutes s1)
+ org-agenda-default-appointment-duration)))))
+
+ ;; Compute the duration
+ (when s2
+ (setq duration (- (org-hh:mm-string-to-minutes s2)
+ (org-hh:mm-string-to-minutes s1)))))
+
+ (when (string-match "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" txt)
+ ;; Tags are in the string
+ (if (or (eq org-agenda-remove-tags t)
+ (and org-agenda-remove-tags
+ org-prefix-has-tag))
+ (setq txt (replace-match "" t t txt))
+ (setq txt (replace-match
+ (concat (make-string (max (- 50 (length txt)) 1) ?\ )
+ (match-string 2 txt))
+ t t txt))))
+
+ (when remove-re
+ (while (string-match remove-re txt)
+ (setq txt (replace-match "" t t txt))))
+
+ ;; Set org-heading property on `txt' to mark the start of the
+ ;; heading.
+ (add-text-properties 0 (length txt) '(org-heading t) txt)
+
+ ;; Prepare the variables needed in the eval of the compiled format
+ (if org-prefix-has-breadcrumbs
+ (setq breadcrumbs (org-with-point-at (org-get-at-bol 'org-marker)
+ (let ((s (org-display-outline-path nil nil "->" t)))
+ (if (eq "" s) "" (concat s "->"))))))
+ (setq time (cond (s2 (concat
+ (org-agenda-time-of-day-to-ampm-maybe s1)
+ "-" (org-agenda-time-of-day-to-ampm-maybe s2)
+ (if org-agenda-timegrid-use-ampm " ")))
+ (s1 (concat
+ (org-agenda-time-of-day-to-ampm-maybe s1)
+ (if org-agenda-timegrid-use-ampm
+ "........ "
+ "......")))
+ (t ""))
+ extra (or (and (not habitp) extra) "")
+ category (if (symbolp category) (symbol-name category) category)
+ level (or level ""))
+ (if (string-match org-bracket-link-regexp category)
+ (progn
+ (setq l (if (match-end 3)
+ (- (match-end 3) (match-beginning 3))
+ (- (match-end 1) (match-beginning 1))))
+ (when (< l (or org-prefix-category-length 0))
+ (setq category (copy-sequence category))
+ (org-add-props category nil
+ 'extra-space (make-string
+ (- org-prefix-category-length l 1) ?\ ))))
+ (if (and org-prefix-category-max-length
+ (>= (length category) org-prefix-category-max-length))
+ (setq category (substring category 0 (1- org-prefix-category-max-length)))))
+ ;; Evaluate the compiled format
+ (setq rtn (concat (eval formatter) txt))
+
+ ;; And finally add the text properties
+ (remove-text-properties 0 (length rtn) '(line-prefix t wrap-prefix t) rtn)
+ (org-add-props rtn nil
+ 'org-category category
+ 'tags (mapcar 'org-downcase-keep-props tags)
+ 'org-highest-priority org-highest-priority
+ 'org-lowest-priority org-lowest-priority
+ 'time-of-day time-of-day
+ 'duration duration
+ 'breadcrumbs breadcrumbs
+ 'txt txt
+ 'level level
+ 'time time
+ 'extra extra
+ 'format org-prefix-format-compiled
+ 'dotime dotime)))))
+
+(defun org-agenda-fix-displayed-tags (txt tags add-inherited hide-re)
+ "Remove tags string from TXT, and add a modified list of tags.
+The modified list may contain inherited tags, and tags matched by
+`org-agenda-hide-tags-regexp' will be removed."
+ (when (or add-inherited hide-re)
+ (if (string-match "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" txt)
+ (setq txt (substring txt 0 (match-beginning 0))))
+ (setq tags
+ (delq nil
+ (mapcar (lambda (tg)
+ (if (or (and hide-re (string-match hide-re tg))
+ (and (not add-inherited)
+ (get-text-property 0 'inherited tg)))
+ nil
+ tg))
+ tags)))
+ (when tags
+ (let ((have-i (get-text-property 0 'inherited (car tags)))
+ i)
+ (setq txt (concat txt " :"
+ (mapconcat
+ (lambda (x)
+ (setq i (get-text-property 0 'inherited x))
+ (if (and have-i (not i))
+ (progn
+ (setq have-i nil)
+ (concat ":" x))
+ x))
+ tags ":")
+ (if have-i "::" ":"))))))
+ txt)
+
+(defun org-downcase-keep-props (s)
+ (let ((props (text-properties-at 0 s)))
+ (setq s (downcase s))
+ (add-text-properties 0 (length s) props s)
+ s))
+
+(defvar org-agenda-sorting-strategy) ;; because the def is in a let form
+
+(defun org-agenda-add-time-grid-maybe (list ndays todayp)
+ "Add a time-grid for agenda items which need it.
+
+LIST is the list of agenda items formatted by `org-agenda-list'.
+NDAYS is the span of the current agenda view.
+TODAYP is t when the current agenda view is on today."
+ (catch 'exit
+ (cond ((not org-agenda-use-time-grid) (throw 'exit list))
+ ((and todayp (member 'today (car org-agenda-time-grid))))
+ ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
+ ((member 'weekly (car org-agenda-time-grid)))
+ (t (throw 'exit list)))
+ (let* ((have (delq nil (mapcar
+ (lambda (x) (get-text-property 1 'time-of-day x))
+ list)))
+ (string (nth 1 org-agenda-time-grid))
+ (gridtimes (nth 2 org-agenda-time-grid))
+ (req (car org-agenda-time-grid))
+ (remove (member 'remove-match req))
+ new time)
+ (if (and (member 'require-timed req) (not have))
+ ;; don't show empty grid
+ (throw 'exit list))
+ (while (setq time (pop gridtimes))
+ (unless (and remove (member time have))
+ (setq time (replace-regexp-in-string " " "0" (format "%04s" time)))
+ (push (org-agenda-format-item
+ nil string nil "" nil
+ (concat (substring time 0 -2) ":" (substring time -2)))
+ new)
+ (put-text-property
+ 2 (length (car new)) 'face 'org-time-grid (car new))))
+ (when (and todayp org-agenda-show-current-time-in-grid)
+ (push (org-agenda-format-item
+ nil org-agenda-current-time-string nil "" nil
+ (format-time-string "%H:%M "))
+ new)
+ (put-text-property
+ 2 (length (car new)) 'face 'org-agenda-current-time (car new)))
+
+ (if (member 'time-up org-agenda-sorting-strategy-selected)
+ (append new list)
+ (append list new)))))
+
+(defun org-compile-prefix-format (key)
+ "Compile the prefix format into a Lisp form that can be evaluated.
+The resulting form and associated variable bindings is returned
+and stored in the variable `org-prefix-format-compiled'."
+ (setq org-prefix-has-time nil
+ org-prefix-has-tag nil
+ org-prefix-category-length nil
+ org-prefix-has-effort nil
+ org-prefix-has-breadcrumbs nil)
+ (let ((s (cond
+ ((stringp org-agenda-prefix-format)
+ org-agenda-prefix-format)
+ ((assq key org-agenda-prefix-format)
+ (cdr (assq key org-agenda-prefix-format)))
+ (t " %-12:c%?-12t% s")))
+ (start 0)
+ varform vars var e c f opt)
+ (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cltseib]\\|(.+)\\)"
+ s start)
+ (setq var (or (cdr (assoc (match-string 4 s)
+ '(("c" . category) ("t" . time) ("l" . level) ("s" . extra)
+ ("i" . category-icon) ("T" . tag) ("e" . effort) ("b" . breadcrumbs))))
+ 'eval)
+ c (or (match-string 3 s) "")
+ opt (match-beginning 1)
+ start (1+ (match-beginning 0)))
+ (if (eq var 'time) (setq org-prefix-has-time t))
+ (if (eq var 'tag) (setq org-prefix-has-tag t))
+ (if (eq var 'effort) (setq org-prefix-has-effort t))
+ (if (eq var 'breadcrumbs) (setq org-prefix-has-breadcrumbs t))
+ (setq f (concat "%" (match-string 2 s) "s"))
+ (when (eq var 'category)
+ (setq org-prefix-category-length
+ (floor (abs (string-to-number (match-string 2 s)))))
+ (setq org-prefix-category-max-length
+ (let ((x (match-string 2 s)))
+ (save-match-data
+ (if (string-match "\\.[0-9]+" x)
+ (string-to-number (substring (match-string 0 x) 1)))))))
+ (if (eq var 'eval)
+ (setq varform `(format ,f (org-eval ,(read (match-string 4 s)))))
+ (if opt
+ (setq varform
+ `(if (or (equal "" ,var) (equal nil ,var))
+ ""
+ (format ,f (concat ,var ,c))))
+ (setq varform
+ `(format ,f (if (or (equal ,var "")
+ (equal ,var nil)) ""
+ (concat ,var ,c (get-text-property 0 'extra-space ,var)))))))
+ (setq s (replace-match "%s" t nil s))
+ (push varform vars))
+ (setq vars (nreverse vars))
+ (with-current-buffer (or org-agenda-buffer (current-buffer))
+ (setq org-prefix-format-compiled
+ (list
+ `((org-prefix-has-time ,org-prefix-has-time)
+ (org-prefix-has-tag ,org-prefix-has-tag)
+ (org-prefix-category-length ,org-prefix-category-length)
+ (org-prefix-has-effort ,org-prefix-has-effort)
+ (org-prefix-has-breadcrumbs ,org-prefix-has-breadcrumbs))
+ `(format ,s ,@vars))))))
+
+(defun org-set-sorting-strategy (key)
+ (if (symbolp (car org-agenda-sorting-strategy))
+ ;; the old format
+ (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
+ (setq org-agenda-sorting-strategy-selected
+ (or (cdr (assq key org-agenda-sorting-strategy))
+ (cdr (assq 'agenda org-agenda-sorting-strategy))
+ '(time-up category-keep priority-down)))))
+
+(defun org-get-time-of-day (s &optional string mod24)
+ "Check string S for a time of day.
+If found, return it as a military time number between 0 and 2400.
+If not found, return nil.
+The optional STRING argument forces conversion into a 5 character wide string
+HH:MM."
+ (save-match-data
+ (when
+ (and
+ (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
+ (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
+ (not (eq (get-text-property 1 'face s) 'org-link)))
+ (let* ((h (string-to-number (match-string 1 s)))
+ (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
+ (ampm (if (match-end 4) (downcase (match-string 4 s))))
+ (am-p (equal ampm "am"))
+ (h1 (cond ((not ampm) h)
+ ((= h 12) (if am-p 0 12))
+ (t (+ h (if am-p 0 12)))))
+ (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
+ (mod h1 24) h1))
+ (t0 (+ (* 100 h2) m))
+ (t1 (concat (if (>= h1 24) "+" " ")
+ (if (and org-agenda-time-leading-zero
+ (< t0 1000)) "0" "")
+ (if (< t0 100) "0" "")
+ (if (< t0 10) "0" "")
+ (int-to-string t0))))
+ (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
+
+(defvar org-agenda-before-sorting-filter-function nil
+ "Function to be applied to agenda items prior to sorting.
+Prior to sorting also means just before they are inserted into the agenda.
+
+To aid sorting, you may revisit the original entries and add more text
+properties which will later be used by the sorting functions.
+
+The function should take a string argument, an agenda line.
+It has access to the text properties in that line, which contain among
+other things, the property `org-hd-marker' that points to the entry
+where the line comes from. Note that not all lines going into the agenda
+have this property, only most.
+
+The function should return the modified string. It is probably best
+to ONLY change text properties.
+
+You can also use this function as a filter, by returning nil for lines
+you don't want to have in the agenda at all. For this application, you
+could bind the variable in the options section of a custom command.")
+
+(defun org-agenda-finalize-entries (list &optional type)
+ "Sort, limit and concatenate the LIST of agenda items.
+The optional argument TYPE tells the agenda type."
+ (let ((max-effort (cond ((listp org-agenda-max-effort)
+ (cdr (assoc type org-agenda-max-effort)))
+ (t org-agenda-max-effort)))
+ (max-todo (cond ((listp org-agenda-max-todos)
+ (cdr (assoc type org-agenda-max-todos)))
+ (t org-agenda-max-todos)))
+ (max-tags (cond ((listp org-agenda-max-tags)
+ (cdr (assoc type org-agenda-max-tags)))
+ (t org-agenda-max-tags)))
+ (max-entries (cond ((listp org-agenda-max-entries)
+ (cdr (assoc type org-agenda-max-entries)))
+ (t org-agenda-max-entries))))
+ (when org-agenda-before-sorting-filter-function
+ (setq list
+ (delq nil
+ (mapcar
+ org-agenda-before-sorting-filter-function list))))
+ (setq list (mapcar 'org-agenda-highlight-todo list)
+ list (mapcar 'identity (sort list 'org-entries-lessp)))
+ (when max-effort
+ (setq list (org-agenda-limit-entries
+ list 'effort-minutes max-effort
+ (lambda (e) (or e (if org-sort-agenda-noeffort-is-high
+ 32767 -1))))))
+ (when max-todo
+ (setq list (org-agenda-limit-entries list 'todo-state max-todo)))
+ (when max-tags
+ (setq list (org-agenda-limit-entries list 'tags max-tags)))
+ (when max-entries
+ (setq list (org-agenda-limit-entries list 'org-hd-marker max-entries)))
+ (mapconcat 'identity list "\n")))
+
+(defun org-agenda-limit-entries (list prop limit &optional fn)
+ "Limit the number of agenda entries."
+ (let ((include (and limit (< limit 0))))
+ (if limit
+ (let ((fun (or fn (lambda (p) (if p 1))))
+ (lim 0))
+ (delq nil
+ (mapcar
+ (lambda (e)
+ (let ((pval (funcall
+ fun (get-text-property (1- (length e))
+ prop e))))
+ (if pval (setq lim (+ lim pval)))
+ (cond ((and pval (<= lim (abs limit))) e)
+ ((and include (not pval)) e))))
+ list)))
+ list)))
+
+(defun org-agenda-limit-interactively (remove)
+ "In agenda, interactively limit entries to various maximums."
+ (interactive "P")
+ (if remove
+ (progn (setq org-agenda-max-entries nil
+ org-agenda-max-todos nil
+ org-agenda-max-tags nil
+ org-agenda-max-effort nil)
+ (org-agenda-redo))
+ (let* ((max (read-char "Number of [e]ntries [t]odos [T]ags [E]ffort? "))
+ (msg (cond ((= max ?E) "How many minutes? ")
+ ((= max ?e) "How many entries? ")
+ ((= max ?t) "How many TODO entries? ")
+ ((= max ?T) "How many tagged entries? ")
+ (t (user-error "Wrong input"))))
+ (num (string-to-number (read-from-minibuffer msg))))
+ (cond ((equal max ?e)
+ (let ((org-agenda-max-entries num)) (org-agenda-redo)))
+ ((equal max ?t)
+ (let ((org-agenda-max-todos num)) (org-agenda-redo)))
+ ((equal max ?T)
+ (let ((org-agenda-max-tags num)) (org-agenda-redo)))
+ ((equal max ?E)
+ (let ((org-agenda-max-effort num)) (org-agenda-redo))))))
+ (org-agenda-fit-window-to-buffer))
+
+(defun org-agenda-highlight-todo (x)
+ (let ((org-done-keywords org-done-keywords-for-agenda)
+ (case-fold-search nil)
+ re)
+ (if (eq x 'line)
+ (save-excursion
+ (beginning-of-line 1)
+ (setq re (org-get-at-bol 'org-todo-regexp))
+ (goto-char (or (text-property-any (point-at-bol) (point-at-eol) 'org-heading t) (point)))
+ (when (looking-at (concat "[ \t]*\\.*\\(" re "\\) +"))
+ (add-text-properties (match-beginning 0) (match-end 1)
+ (list 'face (org-get-todo-face 1)))
+ (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
+ (delete-region (match-beginning 1) (1- (match-end 0)))
+ (goto-char (match-beginning 1))
+ (insert (format org-agenda-todo-keyword-format s)))))
+ (let ((pl (text-property-any 0 (length x) 'org-heading t x)))
+ (setq re (get-text-property 0 'org-todo-regexp x))
+ (when (and re
+ ;; Test `pl' because if there's no heading content,
+ ;; there's no point matching to highlight. Note
+ ;; that if we didn't test `pl' first, and there
+ ;; happened to be no keyword from `org-todo-regexp'
+ ;; on this heading line, then the `equal' comparison
+ ;; afterwards would spuriously succeed in the case
+ ;; where `pl' is nil -- causing an args-out-of-range
+ ;; error when we try to add text properties to text
+ ;; that isn't there.
+ pl
+ (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
+ x pl) pl))
+ (add-text-properties
+ (or (match-end 1) (match-end 0)) (match-end 0)
+ (list 'face (org-get-todo-face (match-string 2 x)))
+ x)
+ (when (match-end 1)
+ (setq x (concat (substring x 0 (match-end 1))
+ (format org-agenda-todo-keyword-format
+ (match-string 2 x))
+ (org-add-props " " (text-properties-at 0 x))
+ (substring x (match-end 3)))))))
+ x)))
+
+(defsubst org-cmp-values (a b property)
+ "Compare the numeric value of text PROPERTY for string A and B."
+ (let ((pa (or (get-text-property (1- (length a)) property a) 0))
+ (pb (or (get-text-property (1- (length b)) property b) 0)))
+ (cond ((> pa pb) +1)
+ ((< pa pb) -1))))
+
+(defsubst org-cmp-effort (a b)
+ "Compare the effort values of string A and B."
+ (let* ((def (if org-sort-agenda-noeffort-is-high 32767 -1))
+ ;; `effort-minutes' property is not directly accessible from
+ ;; the strings, but is stored as a property in `txt'.
+ (ea (or (get-text-property
+ 0 'effort-minutes (get-text-property 0 'txt a))
+ def))
+ (eb (or (get-text-property
+ 0 'effort-minutes (get-text-property 0 'txt b))
+ def)))
+ (cond ((> ea eb) +1)
+ ((< ea eb) -1))))
+
+(defsubst org-cmp-category (a b)
+ "Compare the string values of categories of strings A and B."
+ (let ((ca (or (get-text-property (1- (length a)) 'org-category a) ""))
+ (cb (or (get-text-property (1- (length b)) 'org-category b) "")))
+ (cond ((string-lessp ca cb) -1)
+ ((string-lessp cb ca) +1))))
+
+(defsubst org-cmp-todo-state (a b)
+ "Compare the todo states of strings A and B."
+ (let* ((ma (or (get-text-property 1 'org-marker a)
+ (get-text-property 1 'org-hd-marker a)))
+ (mb (or (get-text-property 1 'org-marker b)
+ (get-text-property 1 'org-hd-marker b)))
+ (fa (and ma (marker-buffer ma)))
+ (fb (and mb (marker-buffer mb)))
+ (todo-kwds
+ (or (and fa (with-current-buffer fa org-todo-keywords-1))
+ (and fb (with-current-buffer fb org-todo-keywords-1))))
+ (ta (or (get-text-property 1 'todo-state a) ""))
+ (tb (or (get-text-property 1 'todo-state b) ""))
+ (la (- (length (member ta todo-kwds))))
+ (lb (- (length (member tb todo-kwds))))
+ (donepa (member ta org-done-keywords-for-agenda))
+ (donepb (member tb org-done-keywords-for-agenda)))
+ (cond ((and donepa (not donepb)) -1)
+ ((and (not donepa) donepb) +1)
+ ((< la lb) -1)
+ ((< lb la) +1))))
+
+(defsubst org-cmp-alpha (a b)
+ "Compare the headlines, alphabetically."
+ (let* ((pla (text-property-any 0 (length a) 'org-heading t a))
+ (plb (text-property-any 0 (length b) 'org-heading t b))
+ (ta (and pla (substring a pla)))
+ (tb (and plb (substring b plb)))
+ (case-fold-search nil))
+ (when pla
+ (if (string-match (concat "\\`[ \t]*" (or (get-text-property 0 'org-todo-regexp a) "")
+ "\\([ \t]*\\[[a-zA-Z0-9]\\]\\)? *") ta)
+ (setq ta (substring ta (match-end 0))))
+ (setq ta (downcase ta)))
+ (when plb
+ (if (string-match (concat "\\`[ \t]*" (or (get-text-property 0 'org-todo-regexp b) "")
+ "\\([ \t]*\\[[a-zA-Z0-9]\\]\\)? *") tb)
+ (setq tb (substring tb (match-end 0))))
+ (setq tb (downcase tb)))
+ (cond ((not ta) +1)
+ ((not tb) -1)
+ ((string-lessp ta tb) -1)
+ ((string-lessp tb ta) +1))))
+
+(defsubst org-cmp-tag (a b)
+ "Compare the string values of the first tags of A and B."
+ (let ((ta (car (last (get-text-property 1 'tags a))))
+ (tb (car (last (get-text-property 1 'tags b)))))
+ (cond ((not ta) +1)
+ ((not tb) -1)
+ ((string-lessp ta tb) -1)
+ ((string-lessp tb ta) +1))))
+
+(defsubst org-cmp-time (a b)
+ "Compare the time-of-day values of strings A and B."
+ (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
+ (ta (or (get-text-property 1 'time-of-day a) def))
+ (tb (or (get-text-property 1 'time-of-day b) def)))
+ (cond ((< ta tb) -1)
+ ((< tb ta) +1))))
+
+(defsubst org-cmp-ts (a b type)
+ "Compare the timestamps values of entries A and B.
+When TYPE is \"scheduled\", \"deadline\", \"timestamp\" or
+\"timestamp_ia\", compare within each of these type. When TYPE
+is the empty string, compare all timestamps without respect of
+their type."
+ (let* ((def (if org-sort-agenda-notime-is-late most-positive-fixnum -1))
+ (ta (or (and (string-match type (or (get-text-property 1 'type a) ""))
+ (get-text-property 1 'ts-date a))
+ def))
+ (tb (or (and (string-match type (or (get-text-property 1 'type b) ""))
+ (get-text-property 1 'ts-date b))
+ def)))
+ (cond ((< ta tb) -1)
+ ((< tb ta) +1))))
+
+(defsubst org-cmp-habit-p (a b)
+ "Compare the todo states of strings A and B."
+ (let ((ha (get-text-property 1 'org-habit-p a))
+ (hb (get-text-property 1 'org-habit-p b)))
+ (cond ((and ha (not hb)) -1)
+ ((and (not ha) hb) +1))))
+
+(defun org-entries-lessp (a b)
+ "Predicate for sorting agenda entries."
+ ;; The following variables will be used when the form is evaluated.
+ ;; So even though the compiler complains, keep them.
+ (let* ((ss org-agenda-sorting-strategy-selected)
+ (timestamp-up (and (org-em 'timestamp-up 'timestamp-down ss)
+ (org-cmp-ts a b "")))
+ (timestamp-down (if timestamp-up (- timestamp-up) nil))
+ (scheduled-up (and (org-em 'scheduled-up 'scheduled-down ss)
+ (org-cmp-ts a b "scheduled")))
+ (scheduled-down (if scheduled-up (- scheduled-up) nil))
+ (deadline-up (and (org-em 'deadline-up 'deadline-down ss)
+ (org-cmp-ts a b "deadline")))
+ (deadline-down (if deadline-up (- deadline-up) nil))
+ (tsia-up (and (org-em 'tsia-up 'tsia-down ss)
+ (org-cmp-ts a b "timestamp_ia")))
+ (tsia-down (if tsia-up (- tsia-up) nil))
+ (ts-up (and (org-em 'ts-up 'ts-down ss)
+ (org-cmp-ts a b "timestamp")))
+ (ts-down (if ts-up (- ts-up) nil))
+ (time-up (and (org-em 'time-up 'time-down ss)
+ (org-cmp-time a b)))
+ (time-down (if time-up (- time-up) nil))
+ (stats-up (and (org-em 'stats-up 'stats-down ss)
+ (org-cmp-values a b 'org-stats)))
+ (stats-down (if stats-up (- stats-up) nil))
+ (priority-up (and (org-em 'priority-up 'priority-down ss)
+ (org-cmp-values a b 'priority)))
+ (priority-down (if priority-up (- priority-up) nil))
+ (effort-up (and (org-em 'effort-up 'effort-down ss)
+ (org-cmp-effort a b)))
+ (effort-down (if effort-up (- effort-up) nil))
+ (category-up (and (or (org-em 'category-up 'category-down ss)
+ (memq 'category-keep ss))
+ (org-cmp-category a b)))
+ (category-down (if category-up (- category-up) nil))
+ (category-keep (if category-up +1 nil))
+ (tag-up (and (org-em 'tag-up 'tag-down ss)
+ (org-cmp-tag a b)))
+ (tag-down (if tag-up (- tag-up) nil))
+ (todo-state-up (and (org-em 'todo-state-up 'todo-state-down ss)
+ (org-cmp-todo-state a b)))
+ (todo-state-down (if todo-state-up (- todo-state-up) nil))
+ (habit-up (and (org-em 'habit-up 'habit-down ss)
+ (org-cmp-habit-p a b)))
+ (habit-down (if habit-up (- habit-up) nil))
+ (alpha-up (and (org-em 'alpha-up 'alpha-down ss)
+ (org-cmp-alpha a b)))
+ (alpha-down (if alpha-up (- alpha-up) nil))
+ (need-user-cmp (org-em 'user-defined-up 'user-defined-down ss))
+ user-defined-up user-defined-down)
+ (if (and need-user-cmp org-agenda-cmp-user-defined
+ (functionp org-agenda-cmp-user-defined))
+ (setq user-defined-up
+ (funcall org-agenda-cmp-user-defined a b)
+ user-defined-down (if user-defined-up (- user-defined-up) nil)))
+ (cdr (assoc
+ (eval (cons 'or org-agenda-sorting-strategy-selected))
+ '((-1 . t) (1 . nil) (nil . nil))))))
+
+;;; Agenda restriction lock
+
+(defvar org-agenda-restriction-lock-overlay (make-overlay 1 1)
+ "Overlay to mark the headline to which agenda commands are restricted.")
+(overlay-put org-agenda-restriction-lock-overlay
+ 'face 'org-agenda-restriction-lock)
+(overlay-put org-agenda-restriction-lock-overlay
+ 'help-echo "Agendas are currently limited to this subtree.")
+(delete-overlay org-agenda-restriction-lock-overlay)
+
+;;;###autoload
+(defun org-agenda-set-restriction-lock (&optional type)
+ "Set restriction lock for agenda, to current subtree or file.
+Restriction will be the file if TYPE is `file', or if type is the
+universal prefix \\='(4), or if the cursor is before the first headline
+in the file. Otherwise, restriction will be to the current subtree."
+ (interactive "P")
+ (org-agenda-remove-restriction-lock 'noupdate)
+ (and (equal type '(4)) (setq type 'file))
+ (setq type (cond
+ (type type)
+ ((org-at-heading-p) 'subtree)
+ ((condition-case nil (org-back-to-heading t) (error nil))
+ 'subtree)
+ (t 'file)))
+ (if (eq type 'subtree)
+ (progn
+ (setq org-agenda-restrict (current-buffer))
+ (setq org-agenda-overriding-restriction 'subtree)
+ (put 'org-agenda-files 'org-restrict
+ (list (buffer-file-name (buffer-base-buffer))))
+ (org-back-to-heading t)
+ (move-overlay org-agenda-restriction-lock-overlay
+ (point)
+ (if org-agenda-restriction-lock-highlight-subtree
+ (save-excursion (org-end-of-subtree t t) (point))
+ (point-at-eol)))
+ (move-marker org-agenda-restrict-begin (point))
+ (move-marker org-agenda-restrict-end
+ (save-excursion (org-end-of-subtree t t)))
+ (message "Locking agenda restriction to subtree"))
+ (put 'org-agenda-files 'org-restrict
+ (list (buffer-file-name (buffer-base-buffer))))
+ (setq org-agenda-restrict nil)
+ (setq org-agenda-overriding-restriction 'file)
+ (move-marker org-agenda-restrict-begin nil)
+ (move-marker org-agenda-restrict-end nil)
+ (message "Locking agenda restriction to file"))
+ (setq current-prefix-arg nil)
+ (org-agenda-maybe-redo))
+
+(defun org-agenda-remove-restriction-lock (&optional noupdate)
+ "Remove the agenda restriction lock."
+ (interactive "P")
+ (delete-overlay org-agenda-restriction-lock-overlay)
+ (delete-overlay org-speedbar-restriction-lock-overlay)
+ (setq org-agenda-overriding-restriction nil)
+ (setq org-agenda-restrict nil)
+ (put 'org-agenda-files 'org-restrict nil)
+ (move-marker org-agenda-restrict-begin nil)
+ (move-marker org-agenda-restrict-end nil)
+ (setq current-prefix-arg nil)
+ (message "Agenda restriction lock removed")
+ (or noupdate (org-agenda-maybe-redo)))
+
+(defun org-agenda-maybe-redo ()
+ "If there is any window showing the agenda view, update it."
+ (let ((w (get-buffer-window (or org-agenda-this-buffer-name
+ org-agenda-buffer-name)
+ t))
+ (w0 (selected-window)))
+ (when w
+ (select-window w)
+ (org-agenda-redo)
+ (select-window w0)
+ (if org-agenda-overriding-restriction
+ (message "Agenda view shifted to new %s restriction"
+ org-agenda-overriding-restriction)
+ (message "Agenda restriction lock removed")))))
+
+;;; Agenda commands
+
+(defun org-agenda-check-type (error &rest types)
+ "Check if agenda buffer is of allowed type.
+If ERROR is non-nil, throw an error, otherwise just return nil.
+Allowed types are `agenda' `timeline' `todo' `tags' `search'."
+ (if (not org-agenda-type)
+ (error "No Org agenda currently displayed")
+ (if (memq org-agenda-type types)
+ t
+ (if error
+ (error "Not allowed in %s-type agenda buffers" org-agenda-type)
+ nil))))
+
+(defun org-agenda-Quit ()
+ "Exit the agenda, killing the agenda buffer.
+Like `org-agenda-quit', but kill the buffer even when
+`org-agenda-sticky' is non-nil."
+ (interactive)
+ (org-agenda--quit))
+
+(defun org-agenda-quit ()
+ "Exit the agenda.
+
+When `org-agenda-sticky' is non-nil, bury the agenda buffer
+instead of killing it.
+
+When `org-agenda-restore-windows-after-quit' is non-nil, restore
+the pre-agenda window configuration.
+
+When column view is active, exit column view instead of the
+agenda."
+ (interactive)
+ (org-agenda--quit org-agenda-sticky))
+
+(defun org-agenda--quit (&optional bury)
+ (if org-agenda-columns-active
+ (org-columns-quit)
+ (let ((wconf org-agenda-pre-window-conf)
+ (buf (current-buffer))
+ (org-agenda-last-indirect-window
+ (and (eq org-indirect-buffer-display 'other-window)
+ org-agenda-last-indirect-buffer
+ (get-buffer-window org-agenda-last-indirect-buffer))))
+ (cond
+ ((eq org-agenda-window-setup 'other-frame)
+ (delete-frame))
+ ((and org-agenda-restore-windows-after-quit
+ wconf)
+ ;; Maybe restore the pre-agenda window configuration. Reset
+ ;; `org-agenda-pre-window-conf' before running
+ ;; `set-window-configuration', which loses the current buffer.
+ (setq org-agenda-pre-window-conf nil)
+ (set-window-configuration wconf))
+ (t
+ (when org-agenda-last-indirect-window
+ (delete-window org-agenda-last-indirect-window))
+ (and (not (eq org-agenda-window-setup 'current-window))
+ (not (one-window-p))
+ (delete-window))))
+ (if bury
+ ;; Set the agenda buffer as the current buffer instead of
+ ;; passing it as an argument to `bury-buffer' so that
+ ;; `bury-buffer' removes it from the window.
+ (with-current-buffer buf
+ (bury-buffer))
+ (kill-buffer buf)
+ (setq org-agenda-archives-mode nil
+ org-agenda-buffer nil)))))
+
+(defun org-agenda-exit ()
+ "Exit the agenda, killing Org buffers loaded by the agenda.
+Like `org-agenda-Quit', but kill any buffers that were created by
+the agenda. Org buffers visited directly by the user will not be
+touched. Also, exit the agenda even if it is in column view."
+ (interactive)
+ (when org-agenda-columns-active
+ (org-columns-quit))
+ (org-release-buffers org-agenda-new-buffers)
+ (setq org-agenda-new-buffers nil)
+ (org-agenda-Quit))
+
+(defun org-agenda-kill-all-agenda-buffers ()
+ "Kill all buffers in `org-agenda-mode'.
+This is used when toggling sticky agendas."
+ (interactive)
+ (let (blist)
+ (dolist (buf (buffer-list))
+ (when (with-current-buffer buf (eq major-mode 'org-agenda-mode))
+ (push buf blist)))
+ (mapc 'kill-buffer blist)))
+
+(defun org-agenda-execute (arg)
+ "Execute another agenda command, keeping same window.
+So this is just a shortcut for \\<global-map>`\\[org-agenda]', available
+in the agenda."
+ (interactive "P")
+ (let ((org-agenda-window-setup 'current-window))
+ (org-agenda arg)))
+
+(defun org-agenda-redo (&optional all)
+ "Rebuild possibly ALL agenda view(s) in the current buffer."
+ (interactive "P")
+ (let* ((p (or (and (looking-at "\\'") (1- (point))) (point)))
+ (cpa (unless (eq all t) current-prefix-arg))
+ (org-agenda-doing-sticky-redo org-agenda-sticky)
+ (org-agenda-sticky nil)
+ (org-agenda-buffer-name (or org-agenda-this-buffer-name
+ org-agenda-buffer-name))
+ (org-agenda-keep-modes t)
+ (tag-filter org-agenda-tag-filter)
+ (tag-preset (get 'org-agenda-tag-filter :preset-filter))
+ (top-hl-filter org-agenda-top-headline-filter)
+ (cat-filter org-agenda-category-filter)
+ (cat-preset (get 'org-agenda-category-filter :preset-filter))
+ (re-filter org-agenda-regexp-filter)
+ (re-preset (get 'org-agenda-regexp-filter :preset-filter))
+ (effort-filter org-agenda-effort-filter)
+ (effort-preset (get 'org-agenda-effort-filter :preset-filter))
+ (org-agenda-tag-filter-while-redo (or tag-filter tag-preset))
+ (cols org-agenda-columns-active)
+ (line (org-current-line))
+ (window-line (- line (org-current-line (window-start))))
+ (lprops (get 'org-agenda-redo-command 'org-lprops))
+ (redo-cmd (get-text-property p 'org-redo-cmd))
+ (last-args (get-text-property p 'org-last-args))
+ (org-agenda-overriding-cmd (get-text-property p 'org-series-cmd))
+ (org-agenda-overriding-cmd-arguments
+ (unless (eq all t)
+ (cond ((listp last-args)
+ (cons (or cpa (car last-args)) (cdr last-args)))
+ ((stringp last-args)
+ last-args))))
+ (series-redo-cmd (get-text-property p 'org-series-redo-cmd)))
+ (put 'org-agenda-tag-filter :preset-filter nil)
+ (put 'org-agenda-category-filter :preset-filter nil)
+ (put 'org-agenda-regexp-filter :preset-filter nil)
+ (put 'org-agenda-effort-filter :preset-filter nil)
+ (and cols (org-columns-quit))
+ (message "Rebuilding agenda buffer...")
+ (if series-redo-cmd
+ (eval series-redo-cmd)
+ (org-let lprops redo-cmd))
+ (setq org-agenda-undo-list nil
+ org-agenda-pending-undo-list nil
+ org-agenda-tag-filter tag-filter
+ org-agenda-category-filter cat-filter
+ org-agenda-regexp-filter re-filter
+ org-agenda-effort-filter effort-filter
+ org-agenda-top-headline-filter top-hl-filter)
+ (message "Rebuilding agenda buffer...done")
+ (put 'org-agenda-tag-filter :preset-filter tag-preset)
+ (put 'org-agenda-category-filter :preset-filter cat-preset)
+ (put 'org-agenda-regexp-filter :preset-filter re-preset)
+ (put 'org-agenda-effort-filter :preset-filter effort-preset)
+ (let ((tag (or tag-filter tag-preset))
+ (cat (or cat-filter cat-preset))
+ (effort (or effort-filter effort-preset))
+ (re (or re-filter re-preset)))
+ (when tag (org-agenda-filter-apply tag 'tag t))
+ (when cat (org-agenda-filter-apply cat 'category))
+ (when effort (org-agenda-filter-apply effort 'effort))
+ (when re (org-agenda-filter-apply re 'regexp)))
+ (and top-hl-filter (org-agenda-filter-top-headline-apply top-hl-filter))
+ (and cols (called-interactively-p 'any) (org-agenda-columns))
+ (org-goto-line line)
+ (recenter window-line)))
+
+(defvar org-global-tags-completion-table nil)
+(defvar org-agenda-filter-form nil)
+(defvar org-agenda-filtered-by-category nil)
+
+(defun org-agenda-filter-by-category (strip)
+ "Filter lines in the agenda buffer that have a specific category.
+The category is that of the current line.
+Without prefix argument, keep only the lines of that category.
+With a prefix argument, exclude the lines of that category.
+"
+ (interactive "P")
+ (if (and org-agenda-filtered-by-category
+ org-agenda-category-filter)
+ (org-agenda-filter-show-all-cat)
+ (let ((cat (org-no-properties (org-get-at-eol 'org-category 1))))
+ (cond
+ ((and cat strip)
+ (org-agenda-filter-apply
+ (push (concat "-" cat) org-agenda-category-filter) 'category))
+ (cat
+ (org-agenda-filter-apply
+ (setq org-agenda-category-filter
+ (list (concat "+" cat))) 'category))
+ (t (error "No category at point"))))))
+
+(defun org-find-top-headline (&optional pos)
+ "Find the topmost parent headline and return it.
+POS when non-nil is the marker or buffer position to start the
+search from."
+ (save-excursion
+ (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
+ (when pos (goto-char pos))
+ ;; Skip up to the topmost parent.
+ (while (org-up-heading-safe))
+ (ignore-errors (nth 4 (org-heading-components))))))
+
+(defvar org-agenda-filtered-by-top-headline nil)
+(defun org-agenda-filter-by-top-headline (strip)
+ "Keep only those lines that are descendants from the same top headline.
+The top headline is that of the current line."
+ (interactive "P")
+ (if org-agenda-filtered-by-top-headline
+ (progn
+ (setq org-agenda-filtered-by-top-headline nil
+ org-agenda-top-headline-filter nil)
+ (org-agenda-filter-show-all-top-filter))
+ (let ((toph (org-find-top-headline (org-get-at-bol 'org-hd-marker))))
+ (if toph (org-agenda-filter-top-headline-apply toph strip)
+ (error "No top-level headline at point")))))
+
+(defvar org-agenda-regexp-filter nil)
+(defun org-agenda-filter-by-regexp (strip)
+ "Filter agenda entries by a regular expression.
+Regexp filters are cumulative.
+With no prefix argument, keep entries matching the regexp.
+With one prefix argument, filter out entries matching the regexp.
+With two prefix arguments, remove the regexp filters."
+ (interactive "P")
+ (if (not (equal strip '(16)))
+ (let ((flt (concat (if (equal strip '(4)) "-" "+")
+ (read-from-minibuffer
+ (if (equal strip '(4))
+ "Filter out entries matching regexp: "
+ "Narrow to entries matching regexp: ")))))
+ (push flt org-agenda-regexp-filter)
+ (org-agenda-filter-apply org-agenda-regexp-filter 'regexp))
+ (org-agenda-filter-show-all-re)
+ (message "Regexp filter removed")))
+
+(defvar org-agenda-effort-filter nil)
+(defun org-agenda-filter-by-effort (strip)
+ "Filter agenda entries by effort.
+With no prefix argument, keep entries matching the effort condition.
+With one prefix argument, filter out entries matching the condition.
+With two prefix arguments, remove the effort filters."
+ (interactive "P")
+ (cond
+ ((member strip '(nil 4))
+ (let* ((efforts (split-string
+ (or (cdr (assoc (concat org-effort-property "_ALL")
+ org-global-properties))
+ "0 0:10 0:30 1:00 2:00 3:00 4:00 5:00 6:00 7:00")))
+ ;; XXX: the following handles only up to 10 different
+ ;; effort values.
+ (allowed-keys (if (null efforts) nil
+ (mapcar (lambda (n) (mod n 10)) ;turn 10 into 0
+ (number-sequence 1 (length efforts)))))
+ (op nil))
+ (while (not (memq op '(?< ?> ?=)))
+ (setq op (read-char-exclusive "Effort operator? (> = or <)")))
+ ;; Select appropriate duration. Ignore non-digit characters.
+ (let ((prompt
+ (apply #'format
+ (concat "Effort %c "
+ (mapconcat (lambda (s) (concat "[%d]" s))
+ efforts
+ " "))
+ op allowed-keys))
+ (eff -1))
+ (while (not (memq eff allowed-keys))
+ (message prompt)
+ (setq eff (- (read-char-exclusive) 48)))
+ (setq org-agenda-effort-filter
+ (list (concat (if strip "-" "+")
+ (char-to-string op)
+ ;; Numbering is 1 2 3 ... 9 0, but we want
+ ;; 0 1 2 ... 8 9.
+ (nth (mod (1- eff) 10) efforts)))))
+ (org-agenda-filter-apply org-agenda-effort-filter 'effort)))
+ (t (org-agenda-filter-show-all-effort)
+ (message "Effort filter removed"))))
+
+(defun org-agenda-filter-remove-all ()
+ "Remove all filters from the current agenda buffer."
+ (interactive)
+ (when org-agenda-tag-filter
+ (org-agenda-filter-show-all-tag))
+ (when org-agenda-category-filter
+ (org-agenda-filter-show-all-cat))
+ (when org-agenda-regexp-filter
+ (org-agenda-filter-show-all-re))
+ (when org-agenda-top-headline-filter
+ (org-agenda-filter-show-all-top-filter))
+ (when org-agenda-effort-filter
+ (org-agenda-filter-show-all-effort))
+ (org-agenda-finalize))
+
+(defun org-agenda-filter-by-tag (arg &optional char exclude)
+ "Keep only those lines in the agenda buffer that have a specific tag.
+
+The tag is selected with its fast selection letter, as configured.
+
+With a `\\[universal-argument]' prefix, exclude the agenda search.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix, filter the literal tag, \
+i.e. don't
+filter on all its group members.
+
+A lisp caller can specify CHAR. EXCLUDE means that the new tag
+should be used to exclude the search - the interactive user can
+also press `-' or `+' to switch between filtering and excluding."
+ (interactive "P")
+ (let* ((alist org-tag-alist-for-agenda)
+ (tag-chars (mapconcat
+ (lambda (x) (if (and (not (symbolp (car x)))
+ (cdr x))
+ (char-to-string (cdr x))
+ ""))
+ org-tag-alist-for-agenda ""))
+ (valid-char-list (append '(?\t ?\r ?/ ?. ?\s ?q)
+ (string-to-list tag-chars)))
+ (exclude (or exclude (equal arg '(4))))
+ (expand (not (equal arg '(16))))
+ (inhibit-read-only t)
+ (current org-agenda-tag-filter)
+ a n tag)
+ (unless char
+ (while (not (memq char valid-char-list))
+ (message
+ "%s by tag [%s ], [TAB], %s[/]:off, [+/-]:filter/exclude%s, [q]:quit"
+ (if exclude "Exclude" "Filter") tag-chars
+ (if org-agenda-auto-exclude-function "[RET], " "")
+ (if expand "" ", no grouptag expand"))
+ (setq char (read-char-exclusive))
+ ;; Excluding or filtering down
+ (cond ((eq char ?-) (setq exclude t))
+ ((eq char ?+) (setq exclude nil)))))
+ (when (eq char ?\t)
+ (unless (local-variable-p 'org-global-tags-completion-table (current-buffer))
+ (setq-local org-global-tags-completion-table
+ (org-global-tags-completion-table)))
+ (let ((completion-ignore-case t))
+ (setq tag (completing-read
+ "Tag: " org-global-tags-completion-table))))
+ (cond
+ ((eq char ?\r)
+ (org-agenda-filter-show-all-tag)
+ (when org-agenda-auto-exclude-function
+ (setq org-agenda-tag-filter nil)
+ (dolist (tag (org-agenda-get-represented-tags))
+ (let ((modifier (funcall org-agenda-auto-exclude-function tag)))
+ (if modifier
+ (push modifier org-agenda-tag-filter))))
+ (if (not (null org-agenda-tag-filter))
+ (org-agenda-filter-apply org-agenda-tag-filter 'tag expand))))
+ ((eq char ?/)
+ (org-agenda-filter-show-all-tag)
+ (when (get 'org-agenda-tag-filter :preset-filter)
+ (org-agenda-filter-apply org-agenda-tag-filter 'tag expand)))
+ ((eq char ?.)
+ (setq org-agenda-tag-filter
+ (mapcar (lambda(tag) (concat "+" tag))
+ (org-get-at-bol 'tags)))
+ (org-agenda-filter-apply org-agenda-tag-filter 'tag expand))
+ ((eq char ?q)) ;If q, abort (even if there is a q-key for a tag...)
+ ((or (eq char ?\s)
+ (setq a (rassoc char alist))
+ (and tag (setq a (cons tag nil))))
+ (org-agenda-filter-show-all-tag)
+ (setq tag (car a))
+ (setq org-agenda-tag-filter
+ (cons (concat (if exclude "-" "+") tag)
+ current))
+ (org-agenda-filter-apply org-agenda-tag-filter 'tag expand))
+ (t (error "Invalid tag selection character %c" char)))))
+
+(defun org-agenda-get-represented-tags ()
+ "Get a list of all tags currently represented in the agenda."
+ (let (p tags)
+ (save-excursion
+ (goto-char (point-min))
+ (while (setq p (next-single-property-change (point) 'tags))
+ (goto-char p)
+ (mapc (lambda (x) (add-to-list 'tags x))
+ (get-text-property (point) 'tags))))
+ tags))
+
+
+(defun org-agenda-filter-make-matcher (filter type &optional expand)
+ "Create the form that tests a line for agenda filter. Optional
+argument EXPAND can be used for the TYPE tag and will expand the
+tags in the FILTER if any of the tags in FILTER are grouptags."
+ (let (f f1)
+ (cond
+ ;; Tag filter
+ ((eq type 'tag)
+ (setq filter
+ (delete-dups
+ (append (get 'org-agenda-tag-filter :preset-filter)
+ filter)))
+ (dolist (x filter)
+ (let ((op (string-to-char x)))
+ (if expand (setq x (org-agenda-filter-expand-tags (list x) t))
+ (setq x (list x)))
+ (setq f1 (org-agenda-filter-make-matcher-tag-exp x op))
+ (push f1 f))))
+ ;; Category filter
+ ((eq type 'category)
+ (setq filter
+ (delete-dups
+ (append (get 'org-agenda-category-filter :preset-filter)
+ filter)))
+ (dolist (x filter)
+ (if (equal "-" (substring x 0 1))
+ (setq f1 (list 'not (list 'equal (substring x 1) 'cat)))
+ (setq f1 (list 'equal (substring x 1) 'cat)))
+ (push f1 f)))
+ ;; Regexp filter
+ ((eq type 'regexp)
+ (setq filter
+ (delete-dups
+ (append (get 'org-agenda-regexp-filter :preset-filter)
+ filter)))
+ (dolist (x filter)
+ (if (equal "-" (substring x 0 1))
+ (setq f1 (list 'not (list 'string-match (substring x 1) 'txt)))
+ (setq f1 (list 'string-match (substring x 1) 'txt)))
+ (push f1 f)))
+ ;; Effort filter
+ ((eq type 'effort)
+ (setq filter
+ (delete-dups
+ (append (get 'org-agenda-effort-filter :preset-filter)
+ filter)))
+ (dolist (x filter)
+ (push (org-agenda-filter-effort-form x) f))))
+ (cons 'and (nreverse f))))
+
+(defun org-agenda-filter-make-matcher-tag-exp (tags op)
+ "Return a form associated to tag-expression TAGS.
+Build a form testing a line for agenda filter for
+tag-expressions. OP is an operator of type CHAR that allows the
+function to set the right switches in the returned form."
+ (let (form)
+ ;; Any of the expressions can match if OP is +, all must match if
+ ;; the operator is -.
+ (dolist (x tags (cons (if (eq op ?-) 'and 'or) form))
+ (let* ((tag (substring x 1))
+ (f (cond
+ ((string= "" tag) '(not tags))
+ ((and (string-match-p "\\`{" tag) (string-match-p "}\\'" tag))
+ ;; TAG is a regexp.
+ (list 'org-match-any-p (substring tag 1 -1) 'tags))
+ (t (list 'member (downcase tag) 'tags)))))
+ (push (if (eq op ?-) (list 'not f) f) form)))))
+
+(defun org-agenda-filter-effort-form (e)
+ "Return the form to compare the effort of the current line with what E says.
+E looks like \"+<2:25\"."
+ (let (op)
+ (setq e (substring e 1))
+ (setq op (string-to-char e) e (substring e 1))
+ (setq op (cond ((equal op ?<) '<=)
+ ((equal op ?>) '>=)
+ ((equal op ??) op)
+ (t '=)))
+ (list 'org-agenda-compare-effort (list 'quote op)
+ (org-duration-string-to-minutes e))))
+
+(defun org-agenda-compare-effort (op value)
+ "Compare the effort of the current line with VALUE, using OP.
+If the line does not have an effort defined, return nil."
+ ;; `effort-minutes' property cannot be extracted directly from
+ ;; current line but is stored as a property in `txt'.
+ (let ((effort (get-text-property 0 'effort-minutes (org-get-at-bol 'txt))))
+ (funcall op
+ (or effort (if org-sort-agenda-noeffort-is-high 32767 -1))
+ value)))
+
+(defun org-agenda-filter-expand-tags (filter &optional no-operator)
+ "Expand group tags in FILTER for the agenda.
+When NO-OPERATOR is non-nil, do not add the + operator to returned tags."
+ (if org-group-tags
+ (let ((case-fold-search t) rtn)
+ (mapc
+ (lambda (f)
+ (let (f0 dir)
+ (if (string-match "^\\([+-]\\)\\(.+\\)" f)
+ (setq dir (match-string 1 f) f0 (match-string 2 f))
+ (setq dir (if no-operator "" "+") f0 f))
+ (setq rtn (append (mapcar (lambda(f1) (concat dir f1))
+ (org-tags-expand f0 t t))
+ rtn))))
+ filter)
+ (reverse rtn))
+ filter))
+
+(defun org-agenda-filter-apply (filter type &optional expand)
+ "Set FILTER as the new agenda filter and apply it. Optional
+argument EXPAND can be used for the TYPE tag and will expand the
+tags in the FILTER if any of the tags in FILTER are grouptags."
+ ;; Deactivate `org-agenda-entry-text-mode' when filtering
+ (if org-agenda-entry-text-mode (org-agenda-entry-text-mode))
+ (let (tags cat txt)
+ (setq org-agenda-filter-form (org-agenda-filter-make-matcher filter type expand))
+ ;; Only set `org-agenda-filtered-by-category' to t when a unique
+ ;; category is used as the filter:
+ (setq org-agenda-filtered-by-category
+ (and (eq type 'category)
+ (not (equal (substring (car filter) 0 1) "-"))))
+ (org-agenda-set-mode-name)
+ (save-excursion
+ (goto-char (point-min))
+ (while (not (eobp))
+ (if (org-get-at-bol 'org-marker)
+ (progn
+ (setq tags (org-get-at-bol 'tags)
+ cat (org-get-at-eol 'org-category 1)
+ txt (org-get-at-bol 'txt))
+ (if (not (eval org-agenda-filter-form))
+ (org-agenda-filter-hide-line type))
+ (beginning-of-line 2))
+ (beginning-of-line 2))))
+ (if (get-char-property (point) 'invisible)
+ (ignore-errors (org-agenda-previous-line)))))
+
+(defun org-agenda-filter-top-headline-apply (hl &optional negative)
+ "Filter by top headline HL."
+ (org-agenda-set-mode-name)
+ (save-excursion
+ (goto-char (point-min))
+ (while (not (eobp))
+ (let* ((pos (org-get-at-bol 'org-hd-marker))
+ (tophl (and pos (org-find-top-headline pos))))
+ (if (and tophl (funcall (if negative 'identity 'not)
+ (string= hl tophl)))
+ (org-agenda-filter-hide-line 'top-headline)))
+ (beginning-of-line 2)))
+ (if (get-char-property (point) 'invisible)
+ (org-agenda-previous-line))
+ (setq org-agenda-top-headline-filter hl
+ org-agenda-filtered-by-top-headline t))
+
+(defun org-agenda-filter-hide-line (type)
+ "Hide lines with TYPE in the agenda buffer."
+ (let* ((b (max (point-min) (1- (point-at-bol))))
+ (e (point-at-eol)))
+ (let ((inhibit-read-only t))
+ (add-text-properties
+ b e `(invisible org-filtered org-filter-type ,type)))))
+
+(defun org-agenda-remove-filter (type)
+ (interactive)
+ "Remove filter of type TYPE from the agenda buffer."
+ (save-excursion
+ (goto-char (point-min))
+ (let ((inhibit-read-only t) pos)
+ (while (setq pos (text-property-any (point) (point-max) 'org-filter-type type))
+ (goto-char pos)
+ (remove-text-properties
+ (point) (next-single-property-change (point) 'org-filter-type)
+ `(invisible org-filtered org-filter-type ,type))))
+ (set (intern (format "org-agenda-%s-filter" (intern-soft type))) nil)
+ (setq org-agenda-filter-form nil)
+ (org-agenda-set-mode-name)
+ (org-agenda-finalize)))
+
+(defun org-agenda-filter-show-all-tag nil
+ (org-agenda-remove-filter 'tag))
+(defun org-agenda-filter-show-all-re nil
+ (org-agenda-remove-filter 'regexp))
+(defun org-agenda-filter-show-all-effort nil
+ (org-agenda-remove-filter 'effort))
+(defun org-agenda-filter-show-all-cat nil
+ (org-agenda-remove-filter 'category))
+(defun org-agenda-filter-show-all-top-filter nil
+ (org-agenda-remove-filter 'top-headline))
+
+(defun org-agenda-manipulate-query-add ()
+ "Manipulate the query by adding a search term with positive selection.
+Positive selection means the term must be matched for selection of an entry."
+ (interactive)
+ (org-agenda-manipulate-query ?\[))
+(defun org-agenda-manipulate-query-subtract ()
+ "Manipulate the query by adding a search term with negative selection.
+Negative selection means term must not be matched for selection of an entry."
+ (interactive)
+ (org-agenda-manipulate-query ?\]))
+(defun org-agenda-manipulate-query-add-re ()
+ "Manipulate the query by adding a search regexp with positive selection.
+Positive selection means the regexp must match for selection of an entry."
+ (interactive)
+ (org-agenda-manipulate-query ?\{))
+(defun org-agenda-manipulate-query-subtract-re ()
+ "Manipulate the query by adding a search regexp with negative selection.
+Negative selection means regexp must not match for selection of an entry."
+ (interactive)
+ (org-agenda-manipulate-query ?\}))
+(defun org-agenda-manipulate-query (char)
+ (cond
+ ((memq org-agenda-type '(timeline agenda))
+ (let ((org-agenda-include-inactive-timestamps t))
+ (org-agenda-redo))
+ (message "Display now includes inactive timestamps as well"))
+ ((eq org-agenda-type 'search)
+ (org-add-to-string
+ 'org-agenda-query-string
+ (if org-agenda-last-search-view-search-was-boolean
+ (cdr (assoc char '((?\[ . " +") (?\] . " -")
+ (?\{ . " +{}") (?\} . " -{}"))))
+ " "))
+ (setq org-agenda-redo-command
+ (list 'org-search-view
+ (car (get-text-property (min (1- (point-max)) (point))
+ 'org-last-args))
+ org-agenda-query-string
+ (+ (length org-agenda-query-string)
+ (if (member char '(?\{ ?\})) 0 1))))
+ (set-register org-agenda-query-register org-agenda-query-string)
+ (let ((org-agenda-overriding-arguments
+ (cdr org-agenda-redo-command)))
+ (org-agenda-redo)))
+ (t (error "Cannot manipulate query for %s-type agenda buffers"
+ org-agenda-type))))
+
+(defun org-add-to-string (var string)
+ (set var (concat (symbol-value var) string)))
+
+(defun org-agenda-goto-date (span)
+ "Jump to DATE in agenda."
+ (interactive "P")
+ (let* ((org-read-date-prefer-future
+ (eval org-agenda-jump-prefer-future))
+ (date (org-read-date))
+ (day (time-to-days (org-time-string-to-time date)))
+ (org-agenda-sticky-orig org-agenda-sticky)
+ (org-agenda-buffer-tmp-name (buffer-name))
+ (args (get-text-property (min (1- (point-max)) (point)) 'org-last-args))
+ (0-arg (or current-prefix-arg (car args)))
+ (2-arg (nth 2 args))
+ (with-hour-p (nth 4 org-agenda-redo-command))
+ (newcmd (list 'org-agenda-list 0-arg date
+ (org-agenda-span-to-ndays
+ 2-arg (org-time-string-to-absolute date))
+ with-hour-p))
+ (newargs (cdr newcmd))
+ (inhibit-read-only t)
+ org-agenda-sticky)
+ (if (not (org-agenda-check-type t 'agenda))
+ (error "Not available in non-agenda views")
+ (add-text-properties (point-min) (point-max)
+ `(org-redo-cmd ,newcmd org-last-args ,newargs))
+ (org-agenda-redo)
+ (goto-char (point-min))
+ (while (not (or (= (or (get-text-property (point) 'day) 0) day)
+ (save-excursion (move-beginning-of-line 2) (eobp))))
+ (move-beginning-of-line 2))
+ (setq org-agenda-sticky org-agenda-sticky-orig
+ org-agenda-this-buffer-is-sticky org-agenda-sticky))))
+
+(defun org-agenda-goto-today ()
+ "Go to today."
+ (interactive)
+ (org-agenda-check-type t 'timeline 'agenda)
+ (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args))
+ (curspan (nth 2 args))
+ (tdpos (text-property-any (point-min) (point-max) 'org-today t)))
+ (cond
+ (tdpos (goto-char tdpos))
+ ((eq org-agenda-type 'agenda)
+ (let* ((sd (org-agenda-compute-starting-span
+ (org-today) (or curspan org-agenda-span)))
+ (org-agenda-overriding-arguments args))
+ (setf (nth 1 org-agenda-overriding-arguments) sd)
+ (org-agenda-redo)
+ (org-agenda-find-same-or-today-or-agenda)))
+ (t (error "Cannot find today")))))
+
+(defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
+ (goto-char
+ (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
+ (text-property-any (point-min) (point-max) 'org-today t)
+ (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
+ (and (get-text-property (min (1- (point-max)) (point)) 'org-series)
+ (org-agenda-backward-block))
+ (point-min))))
+
+(defun org-agenda-backward-block ()
+ "Move backward by one agenda block."
+ (interactive)
+ (org-agenda-forward-block 'backward))
+
+(defun org-agenda-forward-block (&optional backward)
+ "Move forward by one agenda block.
+When optional argument BACKWARD is set, go backward"
+ (interactive)
+ (cond ((not (derived-mode-p 'org-agenda-mode))
+ (user-error
+ "Cannot execute this command outside of org-agenda-mode buffers"))
+ ((looking-at (if backward "\\`" "\\'"))
+ (message "Already at the %s block" (if backward "first" "last")))
+ (t (let ((pos (prog1 (point)
+ (ignore-errors (if backward (backward-char 1)
+ (move-end-of-line 1)))))
+ (f (if backward
+ 'previous-single-property-change
+ 'next-single-property-change))
+ moved dest)
+ (while (and (setq dest (funcall
+ f (point) 'org-agenda-structural-header))
+ (not (get-text-property
+ (point) 'org-agenda-structural-header)))
+ (setq moved t)
+ (goto-char dest))
+ (if moved (move-beginning-of-line 1)
+ (goto-char (if backward (point-min) (point-max)))
+ (move-beginning-of-line 1)
+ (message "No %s block" (if backward "previous" "further")))))))
+
+(defun org-agenda-later (arg)
+ "Go forward in time by the current span.
+With prefix ARG, go forward that many times the current span."
+ (interactive "p")
+ (org-agenda-check-type t 'agenda)
+ (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args))
+ (span (or (nth 2 args) org-agenda-current-span))
+ (sd (or (nth 1 args) (org-get-at-bol 'day) org-starting-day))
+ (greg (calendar-gregorian-from-absolute sd))
+ (cnt (org-get-at-bol 'org-day-cnt))
+ greg2)
+ (cond
+ ((numberp span)
+ (setq sd (+ (* span arg) sd)))
+ ((eq span 'day)
+ (setq sd (+ arg sd)))
+ ((eq span 'week)
+ (setq sd (+ (* 7 arg) sd)))
+ ((eq span 'fortnight)
+ (setq sd (+ (* 14 arg) sd)))
+ ((eq span 'month)
+ (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
+ sd (calendar-absolute-from-gregorian greg2))
+ (setcar greg2 (1+ (car greg2))))
+ ((eq span 'year)
+ (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
+ sd (calendar-absolute-from-gregorian greg2))
+ (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2))))
+ (t
+ (setq sd (+ (* span arg) sd))))
+ (let ((org-agenda-overriding-cmd
+ ;; `cmd' may have been set by `org-agenda-run-series' which
+ ;; uses `org-agenda-overriding-cmd' to decide whether
+ ;; overriding is allowed for `cmd'
+ (get-text-property (min (1- (point-max)) (point)) 'org-series-cmd))
+ (org-agenda-overriding-arguments
+ (list (car args) sd span)))
+ (org-agenda-redo)
+ (org-agenda-find-same-or-today-or-agenda cnt))))
+
+(defun org-agenda-earlier (arg)
+ "Go backward in time by the current span.
+With prefix ARG, go backward that many times the current span."
+ (interactive "p")
+ (org-agenda-later (- arg)))
+
+(defun org-agenda-view-mode-dispatch ()
+ "Call one of the view mode commands."
+ (interactive)
+ (message "View: [d]ay [w]eek for[t]night [m]onth [y]ear [SPC]reset [q]uit/abort
+ time[G]rid [[]inactive [f]ollow [l]og [L]og-all [c]lockcheck
+ [a]rch-trees [A]rch-files clock[R]eport include[D]iary [E]ntryText")
+ (pcase (read-char-exclusive)
+ (?\ (call-interactively 'org-agenda-reset-view))
+ (?d (call-interactively 'org-agenda-day-view))
+ (?w (call-interactively 'org-agenda-week-view))
+ (?t (call-interactively 'org-agenda-fortnight-view))
+ (?m (call-interactively 'org-agenda-month-view))
+ (?y (call-interactively 'org-agenda-year-view))
+ (?l (call-interactively 'org-agenda-log-mode))
+ (?L (org-agenda-log-mode '(4)))
+ (?c (org-agenda-log-mode 'clockcheck))
+ ((or ?F ?f) (call-interactively 'org-agenda-follow-mode))
+ (?a (call-interactively 'org-agenda-archives-mode))
+ (?A (org-agenda-archives-mode 'files))
+ ((or ?R ?r) (call-interactively 'org-agenda-clockreport-mode))
+ ((or ?E ?e) (call-interactively 'org-agenda-entry-text-mode))
+ (?G (call-interactively 'org-agenda-toggle-time-grid))
+ (?D (call-interactively 'org-agenda-toggle-diary))
+ (?\! (call-interactively 'org-agenda-toggle-deadlines))
+ (?\[ (let ((org-agenda-include-inactive-timestamps t))
+ (org-agenda-check-type t 'timeline 'agenda)
+ (org-agenda-redo))
+ (message "Display now includes inactive timestamps as well"))
+ (?q (message "Abort"))
+ (key (user-error "Invalid key: %s" key))))
+
+(defun org-agenda-reset-view ()
+ "Switch to default view for agenda."
+ (interactive)
+ (org-agenda-change-time-span org-agenda-span))
+
+(defun org-agenda-day-view (&optional day-of-month)
+ "Switch to daily view for agenda.
+With argument DAY-OF-MONTH, switch to that day of the month."
+ (interactive "P")
+ (org-agenda-change-time-span 'day day-of-month))
+
+(defun org-agenda-week-view (&optional iso-week)
+ "Switch to weekly view for agenda.
+With argument ISO-WEEK, switch to the corresponding ISO week.
+If ISO-WEEK has more then 2 digits, only the last two encode
+the week. Any digits before this encode a year. So 200712
+means week 12 of year 2007. Years ranging from 70 years ago
+to 30 years in the future can also be written as 2-digit years."
+ (interactive "P")
+ (org-agenda-change-time-span 'week iso-week))
+
+(defun org-agenda-fortnight-view (&optional iso-week)
+ "Switch to fortnightly view for agenda.
+With argument ISO-WEEK, switch to the corresponding ISO week.
+If ISO-WEEK has more then 2 digits, only the last two encode
+the week. Any digits before this encode a year. So 200712
+means week 12 of year 2007. Years ranging from 70 years ago
+to 30 years in the future can also be written as 2-digit years."
+ (interactive "P")
+ (org-agenda-change-time-span 'fortnight iso-week))
+
+(defun org-agenda-month-view (&optional month)
+ "Switch to monthly view for agenda.
+With argument MONTH, switch to that month. If MONTH has more
+then 2 digits, only the last two encode the month. Any digits
+before this encode a year. So 200712 means December year 2007.
+Years ranging from 70 years ago to 30 years in the future can
+also be written as 2-digit years."
+ (interactive "P")
+ (org-agenda-change-time-span 'month month))
+
+(defun org-agenda-year-view (&optional year)
+ "Switch to yearly view for agenda.
+With argument YEAR, switch to that year. Years ranging from 70
+years ago to 30 years in the future can also be written as
+2-digit years."
+ (interactive "P")
+ (when year
+ (setq year (org-small-year-to-year year)))
+ (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
+ (org-agenda-change-time-span 'year year)
+ (error "Abort")))
+
+(defun org-agenda-change-time-span (span &optional n)
+ "Change the agenda view to SPAN.
+SPAN may be `day', `week', `fortnight', `month', `year'."
+ (org-agenda-check-type t 'agenda)
+ (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args))
+ (curspan (nth 2 args)))
+ (if (and (not n) (equal curspan span))
+ (error "Viewing span is already \"%s\"" span))
+ (let* ((sd (or (org-get-at-bol 'day)
+ (nth 1 args)
+ org-starting-day))
+ (sd (org-agenda-compute-starting-span sd span n))
+ (org-agenda-overriding-cmd
+ (get-text-property (min (1- (point-max)) (point)) 'org-series-cmd))
+ (org-agenda-overriding-arguments
+ (list (car args) sd span)))
+ (org-agenda-redo)
+ (org-agenda-find-same-or-today-or-agenda))
+ (org-agenda-set-mode-name)
+ (message "Switched to %s view" span)))
+
+(defun org-agenda-compute-starting-span (sd span &optional n)
+ "Compute starting date for agenda.
+SPAN may be `day', `week', `fortnight', `month', `year'. The return value
+is a cons cell with the starting date and the number of days,
+so that the date SD will be in that range."
+ (let* ((greg (calendar-gregorian-from-absolute sd))
+ (dg (nth 1 greg))
+ (mg (car greg))
+ (yg (nth 2 greg)))
+ (cond
+ ((eq span 'day)
+ (when n
+ (setq sd (+ (calendar-absolute-from-gregorian
+ (list mg 1 yg))
+ n -1))))
+ ((or (eq span 'week) (eq span 'fortnight))
+ (let* ((nt (calendar-day-of-week
+ (calendar-gregorian-from-absolute sd)))
+ (d (if org-agenda-start-on-weekday
+ (- nt org-agenda-start-on-weekday)
+ 0))
+ y1)
+ (setq sd (- sd (+ (if (< d 0) 7 0) d)))
+ (when n
+ (require 'cal-iso)
+ (when (> n 99)
+ (setq y1 (org-small-year-to-year (/ n 100))
+ n (mod n 100)))
+ (setq sd
+ (calendar-iso-to-absolute
+ (list n 1
+ (or y1 (nth 2 (calendar-iso-from-absolute sd)))))))))
+ ((eq span 'month)
+ (let (y1)
+ (when (and n (> n 99))
+ (setq y1 (org-small-year-to-year (/ n 100))
+ n (mod n 100)))
+ (setq sd (calendar-absolute-from-gregorian
+ (list (or n mg) 1 (or y1 yg))))))
+ ((eq span 'year)
+ (setq sd (calendar-absolute-from-gregorian
+ (list 1 1 (or n yg))))))
+ sd))
+
+(defun org-agenda-next-date-line (&optional arg)
+ "Jump to the next line indicating a date in agenda buffer."
+ (interactive "p")
+ (org-agenda-check-type t 'agenda 'timeline)
+ (beginning-of-line 1)
+ ;; This does not work if user makes date format that starts with a blank
+ (if (looking-at "^\\S-") (forward-char 1))
+ (if (not (re-search-forward "^\\S-" nil t arg))
+ (progn
+ (backward-char 1)
+ (error "No next date after this line in this buffer")))
+ (goto-char (match-beginning 0)))
+
+(defun org-agenda-previous-date-line (&optional arg)
+ "Jump to the previous line indicating a date in agenda buffer."
+ (interactive "p")
+ (org-agenda-check-type t 'agenda 'timeline)
+ (beginning-of-line 1)
+ (if (not (re-search-backward "^\\S-" nil t arg))
+ (error "No previous date before this line in this buffer")))
+
+;; Initialize the highlight
+(defvar org-hl (make-overlay 1 1))
+(overlay-put org-hl 'face 'highlight)
+
+(defun org-highlight (begin end &optional buffer)
+ "Highlight a region with overlay."
+ (move-overlay org-hl begin end (or buffer (current-buffer))))
+
+(defun org-unhighlight ()
+ "Detach overlay INDEX."
+ (delete-overlay org-hl))
+
+(defun org-unhighlight-once ()
+ "Remove the highlight from its position, and this function from the hook."
+ (remove-hook 'pre-command-hook 'org-unhighlight-once)
+ (org-unhighlight))
+
+(defvar org-agenda-pre-follow-window-conf nil)
+(defun org-agenda-follow-mode ()
+ "Toggle follow mode in an agenda buffer."
+ (interactive)
+ (unless org-agenda-follow-mode
+ (setq org-agenda-pre-follow-window-conf
+ (current-window-configuration)))
+ (setq org-agenda-follow-mode (not org-agenda-follow-mode))
+ (unless org-agenda-follow-mode
+ (set-window-configuration org-agenda-pre-follow-window-conf))
+ (org-agenda-set-mode-name)
+ (org-agenda-do-context-action)
+ (message "Follow mode is %s"
+ (if org-agenda-follow-mode "on" "off")))
+
+(defun org-agenda-entry-text-mode (&optional arg)
+ "Toggle entry text mode in an agenda buffer."
+ (interactive "P")
+ (if (or org-agenda-tag-filter
+ org-agenda-category-filter
+ org-agenda-regexp-filter
+ org-agenda-top-headline-filter)
+ (user-error "Can't show entry text in filtered views")
+ (setq org-agenda-entry-text-mode (or (integerp arg)
+ (not org-agenda-entry-text-mode)))
+ (org-agenda-entry-text-hide)
+ (and org-agenda-entry-text-mode
+ (let ((org-agenda-entry-text-maxlines
+ (if (integerp arg) arg org-agenda-entry-text-maxlines)))
+ (org-agenda-entry-text-show)))
+ (org-agenda-set-mode-name)
+ (message "Entry text mode is %s%s"
+ (if org-agenda-entry-text-mode "on" "off")
+ (if (not org-agenda-entry-text-mode) ""
+ (format " (maximum number of lines is %d)"
+ (if (integerp arg) arg org-agenda-entry-text-maxlines))))))
+
+(defun org-agenda-clockreport-mode ()
+ "Toggle clocktable mode in an agenda buffer."
+ (interactive)
+ (org-agenda-check-type t 'agenda)
+ (setq org-agenda-clockreport-mode (not org-agenda-clockreport-mode))
+ (setq org-agenda-start-with-clockreport-mode org-agenda-clockreport-mode)
+ (org-agenda-set-mode-name)
+ (org-agenda-redo)
+ (message "Clocktable mode is %s"
+ (if org-agenda-clockreport-mode "on" "off")))
+
+(defun org-agenda-log-mode (&optional special)
+ "Toggle log mode in an agenda buffer.
+
+With argument SPECIAL, show all possible log items, not only the ones
+configured in `org-agenda-log-mode-items'.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix, show *only* \
+log items, nothing else."
+ (interactive "P")
+ (org-agenda-check-type t 'agenda 'timeline)
+ (setq org-agenda-show-log
+ (cond
+ ((equal special '(16)) 'only)
+ ((eq special 'clockcheck)
+ (if (eq org-agenda-show-log 'clockcheck)
+ nil 'clockcheck))
+ (special '(closed clock state))
+ (t (not org-agenda-show-log))))
+ (setq org-agenda-start-with-log-mode org-agenda-show-log)
+ (org-agenda-set-mode-name)
+ (org-agenda-redo)
+ (message "Log mode is %s" (if org-agenda-show-log "on" "off")))
+
+(defun org-agenda-archives-mode (&optional with-files)
+ "Toggle inclusion of items in trees marked with :ARCHIVE:.
+When called with a prefix argument, include all archive files as well."
+ (interactive "P")
+ (setq org-agenda-archives-mode
+ (if with-files t (if org-agenda-archives-mode nil 'trees)))
+ (org-agenda-set-mode-name)
+ (org-agenda-redo)
+ (message
+ "%s"
+ (cond
+ ((eq org-agenda-archives-mode nil)
+ "No archives are included")
+ ((eq org-agenda-archives-mode 'trees)
+ (format "Trees with :%s: tag are included" org-archive-tag))
+ ((eq org-agenda-archives-mode t)
+ (format "Trees with :%s: tag and all active archive files are included"
+ org-archive-tag)))))
+
+(defun org-agenda-toggle-diary ()
+ "Toggle diary inclusion in an agenda buffer."
+ (interactive)
+ (org-agenda-check-type t 'agenda)
+ (setq org-agenda-include-diary (not org-agenda-include-diary))
+ (org-agenda-redo)
+ (org-agenda-set-mode-name)
+ (message "Diary inclusion turned %s"
+ (if org-agenda-include-diary "on" "off")))
+
+(defun org-agenda-toggle-deadlines ()
+ "Toggle inclusion of entries with a deadline in an agenda buffer."
+ (interactive)
+ (org-agenda-check-type t 'agenda)
+ (setq org-agenda-include-deadlines (not org-agenda-include-deadlines))
+ (org-agenda-redo)
+ (org-agenda-set-mode-name)
+ (message "Deadlines inclusion turned %s"
+ (if org-agenda-include-deadlines "on" "off")))
+
+(defun org-agenda-toggle-time-grid ()
+ "Toggle time grid in an agenda buffer."
+ (interactive)
+ (org-agenda-check-type t 'agenda)
+ (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
+ (org-agenda-redo)
+ (org-agenda-set-mode-name)
+ (message "Time-grid turned %s"
+ (if org-agenda-use-time-grid "on" "off")))
+
+(defun org-agenda-set-mode-name ()
+ "Set the mode name to indicate all the small mode settings."
+ (setq mode-name
+ (list "Org-Agenda"
+ (if (get 'org-agenda-files 'org-restrict) " []" "")
+ " "
+ '(:eval (org-agenda-span-name org-agenda-current-span))
+ (if org-agenda-follow-mode " Follow" "")
+ (if org-agenda-entry-text-mode " ETxt" "")
+ (if org-agenda-include-diary " Diary" "")
+ (if org-agenda-include-deadlines " Ddl" "")
+ (if org-agenda-use-time-grid " Grid" "")
+ (if (and (boundp 'org-habit-show-habits)
+ org-habit-show-habits) " Habit" "")
+ (cond
+ ((consp org-agenda-show-log) " LogAll")
+ ((eq org-agenda-show-log 'clockcheck) " ClkCk")
+ (org-agenda-show-log " Log")
+ (t ""))
+ (if (or org-agenda-category-filter
+ (get 'org-agenda-category-filter :preset-filter))
+ '(:eval (propertize
+ (concat " <"
+ (mapconcat
+ 'identity
+ (append
+ (get 'org-agenda-category-filter :preset-filter)
+ org-agenda-category-filter)
+ "")
+ ">")
+ 'face 'org-agenda-filter-category
+ 'help-echo "Category used in filtering")) "")
+ (if (or org-agenda-tag-filter
+ (get 'org-agenda-tag-filter :preset-filter))
+ '(:eval (propertize
+ (concat " {"
+ (mapconcat
+ 'identity
+ (append
+ (get 'org-agenda-tag-filter :preset-filter)
+ org-agenda-tag-filter)
+ "")
+ "}")
+ 'face 'org-agenda-filter-tags
+ 'help-echo "Tags used in filtering")) "")
+ (if (or org-agenda-effort-filter
+ (get 'org-agenda-effort-filter :preset-filter))
+ '(:eval (propertize
+ (concat " {"
+ (mapconcat
+ 'identity
+ (append
+ (get 'org-agenda-effort-filter :preset-filter)
+ org-agenda-effort-filter)
+ "")
+ "}")
+ 'face 'org-agenda-filter-effort
+ 'help-echo "Effort conditions used in filtering")) "")
+ (if (or org-agenda-regexp-filter
+ (get 'org-agenda-regexp-filter :preset-filter))
+ '(:eval (propertize
+ (concat " ["
+ (mapconcat
+ 'identity
+ (append
+ (get 'org-agenda-regexp-filter :preset-filter)
+ org-agenda-regexp-filter)
+ "")
+ "]")
+ 'face 'org-agenda-filter-regexp
+ 'help-echo "Regexp used in filtering")) "")
+ (if org-agenda-archives-mode
+ (if (eq org-agenda-archives-mode t)
+ " Archives"
+ (format " :%s:" org-archive-tag))
+ "")
+ (if org-agenda-clockreport-mode " Clock" "")))
+ (force-mode-line-update))
+
+(defun org-agenda-update-agenda-type ()
+ "Update the agenda type after each command."
+ (setq org-agenda-type
+ (or (get-text-property (point) 'org-agenda-type)
+ (get-text-property (max (point-min) (1- (point))) 'org-agenda-type))))
+
+(defun org-agenda-next-line ()
+ "Move cursor to the next line, and show if follow mode is active."
+ (interactive)
+ (call-interactively 'next-line)
+ (org-agenda-do-context-action))
+
+(defun org-agenda-previous-line ()
+ "Move cursor to the previous line, and show if follow-mode is active."
+ (interactive)
+ (call-interactively 'previous-line)
+ (org-agenda-do-context-action))
+
+(defun org-agenda-next-item (n)
+ "Move cursor to next agenda item."
+ (interactive "p")
+ (let ((col (current-column)))
+ (dotimes (c n)
+ (when (next-single-property-change (point-at-eol) 'org-marker)
+ (move-end-of-line 1)
+ (goto-char (next-single-property-change (point) 'org-marker))))
+ (org-move-to-column col))
+ (org-agenda-do-context-action))
+
+(defun org-agenda-previous-item (n)
+ "Move cursor to next agenda item."
+ (interactive "p")
+ (dotimes (c n)
+ (let ((col (current-column))
+ (goto (save-excursion
+ (move-end-of-line 0)
+ (previous-single-property-change (point) 'org-marker))))
+ (if goto (goto-char goto))
+ (org-move-to-column col)))
+ (org-agenda-do-context-action))
+
+(defun org-agenda-do-context-action ()
+ "Show outline path and, maybe, follow mode window."
+ (let ((m (org-get-at-bol 'org-marker)))
+ (when (and (markerp m) (marker-buffer m))
+ (and org-agenda-follow-mode
+ (if org-agenda-follow-indirect
+ (org-agenda-tree-to-indirect-buffer nil)
+ (org-agenda-show)))
+ (and org-agenda-show-outline-path
+ (org-with-point-at m (org-display-outline-path t))))))
+
+(defun org-agenda-show-tags ()
+ "Show the tags applicable to the current item."
+ (interactive)
+ (let* ((tags (org-get-at-bol 'tags)))
+ (if tags
+ (message "Tags are :%s:"
+ (org-no-properties (mapconcat 'identity tags ":")))
+ (message "No tags associated with this line"))))
+
+(defun org-agenda-goto (&optional highlight)
+ "Go to the entry at point in the corresponding Org file."
+ (interactive)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker)))
+ (switch-to-buffer-other-window buffer)
+ (widen)
+ (push-mark)
+ (goto-char pos)
+ (when (derived-mode-p 'org-mode)
+ (org-show-context 'agenda)
+ (recenter (/ (window-height) 2))
+ (org-back-to-heading t)
+ (let ((case-fold-search nil))
+ (when (re-search-forward org-complex-heading-regexp nil t)
+ (goto-char (match-beginning 4)))))
+ (run-hooks 'org-agenda-after-show-hook)
+ (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
+
+(defvar org-agenda-after-show-hook nil
+ "Normal hook run after an item has been shown from the agenda.
+Point is in the buffer where the item originated.")
+
+(defun org-agenda-kill ()
+ "Kill the entry or subtree belonging to the current agenda entry."
+ (interactive)
+ (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
+ (let* ((bufname-orig (buffer-name))
+ (marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ (type (org-get-at-bol 'type))
+ dbeg dend (n 0) conf)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char pos)
+ (if (and (derived-mode-p 'org-mode) (not (member type '("sexp"))))
+ (setq dbeg (progn (org-back-to-heading t) (point))
+ dend (org-end-of-subtree t t))
+ (setq dbeg (point-at-bol)
+ dend (min (point-max) (1+ (point-at-eol)))))
+ (goto-char dbeg)
+ (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
+ (setq conf (or (eq t org-agenda-confirm-kill)
+ (and (numberp org-agenda-confirm-kill)
+ (> n org-agenda-confirm-kill))))
+ (and conf
+ (not (y-or-n-p
+ (format "Delete entry with %d lines in buffer \"%s\"? "
+ n (buffer-name buffer))))
+ (error "Abort"))
+ (let ((org-agenda-buffer-name bufname-orig))
+ (org-remove-subtree-entries-from-agenda buffer dbeg dend))
+ (with-current-buffer buffer (delete-region dbeg dend))
+ (message "Agenda item and source killed"))))
+
+(defvar org-archive-default-command) ; defined in org-archive.el
+(defun org-agenda-archive-default ()
+ "Archive the entry or subtree belonging to the current agenda entry."
+ (interactive)
+ (require 'org-archive)
+ (org-agenda-archive-with org-archive-default-command))
+
+(defun org-agenda-archive-default-with-confirmation ()
+ "Archive the entry or subtree belonging to the current agenda entry."
+ (interactive)
+ (require 'org-archive)
+ (org-agenda-archive-with org-archive-default-command 'confirm))
+
+(defun org-agenda-archive ()
+ "Archive the entry or subtree belonging to the current agenda entry."
+ (interactive)
+ (org-agenda-archive-with 'org-archive-subtree))
+
+(defun org-agenda-archive-to-archive-sibling ()
+ "Move the entry to the archive sibling."
+ (interactive)
+ (org-agenda-archive-with 'org-archive-to-archive-sibling))
+
+(defun org-agenda-archive-with (cmd &optional confirm)
+ "Move the entry to the archive sibling."
+ (interactive)
+ (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
+ (let* ((bufname-orig (buffer-name))
+ (marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker)))
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (if (derived-mode-p 'org-mode)
+ (if (and confirm
+ (not (y-or-n-p "Archive this subtree or entry? ")))
+ (error "Abort")
+ (save-window-excursion
+ (goto-char pos)
+ (let ((org-agenda-buffer-name bufname-orig))
+ (org-remove-subtree-entries-from-agenda))
+ (org-back-to-heading t)
+ (funcall cmd)))
+ (error "Archiving works only in Org files"))))))
+
+(defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
+ "Remove all lines in the agenda that correspond to a given subtree.
+The subtree is the one in buffer BUF, starting at BEG and ending at END.
+If this information is not given, the function uses the tree at point."
+ (let ((buf (or buf (current-buffer))) m p)
+ (save-excursion
+ (unless (and beg end)
+ (org-back-to-heading t)
+ (setq beg (point))
+ (org-end-of-subtree t)
+ (setq end (point)))
+ (set-buffer (get-buffer org-agenda-buffer-name))
+ (save-excursion
+ (goto-char (point-max))
+ (beginning-of-line 1)
+ (while (not (bobp))
+ (when (and (setq m (org-get-at-bol 'org-marker))
+ (equal buf (marker-buffer m))
+ (setq p (marker-position m))
+ (>= p beg)
+ (< p end))
+ (let ((inhibit-read-only t))
+ (delete-region (point-at-bol) (1+ (point-at-eol)))))
+ (beginning-of-line 0))))))
+
+(defun org-agenda-refile (&optional goto rfloc no-update)
+ "Refile the item at point.
+
+When called with `\\[universal-argument] \\[universal-argument]', \
+go to the location of the last
+refiled item.
+
+When called with `\\[universal-argument] \\[universal-argument] \
+\\[universal-argument]' prefix or when GOTO is 0, clear
+the refile cache.
+
+RFLOC can be a refile location obtained in a different way.
+
+When NO-UPDATE is non-nil, don't redo the agenda buffer."
+ (interactive "P")
+ (cond
+ ((member goto '(0 (64)))
+ (org-refile-cache-clear))
+ ((equal goto '(16))
+ (org-refile-goto-last-stored))
+ (t
+ (let* ((buffer-orig (buffer-name))
+ (marker (or (org-get-at-bol 'org-hd-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ (rfloc (or rfloc
+ (org-refile-get-location
+ (if goto "Goto" "Refile to") buffer
+ org-refile-allow-creating-parent-nodes))))
+ (with-current-buffer buffer
+ (org-with-wide-buffer
+ (goto-char marker)
+ (let ((org-agenda-buffer-name buffer-orig))
+ (org-remove-subtree-entries-from-agenda))
+ (org-refile goto buffer rfloc))))
+ (unless no-update (org-agenda-redo)))))
+
+(defun org-agenda-open-link (&optional arg)
+ "Open the link(s) in the current entry, if any.
+This looks for a link in the displayed line in the agenda.
+It also looks at the text of the entry itself."
+ (interactive "P")
+ (let* ((marker (or (org-get-at-bol 'org-hd-marker)
+ (org-get-at-bol 'org-marker)))
+ (buffer (and marker (marker-buffer marker)))
+ (prefix (buffer-substring (point-at-bol) (point-at-eol)))
+ (lkall (and buffer (org-offer-links-in-entry
+ buffer marker arg prefix)))
+ (lk0 (car lkall))
+ (lk (if (stringp lk0) (list lk0) lk0))
+ (lkend (cdr lkall))
+ trg)
+ (cond
+ ((and buffer lk)
+ (mapcar (lambda(l)
+ (with-current-buffer buffer
+ (setq trg (and (string-match org-bracket-link-regexp l)
+ (match-string 1 l)))
+ (if (or (not trg) (string-match org-any-link-re trg))
+ (org-with-wide-buffer
+ (goto-char marker)
+ (when (search-forward l nil lkend)
+ (goto-char (match-beginning 0))
+ (org-open-at-point)))
+ ;; This is an internal link, widen the buffer
+ (switch-to-buffer-other-window buffer)
+ (widen)
+ (goto-char marker)
+ (when (search-forward l nil lkend)
+ (goto-char (match-beginning 0))
+ (org-open-at-point)))))
+ lk))
+ ((or (org-in-regexp (concat "\\(" org-bracket-link-regexp "\\)"))
+ (save-excursion
+ (beginning-of-line 1)
+ (looking-at (concat ".*?\\(" org-bracket-link-regexp "\\)"))))
+ (org-open-link-from-string (match-string 1)))
+ (t (message "No link to open here")))))
+
+(defun org-agenda-copy-local-variable (var)
+ "Get a variable from a referenced buffer and install it here."
+ (let ((m (org-get-at-bol 'org-marker)))
+ (when (and m (buffer-live-p (marker-buffer m)))
+ (set (make-local-variable var)
+ (with-current-buffer (marker-buffer m)
+ (symbol-value var))))))
+
+(defun org-agenda-switch-to (&optional delete-other-windows)
+ "Go to the Org mode file which contains the item at point.
+When optional argument DELETE-OTHER-WINDOWS is non-nil, the
+displayed Org file fills the frame."
+ (interactive)
+ (if (and org-return-follows-link
+ (not (org-get-at-bol 'org-marker))
+ (org-in-regexp org-bracket-link-regexp))
+ (org-open-link-from-string (match-string 0))
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker)))
+ (unless buffer (user-error "Trying to switch to non-existent buffer"))
+ (pop-to-buffer-same-window buffer)
+ (when delete-other-windows (delete-other-windows))
+ (widen)
+ (goto-char pos)
+ (when (derived-mode-p 'org-mode)
+ (org-show-context 'agenda)
+ (run-hooks 'org-agenda-after-show-hook)))))
+
+(defun org-agenda-goto-mouse (ev)
+ "Go to the Org file which contains the item at the mouse click."
+ (interactive "e")
+ (mouse-set-point ev)
+ (org-agenda-goto))
+
+(defun org-agenda-show (&optional full-entry)
+ "Display the Org file which contains the item at point.
+With prefix argument FULL-ENTRY, make the entire entry visible
+if it was hidden in the outline."
+ (interactive "P")
+ (let ((win (selected-window)))
+ (org-agenda-goto t)
+ (when full-entry (org-show-entry))
+ (select-window win)))
+
+(defvar org-agenda-show-window nil)
+(defun org-agenda-show-and-scroll-up (&optional arg)
+ "Display the Org file which contains the item at point.
+
+When called repeatedly, scroll the window that is displaying the buffer.
+
+With a `\\[universal-argument]' prefix, use `org-show-entry' instead of \
+`outline-show-subtree'
+to display the item, so that drawers and logbooks stay folded."
+ (interactive "P")
+ (let ((win (selected-window)))
+ (if (and (window-live-p org-agenda-show-window)
+ (eq this-command last-command))
+ (progn
+ (select-window org-agenda-show-window)
+ (ignore-errors (scroll-up)))
+ (org-agenda-goto t)
+ (if arg (org-show-entry) (outline-show-subtree))
+ (setq org-agenda-show-window (selected-window)))
+ (select-window win)))
+
+(defun org-agenda-show-scroll-down ()
+ "Scroll down the window showing the agenda."
+ (interactive)
+ (let ((win (selected-window)))
+ (when (window-live-p org-agenda-show-window)
+ (select-window org-agenda-show-window)
+ (ignore-errors (scroll-down))
+ (select-window win))))
+
+(defun org-agenda-show-1 (&optional more)
+ "Display the Org file which contains the item at point.
+The prefix arg selects the amount of information to display:
+
+0 hide the subtree
+1 just show the entry according to defaults.
+2 show the children view
+3 show the subtree view
+4 show the entire subtree and any LOGBOOK drawers
+5 show the entire subtree and any drawers
+With prefix argument FULL-ENTRY, make the entire entry visible
+if it was hidden in the outline."
+ (interactive "p")
+ (let ((win (selected-window)))
+ (org-agenda-goto t)
+ (org-back-to-heading)
+ (set-window-start (selected-window) (point-at-bol))
+ (cond
+ ((= more 0)
+ (outline-hide-subtree)
+ (save-excursion
+ (org-back-to-heading)
+ (run-hook-with-args 'org-cycle-hook 'folded))
+ (message "Remote: FOLDED"))
+ ((and (called-interactively-p 'any) (= more 1))
+ (message "Remote: show with default settings"))
+ ((= more 2)
+ (outline-show-entry)
+ (org-show-children)
+ (save-excursion
+ (org-back-to-heading)
+ (run-hook-with-args 'org-cycle-hook 'children))
+ (message "Remote: CHILDREN"))
+ ((= more 3)
+ (outline-show-subtree)
+ (save-excursion
+ (org-back-to-heading)
+ (run-hook-with-args 'org-cycle-hook 'subtree))
+ (message "Remote: SUBTREE"))
+ ((= more 4)
+ (outline-show-subtree)
+ (save-excursion
+ (org-back-to-heading)
+ (org-cycle-hide-drawers 'subtree '("LOGBOOK")))
+ (message "Remote: SUBTREE AND LOGBOOK"))
+ ((> more 4)
+ (outline-show-subtree)
+ (message "Remote: SUBTREE AND ALL DRAWERS")))
+ (select-window win)))
+
+(defvar org-agenda-cycle-counter nil)
+(defun org-agenda-cycle-show (&optional n)
+ "Show the current entry in another window, with default settings.
+
+Default settings are taken from `org-show-context-detail'. When
+use repeatedly in immediate succession, the remote entry will
+cycle through visibility
+
+ children -> subtree -> folded
+
+When called with a numeric prefix arg, that arg will be passed through to
+`org-agenda-show-1'. For the interpretation of that argument, see the
+docstring of `org-agenda-show-1'."
+ (interactive "P")
+ (if (integerp n)
+ (setq org-agenda-cycle-counter n)
+ (if (not (eq last-command this-command))
+ (setq org-agenda-cycle-counter 1)
+ (if (equal org-agenda-cycle-counter 0)
+ (setq org-agenda-cycle-counter 2)
+ (setq org-agenda-cycle-counter (1+ org-agenda-cycle-counter))
+ (if (> org-agenda-cycle-counter 3)
+ (setq org-agenda-cycle-counter 0)))))
+ (org-agenda-show-1 org-agenda-cycle-counter))
+
+(defun org-agenda-recenter (arg)
+ "Display the Org file which contains the item at point and recenter."
+ (interactive "P")
+ (let ((win (selected-window)))
+ (org-agenda-goto t)
+ (recenter arg)
+ (select-window win)))
+
+(defun org-agenda-show-mouse (ev)
+ "Display the Org file which contains the item at the mouse click."
+ (interactive "e")
+ (mouse-set-point ev)
+ (org-agenda-show))
+
+(defun org-agenda-check-no-diary ()
+ "Check if the entry is a diary link and abort if yes."
+ (if (org-get-at-bol 'org-agenda-diary-link)
+ (org-agenda-error)))
+
+(defun org-agenda-error ()
+ "Throw an error when a command is not allowed in the agenda."
+ (user-error "Command not allowed in this line"))
+
+(defun org-agenda-tree-to-indirect-buffer (arg)
+ "Show the subtree corresponding to the current entry in an indirect buffer.
+This calls the command `org-tree-to-indirect-buffer' from the original buffer.
+
+With a numerical prefix ARG, go up to this level and then take that tree.
+With a negative numeric ARG, go up by this number of levels.
+
+With a `\\[universal-argument]' prefix, make a separate frame for this tree, \
+i.e. don't use
+the dedicated frame."
+ (interactive "P")
+ (if current-prefix-arg
+ (org-agenda-do-tree-to-indirect-buffer arg)
+ (let ((agenda-buffer (buffer-name))
+ (agenda-window (selected-window))
+ (indirect-window
+ (and org-last-indirect-buffer
+ (get-buffer-window org-last-indirect-buffer))))
+ (save-window-excursion (org-agenda-do-tree-to-indirect-buffer arg))
+ (unless (or (eq org-indirect-buffer-display 'new-frame)
+ (eq org-indirect-buffer-display 'dedicated-frame))
+ (unwind-protect
+ (unless (and indirect-window (window-live-p indirect-window))
+ (setq indirect-window (split-window agenda-window)))
+ (and indirect-window (select-window indirect-window))
+ (switch-to-buffer org-last-indirect-buffer :norecord)
+ (fit-window-to-buffer indirect-window)))
+ (select-window (get-buffer-window agenda-buffer))
+ (setq org-agenda-last-indirect-buffer org-last-indirect-buffer))))
+
+(defun org-agenda-do-tree-to-indirect-buffer (arg)
+ "Same as `org-agenda-tree-to-indirect-buffer' without saving window."
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker)))
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char pos)
+ (funcall 'org-tree-to-indirect-buffer arg)))))
+
+(defvar org-last-heading-marker (make-marker)
+ "Marker pointing to the headline that last changed its TODO state
+by a remote command from the agenda.")
+
+(defun org-agenda-todo-nextset ()
+ "Switch TODO entry to next sequence."
+ (interactive)
+ (org-agenda-todo 'nextset))
+
+(defun org-agenda-todo-previousset ()
+ "Switch TODO entry to previous sequence."
+ (interactive)
+ (org-agenda-todo 'previousset))
+
+(defun org-agenda-todo (&optional arg)
+ "Cycle TODO state of line at point, also in Org file.
+This changes the line at point, all other lines in the agenda referring to
+the same tree node, and the headline of the tree node in the Org file."
+ (interactive "P")
+ (org-agenda-check-no-diary)
+ (let* ((col (current-column))
+ (marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ (hdmarker (org-get-at-bol 'org-hd-marker))
+ (todayp (org-agenda-today-p (org-get-at-bol 'day)))
+ (inhibit-read-only t)
+ org-agenda-headline-snapshot-before-repeat newhead just-one)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (let ((current-prefix-arg arg))
+ (call-interactively 'org-todo))
+ (and (bolp) (forward-char 1))
+ (setq newhead (org-get-heading))
+ (when (and (bound-and-true-p
+ org-agenda-headline-snapshot-before-repeat)
+ (not (equal org-agenda-headline-snapshot-before-repeat
+ newhead))
+ todayp)
+ (setq newhead org-agenda-headline-snapshot-before-repeat
+ just-one t))
+ (save-excursion
+ (org-back-to-heading)
+ (move-marker org-last-heading-marker (point))))
+ (beginning-of-line 1)
+ (save-window-excursion
+ (org-agenda-change-all-lines newhead hdmarker 'fixface just-one))
+ (when (bound-and-true-p org-clock-out-when-done)
+ (string-match (concat "^" (regexp-opt org-done-keywords-for-agenda))
+ newhead)
+ (org-agenda-unmark-clocking-task))
+ (org-move-to-column col)
+ (org-agenda-mark-clocking-task))))
+
+(defun org-agenda-add-note (&optional arg)
+ "Add a time-stamped note to the entry at point."
+ (interactive "P")
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ (hdmarker (org-get-at-bol 'org-hd-marker))
+ (inhibit-read-only t))
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (org-add-note))))
+
+(defun org-agenda-change-all-lines (newhead hdmarker
+ &optional fixface just-this)
+ "Change all lines in the agenda buffer which match HDMARKER.
+The new content of the line will be NEWHEAD (as modified by
+`org-agenda-format-item'). HDMARKER is checked with
+`equal' against all `org-hd-marker' text properties in the file.
+If FIXFACE is non-nil, the face of each item is modified according to
+the new TODO state.
+If JUST-THIS is non-nil, change just the current line, not all.
+If FORCE-TAGS is non nil, the car of it returns the new tags."
+ (let* ((inhibit-read-only t)
+ (line (org-current-line))
+ (org-agenda-buffer (current-buffer))
+ (thetags (with-current-buffer (marker-buffer hdmarker)
+ (org-with-wide-buffer
+ (goto-char hdmarker)
+ (org-get-tags-at))))
+ props m pl undone-face done-face finish new dotime level cat tags)
+ (save-excursion
+ (goto-char (point-max))
+ (beginning-of-line 1)
+ (while (not finish)
+ (setq finish (bobp))
+ (when (and (setq m (org-get-at-bol 'org-hd-marker))
+ (or (not just-this) (= (org-current-line) line))
+ (equal m hdmarker))
+ (setq props (text-properties-at (point))
+ dotime (org-get-at-bol 'dotime)
+ cat (org-get-at-eol 'org-category 1)
+ level (org-get-at-bol 'level)
+ tags thetags
+ new
+ (let ((org-prefix-format-compiled
+ (or (get-text-property (min (1- (point-max)) (point)) 'format)
+ org-prefix-format-compiled))
+ (extra (org-get-at-bol 'extra)))
+ (with-current-buffer (marker-buffer hdmarker)
+ (org-with-wide-buffer
+ (org-agenda-format-item extra newhead level cat tags dotime))))
+ pl (text-property-any (point-at-bol) (point-at-eol) 'org-heading t)
+ undone-face (org-get-at-bol 'undone-face)
+ done-face (org-get-at-bol 'done-face))
+ (beginning-of-line 1)
+ (cond
+ ((equal new "") (delete-region (point) (line-beginning-position 2)))
+ ((looking-at ".*")
+ ;; When replacing the whole line, preserve bulk mark
+ ;; overlay, if any.
+ (let ((mark (catch :overlay
+ (dolist (o (overlays-in (point) (+ 2 (point))))
+ (when (eq (overlay-get o 'type)
+ 'org-marked-entry-overlay)
+ (throw :overlay o))))))
+ (replace-match new t t)
+ (beginning-of-line)
+ (when mark (move-overlay mark (point) (+ 2 (point)))))
+ (add-text-properties (point-at-bol) (point-at-eol) props)
+ (when fixface
+ (add-text-properties
+ (point-at-bol) (point-at-eol)
+ (list 'face
+ (if org-last-todo-state-is-todo
+ undone-face done-face))))
+ (org-agenda-highlight-todo 'line)
+ (beginning-of-line 1))
+ (t (error "Line update did not work")))
+ (save-restriction
+ (narrow-to-region (point-at-bol) (point-at-eol))
+ (org-agenda-finalize)))
+ (beginning-of-line 0)))))
+
+(defun org-agenda-align-tags (&optional line)
+ "Align all tags in agenda items to `org-agenda-tags-column'."
+ (let ((inhibit-read-only t) l c)
+ (save-excursion
+ (goto-char (if line (point-at-bol) (point-min)))
+ (while (re-search-forward "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
+ (if line (point-at-eol) nil) t)
+ (add-text-properties
+ (match-beginning 2) (match-end 2)
+ (list 'face (delq nil (let ((prop (get-text-property
+ (match-beginning 2) 'face)))
+ (or (listp prop) (setq prop (list prop)))
+ (if (memq 'org-tag prop)
+ prop
+ (cons 'org-tag prop))))))
+ (setq l (- (match-end 2) (match-beginning 2))
+ c (if (< org-agenda-tags-column 0)
+ (- (abs org-agenda-tags-column) l)
+ org-agenda-tags-column))
+ (delete-region (match-beginning 1) (match-end 1))
+ (goto-char (match-beginning 1))
+ (insert (org-add-props
+ (make-string (max 1 (- c (current-column))) ?\ )
+ (plist-put (copy-sequence (text-properties-at (point)))
+ 'face nil))))
+ (goto-char (point-min))
+ (org-font-lock-add-tag-faces (point-max)))))
+
+(defun org-agenda-priority-up ()
+ "Increase the priority of line at point, also in Org file."
+ (interactive)
+ (org-agenda-priority 'up))
+
+(defun org-agenda-priority-down ()
+ "Decrease the priority of line at point, also in Org file."
+ (interactive)
+ (org-agenda-priority 'down))
+
+(defun org-agenda-priority (&optional force-direction)
+ "Set the priority of line at point, also in Org file.
+This changes the line at point, all other lines in the agenda referring to
+the same tree node, and the headline of the tree node in the Org file.
+Called with a universal prefix arg, show the priority instead of setting it."
+ (interactive "P")
+ (if (equal force-direction '(4))
+ (org-show-priority)
+ (unless org-enable-priority-commands
+ (error "Priority commands are disabled"))
+ (org-agenda-check-no-diary)
+ (let* ((col (current-column))
+ (marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (hdmarker (org-get-at-bol 'org-hd-marker))
+ (buffer (marker-buffer hdmarker))
+ (pos (marker-position hdmarker))
+ (inhibit-read-only t)
+ newhead)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (funcall 'org-priority force-direction)
+ (end-of-line 1)
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead hdmarker)
+ (org-move-to-column col)))))
+
+;; FIXME: should fix the tags property of the agenda line.
+(defun org-agenda-set-tags (&optional tag onoff)
+ "Set tags for the current headline."
+ (interactive)
+ (org-agenda-check-no-diary)
+ (if (and (org-region-active-p) (called-interactively-p 'any))
+ (call-interactively 'org-change-tag-in-region)
+ (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer hdmarker))
+ (pos (marker-position hdmarker))
+ (inhibit-read-only t)
+ newhead)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (if tag
+ (org-toggle-tag tag onoff)
+ (call-interactively 'org-set-tags))
+ (end-of-line 1)
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead hdmarker)
+ (beginning-of-line 1)))))
+
+(defun org-agenda-set-property ()
+ "Set a property for the current headline."
+ (interactive)
+ (org-agenda-check-no-diary)
+ (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer hdmarker))
+ (pos (marker-position hdmarker))
+ (inhibit-read-only t)
+ newhead)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (call-interactively 'org-set-property)))))
+
+(defun org-agenda-set-effort ()
+ "Set the effort property for the current headline."
+ (interactive)
+ (org-agenda-check-no-diary)
+ (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer hdmarker))
+ (pos (marker-position hdmarker))
+ (inhibit-read-only t)
+ newhead)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (call-interactively 'org-set-effort)
+ (end-of-line 1)
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead hdmarker))))
+
+(defun org-agenda-toggle-archive-tag ()
+ "Toggle the archive tag for the current entry."
+ (interactive)
+ (org-agenda-check-no-diary)
+ (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer hdmarker))
+ (pos (marker-position hdmarker))
+ (inhibit-read-only t)
+ newhead)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (call-interactively 'org-toggle-archive-tag)
+ (end-of-line 1)
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead hdmarker)
+ (beginning-of-line 1))))
+
+(defun org-agenda-do-date-later (arg)
+ (interactive "P")
+ (cond
+ ((or (equal arg '(16))
+ (memq last-command
+ '(org-agenda-date-later-minutes org-agenda-date-earlier-minutes)))
+ (setq this-command 'org-agenda-date-later-minutes)
+ (org-agenda-date-later-minutes 1))
+ ((or (equal arg '(4))
+ (memq last-command
+ '(org-agenda-date-later-hours org-agenda-date-earlier-hours)))
+ (setq this-command 'org-agenda-date-later-hours)
+ (org-agenda-date-later-hours 1))
+ (t
+ (org-agenda-date-later (prefix-numeric-value arg)))))
+
+(defun org-agenda-do-date-earlier (arg)
+ (interactive "P")
+ (cond
+ ((or (equal arg '(16))
+ (memq last-command
+ '(org-agenda-date-later-minutes org-agenda-date-earlier-minutes)))
+ (setq this-command 'org-agenda-date-earlier-minutes)
+ (org-agenda-date-earlier-minutes 1))
+ ((or (equal arg '(4))
+ (memq last-command
+ '(org-agenda-date-later-hours org-agenda-date-earlier-hours)))
+ (setq this-command 'org-agenda-date-earlier-hours)
+ (org-agenda-date-earlier-hours 1))
+ (t
+ (org-agenda-date-earlier (prefix-numeric-value arg)))))
+
+(defun org-agenda-date-later (arg &optional what)
+ "Change the date of this item to ARG day(s) later."
+ (interactive "p")
+ (org-agenda-check-type t 'agenda 'timeline)
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ cdate today)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (if (not (org-at-timestamp-p))
+ (error "Cannot find time stamp"))
+ (when (and org-agenda-move-date-from-past-immediately-to-today
+ (equal arg 1)
+ (or (not what) (eq what 'day))
+ (not (save-match-data (org-at-date-range-p))))
+ (setq cdate (org-parse-time-string (match-string 0) 'nodefault)
+ cdate (calendar-absolute-from-gregorian
+ (list (nth 4 cdate) (nth 3 cdate) (nth 5 cdate)))
+ today (org-today))
+ (if (> today cdate)
+ ;; immediately shift to today
+ (setq arg (- today cdate))))
+ (org-timestamp-change arg (or what 'day))
+ (when (and (org-at-date-range-p)
+ (re-search-backward org-tr-regexp-both (point-at-bol)))
+ (let ((end org-last-changed-timestamp))
+ (org-timestamp-change arg (or what 'day))
+ (setq org-last-changed-timestamp
+ (concat org-last-changed-timestamp "--" end)))))
+ (org-agenda-show-new-time marker org-last-changed-timestamp))
+ (message "Time stamp changed to %s" org-last-changed-timestamp)))
+
+(defun org-agenda-date-earlier (arg &optional what)
+ "Change the date of this item to ARG day(s) earlier."
+ (interactive "p")
+ (org-agenda-date-later (- arg) what))
+
+(defun org-agenda-date-later-minutes (arg)
+ "Change the time of this item, in units of `org-time-stamp-rounding-minutes'."
+ (interactive "p")
+ (setq arg (* arg (cadr org-time-stamp-rounding-minutes)))
+ (org-agenda-date-later arg 'minute))
+
+(defun org-agenda-date-earlier-minutes (arg)
+ "Change the time of this item, in units of `org-time-stamp-rounding-minutes'."
+ (interactive "p")
+ (setq arg (* arg (cadr org-time-stamp-rounding-minutes)))
+ (org-agenda-date-earlier arg 'minute))
+
+(defun org-agenda-date-later-hours (arg)
+ "Change the time of this item, in hour steps."
+ (interactive "p")
+ (org-agenda-date-later arg 'hour))
+
+(defun org-agenda-date-earlier-hours (arg)
+ "Change the time of this item, in hour steps."
+ (interactive "p")
+ (org-agenda-date-earlier arg 'hour))
+
+(defun org-agenda-show-new-time (marker stamp &optional prefix)
+ "Show new date stamp via text properties."
+ ;; We use text properties to make this undoable
+ (let ((inhibit-read-only t))
+ (setq stamp (concat prefix " => " stamp " "))
+ (save-excursion
+ (goto-char (point-max))
+ (while (not (bobp))
+ (when (equal marker (org-get-at-bol 'org-marker))
+ (remove-text-properties (point-at-bol) (point-at-eol) '(display))
+ (org-move-to-column (- (window-width) (length stamp)) t)
+ (add-text-properties
+ (1- (point)) (point-at-eol)
+ (list 'display (org-add-props stamp nil
+ 'face '(secondary-selection default))))
+ (beginning-of-line 1))
+ (beginning-of-line 0)))))
+
+(defun org-agenda-date-prompt (arg)
+ "Change the date of this item. Date is prompted for, with default today.
+The prefix ARG is passed to the `org-time-stamp' command and can therefore
+be used to request time specification in the time stamp."
+ (interactive "P")
+ (org-agenda-check-type t 'agenda 'timeline)
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker)))
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (if (not (org-at-timestamp-p t))
+ (error "Cannot find time stamp"))
+ (org-time-stamp arg (equal (char-after (match-beginning 0)) ?\[)))
+ (org-agenda-show-new-time marker org-last-changed-timestamp))
+ (message "Time stamp changed to %s" org-last-changed-timestamp)))
+
+(defun org-agenda-schedule (arg &optional time)
+ "Schedule the item at point.
+ARG is passed through to `org-schedule'."
+ (interactive "P")
+ (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (type (marker-insertion-type marker))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ ts)
+ (set-marker-insertion-type marker t)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (setq ts (org-schedule arg time)))
+ (org-agenda-show-new-time marker ts " S"))
+ (message "%s" ts)))
+
+(defun org-agenda-deadline (arg &optional time)
+ "Schedule the item at point.
+ARG is passed through to `org-deadline'."
+ (interactive "P")
+ (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
+ (org-agenda-check-no-diary)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ ts)
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (setq ts (org-deadline arg time)))
+ (org-agenda-show-new-time marker ts " D"))
+ (message "%s" ts)))
+
+(defun org-agenda-clock-in (&optional arg)
+ "Start the clock on the currently selected item."
+ (interactive "P")
+ (org-agenda-check-no-diary)
+ (if (equal arg '(4))
+ (org-clock-in arg)
+ (let* ((marker (or (org-get-at-bol 'org-marker)
+ (org-agenda-error)))
+ (hdmarker (or (org-get-at-bol 'org-hd-marker) marker))
+ (pos (marker-position marker))
+ (col (current-column))
+ newhead)
+ (org-with-remote-undo (marker-buffer marker)
+ (with-current-buffer (marker-buffer marker)
+ (widen)
+ (goto-char pos)
+ (org-show-context 'agenda)
+ (org-cycle-hide-drawers 'children)
+ (org-clock-in arg)
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead hdmarker))
+ (org-move-to-column col))))
+
+(defun org-agenda-clock-out ()
+ "Stop the currently running clock."
+ (interactive)
+ (unless (marker-buffer org-clock-marker)
+ (error "No running clock"))
+ (let ((marker (make-marker)) (col (current-column)) newhead)
+ (org-with-remote-undo (marker-buffer org-clock-marker)
+ (with-current-buffer (marker-buffer org-clock-marker)
+ (org-with-wide-buffer
+ (goto-char org-clock-marker)
+ (org-back-to-heading t)
+ (move-marker marker (point))
+ (org-clock-out)
+ (setq newhead (org-get-heading)))))
+ (org-agenda-change-all-lines newhead marker)
+ (move-marker marker nil)
+ (org-move-to-column col)
+ (org-agenda-unmark-clocking-task)))
+
+(defun org-agenda-clock-cancel (&optional arg)
+ "Cancel the currently running clock."
+ (interactive "P")
+ (unless (marker-buffer org-clock-marker)
+ (user-error "No running clock"))
+ (org-with-remote-undo (marker-buffer org-clock-marker)
+ (org-clock-cancel)))
+
+(defun org-agenda-clock-goto ()
+ "Jump to the currently clocked in task within the agenda.
+If the currently clocked in task is not listed in the agenda
+buffer, display it in another window."
+ (interactive)
+ (let (pos)
+ (mapc (lambda (o)
+ (if (eq (overlay-get o 'type) 'org-agenda-clocking)
+ (setq pos (overlay-start o))))
+ (overlays-in (point-min) (point-max)))
+ (cond (pos (goto-char pos))
+ ;; If the currently clocked entry is not in the agenda
+ ;; buffer, we visit it in another window:
+ ((bound-and-true-p org-clock-current-task)
+ (org-switch-to-buffer-other-window (org-clock-goto)))
+ (t (message "No running clock, use `C-c C-x C-j' to jump to the most recent one")))))
+
+(defun org-agenda-diary-entry-in-org-file ()
+ "Make a diary entry in the file `org-agenda-diary-file'."
+ (let (d1 d2 char (text "") dp1 dp2)
+ (if (equal (buffer-name) "*Calendar*")
+ (setq d1 (calendar-cursor-to-date t)
+ d2 (car calendar-mark-ring))
+ (setq dp1 (get-text-property (point-at-bol) 'day))
+ (unless dp1 (user-error "No date defined in current line"))
+ (setq d1 (calendar-gregorian-from-absolute dp1)
+ d2 (and (ignore-errors (mark))
+ (save-excursion
+ (goto-char (mark))
+ (setq dp2 (get-text-property (point-at-bol) 'day)))
+ (calendar-gregorian-from-absolute dp2))))
+ (message "Diary entry: [d]ay [a]nniversary [b]lock [j]ump to date tree")
+ (setq char (read-char-exclusive))
+ (cond
+ ((equal char ?d)
+ (setq text (read-string "Day entry: "))
+ (org-agenda-add-entry-to-org-agenda-diary-file 'day text d1)
+ (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo)))
+ ((equal char ?a)
+ (setq d1 (list (car d1) (nth 1 d1)
+ (read-number (format "Reference year [%d]: " (nth 2 d1))
+ (nth 2 d1))))
+ (setq text (read-string "Anniversary (use %d to show years): "))
+ (org-agenda-add-entry-to-org-agenda-diary-file 'anniversary text d1)
+ (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo)))
+ ((equal char ?b)
+ (setq text (read-string "Block entry: "))
+ (unless (and d1 d2 (not (equal d1 d2)))
+ (user-error "No block of days selected"))
+ (org-agenda-add-entry-to-org-agenda-diary-file 'block text d1 d2)
+ (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo)))
+ ((equal char ?j)
+ (org-switch-to-buffer-other-window
+ (find-file-noselect org-agenda-diary-file))
+ (require 'org-datetree)
+ (org-datetree-find-date-create d1)
+ (org-reveal t))
+ (t (user-error "Invalid selection character `%c'" char)))))
+
+(defcustom org-agenda-insert-diary-strategy 'date-tree
+ "Where in `org-agenda-diary-file' should new entries be added?
+Valid values:
+
+date-tree in the date tree, as first child of the date
+date-tree-last in the date tree, as last child of the date
+top-level as top-level entries at the end of the file."
+ :group 'org-agenda
+ :type '(choice
+ (const :tag "first in a date tree" date-tree)
+ (const :tag "last in a date tree" date-tree-last)
+ (const :tag "as top level at end of file" top-level)))
+
+(defcustom org-agenda-insert-diary-extract-time nil
+ "Non-nil means extract any time specification from the diary entry."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-agenda-bulk-mark-char ">"
+ "A single-character string to be used as the bulk mark."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'string)
+
+(defun org-agenda-add-entry-to-org-agenda-diary-file (type text &optional d1 d2)
+ "Add a diary entry with TYPE to `org-agenda-diary-file'.
+If TEXT is not empty, it will become the headline of the new entry, and
+the resulting entry will not be shown. When TEXT is empty, switch to
+`org-agenda-diary-file' and let the user finish the entry there."
+ (let ((cw (current-window-configuration)))
+ (org-switch-to-buffer-other-window
+ (find-file-noselect org-agenda-diary-file))
+ (widen)
+ (goto-char (point-min))
+ (cond
+ ((eq type 'anniversary)
+ (or (re-search-forward "^*[ \t]+Anniversaries" nil t)
+ (progn
+ (or (org-at-heading-p t)
+ (progn
+ (outline-next-heading)
+ (insert "* Anniversaries\n\n")
+ (beginning-of-line -1)))))
+ (outline-next-heading)
+ (org-back-over-empty-lines)
+ (backward-char 1)
+ (insert "\n")
+ (insert (format "%%%%(org-anniversary %d %2d %2d) %s"
+ (nth 2 d1) (car d1) (nth 1 d1) text)))
+ ((eq type 'day)
+ (let ((org-prefix-has-time t)
+ (org-agenda-time-leading-zero t)
+ fmt time time2)
+ (if org-agenda-insert-diary-extract-time
+ ;; Use org-agenda-format-item to parse text for a time-range and
+ ;; remove it. FIXME: This is a hack, we should refactor
+ ;; that function to make time extraction available separately
+ (setq fmt (org-agenda-format-item nil text nil nil nil t)
+ time (get-text-property 0 'time fmt)
+ time2 (if (> (length time) 0)
+ ;; split-string removes trailing ...... if
+ ;; no end time given. First space
+ ;; separates time from date.
+ (concat " " (car (split-string time "\\.")))
+ nil)
+ text (get-text-property 0 'txt fmt)))
+ (if (eq org-agenda-insert-diary-strategy 'top-level)
+ (org-agenda-insert-diary-as-top-level text)
+ (require 'org-datetree)
+ (org-datetree-find-date-create d1)
+ (org-agenda-insert-diary-make-new-entry text))
+ (org-insert-time-stamp (org-time-from-absolute
+ (calendar-absolute-from-gregorian d1))
+ nil nil nil nil time2))
+ (end-of-line 0))
+ ((eq type 'block)
+ (if (> (calendar-absolute-from-gregorian d1)
+ (calendar-absolute-from-gregorian d2))
+ (setq d1 (prog1 d2 (setq d2 d1))))
+ (if (eq org-agenda-insert-diary-strategy 'top-level)
+ (org-agenda-insert-diary-as-top-level text)
+ (require 'org-datetree)
+ (org-datetree-find-date-create d1)
+ (org-agenda-insert-diary-make-new-entry text))
+ (org-insert-time-stamp (org-time-from-absolute
+ (calendar-absolute-from-gregorian d1)))
+ (insert "--")
+ (org-insert-time-stamp (org-time-from-absolute
+ (calendar-absolute-from-gregorian d2)))
+ (end-of-line 0)))
+ (if (string-match "\\S-" text)
+ (progn
+ (set-window-configuration cw)
+ (message "%s entry added to %s"
+ (capitalize (symbol-name type))
+ (abbreviate-file-name org-agenda-diary-file)))
+ (org-reveal t)
+ (message "Please finish entry here"))))
+
+(defun org-agenda-insert-diary-as-top-level (text)
+ "Make new entry as a top-level entry at the end of the file.
+Add TEXT as headline, and position the cursor in the second line so that
+a timestamp can be added there."
+ (widen)
+ (goto-char (point-max))
+ (unless (bolp) (insert "\n"))
+ (org-insert-heading nil t t)
+ (insert text)
+ (org-end-of-meta-data)
+ (unless (bolp) (insert "\n"))
+ (when org-adapt-indentation (indent-to-column 2)))
+
+(defun org-agenda-insert-diary-make-new-entry (text)
+ "Make a new entry with TEXT as a child of the current subtree.
+Position the point in the heading's first body line so that
+a timestamp can be added there."
+ (cond
+ ((eq org-agenda-insert-diary-strategy 'date-tree-last)
+ (end-of-line)
+ (org-insert-heading '(4) t)
+ (org-do-demote))
+ (t
+ (outline-next-heading)
+ (org-back-over-empty-lines)
+ (unless (looking-at "[ \t]*$") (save-excursion (insert "\n")))
+ (org-insert-heading nil t)
+ (org-do-demote)))
+ (let ((col (current-column)))
+ (insert text)
+ (org-end-of-meta-data)
+ ;; Ensure point is left on a blank line, at proper indentation.
+ (unless (bolp) (insert "\n"))
+ (unless (looking-at-p "^[ \t]*$") (save-excursion (insert "\n")))
+ (when org-adapt-indentation (indent-to-column col)))
+ (org-show-set-visibility 'lineage))
+
+(defun org-agenda-diary-entry ()
+ "Make a diary entry, like the `i' command from the calendar.
+All the standard commands work: block, weekly etc.
+When `org-agenda-diary-file' points to a file,
+`org-agenda-diary-entry-in-org-file' is called instead to create
+entries in that Org file."
+ (interactive)
+ (if (not (eq org-agenda-diary-file 'diary-file))
+ (org-agenda-diary-entry-in-org-file)
+ (require 'diary-lib)
+ (let* ((char (progn
+ (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
+ (read-char-exclusive)))
+ (cmd (cdr (assoc char
+ '((?d . diary-insert-entry)
+ (?w . diary-insert-weekly-entry)
+ (?m . diary-insert-monthly-entry)
+ (?y . diary-insert-yearly-entry)
+ (?a . diary-insert-anniversary-entry)
+ (?b . diary-insert-block-entry)
+ (?c . diary-insert-cyclic-entry)))))
+ (oldf (symbol-function 'calendar-cursor-to-date))
+ ;; (buf (get-file-buffer (substitute-in-file-name diary-file)))
+ (point (point))
+ (mark (or (mark t) (point))))
+ (unless cmd
+ (user-error "No command associated with <%c>" char))
+ (unless (and (get-text-property point 'day)
+ (or (not (equal ?b char))
+ (get-text-property mark 'day)))
+ (user-error "Don't know which date to use for diary entry"))
+ ;; We implement this by hacking the `calendar-cursor-to-date' function
+ ;; and the `calendar-mark-ring' variable. Saves a lot of code.
+ (let ((calendar-mark-ring
+ (list (calendar-gregorian-from-absolute
+ (or (get-text-property mark 'day)
+ (get-text-property point 'day))))))
+ (unwind-protect
+ (progn
+ (fset 'calendar-cursor-to-date
+ (lambda (&optional error dummy)
+ (calendar-gregorian-from-absolute
+ (get-text-property point 'day))))
+ (call-interactively cmd))
+ (fset 'calendar-cursor-to-date oldf))))))
+
+(defun org-agenda-execute-calendar-command (cmd)
+ "Execute a calendar command from the agenda with date from cursor."
+ (org-agenda-check-type t 'agenda 'timeline)
+ (require 'diary-lib)
+ (unless (get-text-property (min (1- (point-max)) (point)) 'day)
+ (user-error "Don't know which date to use for the calendar command"))
+ (let* ((oldf (symbol-function 'calendar-cursor-to-date))
+ (point (point))
+ (date (calendar-gregorian-from-absolute
+ (get-text-property point 'day)))
+ ;; the following 2 vars are needed in the calendar
+ (displayed-month (car date))
+ (displayed-year (nth 2 date)))
+ (unwind-protect
+ (progn
+ (fset 'calendar-cursor-to-date
+ (lambda (&optional error dummy)
+ (calendar-gregorian-from-absolute
+ (get-text-property point 'day))))
+ (call-interactively cmd))
+ (fset 'calendar-cursor-to-date oldf))))
+
+(defun org-agenda-phases-of-moon ()
+ "Display the phases of the moon for the 3 months around the cursor date."
+ (interactive)
+ (org-agenda-execute-calendar-command 'calendar-lunar-phases))
+
+(defun org-agenda-holidays ()
+ "Display the holidays for the 3 months around the cursor date."
+ (interactive)
+ (org-agenda-execute-calendar-command 'calendar-list-holidays))
+
+(defvar calendar-longitude) ; defined in calendar.el
+(defvar calendar-latitude) ; defined in calendar.el
+(defvar calendar-location-name) ; defined in calendar.el
+
+(defun org-agenda-sunrise-sunset (arg)
+ "Display sunrise and sunset for the cursor date.
+Latitude and longitude can be specified with the variables
+`calendar-latitude' and `calendar-longitude'. When called with prefix
+argument, latitude and longitude will be prompted for."
+ (interactive "P")
+ (require 'solar)
+ (let ((calendar-longitude (if arg nil calendar-longitude))
+ (calendar-latitude (if arg nil calendar-latitude))
+ (calendar-location-name
+ (if arg "the given coordinates" calendar-location-name)))
+ (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
+
+(defun org-agenda-goto-calendar ()
+ "Open the Emacs calendar with the date at the cursor."
+ (interactive)
+ (org-agenda-check-type t 'agenda 'timeline)
+ (let* ((day (or (get-text-property (min (1- (point-max)) (point)) 'day)
+ (user-error "Don't know which date to open in calendar")))
+ (date (calendar-gregorian-from-absolute day))
+ (calendar-move-hook nil)
+ (calendar-view-holidays-initially-flag nil)
+ (calendar-view-diary-initially-flag nil))
+ (calendar)
+ (calendar-goto-date date)))
+
+;;;###autoload
+(defun org-calendar-goto-agenda ()
+ "Compute the Org agenda for the calendar date displayed at the cursor.
+This is a command that has to be installed in `calendar-mode-map'."
+ (interactive)
+ ;; Temporarily disable sticky agenda since user clearly wants to
+ ;; refresh view anyway.
+ (let ((org-agenda-buffer-tmp-name "*Org Agenda(a)*")
+ (org-agenda-sticky nil))
+ (org-agenda-list nil (calendar-absolute-from-gregorian
+ (calendar-cursor-to-date))
+ nil)))
+
+(defun org-agenda-convert-date ()
+ (interactive)
+ (org-agenda-check-type t 'agenda 'timeline)
+ (let ((day (get-text-property (min (1- (point-max)) (point)) 'day))
+ date s)
+ (unless day
+ (user-error "Don't know which date to convert"))
+ (setq date (calendar-gregorian-from-absolute day))
+ (setq s (concat
+ "Gregorian: " (calendar-date-string date) "\n"
+ "ISO: " (calendar-iso-date-string date) "\n"
+ "Day of Yr: " (calendar-day-of-year-string date) "\n"
+ "Julian: " (calendar-julian-date-string date) "\n"
+ "Astron. JD: " (calendar-astro-date-string date)
+ " (Julian date number at noon UTC)\n"
+ "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
+ "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
+ "French: " (calendar-french-date-string date) "\n"
+ "Bahá’í: " (calendar-bahai-date-string date) " (until sunset)\n"
+ "Mayan: " (calendar-mayan-date-string date) "\n"
+ "Coptic: " (calendar-coptic-date-string date) "\n"
+ "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
+ "Persian: " (calendar-persian-date-string date) "\n"
+ "Chinese: " (calendar-chinese-date-string date) "\n"))
+ (with-output-to-temp-buffer "*Dates*"
+ (princ s))
+ (org-fit-window-to-buffer (get-buffer-window "*Dates*"))))
+
+;;; Bulk commands
+
+(defun org-agenda-bulk-marked-p ()
+ "Non-nil when current entry is marked for bulk action."
+ (eq (get-char-property (point-at-bol) 'type)
+ 'org-marked-entry-overlay))
+
+(defun org-agenda-bulk-mark (&optional arg)
+ "Mark the entry at point for future bulk action."
+ (interactive "p")
+ (dotimes (i (or arg 1))
+ (unless (org-get-at-bol 'org-agenda-diary-link)
+ (let* ((m (org-get-at-bol 'org-hd-marker))
+ ov)
+ (unless (org-agenda-bulk-marked-p)
+ (unless m (user-error "Nothing to mark at point"))
+ (push m org-agenda-bulk-marked-entries)
+ (setq ov (make-overlay (point-at-bol) (+ 2 (point-at-bol))))
+ (org-overlay-display ov (concat org-agenda-bulk-mark-char " ")
+ (org-get-todo-face "TODO")
+ 'evaporate)
+ (overlay-put ov 'type 'org-marked-entry-overlay))
+ (end-of-line 1)
+ (or (ignore-errors
+ (goto-char (next-single-property-change (point) 'org-hd-marker)))
+ (beginning-of-line 2))
+ (while (and (get-char-property (point) 'invisible) (not (eobp)))
+ (beginning-of-line 2))
+ (message "%d entries marked for bulk action"
+ (length org-agenda-bulk-marked-entries))))))
+
+(defun org-agenda-bulk-mark-all ()
+ "Mark all entries for future agenda bulk action."
+ (interactive)
+ (org-agenda-bulk-mark-regexp "."))
+
+(defun org-agenda-bulk-mark-regexp (regexp)
+ "Mark entries matching REGEXP for future agenda bulk action."
+ (interactive "sMark entries matching regexp: ")
+ (let ((entries-marked 0) txt-at-point)
+ (save-excursion
+ (goto-char (point-min))
+ (goto-char (next-single-property-change (point) 'org-hd-marker))
+ (while (and (re-search-forward regexp nil t)
+ (setq txt-at-point (get-text-property (point) 'txt)))
+ (if (get-char-property (point) 'invisible)
+ (beginning-of-line 2)
+ (when (string-match regexp txt-at-point)
+ (setq entries-marked (1+ entries-marked))
+ (call-interactively 'org-agenda-bulk-mark)))))
+
+ (if (not entries-marked)
+ (message "No entry matching this regexp."))))
+
+(defun org-agenda-bulk-unmark (&optional arg)
+ "Unmark the entry at point for future bulk action."
+ (interactive "P")
+ (if arg
+ (org-agenda-bulk-unmark-all)
+ (cond ((org-agenda-bulk-marked-p)
+ (org-agenda-bulk-remove-overlays
+ (point-at-bol) (+ 2 (point-at-bol)))
+ (setq org-agenda-bulk-marked-entries
+ (delete (org-get-at-bol 'org-hd-marker)
+ org-agenda-bulk-marked-entries))
+ (end-of-line 1)
+ (or (ignore-errors
+ (goto-char (next-single-property-change (point) 'txt)))
+ (beginning-of-line 2))
+ (while (and (get-char-property (point) 'invisible) (not (eobp)))
+ (beginning-of-line 2))
+ (message "%d entries left marked for bulk action"
+ (length org-agenda-bulk-marked-entries)))
+ (t (message "No entry to unmark here")))))
+
+(defun org-agenda-bulk-toggle-all ()
+ "Toggle all marks for bulk action."
+ (interactive)
+ (save-excursion
+ (goto-char (point-min))
+ (while (ignore-errors
+ (goto-char (next-single-property-change (point) 'org-hd-marker)))
+ (org-agenda-bulk-toggle))))
+
+(defun org-agenda-bulk-toggle ()
+ "Toggle the mark at point for bulk action."
+ (interactive)
+ (if (org-agenda-bulk-marked-p)
+ (org-agenda-bulk-unmark)
+ (org-agenda-bulk-mark)))
+
+(defun org-agenda-bulk-remove-overlays (&optional beg end)
+ "Remove the mark overlays between BEG and END in the agenda buffer.
+BEG and END default to the buffer limits.
+
+This only removes the overlays, it does not remove the markers
+from the list in `org-agenda-bulk-marked-entries'."
+ (interactive)
+ (mapc (lambda (ov)
+ (and (eq (overlay-get ov 'type) 'org-marked-entry-overlay)
+ (delete-overlay ov)))
+ (overlays-in (or beg (point-min)) (or end (point-max)))))
+
+(defun org-agenda-bulk-unmark-all ()
+ "Remove all marks in the agenda buffer.
+This will remove the markers and the overlays."
+ (interactive)
+ (if (null org-agenda-bulk-marked-entries)
+ (message "No entry to unmark")
+ (setq org-agenda-bulk-marked-entries nil)
+ (org-agenda-bulk-remove-overlays (point-min) (point-max))))
+
+(defcustom org-agenda-persistent-marks nil
+ "Non-nil means marked items will stay marked after a bulk action.
+You can toggle this interactively by typing `p' when prompted for a
+bulk action."
+ :group 'org-agenda
+ :version "24.1"
+ :type 'boolean)
+
+(defun org-agenda-bulk-action (&optional arg)
+ "Execute an remote-editing action on all marked entries.
+The prefix arg is passed through to the command if possible."
+ (interactive "P")
+ ;; Make sure we have markers, and only valid ones
+ (unless org-agenda-bulk-marked-entries (user-error "No entries are marked"))
+ (mapc
+ (lambda (m)
+ (unless (and (markerp m)
+ (marker-buffer m)
+ (buffer-live-p (marker-buffer m))
+ (marker-position m))
+ (user-error "Marker %s for bulk command is invalid" m)))
+ org-agenda-bulk-marked-entries)
+
+ ;; Prompt for the bulk command
+ (let* ((msg (if org-agenda-persistent-marks "Bulk (persistent): " "Bulk: ")))
+ (message (concat msg "[$]arch [A]rch->sib [t]odo [+/-]tag [s]chd [d]eadline [r]efile "
+ "[S]catter [f]unction "
+ (when org-agenda-bulk-custom-functions
+ (concat " Custom: ["
+ (mapconcat (lambda(f) (char-to-string (car f)))
+ org-agenda-bulk-custom-functions "")
+ "]"))))
+ (catch 'exit
+ (let* ((action (read-char-exclusive))
+ (org-log-refile (if org-log-refile 'time nil))
+ (entries (reverse org-agenda-bulk-marked-entries))
+ (org-overriding-default-time
+ (if (get-text-property (point) 'org-agenda-date-header)
+ (org-get-cursor-date)))
+ redo-at-end
+ cmd rfloc state e tag pos (cnt 0) (cntskip 0))
+ (cond
+ ((equal action ?p)
+ (let ((org-agenda-persistent-marks
+ (not org-agenda-persistent-marks)))
+ (org-agenda-bulk-action)
+ (throw 'exit nil)))
+
+ ((equal action ?$)
+ (setq cmd '(org-agenda-archive)))
+
+ ((equal action ?A)
+ (setq cmd '(org-agenda-archive-to-archive-sibling)))
+
+ ((member action '(?r ?w))
+ (setq rfloc (org-refile-get-location
+ "Refile to"
+ (marker-buffer (car entries))
+ org-refile-allow-creating-parent-nodes))
+ (if (nth 3 rfloc)
+ (setcar (nthcdr 3 rfloc)
+ (move-marker (make-marker) (nth 3 rfloc)
+ (or (get-file-buffer (nth 1 rfloc))
+ (find-buffer-visiting (nth 1 rfloc))
+ (error "This should not happen")))))
+
+ (setq cmd (list 'org-agenda-refile nil (list 'quote rfloc) t)
+ redo-at-end t))
+
+ ((equal action ?t)
+ (setq state (completing-read
+ "Todo state: "
+ (with-current-buffer (marker-buffer (car entries))
+ (mapcar #'list org-todo-keywords-1))))
+ (setq cmd `(let ((org-inhibit-blocking t)
+ (org-inhibit-logging 'note))
+ (org-agenda-todo ,state))))
+
+ ((memq action '(?- ?+))
+ (setq tag (completing-read
+ (format "Tag to %s: " (if (eq action ?+) "add" "remove"))
+ (with-current-buffer (marker-buffer (car entries))
+ (delq nil
+ (mapcar (lambda (x) (and (stringp (car x)) x))
+ org-current-tag-alist)))))
+ (setq cmd `(org-agenda-set-tags ,tag ,(if (eq action ?+) ''on ''off))))
+
+ ((memq action '(?s ?d))
+ (let* ((time
+ (unless arg
+ (org-read-date
+ nil nil nil
+ (if (eq action ?s) "(Re)Schedule to" "(Re)Set Deadline to")
+ org-overriding-default-time)))
+ (c1 (if (eq action ?s) 'org-agenda-schedule
+ 'org-agenda-deadline)))
+ ;; Make sure to not prompt for a note when bulk
+ ;; rescheduling as Org cannot cope with simultaneous
+ ;; notes. Besides, it could be annoying depending on the
+ ;; number of items re-scheduled.
+ (setq cmd `(eval '(let ((org-log-reschedule
+ (and org-log-reschedule 'time))
+ (org-log-redeadline
+ (and org-log-redeadline 'time)))
+ (,c1 arg ,time))))))
+
+ ((equal action ?S)
+ (if (not (org-agenda-check-type nil 'agenda 'timeline 'todo))
+ (user-error "Can't scatter tasks in \"%s\" agenda view" org-agenda-type)
+ (let ((days (read-number
+ (format "Scatter tasks across how many %sdays: "
+ (if arg "week" "")) 7)))
+ (setq cmd
+ `(let ((distance (1+ (random ,days))))
+ (if arg
+ (let ((dist distance)
+ (day-of-week
+ (calendar-day-of-week
+ (calendar-gregorian-from-absolute (org-today)))))
+ (dotimes (i (1+ dist))
+ (while (member day-of-week org-agenda-weekend-days)
+ (cl-incf distance)
+ (cl-incf day-of-week)
+ (when (= day-of-week 7)
+ (setq day-of-week 0)))
+ (cl-incf day-of-week)
+ (when (= day-of-week 7)
+ (setq day-of-week 0)))))
+ ;; silently fail when try to replan a sexp entry
+ (condition-case nil
+ (let* ((date (calendar-gregorian-from-absolute
+ (+ (org-today) distance)))
+ (time (encode-time 0 0 0 (nth 1 date) (nth 0 date)
+ (nth 2 date))))
+ (org-agenda-schedule nil time))
+ (error nil)))))))
+
+ ((assoc action org-agenda-bulk-custom-functions)
+ (setq cmd (list (cadr (assoc action org-agenda-bulk-custom-functions)))
+ redo-at-end t))
+
+ ((equal action ?f)
+ (setq cmd (list (intern
+ (completing-read "Function: "
+ obarray 'fboundp t nil nil)))))
+
+ (t (user-error "Invalid bulk action")))
+
+ ;; Sort the markers, to make sure that parents are handled before children
+ (setq entries (sort entries
+ (lambda (a b)
+ (cond
+ ((equal (marker-buffer a) (marker-buffer b))
+ (< (marker-position a) (marker-position b)))
+ (t
+ (string< (buffer-name (marker-buffer a))
+ (buffer-name (marker-buffer b))))))))
+
+ ;; Now loop over all markers and apply cmd
+ (while (setq e (pop entries))
+ (setq pos (text-property-any (point-min) (point-max) 'org-hd-marker e))
+ (if (not pos)
+ (progn (message "Skipping removed entry at %s" e)
+ (setq cntskip (1+ cntskip)))
+ (goto-char pos)
+ (let (org-loop-over-headlines-in-active-region)
+ (eval cmd))
+ ;; `post-command-hook' is not run yet. We make sure any
+ ;; pending log note is processed.
+ (when (or (memq 'org-add-log-note (default-value 'post-command-hook))
+ (memq 'org-add-log-note post-command-hook))
+ (org-add-log-note))
+ (setq cnt (1+ cnt))))
+ (when redo-at-end (org-agenda-redo))
+ (unless org-agenda-persistent-marks
+ (org-agenda-bulk-unmark-all))
+ (message "Acted on %d entries%s%s"
+ cnt
+ (if (= cntskip 0)
+ ""
+ (format ", skipped %d (disappeared before their turn)"
+ cntskip))
+ (if (not org-agenda-persistent-marks)
+ "" " (kept marked)"))))))
+
+(defun org-agenda-capture (&optional with-time)
+ "Call `org-capture' with the date at point.
+With a `C-1' prefix, use the HH:MM value at point (if any) or the
+current HH:MM time."
+ (interactive "P")
+ (if (not (eq major-mode 'org-agenda-mode))
+ (user-error "You cannot do this outside of agenda buffers")
+ (let ((org-overriding-default-time
+ (org-get-cursor-date (equal with-time 1))))
+ (call-interactively 'org-capture))))
+
+;;; Dragging agenda lines forward/backward
+
+(defun org-agenda-reapply-filters ()
+ "Re-apply all agenda filters."
+ (mapcar
+ (lambda(f) (when (car f) (org-agenda-filter-apply (car f) (cadr f) t)))
+ `((,org-agenda-tag-filter tag)
+ (,org-agenda-category-filter category)
+ (,org-agenda-regexp-filter regexp)
+ (,org-agenda-effort-filter effort)
+ (,(get 'org-agenda-tag-filter :preset-filter) tag)
+ (,(get 'org-agenda-category-filter :preset-filter) category)
+ (,(get 'org-agenda-effort-filter :preset-filter) effort)
+ (,(get 'org-agenda-regexp-filter :preset-filter) regexp))))
+
+(defun org-agenda-drag-line-forward (arg &optional backward)
+ "Drag an agenda line forward by ARG lines.
+When the optional argument `backward' is non-nil, move backward."
+ (interactive "p")
+ (let ((inhibit-read-only t) lst line)
+ (if (or (not (get-text-property (point) 'txt))
+ (save-excursion
+ (dotimes (n arg)
+ (move-beginning-of-line (if backward 0 2))
+ (push (not (get-text-property (point) 'txt)) lst))
+ (delq nil lst)))
+ (message "Cannot move line forward")
+ (let ((end (save-excursion (move-beginning-of-line 2) (point))))
+ (move-beginning-of-line 1)
+ (setq line (buffer-substring (point) end))
+ (delete-region (point) end)
+ (move-beginning-of-line (funcall (if backward '1- '1+) arg))
+ (insert line)
+ (org-agenda-reapply-filters)
+ (org-agenda-mark-clocking-task)
+ (move-beginning-of-line 0)))))
+
+(defun org-agenda-drag-line-backward (arg)
+ "Drag an agenda line backward by ARG lines."
+ (interactive "p")
+ (org-agenda-drag-line-forward arg t))
+
+;;; Flagging notes
+
+(defun org-agenda-show-the-flagging-note ()
+ "Display the flagging note in the other window.
+When called a second time in direct sequence, offer to remove the FLAGGING
+tag and (if present) the flagging note."
+ (interactive)
+ (let ((hdmarker (org-get-at-bol 'org-hd-marker))
+ (win (selected-window))
+ note heading newhead)
+ (unless hdmarker
+ (user-error "No linked entry at point"))
+ (if (and (eq this-command last-command)
+ (y-or-n-p "Unflag and remove any flagging note? "))
+ (progn
+ (org-agenda-remove-flag hdmarker)
+ (let ((win (get-buffer-window "*Flagging Note*")))
+ (and win (delete-window win)))
+ (message "Entry unflagged"))
+ (setq note (org-entry-get hdmarker "THEFLAGGINGNOTE"))
+ (unless note
+ (user-error "No flagging note"))
+ (org-kill-new note)
+ (org-switch-to-buffer-other-window "*Flagging Note*")
+ (erase-buffer)
+ (insert note)
+ (goto-char (point-min))
+ (while (re-search-forward "\\\\n" nil t)
+ (replace-match "\n" t t))
+ (goto-char (point-min))
+ (select-window win)
+ (message "%s" (substitute-command-keys "Flagging note pushed to \
+kill ring. Press `\\[org-agenda-show-the-flagging-note]' again to remove \
+tag and note")))))
+
+(defun org-agenda-remove-flag (marker)
+ "Remove the FLAGGED tag and any flagging note in the entry."
+ (let (newhead)
+ (org-with-point-at marker
+ (org-toggle-tag "FLAGGED" 'off)
+ (org-entry-delete nil "THEFLAGGINGNOTE")
+ (setq newhead (org-get-heading)))
+ (org-agenda-change-all-lines newhead marker)
+ (message "Entry unflagged")))
+
+(defun org-agenda-get-any-marker (&optional pos)
+ (or (get-text-property (or pos (point-at-bol)) 'org-hd-marker)
+ (get-text-property (or pos (point-at-bol)) 'org-marker)))
+
+;;; Appointment reminders
+
+(defvar appt-time-msg-list) ; defined in appt.el
+
+;;;###autoload
+(defun org-agenda-to-appt (&optional refresh filter &rest args)
+ "Activate appointments found in `org-agenda-files'.
+
+With a `\\[universal-argument]' prefix, refresh the list of \
+appointments.
+
+If FILTER is t, interactively prompt the user for a regular
+expression, and filter out entries that don't match it.
+
+If FILTER is a string, use this string as a regular expression
+for filtering entries out.
+
+If FILTER is a function, filter out entries against which
+calling the function returns nil. This function takes one
+argument: an entry from `org-agenda-get-day-entries'.
+
+FILTER can also be an alist with the car of each cell being
+either `headline' or `category'. For example:
+
+ \\='((headline \"IMPORTANT\")
+ (category \"Work\"))
+
+will only add headlines containing IMPORTANT or headlines
+belonging to the \"Work\" category.
+
+ARGS are symbols indicating what kind of entries to consider.
+By default `org-agenda-to-appt' will use :deadline*, :scheduled*
+\(i.e., deadlines and scheduled items with a hh:mm specification)
+and :timestamp entries. See the docstring of `org-diary' for
+details and examples.
+
+If an entry has a APPT_WARNTIME property, its value will be used
+to override `appt-message-warning-time'."
+ (interactive "P")
+ (if refresh (setq appt-time-msg-list nil))
+ (if (eq filter t)
+ (setq filter (read-from-minibuffer "Regexp filter: ")))
+ (let* ((cnt 0) ; count added events
+ (scope (or args '(:deadline* :scheduled* :timestamp)))
+ (org-agenda-new-buffers nil)
+ (org-deadline-warning-days 0)
+ ;; Do not use `org-today' here because appt only takes
+ ;; time and without date as argument, so it may pass wrong
+ ;; information otherwise
+ (today (org-date-to-gregorian
+ (time-to-days (current-time))))
+ (org-agenda-restrict nil)
+ (files (org-agenda-files 'unrestricted)) entries file
+ (org-agenda-buffer nil))
+ ;; Get all entries which may contain an appt
+ (org-agenda-prepare-buffers files)
+ (while (setq file (pop files))
+ (setq entries
+ (delq nil
+ (append entries
+ (apply 'org-agenda-get-day-entries
+ file today scope)))))
+ ;; Map thru entries and find if we should filter them out
+ (mapc
+ (lambda (x)
+ (let* ((evt (org-trim
+ (replace-regexp-in-string
+ org-bracket-link-regexp "\\3"
+ (or (get-text-property 1 'txt x) ""))))
+ (cat (get-text-property (1- (length x)) 'org-category x))
+ (tod (get-text-property 1 'time-of-day x))
+ (ok (or (null filter)
+ (and (stringp filter) (string-match filter evt))
+ (and (functionp filter) (funcall filter x))
+ (and (listp filter)
+ (let ((cat-filter (cadr (assq 'category filter)))
+ (evt-filter (cadr (assq 'headline filter))))
+ (or (and (stringp cat-filter)
+ (string-match cat-filter cat))
+ (and (stringp evt-filter)
+ (string-match evt-filter evt)))))))
+ (wrn (get-text-property 1 'warntime x)))
+ ;; FIXME: Shall we remove text-properties for the appt text?
+ ;; (setq evt (set-text-properties 0 (length evt) nil evt))
+ (when (and ok tod (not (string-match "\\`DONE\\|CANCELLED" evt)))
+ (setq tod (concat "00" (number-to-string tod)))
+ (setq tod (when (string-match
+ "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)\\'" tod)
+ (concat (match-string 1 tod) ":"
+ (match-string 2 tod))))
+ (when (if (version< emacs-version "23.3")
+ (appt-add tod evt)
+ (appt-add tod evt wrn))
+ (setq cnt (1+ cnt))))))
+ entries)
+ (org-release-buffers org-agenda-new-buffers)
+ (if (eq cnt 0)
+ (message "No event to add")
+ (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
+
+(defun org-agenda-today-p (date)
+ "Non nil when DATE means today.
+DATE is either a list of the form (month day year) or a number of
+days as returned by `calendar-absolute-from-gregorian' or
+`org-today'. This function considers `org-extend-today-until'
+when defining today."
+ (eq (org-today)
+ (if (consp date) (calendar-absolute-from-gregorian date) date)))
+
+(defun org-agenda-todo-yesterday (&optional arg)
+ "Like `org-agenda-todo' but the time of change will be 23:59 of yesterday."
+ (interactive "P")
+ (let* ((org-use-effective-time t)
+ (hour (nth 2 (decode-time (org-current-time))))
+ (org-extend-today-until (1+ hour)))
+ (org-agenda-todo arg)))
+
+(provide 'org-agenda)
+
+;;; org-agenda.el ends here
diff --git a/lisp/org-archive.el b/lisp/org-archive.el
new file mode 100644
index 0000000..ce1f35d
--- /dev/null
+++ b/lisp/org-archive.el
@@ -0,0 +1,615 @@
+;;; org-archive.el --- Archiving for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the face definitions for Org.
+
+;;; Code:
+
+(require 'org)
+
+(declare-function org-element-type "org-element" (element))
+(declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction))
+(declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
+
+(defcustom org-archive-default-command 'org-archive-subtree
+ "The default archiving command."
+ :group 'org-archive
+ :type '(choice
+ (const org-archive-subtree)
+ (const org-archive-to-archive-sibling)
+ (const org-archive-set-tag)))
+
+(defcustom org-archive-reversed-order nil
+ "Non-nil means make the tree first child under the archive heading, not last."
+ :group 'org-archive
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-archive-sibling-heading "Archive"
+ "Name of the local archive sibling that is used to archive entries locally.
+Locally means: in the tree, under a sibling.
+See `org-archive-to-archive-sibling' for more information."
+ :group 'org-archive
+ :type 'string)
+
+(defcustom org-archive-mark-done nil
+ "Non-nil means mark entries as DONE when they are moved to the archive file.
+This can be a string to set the keyword to use. When non-nil, Org will
+use the first keyword in its list that means done."
+ :group 'org-archive
+ :type '(choice
+ (const :tag "No" nil)
+ (const :tag "Yes" t)
+ (string :tag "Use this keyword")))
+
+(defcustom org-archive-stamp-time t
+ "Non-nil means add a time stamp to entries moved to an archive file.
+This variable is obsolete and has no effect anymore, instead add or remove
+`time' from the variable `org-archive-save-context-info'."
+ :group 'org-archive
+ :type 'boolean)
+
+(defcustom org-archive-file-header-format "\nArchived entries from file %s\n\n"
+ "The header format string for newly created archive files.
+When nil, no header will be inserted.
+When a string, a %s formatter will be replaced by the file name."
+ :group 'org-archive
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-archive-subtree-add-inherited-tags 'infile
+ "Non-nil means append inherited tags when archiving a subtree."
+ :group 'org-archive
+ :version "24.1"
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "When archiving a subtree to the same file" infile)
+ (const :tag "Always" t)))
+
+(defcustom org-archive-save-context-info '(time file olpath category todo itags)
+ "Parts of context info that should be stored as properties when archiving.
+When a subtree is moved to an archive file, it loses information given by
+context, like inherited tags, the category, and possibly also the TODO
+state (depending on the variable `org-archive-mark-done').
+This variable can be a list of any of the following symbols:
+
+time The time of archiving.
+file The file where the entry originates.
+ltags The local tags, in the headline of the subtree.
+itags The tags the subtree inherits from further up the hierarchy.
+todo The pre-archive TODO state.
+category The category, taken from file name or #+CATEGORY lines.
+olpath The outline path to the item. These are all headlines above
+ the current item, separated by /, like a file path.
+
+For each symbol present in the list, a property will be created in
+the archived entry, with a prefix \"ARCHIVE_\", to remember this
+information."
+ :group 'org-archive
+ :type '(set :greedy t
+ (const :tag "Time" time)
+ (const :tag "File" file)
+ (const :tag "Category" category)
+ (const :tag "TODO state" todo)
+ (const :tag "Priority" priority)
+ (const :tag "Inherited tags" itags)
+ (const :tag "Outline path" olpath)
+ (const :tag "Local tags" ltags)))
+
+(defvar org-archive-hook nil
+ "Hook run after successfully archiving a subtree.
+Hook functions are called with point on the subtree in the
+original file. At this stage, the subtree has been added to the
+archive location, but not yet deleted from the original file.")
+
+(defun org-get-local-archive-location ()
+ "Get the archive location applicable at point."
+ (let ((re "^[ \t]*#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
+ prop)
+ (save-excursion
+ (save-restriction
+ (widen)
+ (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
+ (cond
+ ((and prop (string-match "\\S-" prop))
+ prop)
+ ((or (re-search-backward re nil t)
+ (re-search-forward re nil t))
+ (match-string 1))
+ (t org-archive-location))))))
+
+;;;###autoload
+(defun org-add-archive-files (files)
+ "Splice the archive files into the list of files.
+This implies visiting all these files and finding out what the
+archive file is."
+ (org-uniquify
+ (apply
+ 'append
+ (mapcar
+ (lambda (f)
+ (if (not (file-exists-p f))
+ nil
+ (with-current-buffer (org-get-agenda-file-buffer f)
+ (cons f (org-all-archive-files)))))
+ files))))
+
+(defun org-all-archive-files ()
+ "Get a list of all archive files used in the current buffer."
+ (let ((case-fold-search t)
+ files)
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward
+ "^[ \t]*\\(#\\+\\|:\\)ARCHIVE:[ \t]+\\(.*\\)"
+ nil t)
+ (when (save-match-data
+ (if (eq (match-string 1) ":") (org-at-property-p)
+ (eq (org-element-type (org-element-at-point)) 'keyword)))
+ (let ((file (org-extract-archive-file
+ (match-string-no-properties 2))))
+ (when (and (org-string-nw-p file) (file-exists-p file))
+ (push file files))))))
+ (setq files (nreverse files))
+ (let ((file (org-extract-archive-file)))
+ (when (and (org-string-nw-p file) (file-exists-p file))
+ (push file files)))
+ files))
+
+(defun org-extract-archive-file (&optional location)
+ "Extract and expand the file name from archive LOCATION.
+if LOCATION is not given, the value of `org-archive-location' is used."
+ (setq location (or location org-archive-location))
+ (if (string-match "\\(.*\\)::\\(.*\\)" location)
+ (if (= (match-beginning 1) (match-end 1))
+ (buffer-file-name (buffer-base-buffer))
+ (expand-file-name
+ (format (match-string 1 location)
+ (file-name-nondirectory
+ (buffer-file-name (buffer-base-buffer))))))))
+
+(defun org-extract-archive-heading (&optional location)
+ "Extract the heading from archive LOCATION.
+if LOCATION is not given, the value of `org-archive-location' is used."
+ (setq location (or location org-archive-location))
+ (if (string-match "\\(.*\\)::\\(.*\\)" location)
+ (format (match-string 2 location)
+ (file-name-nondirectory
+ (buffer-file-name (buffer-base-buffer))))))
+
+;;;###autoload
+(defun org-archive-subtree (&optional find-done)
+ "Move the current subtree to the archive.
+The archive can be a certain top-level heading in the current
+file, or in a different file. The tree will be moved to that
+location, the subtree heading be marked DONE, and the current
+time will be added.
+
+When called with a single prefix argument FIND-DONE, find whole
+trees without any open TODO items and archive them (after getting
+confirmation from the user). When called with a double prefix
+argument, find whole trees with timestamps before today and
+archive them (after getting confirmation from the user). If the
+cursor is not at a headline when these commands are called, try
+all level 1 trees. If the cursor is on a headline, only try the
+direct children of this heading."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ `(progn (setq org-map-continue-from (progn (org-back-to-heading) (point)))
+ (org-archive-subtree ,find-done))
+ org-loop-over-headlines-in-active-region
+ cl (if (org-invisible-p) (org-end-of-subtree nil t))))
+ (cond
+ ((equal find-done '(4)) (org-archive-all-done))
+ ((equal find-done '(16)) (org-archive-all-old))
+ (t
+ ;; Save all relevant TODO keyword-relatex variables
+ (let* ((tr-org-todo-keywords-1 org-todo-keywords-1)
+ (tr-org-todo-kwd-alist org-todo-kwd-alist)
+ (tr-org-done-keywords org-done-keywords)
+ (tr-org-todo-regexp org-todo-regexp)
+ (tr-org-todo-line-regexp org-todo-line-regexp)
+ (tr-org-odd-levels-only org-odd-levels-only)
+ (this-buffer (current-buffer))
+ (time (format-time-string
+ (substring (cdr org-time-stamp-formats) 1 -1)))
+ (file (abbreviate-file-name
+ (or (buffer-file-name (buffer-base-buffer))
+ (error "No file associated to buffer"))))
+ (location (org-get-local-archive-location))
+ (afile (or (org-extract-archive-file location)
+ (error "Invalid `org-archive-location'")))
+ (heading (org-extract-archive-heading location))
+ (infile-p (equal file (abbreviate-file-name (or afile ""))))
+ (newfile-p (and (org-string-nw-p afile)
+ (not (file-exists-p afile))))
+ (buffer (cond ((not (org-string-nw-p afile)) this-buffer)
+ ((find-buffer-visiting afile))
+ ((find-file-noselect afile))
+ (t (error "Cannot access file \"%s\"" afile))))
+ level datetree-date datetree-subheading-p)
+ (when (string-match "\\`datetree/" heading)
+ ;; Replace with ***, to represent the 3 levels of headings the
+ ;; datetree has.
+ (setq heading (replace-regexp-in-string "\\`datetree/" "***" heading))
+ (setq datetree-subheading-p (> (length heading) 3))
+ (setq datetree-date (org-date-to-gregorian
+ (or (org-entry-get nil "CLOSED" t) time))))
+ (if (and (> (length heading) 0)
+ (string-match "^\\*+" heading))
+ (setq level (match-end 0))
+ (setq heading nil level 0))
+ (save-excursion
+ (org-back-to-heading t)
+ ;; Get context information that will be lost by moving the
+ ;; tree. See `org-archive-save-context-info'.
+ (let* ((all-tags (org-get-tags-at))
+ (local-tags (org-get-tags))
+ (inherited-tags (org-delete-all local-tags all-tags))
+ (context
+ `((category . ,(org-get-category nil 'force-refresh))
+ (file . ,file)
+ (itags . ,(mapconcat #'identity inherited-tags " "))
+ (ltags . ,(mapconcat #'identity local-tags " "))
+ (olpath . ,(mapconcat #'identity
+ (org-get-outline-path)
+ "/"))
+ (time . ,time)
+ (todo . ,(org-entry-get (point) "TODO")))))
+ ;; We first only copy, in case something goes wrong
+ ;; we need to protect `this-command', to avoid kill-region sets it,
+ ;; which would lead to duplication of subtrees
+ (let (this-command) (org-copy-subtree 1 nil t))
+ (set-buffer buffer)
+ ;; Enforce Org mode for the archive buffer
+ (if (not (derived-mode-p 'org-mode))
+ ;; Force the mode for future visits.
+ (let ((org-insert-mode-line-in-empty-file t)
+ (org-inhibit-startup t))
+ (call-interactively 'org-mode)))
+ (when (and newfile-p org-archive-file-header-format)
+ (goto-char (point-max))
+ (insert (format org-archive-file-header-format
+ (buffer-file-name this-buffer))))
+ (when datetree-date
+ (require 'org-datetree)
+ (org-datetree-find-date-create datetree-date)
+ (org-narrow-to-subtree))
+ ;; Force the TODO keywords of the original buffer
+ (let ((org-todo-line-regexp tr-org-todo-line-regexp)
+ (org-todo-keywords-1 tr-org-todo-keywords-1)
+ (org-todo-kwd-alist tr-org-todo-kwd-alist)
+ (org-done-keywords tr-org-done-keywords)
+ (org-todo-regexp tr-org-todo-regexp)
+ (org-todo-line-regexp tr-org-todo-line-regexp)
+ (org-odd-levels-only
+ (if (local-variable-p 'org-odd-levels-only (current-buffer))
+ org-odd-levels-only
+ tr-org-odd-levels-only)))
+ (goto-char (point-min))
+ (outline-show-all)
+ (if (and heading (not (and datetree-date (not datetree-subheading-p))))
+ (progn
+ (if (re-search-forward
+ (concat "^" (regexp-quote heading)
+ "[ \t]*\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\($\\|\r\\)")
+ nil t)
+ (goto-char (match-end 0))
+ ;; Heading not found, just insert it at the end
+ (goto-char (point-max))
+ (or (bolp) (insert "\n"))
+ ;; datetrees don't need too much spacing
+ (insert (if datetree-date "" "\n") heading "\n")
+ (end-of-line 0))
+ ;; Make the subtree visible
+ (outline-show-subtree)
+ (if org-archive-reversed-order
+ (progn
+ (org-back-to-heading t)
+ (outline-next-heading))
+ (org-end-of-subtree t))
+ (skip-chars-backward " \t\r\n")
+ (and (looking-at "[ \t\r\n]*")
+ ;; datetree archives don't need so much spacing.
+ (replace-match (if datetree-date "\n" "\n\n"))))
+ ;; No specific heading, just go to end of file.
+ (goto-char (point-max))
+ ;; Subtree narrowing can let the buffer end on
+ ;; a headline. `org-paste-subtree' then deletes it.
+ ;; To prevent this, make sure visible part of buffer
+ ;; always terminates on a new line, while limiting
+ ;; number of blank lines in a date tree.
+ (unless (and datetree-date (bolp)) (insert "\n")))
+ ;; Paste
+ (org-paste-subtree (org-get-valid-level level (and heading 1)))
+ ;; Shall we append inherited tags?
+ (and inherited-tags
+ (or (and (eq org-archive-subtree-add-inherited-tags 'infile)
+ infile-p)
+ (eq org-archive-subtree-add-inherited-tags t))
+ (org-set-tags-to all-tags))
+ ;; Mark the entry as done
+ (when (and org-archive-mark-done
+ (let ((case-fold-search nil))
+ (looking-at org-todo-line-regexp))
+ (or (not (match-end 2))
+ (not (member (match-string 2) org-done-keywords))))
+ (let (org-log-done org-todo-log-states)
+ (org-todo
+ (car (or (member org-archive-mark-done org-done-keywords)
+ org-done-keywords)))))
+
+ ;; Add the context info.
+ (dolist (item org-archive-save-context-info)
+ (let ((value (cdr (assq item context))))
+ (when (org-string-nw-p value)
+ (org-entry-put
+ (point)
+ (concat "ARCHIVE_" (upcase (symbol-name item)))
+ value))))
+ (widen)
+ ;; Save and kill the buffer, if it is not the same
+ ;; buffer.
+ (unless (eq this-buffer buffer) (save-buffer)))))
+ ;; Here we are back in the original buffer. Everything seems
+ ;; to have worked. So now run hooks, cut the tree and finish
+ ;; up.
+ (run-hooks 'org-archive-hook)
+ (let (this-command) (org-cut-subtree))
+ (when (featurep 'org-inlinetask)
+ (org-inlinetask-remove-END-maybe))
+ (setq org-markers-to-move nil)
+ (message "Subtree archived %s"
+ (if (eq this-buffer buffer)
+ (concat "under heading: " heading)
+ (concat "in file: " (abbreviate-file-name afile)))))))
+ (org-reveal)
+ (if (looking-at "^[ \t]*$")
+ (outline-next-visible-heading 1))))
+
+;;;###autoload
+(defun org-archive-to-archive-sibling ()
+ "Archive the current heading by moving it under the archive sibling.
+
+The archive sibling is a sibling of the heading with the heading name
+`org-archive-sibling-heading' and an `org-archive-tag' tag. If this
+sibling does not exist, it will be created at the end of the subtree.
+
+Archiving time is retained in the ARCHIVE_TIME node property."
+ (interactive)
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (when (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ '(progn (setq org-map-continue-from
+ (progn (org-back-to-heading)
+ (if (looking-at (concat "^.*:" org-archive-tag ":.*$"))
+ (org-end-of-subtree t)
+ (point))))
+ (when (org-at-heading-p)
+ (org-archive-to-archive-sibling)))
+ org-loop-over-headlines-in-active-region
+ cl (if (org-invisible-p) (org-end-of-subtree nil t))))
+ (save-restriction
+ (widen)
+ (let (b e pos leader level)
+ (org-back-to-heading t)
+ (looking-at org-outline-regexp)
+ (setq leader (match-string 0)
+ level (funcall outline-level))
+ (setq pos (point))
+ (condition-case nil
+ (outline-up-heading 1 t)
+ (error (setq e (point-max)) (goto-char (point-min))))
+ (setq b (point))
+ (unless e
+ (condition-case nil
+ (org-end-of-subtree t t)
+ (error (goto-char (point-max))))
+ (setq e (point)))
+ (goto-char b)
+ (unless (re-search-forward
+ (concat "^" (regexp-quote leader)
+ "[ \t]*"
+ org-archive-sibling-heading
+ "[ \t]*:"
+ org-archive-tag ":") e t)
+ (goto-char e)
+ (or (bolp) (newline))
+ (insert leader org-archive-sibling-heading "\n")
+ (beginning-of-line 0)
+ (org-toggle-tag org-archive-tag 'on))
+ (beginning-of-line 1)
+ (if org-archive-reversed-order
+ (outline-next-heading)
+ (org-end-of-subtree t t))
+ (save-excursion
+ (goto-char pos)
+ (let ((this-command this-command)) (org-cut-subtree)))
+ (org-paste-subtree (org-get-valid-level level 1))
+ (org-set-property
+ "ARCHIVE_TIME"
+ (format-time-string
+ (substring (cdr org-time-stamp-formats) 1 -1)))
+ (outline-up-heading 1 t)
+ (outline-hide-subtree)
+ (org-cycle-show-empty-lines 'folded)
+ (goto-char pos)))
+ (org-reveal)
+ (if (looking-at "^[ \t]*$")
+ (outline-next-visible-heading 1))))
+
+(defun org-archive-all-done (&optional tag)
+ "Archive sublevels of the current tree without open TODO items.
+If the cursor is not on a headline, try all level 1 trees. If
+it is on a headline, try all direct children.
+When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
+ (org-archive-all-matches
+ (lambda (_beg end)
+ (let ((case-fold-search nil))
+ (unless (re-search-forward org-not-done-heading-regexp end t)
+ "no open TODO items")))
+ tag))
+
+(defun org-archive-all-old (&optional tag)
+ "Archive sublevels of the current tree with timestamps prior to today.
+If the cursor is not on a headline, try all level 1 trees. If
+it is on a headline, try all direct children.
+When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
+ (org-archive-all-matches
+ (lambda (_beg end)
+ (let (ts)
+ (and (re-search-forward org-ts-regexp end t)
+ (setq ts (match-string 0))
+ (< (org-time-stamp-to-now ts) 0)
+ (if (not (looking-at
+ (concat "--\\(" org-ts-regexp "\\)")))
+ (concat "old timestamp " ts)
+ (setq ts (concat "old timestamp " ts (match-string 0)))
+ (and (< (org-time-stamp-to-now (match-string 1)) 0)
+ ts)))))
+ tag))
+
+(defun org-archive-all-matches (predicate &optional tag)
+ "Archive sublevels of the current tree that match PREDICATE.
+
+PREDICATE is a function of two arguments, BEG and END, which
+specify the beginning and end of the headline being considered.
+It is called with point positioned at BEG. The headline will be
+archived if PREDICATE returns non-nil. If the return value of
+PREDICATE is a string, it should describe the reason for
+archiving the heading.
+
+If the cursor is not on a headline, try all level 1 trees. If it
+is on a headline, try all direct children. When TAG is non-nil,
+don't move trees, but mark them with the ARCHIVE tag."
+ (let ((rea (concat ".*:" org-archive-tag ":")) re1
+ (begm (make-marker))
+ (endm (make-marker))
+ (question (if tag "Set ARCHIVE tag? "
+ "Move subtree to archive? "))
+ reason beg end (cntarch 0))
+ (if (org-at-heading-p)
+ (progn
+ (setq re1 (concat "^" (regexp-quote
+ (make-string
+ (+ (- (match-end 0) (match-beginning 0) 1)
+ (if org-odd-levels-only 2 1))
+ ?*))
+ " "))
+ (move-marker begm (point))
+ (move-marker endm (org-end-of-subtree t)))
+ (setq re1 "^* ")
+ (move-marker begm (point-min))
+ (move-marker endm (point-max)))
+ (save-excursion
+ (goto-char begm)
+ (while (re-search-forward re1 endm t)
+ (setq beg (match-beginning 0)
+ end (save-excursion (org-end-of-subtree t) (point)))
+ (goto-char beg)
+ (if (not (setq reason (funcall predicate beg end)))
+ (goto-char end)
+ (goto-char beg)
+ (if (and (or (not tag) (not (looking-at rea)))
+ (y-or-n-p
+ (if (stringp reason)
+ (concat question "(" reason ")")
+ question)))
+ (progn
+ (if tag
+ (org-toggle-tag org-archive-tag 'on)
+ (org-archive-subtree))
+ (setq cntarch (1+ cntarch)))
+ (goto-char end)))))
+ (message "%d trees archived" cntarch)))
+
+;;;###autoload
+(defun org-toggle-archive-tag (&optional find-done)
+ "Toggle the archive tag for the current headline.
+With prefix ARG, check all children of current headline and offer tagging
+the children that do not contain any open TODO items."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ `(org-toggle-archive-tag ,find-done)
+ org-loop-over-headlines-in-active-region
+ cl (if (org-invisible-p) (org-end-of-subtree nil t))))
+ (if find-done
+ (org-archive-all-done 'tag)
+ (let (set)
+ (save-excursion
+ (org-back-to-heading t)
+ (setq set (org-toggle-tag org-archive-tag))
+ (when set (org-flag-subtree t)))
+ (and set (beginning-of-line 1))
+ (message "Subtree %s" (if set "archived" "unarchived"))))))
+
+(defun org-archive-set-tag ()
+ "Set the ARCHIVE tag."
+ (interactive)
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ 'org-archive-set-tag
+ org-loop-over-headlines-in-active-region
+ cl (if (org-invisible-p) (org-end-of-subtree nil t))))
+ (org-toggle-tag org-archive-tag 'on)))
+
+;;;###autoload
+(defun org-archive-subtree-default ()
+ "Archive the current subtree with the default command.
+This command is set with the variable `org-archive-default-command'."
+ (interactive)
+ (call-interactively org-archive-default-command))
+
+;;;###autoload
+(defun org-archive-subtree-default-with-confirmation ()
+ "Archive the current subtree with the default command.
+This command is set with the variable `org-archive-default-command'."
+ (interactive)
+ (if (y-or-n-p "Archive this subtree or entry? ")
+ (call-interactively org-archive-default-command)
+ (error "Abort")))
+
+(provide 'org-archive)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-archive.el ends here
diff --git a/lisp/org-attach.el b/lisp/org-attach.el
new file mode 100644
index 0000000..a026eee
--- /dev/null
+++ b/lisp/org-attach.el
@@ -0,0 +1,554 @@
+;;; org-attach.el --- Manage file attachments to Org tasks -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: John Wiegley <johnw@newartisans.com>
+;; Keywords: org data task
+
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; See the Org manual for information on how to use it.
+;;
+;; Attachments are managed in a special directory called "data", which
+;; lives in the same directory as the org file itself. If this data
+;; directory is initialized as a Git repository, then org-attach will
+;; automatically commit changes when it sees them.
+;;
+;; Attachment directories are identified using a UUID generated for the
+;; task which has the attachments. These are added as property to the
+;; task when necessary, and should not be deleted or changed by the
+;; user, ever. UUIDs are generated by a mechanism defined in the variable
+;; `org-id-method'.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+(require 'org-id)
+(require 'vc-git)
+
+(defgroup org-attach nil
+ "Options concerning entry attachments in Org mode."
+ :tag "Org Attach"
+ :group 'org)
+
+(defcustom org-attach-directory "data/"
+ "The directory where attachments are stored.
+If this is a relative path, it will be interpreted relative to the directory
+where the Org file lives."
+ :group 'org-attach
+ :type 'directory)
+
+(defcustom org-attach-commit t
+ "If non-nil commit attachments with git.
+This is only done if the Org file is in a git repository."
+ :group 'org-attach
+ :type 'boolean
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defcustom org-attach-git-annex-cutoff (* 32 1024)
+ "If non-nil, files larger than this will be annexed instead of stored."
+ :group 'org-attach
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "None" nil)
+ (integer :tag "Bytes")))
+
+(defcustom org-attach-auto-tag "ATTACH"
+ "Tag that will be triggered automatically when an entry has an attachment."
+ :group 'org-attach
+ :type '(choice
+ (const :tag "None" nil)
+ (string :tag "Tag")))
+
+(defcustom org-attach-file-list-property "Attachments"
+ "The property used to keep a list of attachment belonging to this entry.
+This is not really needed, so you may set this to nil if you don't want it.
+Also, for entries where children inherit the directory, the list of
+attachments is not kept in this property."
+ :group 'org-attach
+ :type '(choice
+ (const :tag "None" nil)
+ (string :tag "Tag")))
+
+(defcustom org-attach-method 'cp
+ "The preferred method to attach a file.
+Allowed values are:
+
+mv rename the file to move it into the attachment directory
+cp copy the file
+ln create a hard link. Note that this is not supported
+ on all systems, and then the result is not defined.
+lns create a symbol link. Note that this is not supported
+ on all systems, and then the result is not defined."
+ :group 'org-attach
+ :type '(choice
+ (const :tag "Copy" cp)
+ (const :tag "Move/Rename" mv)
+ (const :tag "Hard Link" ln)
+ (const :tag "Symbol Link" lns)))
+
+(defcustom org-attach-expert nil
+ "Non-nil means do not show the splash buffer with the attach dispatcher."
+ :group 'org-attach
+ :type 'boolean)
+
+(defcustom org-attach-allow-inheritance t
+ "Non-nil means allow attachment directories be inherited."
+ :group 'org-attach
+ :type 'boolean)
+
+(defvar org-attach-inherited nil
+ "Indicates if the last access to the attachment directory was inherited.")
+
+(defcustom org-attach-store-link-p nil
+ "Non-nil means store a link to a file when attaching it."
+ :group 'org-attach
+ :version "24.1"
+ :type '(choice
+ (const :tag "Don't store link" nil)
+ (const :tag "Link to origin location" t)
+ (const :tag "Link to the attach-dir location" attached)))
+
+(defcustom org-attach-archive-delete nil
+ "Non-nil means attachments are deleted upon archiving a subtree.
+When set to `query', ask the user instead."
+ :group 'org-attach
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "Never delete attachments" nil)
+ (const :tag "Always delete attachments" t)
+ (const :tag "Query the user" query)))
+
+(defcustom org-attach-annex-auto-get 'ask
+ "Confirmation preference for automatically getting annex files.
+If \\='ask, prompt using `y-or-n-p'. If t, always get. If nil, never get."
+ :group 'org-attach
+ :package-version '(Org . "9")
+ :version "26.1"
+ :type '(choice
+ (const :tag "confirm with `y-or-n-p'" ask)
+ (const :tag "always get from annex if necessary" t)
+ (const :tag "never get from annex" nil)))
+
+;;;###autoload
+(defun org-attach ()
+ "The dispatcher for attachment commands.
+Shows a list of commands and prompts for another key to execute a command."
+ (interactive)
+ (let (c marker)
+ (when (eq major-mode 'org-agenda-mode)
+ (setq marker (or (get-text-property (point) 'org-hd-marker)
+ (get-text-property (point) 'org-marker)))
+ (unless marker
+ (error "No task in current line")))
+ (save-excursion
+ (when marker
+ (set-buffer (marker-buffer marker))
+ (goto-char marker))
+ (org-back-to-heading t)
+ (save-excursion
+ (save-window-excursion
+ (unless org-attach-expert
+ (with-output-to-temp-buffer "*Org Attach*"
+ (princ "Select an Attachment Command:
+
+a Select a file and attach it to the task, using `org-attach-method'.
+c/m/l/y Attach a file using copy/move/link/symbolic-link method.
+n Create a new attachment, as an Emacs buffer.
+z Synchronize the current task with its attachment
+ directory, in case you added attachments yourself.
+
+o Open current task's attachments.
+O Like \"o\", but force opening in Emacs.
+f Open current task's attachment directory.
+F Like \"f\", but force using dired in Emacs.
+
+d Delete one attachment, you will be prompted for a file name.
+D Delete all of a task's attachments. A safer way is
+ to open the directory in dired and delete from there.
+
+s Set a specific attachment directory for this entry.
+i Make children of the current entry inherit its attachment directory.")))
+ (org-fit-window-to-buffer (get-buffer-window "*Org Attach*"))
+ (message "Select command: [acmlzoOfFdD]")
+ (setq c (read-char-exclusive))
+ (and (get-buffer "*Org Attach*") (kill-buffer "*Org Attach*"))))
+ (cond
+ ((memq c '(?a ?\C-a)) (call-interactively 'org-attach-attach))
+ ((memq c '(?c ?\C-c))
+ (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach)))
+ ((memq c '(?m ?\C-m))
+ (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach)))
+ ((memq c '(?l ?\C-l))
+ (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach)))
+ ((memq c '(?y ?\C-y))
+ (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach)))
+ ((memq c '(?n ?\C-n)) (call-interactively 'org-attach-new))
+ ((memq c '(?z ?\C-z)) (call-interactively 'org-attach-sync))
+ ((memq c '(?o ?\C-o)) (call-interactively 'org-attach-open))
+ ((eq c ?O) (call-interactively 'org-attach-open-in-emacs))
+ ((memq c '(?f ?\C-f)) (call-interactively 'org-attach-reveal))
+ ((memq c '(?F)) (call-interactively 'org-attach-reveal-in-emacs))
+ ((memq c '(?d ?\C-d)) (call-interactively
+ 'org-attach-delete-one))
+ ((eq c ?D) (call-interactively 'org-attach-delete-all))
+ ((eq c ?q) (message "Abort"))
+ ((memq c '(?s ?\C-s)) (call-interactively
+ 'org-attach-set-directory))
+ ((memq c '(?i ?\C-i)) (call-interactively
+ 'org-attach-set-inherit))
+ (t (error "No such attachment command %c" c))))))
+
+(defun org-attach-dir (&optional create-if-not-exists-p)
+ "Return the directory associated with the current entry.
+This first checks for a local property ATTACH_DIR, and then for an inherited
+property ATTACH_DIR_INHERIT. If neither exists, the default mechanism
+using the entry ID will be invoked to access the unique directory for the
+current entry.
+If the directory does not exist and CREATE-IF-NOT-EXISTS-P is non-nil,
+the directory and (if necessary) the corresponding ID will be created."
+ (let (attach-dir uuid)
+ (setq org-attach-inherited (org-entry-get nil "ATTACH_DIR_INHERIT"))
+ (cond
+ ((setq attach-dir (org-entry-get nil "ATTACH_DIR"))
+ (org-attach-check-absolute-path attach-dir))
+ ((and org-attach-allow-inheritance
+ (org-entry-get nil "ATTACH_DIR_INHERIT" t))
+ (setq attach-dir
+ (org-with-wide-buffer
+ (if (marker-position org-entry-property-inherited-from)
+ (goto-char org-entry-property-inherited-from)
+ (org-back-to-heading t))
+ (let (org-attach-allow-inheritance)
+ (org-attach-dir create-if-not-exists-p))))
+ (org-attach-check-absolute-path attach-dir)
+ (setq org-attach-inherited t))
+ (t ; use the ID
+ (org-attach-check-absolute-path nil)
+ (setq uuid (org-id-get (point) create-if-not-exists-p))
+ (when (or uuid create-if-not-exists-p)
+ (unless uuid (error "ID retrieval/creation failed"))
+ (setq attach-dir (expand-file-name
+ (format "%s/%s"
+ (substring uuid 0 2)
+ (substring uuid 2))
+ (expand-file-name org-attach-directory))))))
+ (when attach-dir
+ (if (and create-if-not-exists-p
+ (not (file-directory-p attach-dir)))
+ (make-directory attach-dir t))
+ (and (file-exists-p attach-dir)
+ attach-dir))))
+
+(defun org-attach-check-absolute-path (dir)
+ "Check if we have enough information to root the attachment directory.
+When DIR is given, check also if it is already absolute. Otherwise,
+assume that it will be relative, and check if `org-attach-directory' is
+absolute, or if at least the current buffer has a file name.
+Throw an error if we cannot root the directory."
+ (or (and dir (file-name-absolute-p dir))
+ (file-name-absolute-p org-attach-directory)
+ (buffer-file-name (buffer-base-buffer))
+ (error "Need absolute `org-attach-directory' to attach in buffers without filename")))
+
+(defun org-attach-set-directory ()
+ "Set the ATTACH_DIR property of the current entry.
+The property defines the directory that is used for attachments
+of the entry."
+ (interactive)
+ (let ((dir (org-entry-get nil "ATTACH_DIR")))
+ (setq dir (read-directory-name "Attachment directory: " dir))
+ (org-entry-put nil "ATTACH_DIR" dir)))
+
+(defun org-attach-set-inherit ()
+ "Set the ATTACH_DIR_INHERIT property of the current entry.
+The property defines the directory that is used for attachments
+of the entry and any children that do not explicitly define (by setting
+the ATTACH_DIR property) their own attachment directory."
+ (interactive)
+ (org-entry-put nil "ATTACH_DIR_INHERIT" "t")
+ (message "Children will inherit attachment directory"))
+
+(defun org-attach-use-annex ()
+ "Return non-nil if git annex can be used."
+ (let ((git-dir (vc-git-root (expand-file-name org-attach-directory))))
+ (and org-attach-git-annex-cutoff
+ (or (file-exists-p (expand-file-name "annex" git-dir))
+ (file-exists-p (expand-file-name ".git/annex" git-dir))))))
+
+(defun org-attach-annex-get-maybe (path)
+ "Call git annex get PATH (via shell) if using git annex.
+Signals an error if the file content is not available and it was not retrieved."
+ (let ((path-relative (file-relative-name path)))
+ (when (and (org-attach-use-annex)
+ (not
+ (string-equal
+ "found"
+ (shell-command-to-string
+ (format "git annex find --format=found --in=here %s"
+ (shell-quote-argument path-relative))))))
+ (let ((should-get
+ (if (eq org-attach-annex-auto-get 'ask)
+ (y-or-n-p (format "Run git annex get %s? " path-relative))
+ org-attach-annex-auto-get)))
+ (if should-get
+ (progn (message "Running git annex get \"%s\"." path-relative)
+ (call-process "git" nil nil nil "annex" "get" path-relative))
+ (error "File %s stored in git annex but it is not available, and was not retrieved"
+ path))))))
+
+(defun org-attach-commit ()
+ "Commit changes to git if `org-attach-directory' is properly initialized.
+This checks for the existence of a \".git\" directory in that directory."
+ (let* ((dir (expand-file-name org-attach-directory))
+ (git-dir (vc-git-root dir))
+ (use-annex (org-attach-use-annex))
+ (changes 0))
+ (when (and git-dir (executable-find "git"))
+ (with-temp-buffer
+ (cd dir)
+ (dolist (new-or-modified
+ (split-string
+ (shell-command-to-string
+ "git ls-files -zmo --exclude-standard") "\0" t))
+ (if (and use-annex
+ (>= (nth 7 (file-attributes new-or-modified))
+ org-attach-git-annex-cutoff))
+ (call-process "git" nil nil nil "annex" "add" new-or-modified)
+ (call-process "git" nil nil nil "add" new-or-modified))
+ (cl-incf changes))
+ (dolist (deleted
+ (split-string
+ (shell-command-to-string "git ls-files -z --deleted") "\0" t))
+ (call-process "git" nil nil nil "rm" deleted)
+ (cl-incf changes))
+ (when (> changes 0)
+ (shell-command "git commit -m 'Synchronized attachments'"))))))
+
+(defun org-attach-tag (&optional off)
+ "Turn the autotag on or (if OFF is set) off."
+ (when org-attach-auto-tag
+ (save-excursion
+ (org-back-to-heading t)
+ (org-toggle-tag org-attach-auto-tag (if off 'off 'on)))))
+
+(defun org-attach-untag ()
+ "Turn the autotag off."
+ (org-attach-tag 'off))
+
+(defun org-attach-store-link (file)
+ "Add a link to `org-stored-link' when attaching a file.
+Only do this when `org-attach-store-link-p' is non-nil."
+ (setq org-stored-links
+ (cons (list (org-attach-expand-link file)
+ (file-name-nondirectory file))
+ org-stored-links)))
+
+(defun org-attach-attach (file &optional visit-dir method)
+ "Move/copy/link FILE into the attachment directory of the current task.
+If VISIT-DIR is non-nil, visit the directory with dired.
+METHOD may be `cp', `mv', `ln', or `lns' default taken from
+`org-attach-method'."
+ (interactive "fFile to keep as an attachment: \nP")
+ (setq method (or method org-attach-method))
+ (let ((basename (file-name-nondirectory file)))
+ (when (and org-attach-file-list-property (not org-attach-inherited))
+ (org-entry-add-to-multivalued-property
+ (point) org-attach-file-list-property basename))
+ (let* ((attach-dir (org-attach-dir t))
+ (fname (expand-file-name basename attach-dir)))
+ (cond
+ ((eq method 'mv) (rename-file file fname))
+ ((eq method 'cp) (copy-file file fname))
+ ((eq method 'ln) (add-name-to-file file fname))
+ ((eq method 'lns) (make-symbolic-link file fname)))
+ (when org-attach-commit
+ (org-attach-commit))
+ (org-attach-tag)
+ (cond ((eq org-attach-store-link-p 'attached)
+ (org-attach-store-link fname))
+ ((eq org-attach-store-link-p t)
+ (org-attach-store-link file)))
+ (if visit-dir
+ (dired attach-dir)
+ (message "File \"%s\" is now a task attachment." basename)))))
+
+(defun org-attach-attach-cp ()
+ "Attach a file by copying it."
+ (interactive)
+ (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach)))
+(defun org-attach-attach-mv ()
+ "Attach a file by moving (renaming) it."
+ (interactive)
+ (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach)))
+(defun org-attach-attach-ln ()
+ "Attach a file by creating a hard link to it.
+Beware that this does not work on systems that do not support hard links.
+On some systems, this apparently does copy the file instead."
+ (interactive)
+ (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach)))
+(defun org-attach-attach-lns ()
+ "Attach a file by creating a symbolic link to it.
+
+Beware that this does not work on systems that do not support symbolic links.
+On some systems, this apparently does copy the file instead."
+ (interactive)
+ (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach)))
+
+(defun org-attach-new (file)
+ "Create a new attachment FILE for the current task.
+The attachment is created as an Emacs buffer."
+ (interactive "sCreate attachment named: ")
+ (when (and org-attach-file-list-property (not org-attach-inherited))
+ (org-entry-add-to-multivalued-property
+ (point) org-attach-file-list-property file))
+ (let ((attach-dir (org-attach-dir t)))
+ (org-attach-tag)
+ (find-file (expand-file-name file attach-dir))
+ (message "New attachment %s" file)))
+
+(defun org-attach-delete-one (&optional file)
+ "Delete a single attachment."
+ (interactive)
+ (let* ((attach-dir (org-attach-dir t))
+ (files (org-attach-file-list attach-dir))
+ (file (or file
+ (completing-read
+ "Delete attachment: "
+ (mapcar (lambda (f)
+ (list (file-name-nondirectory f)))
+ files)))))
+ (setq file (expand-file-name file attach-dir))
+ (unless (file-exists-p file)
+ (error "No such attachment: %s" file))
+ (delete-file file)
+ (when org-attach-commit
+ (org-attach-commit))))
+
+(defun org-attach-delete-all (&optional force)
+ "Delete all attachments from the current task.
+This actually deletes the entire attachment directory.
+A safer way is to open the directory in dired and delete from there."
+ (interactive "P")
+ (when (and org-attach-file-list-property (not org-attach-inherited))
+ (org-entry-delete (point) org-attach-file-list-property))
+ (let ((attach-dir (org-attach-dir)))
+ (when
+ (and attach-dir
+ (or force
+ (y-or-n-p "Are you sure you want to remove all attachments of this entry? ")))
+ (shell-command (format "rm -fr %s" attach-dir))
+ (message "Attachment directory removed")
+ (when org-attach-commit
+ (org-attach-commit))
+ (org-attach-untag))))
+
+(defun org-attach-sync ()
+ "Synchronize the current tasks with its attachments.
+This can be used after files have been added externally."
+ (interactive)
+ (when org-attach-commit
+ (org-attach-commit))
+ (when (and org-attach-file-list-property (not org-attach-inherited))
+ (org-entry-delete (point) org-attach-file-list-property))
+ (let ((attach-dir (org-attach-dir)))
+ (when attach-dir
+ (let ((files (org-attach-file-list attach-dir)))
+ (and files (org-attach-tag))
+ (when org-attach-file-list-property
+ (dolist (file files)
+ (unless (string-match "^\\.\\.?\\'" file)
+ (org-entry-add-to-multivalued-property
+ (point) org-attach-file-list-property file))))))))
+
+(defun org-attach-file-list (dir)
+ "Return a list of files in the attachment directory.
+This ignores files ending in \"~\"."
+ (delq nil
+ (mapcar (lambda (x) (if (string-match "^\\.\\.?\\'" x) nil x))
+ (directory-files dir nil "[^~]\\'"))))
+
+(defun org-attach-reveal (&optional if-exists)
+ "Show the attachment directory of the current task.
+This will attempt to use an external program to show the directory."
+ (interactive "P")
+ (let ((attach-dir (org-attach-dir (not if-exists))))
+ (and attach-dir (org-open-file attach-dir))))
+
+(defun org-attach-reveal-in-emacs ()
+ "Show the attachment directory of the current task in dired."
+ (interactive)
+ (let ((attach-dir (org-attach-dir t)))
+ (dired attach-dir)))
+
+(defun org-attach-open (&optional in-emacs)
+ "Open an attachment of the current task.
+If there are more than one attachment, you will be prompted for the file name.
+This command will open the file using the settings in `org-file-apps'
+and in the system-specific variants of this variable.
+If IN-EMACS is non-nil, force opening in Emacs."
+ (interactive "P")
+ (let* ((attach-dir (org-attach-dir t))
+ (files (org-attach-file-list attach-dir))
+ (file (if (= (length files) 1)
+ (car files)
+ (completing-read "Open attachment: "
+ (mapcar #'list files) nil t)))
+ (path (expand-file-name file attach-dir)))
+ (org-attach-annex-get-maybe path)
+ (org-open-file path in-emacs)))
+
+(defun org-attach-open-in-emacs ()
+ "Open attachment, force opening in Emacs.
+See `org-attach-open'."
+ (interactive)
+ (org-attach-open 'in-emacs))
+
+(defun org-attach-expand (file)
+ "Return the full path to the current entry's attachment file FILE.
+Basically, this adds the path to the attachment directory."
+ (expand-file-name file (org-attach-dir)))
+
+(defun org-attach-expand-link (file)
+ "Return a file link pointing to the current entry's attachment file FILE.
+Basically, this adds the path to the attachment directory, and a \"file:\"
+prefix."
+ (concat "file:" (org-attach-expand file)))
+
+(defun org-attach-archive-delete-maybe ()
+ "Maybe delete subtree attachments when archiving.
+This function is called by `org-archive-hook'. The option
+`org-attach-archive-delete' controls its behavior."
+ (when (if (eq org-attach-archive-delete 'query)
+ (yes-or-no-p "Delete all attachments? ")
+ org-attach-archive-delete)
+ (org-attach-delete-all t)))
+
+(add-hook 'org-archive-hook 'org-attach-archive-delete-maybe)
+
+(provide 'org-attach)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-attach.el ends here
diff --git a/lisp/org-bbdb.el b/lisp/org-bbdb.el
new file mode 100644
index 0000000..f851668
--- /dev/null
+++ b/lisp/org-bbdb.el
@@ -0,0 +1,506 @@
+;;; org-bbdb.el --- Support for links to BBDB entries -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Authors: Carsten Dominik <carsten at orgmode dot org>
+;; Thomas Baumann <thomas dot baumann at ch dot tum dot de>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to BBDB database entries from within Org.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;; It also implements an interface (based on Ivar Rummelhoff's
+;; bbdb-anniv.el) for those Org users, who do not use the diary
+;; but who do want to include the anniversaries stored in the BBDB
+;; into the org-agenda. If you already include the `diary' into the
+;; agenda, you might want to prefer to include the anniversaries in
+;; the diary using bbdb-anniv.el.
+;;
+;; Put the following in /somewhere/at/home/diary.org and make sure
+;; that this file is in `org-agenda-files'.
+;;
+;; %%(org-bbdb-anniversaries)
+;;
+;; For example my diary.org looks like:
+;; * Anniversaries
+;; #+CATEGORY: Anniv
+;; %%(org-bbdb-anniversaries)
+;;
+;;
+;; To add an anniversary to a BBDB record, press `C-o' in the record.
+;; You will be prompted for the field name, in this case it must be
+;; "anniversary". If this is the first time you are using this field,
+;; you need to confirm that it should be created.
+;;
+;; The format of an anniversary field stored in BBDB is the following
+;; (items in {} are optional):
+;;
+;; YYYY-MM-DD{ CLASS-OR-FORMAT-STRING}
+;; {\nYYYY-MM-DD CLASS-OR-FORMAT-STRING}...
+;;
+;; CLASS-OR-FORMAT-STRING is one of two things:
+;;
+;; - an identifier for a class of anniversaries (eg. birthday or
+;; wedding) from `org-bbdb-anniversary-format-alist' which then
+;; defines the format string for this class
+;; - the (format) string displayed in the diary.
+;;
+;; You can enter multiple anniversaries for a single BBDB record by
+;; separating them with a newline character. At the BBDB prompt for
+;; the field value, type `C-q C-j' to enter a newline between two
+;; anniversaries.
+;;
+;; If you omit the CLASS-OR-FORMAT-STRING entirely, it defaults to the
+;; value of `org-bbdb-default-anniversary-format' ("birthday" by
+;; default).
+;;
+;; The substitutions in the format string are (in order):
+;; - the name of the record containing this anniversary
+;; - the number of years
+;; - an ordinal suffix (st, nd, rd, th) for the year
+;;
+;; See the documentation of `org-bbdb-anniversary-format-alist' for
+;; further options.
+;;
+;; Example
+;;
+;; 1973-06-22
+;; 20??-??-?? wedding
+;; 1998-03-12 %s created bbdb-anniv.el %d years ago
+;;
+;; From Org's agenda, you can use `C-c C-o' to jump to the BBDB
+;; link from which the entry at point originates.
+;;
+;;; Code:
+
+(require 'org)
+(require 'cl-lib)
+
+;; Declare external functions and variables
+
+(declare-function bbdb "ext:bbdb-com" (string elidep))
+(declare-function bbdb-company "ext:bbdb-com" (string elidep))
+(declare-function bbdb-current-record "ext:bbdb-com"
+ (&optional planning-on-modifying))
+(declare-function bbdb-name "ext:bbdb-com" (string elidep))
+(declare-function bbdb-completing-read-record "ext:bbdb-com"
+ (prompt &optional omit-records))
+(declare-function bbdb-record-field "ext:bbdb" (recond field))
+(declare-function bbdb-record-getprop "ext:bbdb" (record property))
+(declare-function bbdb-record-name "ext:bbdb" (record))
+(declare-function bbdb-records "ext:bbdb"
+ (&optional dont-check-disk already-in-db-buffer))
+(declare-function bbdb-split "ext:bbdb" (string separators))
+(declare-function bbdb-string-trim "ext:bbdb" (string))
+(declare-function bbdb-record-get-field "ext:bbdb" (record field))
+(declare-function bbdb-search-name "ext:bbdb-com" (regexp &optional layout))
+(declare-function bbdb-search-organization "ext:bbdb-com" (regexp &optional layout))
+
+;; `bbdb-record-note' was part of BBDB v3.x
+(declare-function bbdb-record-note "ext:bbdb" (record label))
+;; `bbdb-record-xfield' replaces it in recent BBDB v3.x+
+(declare-function bbdb-record-xfield "ext:bbdb" (record label))
+
+(declare-function calendar-leap-year-p "calendar" (year))
+(declare-function diary-ordinal-suffix "diary-lib" (n))
+
+(with-no-warnings (defvar date)) ;; unprefixed, from calendar.el
+
+;; Customization
+
+(defgroup org-bbdb-anniversaries nil
+ "Customizations for including anniversaries from BBDB into Agenda."
+ :group 'org-bbdb)
+
+(defcustom org-bbdb-default-anniversary-format "birthday"
+ "Default anniversary class."
+ :type 'string
+ :group 'org-bbdb-anniversaries
+ :require 'bbdb)
+
+(defcustom org-bbdb-anniversary-format-alist
+ '(("birthday" .
+ (lambda (name years suffix)
+ (concat "Birthday: [[bbdb:" name "][" name " ("
+ (format "%s" years) ; handles numbers as well as strings
+ suffix ")]]")))
+ ("wedding" .
+ (lambda (name years suffix)
+ (concat "[[bbdb:" name "][" name "'s "
+ (format "%s" years)
+ suffix " wedding anniversary]]"))))
+ "How different types of anniversaries should be formatted.
+An alist of elements (STRING . FORMAT) where STRING is the name of an
+anniversary class and format is either:
+1) A format string with the following substitutions (in order):
+ - the name of the record containing this anniversary
+ - the number of years
+ - an ordinal suffix (st, nd, rd, th) for the year
+
+2) A function to be called with three arguments: NAME YEARS SUFFIX
+ (string int string) returning a string for the diary or nil.
+
+3) An Emacs Lisp form that should evaluate to a string (or nil) in the
+ scope of variables NAME, YEARS and SUFFIX (among others)."
+ :type '(alist :key-type (string :tag "Class")
+ :value-type (function :tag "Function"))
+ :group 'org-bbdb-anniversaries
+ :require 'bbdb)
+
+(defcustom org-bbdb-anniversary-field 'anniversary
+ "The BBDB field which contains anniversaries.
+The anniversaries are stored in the following format
+
+YYYY-MM-DD Class-or-Format-String
+
+where class is one of the customized classes for anniversaries;
+birthday and wedding are predefined. Format-String can take three
+substitutions 1) the name of the record containing this
+anniversary, 2) the number of years, and 3) an ordinal suffix for
+the year.
+
+Multiple anniversaries can be separated by \\n."
+ :type 'symbol
+ :group 'org-bbdb-anniversaries
+ :require 'bbdb)
+
+(defcustom org-bbdb-extract-date-fun 'org-bbdb-anniv-extract-date
+ "How to retrieve `month date year' from the anniversary field.
+
+Customize if you have already filled your BBDB with dates
+different from YYYY-MM-DD. The function must return a list (month
+date year)."
+ :type 'function
+ :group 'org-bbdb-anniversaries
+ :require 'bbdb)
+
+;; Install the link type
+(org-link-set-parameters "bbdb"
+ :follow #'org-bbdb-open
+ :export #'org-bbdb-export
+ :complete #'org-bbdb-complete-link
+ :store #'org-bbdb-store-link)
+
+;; Implementation
+(defun org-bbdb-store-link ()
+ "Store a link to a BBDB database entry."
+ (when (eq major-mode 'bbdb-mode)
+ ;; This is BBDB, we make this link!
+ (let* ((rec (bbdb-current-record))
+ (name (bbdb-record-name rec))
+ (company (if (fboundp 'bbdb-record-getprop)
+ (bbdb-record-getprop rec 'company)
+ (car (bbdb-record-field rec 'organization))))
+ (link (concat "bbdb:" name)))
+ (org-store-link-props :type "bbdb" :name name :company company
+ :link link :description name)
+ link)))
+
+(defun org-bbdb-export (path desc format)
+ "Create the export version of a BBDB link specified by PATH or DESC.
+If exporting to either HTML or LaTeX FORMAT the link will be
+italicized, in all other cases it is left unchanged."
+ (when (string= desc (format "bbdb:%s" path))
+ (setq desc path))
+ (cond
+ ((eq format 'html) (format "<i>%s</i>" desc))
+ ((eq format 'latex) (format "\\textit{%s}" desc))
+ ((eq format 'odt)
+ (format "<text:span text:style-name=\"Emphasis\">%s</text:span>" desc))
+ (t desc)))
+
+(defun org-bbdb-open (name)
+ "Follow a BBDB link to NAME."
+ (require 'bbdb-com)
+ (let ((inhibit-redisplay (not debug-on-error)))
+ (if (fboundp 'bbdb-name)
+ (org-bbdb-open-old name)
+ (org-bbdb-open-new name))))
+
+(defun org-bbdb-open-old (name)
+ (catch 'exit
+ ;; Exact match on name
+ (bbdb-name (concat "\\`" name "\\'") nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Exact match on name
+ (bbdb-company (concat "\\`" name "\\'") nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Partial match on name
+ (bbdb-name name nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Partial match on company
+ (bbdb-company name nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; General match including network address and notes
+ (bbdb name nil)
+ (when (= 0 (buffer-size (get-buffer "*BBDB*")))
+ (delete-window (get-buffer-window "*BBDB*"))
+ (error "No matching BBDB record"))))
+
+(defun org-bbdb-open-new (name)
+ (catch 'exit
+ ;; Exact match on name
+ (bbdb-search-name (concat "\\`" name "\\'") nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Exact match on name
+ (bbdb-search-organization (concat "\\`" name "\\'") nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Partial match on name
+ (bbdb-search-name name nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; Partial match on company
+ (bbdb-search-organization name nil)
+ (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
+ ;; General match including network address and notes
+ (bbdb name nil)
+ (when (= 0 (buffer-size (get-buffer "*BBDB*")))
+ (delete-window (get-buffer-window "*BBDB*"))
+ (error "No matching BBDB record"))))
+
+(defun org-bbdb-anniv-extract-date (time-str)
+ "Convert YYYY-MM-DD to (month date year).
+Argument TIME-STR is the value retrieved from BBDB. If YYYY- is omitted
+it will be considered unknown."
+ (pcase (org-split-string time-str "-")
+ (`(,a ,b nil) (list (string-to-number a) (string-to-number b) nil))
+ (`(,a ,b ,c) (list (string-to-number b)
+ (string-to-number c)
+ (string-to-number a)))))
+
+(defun org-bbdb-anniv-split (str)
+ "Split multiple entries in the BBDB anniversary field.
+Argument STR is the anniversary field in BBDB."
+ (let ((pos (string-match "[ \t]" str)))
+ (if pos (list (substring str 0 pos)
+ (bbdb-string-trim (substring str pos)))
+ (list str nil))))
+
+(defvar org-bbdb-anniv-hash nil
+ "A hash holding anniversaries extracted from BBDB.
+The hash table is created on first use.")
+
+(defvar org-bbdb-updated-p t
+ "This is non-nil if BBDB has been updated since we last built the hash.")
+
+(defun org-bbdb-make-anniv-hash ()
+ "Create a hash with anniversaries extracted from BBDB, for fast access.
+The anniversaries are assumed to be stored `org-bbdb-anniversary-field'."
+ (let ((old-bbdb (fboundp 'bbdb-record-getprop))
+ (record-func (if (fboundp 'bbdb-record-xfield)
+ 'bbdb-record-xfield
+ 'bbdb-record-note))
+ split tmp annivs)
+ (clrhash org-bbdb-anniv-hash)
+ (dolist (rec (bbdb-records))
+ (when (setq annivs (if old-bbdb
+ (bbdb-record-getprop
+ rec org-bbdb-anniversary-field)
+ (funcall record-func
+ rec org-bbdb-anniversary-field)))
+ (setq annivs (if old-bbdb
+ (bbdb-split annivs "\n")
+ ;; parameter order is reversed in new bbdb
+ (bbdb-split "\n" annivs)))
+ (while annivs
+ (setq split (org-bbdb-anniv-split (pop annivs)))
+ (pcase-let ((`(,m ,d ,y) (funcall org-bbdb-extract-date-fun
+ (car split))))
+ (setq tmp (gethash (list m d) org-bbdb-anniv-hash))
+ (puthash (list m d) (cons (list y
+ (bbdb-record-name rec)
+ (cadr split))
+ tmp)
+ org-bbdb-anniv-hash))))))
+ (setq org-bbdb-updated-p nil))
+
+(defun org-bbdb-updated (_rec)
+ "Record the fact that BBDB has been updated.
+This is used by Org to re-create the anniversary hash table."
+ (setq org-bbdb-updated-p t))
+
+(add-hook 'bbdb-after-change-hook 'org-bbdb-updated)
+
+;;;###autoload
+(defun org-bbdb-anniversaries ()
+ "Extract anniversaries from BBDB for display in the agenda."
+ (require 'bbdb)
+ (require 'diary-lib)
+ (unless (hash-table-p org-bbdb-anniv-hash)
+ (setq org-bbdb-anniv-hash
+ (make-hash-table :test 'equal :size 366)))
+
+ (when (or org-bbdb-updated-p
+ (= 0 (hash-table-count org-bbdb-anniv-hash)))
+ (org-bbdb-make-anniv-hash))
+
+ (let* ((m (car date)) ; month
+ (d (nth 1 date)) ; day
+ (y (nth 2 date)) ; year
+ (annivs (gethash (list m d) org-bbdb-anniv-hash))
+ (text ())
+ rec recs)
+
+ ;; we don't want to miss people born on Feb. 29th
+ (when (and (= m 3) (= d 1)
+ (not (null (gethash (list 2 29) org-bbdb-anniv-hash)))
+ (not (calendar-leap-year-p y)))
+ (setq recs (gethash (list 2 29) org-bbdb-anniv-hash))
+ (while (setq rec (pop recs))
+ (push rec annivs)))
+
+ (when annivs
+ (while (setq rec (pop annivs))
+ (when rec
+ (let* ((class (or (nth 2 rec)
+ org-bbdb-default-anniversary-format))
+ (form (or (cdr (assoc-string
+ class org-bbdb-anniversary-format-alist t))
+ class)) ; (as format string)
+ (name (nth 1 rec))
+ (years (if (eq (car rec) nil)
+ "unknown"
+ (- y (car rec))))
+ (suffix (if (eq (car rec) nil)
+ ""
+ (diary-ordinal-suffix years)))
+ (tmp (cond
+ ((functionp form)
+ (funcall form name years suffix))
+ ((listp form) (eval form))
+ (t (format form name years suffix)))))
+ (org-add-props tmp nil 'org-bbdb-name name)
+ (if text
+ (setq text (append text (list tmp)))
+ (setq text (list tmp)))))
+ ))
+ text))
+
+;;; Return list of anniversaries for today and the next n-1 (default: n=7) days.
+;;; This is meant to be used in an org file instead of org-bbdb-anniversaries:
+;;;
+;;; %%(org-bbdb-anniversaries-future)
+;;;
+;;; or
+;;;
+;;; %%(org-bbdb-anniversaries-future 3)
+;;;
+;;; to override the 7-day default.
+
+(defun org-bbdb-date-list (d n)
+ "Return a list of dates in (m d y) format from the given date D to n-1 days hence."
+ (let ((abs (calendar-absolute-from-gregorian d)))
+ (mapcar (lambda (i) (calendar-gregorian-from-absolute (+ abs i)))
+ (number-sequence 0 (1- n)))))
+
+;;;###autoload
+(defun org-bbdb-anniversaries-future (&optional n)
+ "Return list of anniversaries for today and the next n-1 days (default n=7)."
+ (let ((n (or n 7)))
+ (when (<= n 0)
+ (error "The (optional) argument of `org-bbdb-anniversaries-future' \
+must be positive"))
+ (let (
+ ;; List of relevant dates.
+ (dates (org-bbdb-date-list date n))
+ ;; Function to annotate text of each element of l with the
+ ;; anniversary date d.
+ (annotate-descriptions
+ (lambda (d l)
+ (mapcar (lambda (x)
+ ;; The assumption here is that x is a bbdb link
+ ;; of the form [[bbdb:name][description]].
+ ;; This function rather arbitrarily modifies
+ ;; the description by adding the date to it in
+ ;; a fixed format.
+ (string-match "]]" x)
+ (replace-match (format " -- %d-%02d-%02d\\&"
+ (nth 2 d)
+ (nth 0 d)
+ (nth 1 d))
+ nil nil x))
+ l))))
+ ;; Map a function that generates anniversaries for each date
+ ;; over the dates and nconc the results into a single list. When
+ ;; it is no longer necessary to support older versions of Emacs,
+ ;; this can be done with a cl-mapcan; for now, we use the (apply
+ ;; #'nconc ...) method for compatibility.
+ (apply #'nconc
+ (mapcar
+ (lambda (d)
+ (let ((date d))
+ ;; Rebind 'date' so that org-bbdb-anniversaries will
+ ;; be fooled into giving us the list for the given
+ ;; date and then annotate the descriptions for that
+ ;; date.
+ (funcall annotate-descriptions d (org-bbdb-anniversaries))))
+ dates)))))
+
+(defun org-bbdb-complete-link ()
+ "Read a bbdb link with name completion."
+ (require 'bbdb-com)
+ (let ((rec (bbdb-completing-read-record "Name: ")))
+ (concat "bbdb:"
+ (bbdb-record-name (if (listp rec)
+ (car rec)
+ rec)))))
+
+(defun org-bbdb-anniv-export-ical ()
+ "Extract anniversaries from BBDB and convert them to icalendar format."
+ (require 'bbdb)
+ (require 'diary-lib)
+ (unless (hash-table-p org-bbdb-anniv-hash)
+ (setq org-bbdb-anniv-hash
+ (make-hash-table :test 'equal :size 366)))
+ (when (or org-bbdb-updated-p
+ (= 0 (hash-table-count org-bbdb-anniv-hash)))
+ (org-bbdb-make-anniv-hash))
+ (maphash 'org-bbdb-format-vevent org-bbdb-anniv-hash))
+
+(defun org-bbdb-format-vevent (key recs)
+ (let (rec categ)
+ (while (setq rec (pop recs))
+ (setq categ (or (nth 2 rec) org-bbdb-default-anniversary-format))
+ (princ (format "BEGIN:VEVENT
+UID: ANNIV-%4i%02i%02i-%s
+DTSTART:%4i%02i%02i
+SUMMARY:%s
+DESCRIPTION:%s
+CATEGORIES:%s
+RRULE:FREQ=YEARLY
+END:VEVENT\n"
+ (nth 0 rec) (nth 0 key) (nth 1 key)
+ (mapconcat 'identity
+ (org-split-string (nth 1 rec) "[^a-zA-Z0-90]+")
+ "-")
+ (nth 0 rec) (nth 0 key) (nth 1 key)
+ (nth 1 rec)
+ (concat (capitalize categ) " " (nth 1 rec))
+ categ)))))
+
+(provide 'org-bbdb)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-bbdb.el ends here
diff --git a/lisp/org-bibtex.el b/lisp/org-bibtex.el
new file mode 100644
index 0000000..d81c9f1
--- /dev/null
+++ b/lisp/org-bibtex.el
@@ -0,0 +1,737 @@
+;;; org-bibtex.el --- Org links to BibTeX entries -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+;;
+;; Authors: Bastien Guerry <bzg@gnu.org>
+;; Carsten Dominik <carsten dot dominik at gmail dot com>
+;; Eric Schulte <schulte dot eric at gmail dot com>
+;; Keywords: org, wp, capture
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+;; This file implements links to database entries in BibTeX files.
+;; Instead of defining a special link prefix, it uses the normal file
+;; links combined with a custom search mechanism to find entries
+;; by reference key. And it constructs a nice description tag for
+;; the link that contains the author name, the year and a short title.
+;;
+;; It also stores detailed information about the entry so that
+;; capture templates can access and enter this information easily.
+;;
+;; The available properties for each entry are listed here:
+;;
+;; :author :publisher :volume :pages
+;; :editor :url :number :journal
+;; :title :year :series :address
+;; :booktitle :month :annote :abstract
+;; :key :btype
+;;
+;; Here is an example of a capture template that use some of this
+;; information (:author :year :title :journal :pages):
+;;
+;; (setq org-capture-templates
+;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
+;; In %:journal, %:pages.")))
+;;
+;; Let's say you want to capture this BibTeX entry:
+;;
+;; @Article{dolev83,
+;; author = {Danny Dolev and Andrew C. Yao},
+;; title = {On the security of public-key protocols},
+;; journal = {IEEE Transaction on Information Theory},
+;; year = 1983,
+;; volume = 2,
+;; number = 29,
+;; pages = {198--208},
+;; month = {Mars}
+;; }
+;;
+;; M-x `org-capture' on this entry will produce this buffer:
+;;
+;; =====================================================================
+;; * READ <== [point here]
+;;
+;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
+;;
+;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
+;; In IEEE Transaction on Information Theory, 198--208.
+;; =====================================================================
+;;
+;; Additionally, the following functions are now available for storing
+;; bibtex entries within Org documents.
+;;
+;; - Run `org-bibtex' to export the current file to a .bib.
+;;
+;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
+;; fill in missing field of either the current, or all headlines
+;;
+;; - Run `org-bibtex-create' to add a bibtex entry
+;;
+;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
+;; the active region, then call `org-bibtex-write' in a .org file to
+;; insert a heading for the read bibtex entry
+;;
+;; - All Bibtex information is taken from the document compiled by
+;; Andrew Roberts from the Bibtex manual, available at
+;; http://www.andy-roberts.net/res/writing/latex/bibentries.pdf
+;;
+;;; History:
+;;
+;; The link creation part has been part of Org for a long time.
+;;
+;; Creating better capture template information was inspired by a request
+;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
+;; and then implemented by Bastien Guerry.
+;;
+;; Eric Schulte eventually added the functions for translating between
+;; Org headlines and Bibtex entries, and for fleshing out the Bibtex
+;; fields of existing Org headlines.
+;;
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+(require 'bibtex)
+(require 'cl-lib)
+(require 'org-compat)
+
+(defvar org-agenda-overriding-header)
+(defvar org-agenda-search-view-always-boolean)
+(defvar org-bibtex-description nil) ; dynamically scoped from org.el
+(defvar org-id-locations)
+
+(declare-function bibtex-beginning-of-entry "bibtex" ())
+(declare-function bibtex-generate-autokey "bibtex" ())
+(declare-function bibtex-parse-entry "bibtex" (&optional content))
+(declare-function bibtex-url "bibtex" (&optional pos no-browse))
+
+
+;;; Bibtex data
+(defvar org-bibtex-types
+ '((:article
+ (:description . "An article from a journal or magazine")
+ (:required :author :title :journal :year)
+ (:optional :volume :number :pages :month :note))
+ (:book
+ (:description . "A book with an explicit publisher")
+ (:required (:editor :author) :title :publisher :year)
+ (:optional (:volume :number) :series :address :edition :month :note))
+ (:booklet
+ (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.")
+ (:required :title)
+ (:optional :author :howpublished :address :month :year :note))
+ (:conference
+ (:description . "")
+ (:required :author :title :booktitle :year)
+ (:optional :editor :pages :organization :publisher :address :month :note))
+ (:inbook
+ (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
+ (:required (:author :editor) :title (:chapter :pages) :publisher :year)
+ (:optional :crossref (:volume :number) :series :type :address :edition :month :note))
+ (:incollection
+ (:description . "A part of a book having its own title.")
+ (:required :author :title :booktitle :publisher :year)
+ (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note))
+ (:inproceedings
+ (:description . "An article in a conference proceedings")
+ (:required :author :title :booktitle :year)
+ (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note))
+ (:manual
+ (:description . "Technical documentation.")
+ (:required :title)
+ (:optional :author :organization :address :edition :month :year :note))
+ (:mastersthesis
+ (:description . "A Master’s thesis.")
+ (:required :author :title :school :year)
+ (:optional :type :address :month :note))
+ (:misc
+ (:description . "Use this type when nothing else fits.")
+ (:required)
+ (:optional :author :title :howpublished :month :year :note))
+ (:phdthesis
+ (:description . "A PhD thesis.")
+ (:required :author :title :school :year)
+ (:optional :type :address :month :note))
+ (:proceedings
+ (:description . "The proceedings of a conference.")
+ (:required :title :year)
+ (:optional :editor (:volume :number) :series :address :month :organization :publisher :note))
+ (:techreport
+ (:description . "A report published by a school or other institution.")
+ (:required :author :title :institution :year)
+ (:optional :type :address :month :note))
+ (:unpublished
+ (:description . "A document having an author and title, but not formally published.")
+ (:required :author :title :note)
+ (:optional :month :year)))
+ "Bibtex entry types with required and optional parameters.")
+
+(defvar org-bibtex-fields
+ '((: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.")
+ (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
+ (:author . "The name(s) of the author(s), in the format described in the LaTeX book. Remember, all names are separated with the and keyword, and not commas.")
+ (:booktitle . "Title of a book, part of which is being cited. See the LaTeX book for how to type titles. For book entries, use the title field instead.")
+ (:chapter . "A chapter (or section or whatever) number.")
+ (:crossref . "The database key of the entry being cross referenced.")
+ (:edition . "The edition of a book for example, 'Second'. This should be an ordinal, and should have the first letter capitalized, as shown here; the standard styles convert to lower case when necessary.")
+ (:editor . "Name(s) of editor(s), typed as indicated in the LaTeX book. If there is also an author field, then the editor field gives the editor of the book or collection in which the reference appears.")
+ (:howpublished . "How something strange has been published. The first word should be capitalized.")
+ (:institution . "The sponsoring institution of a technical report.")
+ (:journal . "A journal name.")
+ (:key . "Used for alphabetizing, cross-referencing, and creating a label when the author information is missing. This field should not be confused with the key that appears in the \\cite command and at the beginning of the database entry.")
+ (:month . "The month in which the work was published or, for an unpublished work, in which it was written. You should use the standard three-letter abbreviation,")
+ (:note . "Any additional information that can help the reader. The first word should be capitalized.")
+ (:number . "Any additional information that can help the reader. The first word should be capitalized.")
+ (:organization . "The organization that sponsors a conference or that publishes a manual.")
+ (:pages . "One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97 or 43+ (the ‘+’ in this last example indicates pages following that don’t form simple range). BibTEX requires double dashes for page ranges (--).")
+ (:publisher . "The publisher’s name.")
+ (:school . "The name of the school where a thesis was written.")
+ (:series . "The name of a series or set of books. When citing an entire book, the title field gives its title and an optional series field gives the name of a series or multi-volume set in which the book is published.")
+ (:title . "The work’s title, typed as explained in the LaTeX book.")
+ (:type . "The type of a technical report for example, 'Research Note'.")
+ (:volume . "The volume of a journal or multi-volume book.")
+ (: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)'"))
+ "Bibtex fields with descriptions.")
+
+(defvar org-bibtex-entries nil
+ "List to hold parsed bibtex entries.")
+
+(defcustom org-bibtex-autogen-keys nil
+ "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-bibtex-prefix nil
+ "Optional prefix for all bibtex property names.
+For example setting to `BIB_' would allow interoperability with fireforg."
+ :group 'org-bibtex
+ :version "24.1"
+ :type '(choice
+ (const nil)
+ (string)))
+
+(defcustom org-bibtex-treat-headline-as-title t
+ "Treat headline text as title if title property is absent.
+If an entry is missing a title property, use the headline text as
+the property. If this value is t, `org-bibtex-check' will ignore
+a missing title field."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-bibtex-export-arbitrary-fields nil
+ "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
+This only has effect if `org-bibtex-prefix' is defined, so as to
+ensure that other org-properties, such as CATEGORY or LOGGING are
+not placed in the exported bibtex entry."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-bibtex-key-property "CUSTOM_ID"
+ "Property that holds the bibtex key.
+By default, this is CUSTOM_ID, which enables easy linking to
+bibtex headlines from within an org file. This can be set to ID
+to enable global links, but only with great caution, as global
+IDs must be unique."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-bibtex-tags nil
+ "List of tag(s) that should be added to new bib entries."
+ :group 'org-bibtex
+ :version "24.1"
+ :type '(repeat :tag "Tag" (string)))
+
+(defcustom org-bibtex-tags-are-keywords nil
+ "Convert the value of the keywords field to tags and vice versa.
+
+When non-nil, comma-separated entries in a bibtex entry's keywords
+field will be converted to Org tags. Note: spaces will be escaped
+with underscores, and characters that are not permitted in Org
+tags will be removed.
+
+When non-nil, local tags in an Org entry will be exported as
+a comma-separated string of keywords when exported to bibtex.
+If `org-bibtex-inherit-tags' is non-nil, inherited tags will also
+be exported as keywords. Tags defined in `org-bibtex-tags' or
+`org-bibtex-no-export-tags' will not be exported."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-bibtex-no-export-tags nil
+ "List of tag(s) that should not be converted to keywords.
+This variable is relevant only if `org-bibtex-tags-are-keywords'
+is non-nil."
+ :group 'org-bibtex
+ :version "24.1"
+ :type '(repeat :tag "Tag" (string)))
+
+(defcustom org-bibtex-inherit-tags nil
+ "Controls whether inherited tags are converted to bibtex keywords.
+It is relevant only if `org-bibtex-tags-are-keywords' is non-nil.
+Tag inheritence itself is controlled by `org-use-tag-inheritence'
+and `org-exclude-tags-from-inheritence'."
+ :group 'org-bibtex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'boolean)
+
+(defcustom org-bibtex-type-property-name "btype"
+ "Property in which to store bibtex entry type (e.g., article)."
+ :group 'org-bibtex
+ :version "24.1"
+ :type 'string)
+
+
+;;; Utility functions
+(defun org-bibtex-get (property)
+ (let ((it (let ((org-special-properties
+ (delete "FILE" (copy-sequence org-special-properties))))
+ (or
+ (org-entry-get (point) (upcase property))
+ (org-entry-get (point) (concat org-bibtex-prefix
+ (upcase property)))))))
+ (when it (org-trim it))))
+
+(defun org-bibtex-put (property value)
+ (let ((prop (upcase (if (keywordp property)
+ (substring (symbol-name property) 1)
+ property))))
+ (org-set-property
+ (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
+ prop)
+ value)))
+
+(defun org-bibtex-headline ()
+ "Return a bibtex entry of the given headline as a string."
+ (letrec ((val (lambda (key lst) (cdr (assoc key lst))))
+ (to (lambda (string) (intern (concat ":" string))))
+ (from (lambda (key) (substring (symbol-name key) 1)))
+ (flatten (lambda (&rest lsts)
+ (apply #'append (mapcar
+ (lambda (e)
+ (if (listp e) (apply flatten e) (list e)))
+ lsts))))
+ (id (org-bibtex-get org-bibtex-key-property))
+ (type (org-bibtex-get org-bibtex-type-property-name))
+ (tags (when org-bibtex-tags-are-keywords
+ (delq nil
+ (mapcar
+ (lambda (tag)
+ (unless (member tag
+ (append org-bibtex-tags
+ org-bibtex-no-export-tags))
+ tag))
+ (if org-bibtex-inherit-tags
+ (org-get-tags-at)
+ (org-get-local-tags-at)))))))
+ (when type
+ (let ((entry (format
+ "@%s{%s,\n%s\n}\n" type id
+ (mapconcat
+ (lambda (pair)
+ (format " %s={%s}" (car pair) (cdr pair)))
+ (remove nil
+ (if (and org-bibtex-export-arbitrary-fields
+ org-bibtex-prefix)
+ (mapcar
+ (lambda (kv)
+ (let ((key (car kv)) (val0 (cdr kv)))
+ (when (and
+ (string-match org-bibtex-prefix key)
+ (not (string=
+ (downcase (concat org-bibtex-prefix
+ org-bibtex-type-property-name))
+ (downcase key))))
+ (cons (downcase (replace-regexp-in-string
+ org-bibtex-prefix "" key))
+ val0))))
+ (org-entry-properties nil 'standard))
+ (mapcar
+ (lambda (field)
+ (let ((value (or (org-bibtex-get (funcall from field))
+ (and (eq :title field)
+ (nth 4 (org-heading-components))))))
+ (when value (cons (funcall from field) value))))
+ (funcall flatten
+ (funcall val :required (funcall val (funcall to type) org-bibtex-types))
+ (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
+ ",\n"))))
+ (with-temp-buffer
+ (insert entry)
+ (when tags
+ (bibtex-beginning-of-entry)
+ (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
+ (progn (goto-char (match-end 1)) (insert ", "))
+ (search-forward ",\n" nil t)
+ (insert " keywords={},\n")
+ (search-backward "}," nil t))
+ (insert (mapconcat #'identity tags ", ")))
+ (buffer-string))))))
+
+(defun org-bibtex-ask (field)
+ (unless (assoc field org-bibtex-fields)
+ (error "Field:%s is not known" field))
+ (save-window-excursion
+ (let* ((name (substring (symbol-name field) 1))
+ (buf-name (format "*Bibtex Help %s*" name)))
+ (with-output-to-temp-buffer buf-name
+ (princ (cdr (assoc field org-bibtex-fields))))
+ (with-current-buffer buf-name (visual-line-mode 1))
+ (org-fit-window-to-buffer (get-buffer-window buf-name))
+ (let ((result (read-from-minibuffer (format "%s: " name))))
+ (when (> (length result) 0) result)))))
+
+(defun org-bibtex-autokey ()
+ "Generate an autokey for the current headline."
+ (org-bibtex-put org-bibtex-key-property
+ (if org-bibtex-autogen-keys
+ (let* ((entry (org-bibtex-headline))
+ (key
+ (with-temp-buffer
+ (insert entry)
+ (bibtex-generate-autokey))))
+ ;; test for duplicate IDs if using global ID
+ (when (and
+ (equal org-bibtex-key-property "ID")
+ (featurep 'org-id)
+ (hash-table-p org-id-locations)
+ (gethash key org-id-locations))
+ (warn "Another entry has the same ID"))
+ key)
+ (read-from-minibuffer "id: "))))
+
+(defun org-bibtex-fleshout (type &optional optional)
+ "Fleshout current heading, ensuring all required fields are present.
+With optional argument OPTIONAL, also prompt for optional fields."
+ (let ((val (lambda (key lst) (cdr (assoc key lst))))
+ (keyword (lambda (name) (intern (concat ":" (downcase name)))))
+ (name (lambda (keyword) (substring (symbol-name keyword) 1))))
+ (dolist (field (append
+ (if org-bibtex-treat-headline-as-title
+ (remove :title (funcall val :required (funcall val type org-bibtex-types)))
+ (funcall val :required (funcall val type org-bibtex-types)))
+ (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
+ (when (consp field) ; or'd pair of fields e.g., (:editor :author)
+ (let ((present (nth 0 (remove
+ nil
+ (mapcar
+ (lambda (f)
+ (when (org-bibtex-get (funcall name f)) f))
+ field)))))
+ (setf field (or present (funcall keyword
+ (completing-read
+ "Field: " (mapcar name field)))))))
+ (let ((name (funcall name field)))
+ (unless (org-bibtex-get name)
+ (let ((prop (org-bibtex-ask field)))
+ (when prop (org-bibtex-put name prop)))))))
+ (when (and type (assoc type org-bibtex-types)
+ (not (org-bibtex-get org-bibtex-key-property)))
+ (org-bibtex-autokey)))
+
+
+;;; Bibtex link functions
+(org-link-set-parameters "bibtex"
+ :follow #'org-bibtex-open
+ :store #'org-bibtex-store-link)
+
+(defun org-bibtex-open (path)
+ "Visit the bibliography entry on PATH."
+ (let* ((search (when (string-match "::\\(.+\\)\\'" path)
+ (match-string 1 path)))
+ (path (substring path 0 (match-beginning 0))))
+ (org-open-file path t nil search)))
+
+(defun org-bibtex-store-link ()
+ "Store a link to a BibTeX entry."
+ (when (eq major-mode 'bibtex-mode)
+ (let* ((search (org-create-file-search-in-bibtex))
+ (link (concat "file:" (abbreviate-file-name buffer-file-name)
+ "::" search))
+ (entry (mapcar ; repair strings enclosed in "..." or {...}
+ (lambda(c)
+ (if (string-match
+ "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
+ (cons (car c) (match-string 1 (cdr c))) c))
+ (save-excursion
+ (bibtex-beginning-of-entry)
+ (bibtex-parse-entry)))))
+ (org-store-link-props
+ :key (cdr (assoc "=key=" entry))
+ :author (or (cdr (assoc "author" entry)) "[no author]")
+ :editor (or (cdr (assoc "editor" entry)) "[no editor]")
+ :title (or (cdr (assoc "title" entry)) "[no title]")
+ :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
+ :journal (or (cdr (assoc "journal" entry)) "[no journal]")
+ :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
+ :pages (or (cdr (assoc "pages" entry)) "[no pages]")
+ :url (or (cdr (assoc "url" entry)) "[no url]")
+ :year (or (cdr (assoc "year" entry)) "[no year]")
+ :month (or (cdr (assoc "month" entry)) "[no month]")
+ :address (or (cdr (assoc "address" entry)) "[no address]")
+ :volume (or (cdr (assoc "volume" entry)) "[no volume]")
+ :number (or (cdr (assoc "number" entry)) "[no number]")
+ :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
+ :series (or (cdr (assoc "series" entry)) "[no series]")
+ :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
+ :btype (or (cdr (assoc "=type=" entry)) "[no type]")
+ :type "bibtex"
+ :link link
+ :description org-bibtex-description))))
+
+(defun org-create-file-search-in-bibtex ()
+ "Create the search string and description for a BibTeX database entry."
+ ;; Make a good description for this entry, using names, year and the title
+ ;; Put it into the `description' variable which is dynamically scoped.
+ (let ((bibtex-autokey-names 1)
+ (bibtex-autokey-names-stretch 1)
+ (bibtex-autokey-name-case-convert-function 'identity)
+ (bibtex-autokey-name-separator " & ")
+ (bibtex-autokey-additional-names " et al.")
+ (bibtex-autokey-year-length 4)
+ (bibtex-autokey-name-year-separator " ")
+ (bibtex-autokey-titlewords 3)
+ (bibtex-autokey-titleword-separator " ")
+ (bibtex-autokey-titleword-case-convert-function 'identity)
+ (bibtex-autokey-titleword-length 'infty)
+ (bibtex-autokey-year-title-separator ": "))
+ (setq org-bibtex-description (bibtex-generate-autokey)))
+ ;; Now parse the entry, get the key and return it.
+ (save-excursion
+ (bibtex-beginning-of-entry)
+ (cdr (assoc "=key=" (bibtex-parse-entry)))))
+
+(defun org-execute-file-search-in-bibtex (s)
+ "Find the link search string S as a key for a database entry."
+ (when (eq major-mode 'bibtex-mode)
+ ;; Yes, we want to do the search in this file.
+ ;; We construct a regexp that searches for "@entrytype{" followed by the key
+ (goto-char (point-min))
+ (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
+ (regexp-quote s) "[ \t\n]*,") nil t)
+ (goto-char (match-beginning 0)))
+ (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
+ ;; Use double prefix to indicate that any web link should be browsed
+ (let ((b (current-buffer)) (p (point)))
+ ;; Restore the window configuration because we just use the web link
+ (set-window-configuration org-window-config-before-follow-link)
+ (with-current-buffer b
+ (goto-char p)
+ (bibtex-url)))
+ (recenter 0)) ; Move entry start to beginning of window
+ ;; return t to indicate that the search is done.
+ t))
+
+;; Finally add the link search function to the right hook.
+(add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
+
+
+;;; Bibtex <-> Org headline translation functions
+(defun org-bibtex (filename)
+ "Export each headline in the current file to a bibtex entry.
+Headlines are exported using `org-bibtex-headline'."
+ (interactive
+ (list (read-file-name
+ "Bibtex file: " nil nil nil
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (and file
+ (file-name-nondirectory
+ (concat (file-name-sans-extension file) ".bib")))))))
+ (let ((error-point
+ (catch 'bib
+ (let ((bibtex-entries
+ (remove nil (org-map-entries
+ (lambda ()
+ (condition-case nil
+ (org-bibtex-headline)
+ (error (throw 'bib (point)))))))))
+ (with-temp-file filename
+ (insert (mapconcat #'identity bibtex-entries "\n")))
+ (message "Successfully exported %d BibTeX entries to %s"
+ (length bibtex-entries) filename) nil))))
+ (when error-point
+ (goto-char error-point)
+ (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
+
+(defun org-bibtex-check (&optional optional)
+ "Check the current headline for required fields.
+With prefix argument OPTIONAL also prompt for optional fields."
+ (interactive "P")
+ (save-restriction
+ (org-narrow-to-subtree)
+ (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
+ (when name (intern (concat ":" name))))))
+ (when type (org-bibtex-fleshout type optional)))))
+
+(defun org-bibtex-check-all (&optional optional)
+ "Check all headlines in the current file.
+With prefix argument OPTIONAL also prompt for optional fields."
+ (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
+
+(defun org-bibtex-create (&optional arg nonew)
+ "Create a new entry at the given level.
+With a prefix arg, query for optional fields as well.
+If nonew is t, add data to the headline of the entry at point."
+ (interactive "P")
+ (let* ((type (completing-read
+ "Type: " (mapcar (lambda (type)
+ (substring (symbol-name (car type)) 1))
+ org-bibtex-types)
+ nil nil (when nonew
+ (org-bibtex-get org-bibtex-type-property-name))))
+ (type (if (keywordp type) type (intern (concat ":" type))))
+ (org-bibtex-treat-headline-as-title (if nonew nil t)))
+ (unless (assoc type org-bibtex-types)
+ (error "Type:%s is not known" type))
+ (if nonew
+ (org-back-to-heading)
+ (org-insert-heading)
+ (let ((title (org-bibtex-ask :title)))
+ (insert title)
+ (org-bibtex-put "TITLE" title)))
+ (org-bibtex-put org-bibtex-type-property-name
+ (substring (symbol-name type) 1))
+ (org-bibtex-fleshout type arg)
+ (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on))))
+
+(defun org-bibtex-create-in-current-entry (&optional arg)
+ "Add bibliographical data to the current entry.
+With a prefix arg, query for optional fields."
+ (interactive "P")
+ (org-bibtex-create arg t))
+
+(defun org-bibtex-read ()
+ "Read a bibtex entry and save to `org-bibtex-entries'.
+This uses `bibtex-parse-entry'."
+ (interactive)
+ (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
+ (clean-space (lambda (str) (replace-regexp-in-string
+ "[[:space:]\n\r]+" " " str)))
+ (strip-delim
+ (lambda (str) ; strip enclosing "..." and {...}
+ (dolist (pair '((34 . 34) (123 . 125)))
+ (when (and (> (length str) 1)
+ (= (aref str 0) (car pair))
+ (= (aref str (1- (length str))) (cdr pair)))
+ (setf str (substring str 1 (1- (length str)))))) str)))
+ (push (mapcar
+ (lambda (pair)
+ (cons (let ((field (funcall keyword (car pair))))
+ (pcase field
+ (:=type= :type)
+ (:=key= :key)
+ (_ field)))
+ (funcall clean-space (funcall strip-delim (cdr pair)))))
+ (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
+ org-bibtex-entries)))
+
+(defun org-bibtex-read-buffer (buffer)
+ "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
+Return the number of saved entries."
+ (interactive "bBuffer: ")
+ (let ((start-length (length org-bibtex-entries)))
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char (point-max))
+ (while (not (= (point) (point-min)))
+ (backward-char 1)
+ (org-bibtex-read)
+ (bibtex-beginning-of-entry))))
+ (let ((added (- (length org-bibtex-entries) start-length)))
+ (message "Parsed %d entries" added)
+ added)))
+
+(defun org-bibtex-read-file (file)
+ "Read FILE with `org-bibtex-read-buffer'."
+ (interactive "fFile: ")
+ (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
+
+(defun org-bibtex-write ()
+ "Insert a heading built from the first element of `org-bibtex-entries'."
+ (interactive)
+ (when (= (length org-bibtex-entries) 0)
+ (error "No entries in `org-bibtex-entries'"))
+ (let* ((entry (pop org-bibtex-entries))
+ (org-special-properties nil) ; avoids errors with `org-entry-put'
+ (val (lambda (field) (cdr (assoc field entry))))
+ (togtag (lambda (tag) (org-toggle-tag tag 'on))))
+ (org-insert-heading)
+ (insert (funcall val :title))
+ (org-bibtex-put "TITLE" (funcall val :title))
+ (org-bibtex-put org-bibtex-type-property-name
+ (downcase (funcall val :type)))
+ (dolist (pair entry)
+ (pcase (car pair)
+ (:title nil)
+ (:type nil)
+ (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
+ (:keywords (if org-bibtex-tags-are-keywords
+ (dolist (kw (split-string (cdr pair) ", *"))
+ (funcall
+ togtag
+ (replace-regexp-in-string
+ "[^[:alnum:]_@#%]" ""
+ (replace-regexp-in-string "[ \t]+" "_" kw))))
+ (org-bibtex-put (car pair) (cdr pair))))
+ (_ (org-bibtex-put (car pair) (cdr pair)))))
+ (mapc togtag org-bibtex-tags)))
+
+(defun org-bibtex-yank ()
+ "If kill ring holds a bibtex entry yank it as an Org headline."
+ (interactive)
+ (let (entry)
+ (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
+ (if entry
+ (org-bibtex-write)
+ (error "Yanked text does not appear to contain a BibTeX entry"))))
+
+(defun org-bibtex-import-from-file (file)
+ "Read bibtex entries from FILE and insert as Org headlines after point."
+ (interactive "fFile: ")
+ (dotimes (_ (org-bibtex-read-file file))
+ (save-excursion (org-bibtex-write))
+ (re-search-forward org-property-end-re)
+ (open-line 1) (forward-char 1)))
+
+(defun org-bibtex-export-to-kill-ring ()
+ "Export current headline to kill ring as bibtex entry."
+ (interactive)
+ (let ((result (org-bibtex-headline)))
+ (kill-new result) result))
+
+(defun org-bibtex-search (string)
+ "Search for bibliographical entries in agenda files.
+This function relies `org-search-view' to locate results."
+ (interactive "sSearch string: ")
+ (let ((org-agenda-overriding-header "Bib search results:")
+ (org-agenda-search-view-always-boolean t))
+ (org-search-view nil
+ (format "%s +{:%s%s:}"
+ string (or org-bibtex-prefix "")
+ org-bibtex-type-property-name))))
+
+(provide 'org-bibtex)
+
+;;; org-bibtex.el ends here
diff --git a/lisp/org-capture.el b/lisp/org-capture.el
new file mode 100644
index 0000000..63e23cc
--- /dev/null
+++ b/lisp/org-capture.el
@@ -0,0 +1,1901 @@
+;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains an alternative implementation of the functionality
+;; that used to be provided by org-remember.el. The implementation is more
+;; streamlined, can produce more target types (e.g. plain list items or
+;; table lines). Also, it does not use a temporary buffer for editing
+;; the captured entry - instead it uses an indirect buffer that visits
+;; the new entry already in the target buffer (this was an idea by Samuel
+;; Wales). John Wiegley's excellent `remember.el' is not needed anymore
+;; for this implementation, even though we borrow heavily from its ideas.
+
+;; This implementation heavily draws on ideas by James TD Smith and
+;; Samuel Wales, and, of cause, uses John Wiegley's remember.el as inspiration.
+
+;;; TODO
+
+;; - find a clever way to not always insert an annotation maybe a
+;; predicate function that can check for conditions for %a to be
+;; used. This could be one of the properties.
+
+;; - Should there be plist members that arrange for properties to be
+;; asked for, like James proposed in his RFC?
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+
+(declare-function org-at-encrypted-entry-p "org-crypt" ())
+(declare-function org-datetree-find-date-create "org-datetree"
+ (date &optional keep-restriction))
+(declare-function org-decrypt-entry "org-crypt" ())
+(declare-function org-encrypt-entry "org-crypt" ())
+(declare-function org-table-analyze "org-table" ())
+(declare-function org-table-goto-line "org-table" (N))
+
+(defvar org-end-time-was-given)
+(defvar org-remember-default-headline)
+(defvar org-remember-templates)
+(defvar org-table-hlines)
+(defvar org-table-current-begin-pos)
+(defvar dired-buffers)
+
+(defvar org-capture-clock-was-started nil
+ "Internal flag, noting if the clock was started.")
+
+(defvar org-capture-last-stored-marker (make-marker)
+ "Marker pointing to the entry most recently stored with `org-capture'.")
+
+;; The following variable is scoped dynamically by org-protocol
+;; to indicate that the link properties have already been stored
+(defvar org-capture-link-is-already-stored nil)
+
+(defvar org-capture-is-refiling nil
+ "Non-nil when capture process is refiling an entry.")
+
+(defgroup org-capture nil
+ "Options concerning capturing new entries."
+ :tag "Org Capture"
+ :group 'org)
+
+(defcustom org-capture-templates nil
+ "Templates for the creation of new entries.
+
+Each entry is a list with the following items:
+
+keys The keys that will select the template, as a string, characters
+ only, for example \"a\" for a template to be selected with a
+ single key, or \"bt\" for selection with two keys. When using
+ several keys, keys using the same prefix key must be together
+ in the list and preceded by a 2-element entry explaining the
+ prefix key, for example
+
+ (\"b\" \"Templates for marking stuff to buy\")
+
+ The \"C\" key is used by default for quick access to the
+ customization of the template variable. But if you want to use
+ that key for a template, you can.
+
+description A short string describing the template, will be shown during
+ selection.
+
+type The type of entry. Valid types are:
+ entry an Org node, with a headline. Will be filed
+ as the child of the target entry or as a
+ top-level entry.
+ item a plain list item, will be placed in the
+ first plain list at the target
+ location.
+ checkitem a checkbox item. This differs from the
+ plain list item only is so far as it uses a
+ different default template.
+ table-line a new line in the first table at target location.
+ plain text to be inserted as it is.
+
+target Specification of where the captured item should be placed.
+ In Org files, targets usually define a node. Entries will
+ become children of this node, other types will be added to the
+ table or list in the body of this node.
+
+ Most target specifications contain a file name. If that file
+ name is the empty string, it defaults to `org-default-notes-file'.
+ A file can also be given as a variable, function, or Emacs Lisp
+ form. When an absolute path is not specified for a
+ target, it is taken as relative to `org-directory'.
+
+ Valid values are:
+
+ (file \"path/to/file\")
+ Text will be placed at the beginning or end of that file
+
+ (id \"id of existing Org entry\")
+ File as child of this entry, or in the body of the entry
+
+ (file+headline \"path/to/file\" \"node headline\")
+ Fast configuration if the target heading is unique in the file
+
+ (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
+ For non-unique headings, the full path is safer
+
+ (file+regexp \"path/to/file\" \"regexp to find location\")
+ File to the entry matching regexp
+
+ (file+datetree \"path/to/file\")
+ Will create a heading in a date tree for today's date
+
+ (file+datetree+prompt \"path/to/file\")
+ Will create a heading in a date tree, prompts for date
+
+ (file+weektree \"path/to/file\")
+ Will create a heading in a week tree for today's date
+
+ (file+weektree+prompt \"path/to/file\")
+ Will create a heading in a week tree, prompts for date
+
+ (file+function \"path/to/file\" function-finding-location)
+ A function to find the right location in the file
+
+ (clock)
+ File to the entry that is currently being clocked
+
+ (function function-finding-location)
+ Most general way: write your own function which both visits
+ the file and moves point to the right location
+
+template The template for creating the capture item. If you leave this
+ empty, an appropriate default template will be used. See below
+ for more details. Instead of a string, this may also be one of
+
+ (file \"/path/to/template-file\")
+ (function function-returning-the-template)
+
+ in order to get a template from a file, or dynamically
+ from a function.
+
+The rest of the entry is a property list of additional options. Recognized
+properties are:
+
+ :prepend Normally newly captured information will be appended at
+ the target location (last child, last table line,
+ last list item...). Setting this property will
+ change that.
+
+ :immediate-finish When set, do not offer to edit the information, just
+ file it away immediately. This makes sense if the
+ template only needs information that can be added
+ automatically.
+
+ :jump-to-captured When set, jump to the captured entry when finished.
+
+ :empty-lines Set this to the number of lines the should be inserted
+ before and after the new item. Default 0, only common
+ other value is 1.
+
+ :empty-lines-before Set this to the number of lines the should be inserted
+ before the new item. Overrides :empty-lines for the
+ number lines inserted before.
+
+ :empty-lines-after Set this to the number of lines the should be inserted
+ after the new item. Overrides :empty-lines for the
+ number of lines inserted after.
+
+ :clock-in Start the clock in this item.
+
+ :clock-keep Keep the clock running when filing the captured entry.
+
+ :clock-resume Start the interrupted clock when finishing the capture.
+ Note that :clock-keep has precedence over :clock-resume.
+ When setting both to t, the current clock will run and
+ the previous one will not be resumed.
+
+ :unnarrowed Do not narrow the target buffer, simply show the
+ full buffer. Default is to narrow it so that you
+ only see the new stuff.
+
+ :table-line-pos Specification of the location in the table where the
+ new line should be inserted. It should be a string like
+ \"II-3\", meaning that the new line should become the
+ third line before the second horizontal separator line.
+
+ :kill-buffer If the target file was not yet visited by a buffer when
+ capture was invoked, kill the buffer again after capture
+ is finalized.
+
+The template defines the text to be inserted. Often this is an
+Org mode entry (so the first line should start with a star) that
+will be filed as a child of the target headline. It can also be
+freely formatted text. Furthermore, the following %-escapes will
+be replaced with content and expanded:
+
+ %[pathname] Insert the contents of the file given by
+ `pathname'. These placeholders are expanded at the very
+ beginning of the process so they can be used to extend the
+ current template.
+ %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
+ Only placeholders pre-existing within the template, or
+ introduced with %[pathname] are expanded this way. Since this
+ happens after expanding non-interactive %-escapes, those can
+ be used to fill the expression.
+ %<...> The result of format-time-string on the ... format specification.
+ %t Time stamp, date only.
+ %T Time stamp with date and time.
+ %u, %U Like the above, but inactive time stamps.
+ %i Initial content, copied from the active region. If %i is
+ indented, the entire inserted text will be indented as well.
+ %a Annotation, normally the link created with `org-store-link'.
+ %A Like %a, but prompt for the description part.
+ %l Like %a, but only insert the literal link.
+ %c Current kill ring head.
+ %x Content of the X clipboard.
+ %k Title of currently clocked task.
+ %K Link to currently clocked task.
+ %n User name (taken from the variable `user-full-name').
+ %f File visited by current buffer when org-capture was called.
+ %F Full path of the file or directory visited by current buffer.
+ %:keyword Specific information for certain link types, see below.
+ %^g Prompt for tags, with completion on tags in target file.
+ %^G Prompt for tags, with completion on all tags in all agenda files.
+ %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
+ You may define a prompt like: %^{Please specify birthday}t
+ %^C Interactive selection of which kill or clip to use.
+ %^L Like %^C, but insert as link.
+ %^{prop}p Prompt the user for a value for property `prop'.
+ %^{prompt} Prompt the user for a string and replace this sequence with it.
+ A default value and a completion table ca be specified like this:
+ %^{prompt|default|completion2|completion3|...}.
+ %? After completing the template, position cursor here.
+ %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N
+ is a number, starting from 1.
+
+Apart from these general escapes, you can access information specific to
+the link type that is created. For example, calling `org-capture' in emails
+or in Gnus will record the author and the subject of the message, which you
+can access with \"%:from\" and \"%:subject\", respectively. Here is a
+complete list of what is recorded for each link type.
+
+Link type | Available information
+------------------------+------------------------------------------------------
+bbdb | %:type %:name %:company
+vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
+gnus | %:from %:fromname %:fromaddress
+ | %:to %:toname %:toaddress
+ | %:fromto (either \"to NAME\" or \"from NAME\")
+ | %:date %:date-timestamp (as active timestamp)
+ | %:date-timestamp-inactive (as inactive timestamp)
+gnus | %:group, for messages also all email fields
+eww, w3, w3m | %:type %:url
+info | %:type %:file %:node
+calendar | %:type %:date
+
+When you need to insert a literal percent sign in the template,
+you can escape ambiguous cases with a backward slash, e.g., \\%i."
+ :group 'org-capture
+ :version "24.1"
+ :type
+ (let ((file-variants '(choice :tag "Filename "
+ (file :tag "Literal")
+ (function :tag "Function")
+ (variable :tag "Variable")
+ (sexp :tag "Form"))))
+ `(repeat
+ (choice :value ("" "" entry (file "~/org/notes.org") "")
+ (list :tag "Multikey description"
+ (string :tag "Keys ")
+ (string :tag "Description"))
+ (list :tag "Template entry"
+ (string :tag "Keys ")
+ (string :tag "Description ")
+ (choice :tag "Capture Type " :value entry
+ (const :tag "Org entry" entry)
+ (const :tag "Plain list item" item)
+ (const :tag "Checkbox item" checkitem)
+ (const :tag "Plain text" plain)
+ (const :tag "Table line" table-line))
+ (choice :tag "Target location"
+ (list :tag "File"
+ (const :format "" file)
+ ,file-variants)
+ (list :tag "ID"
+ (const :format "" id)
+ (string :tag " ID"))
+ (list :tag "File & Headline"
+ (const :format "" file+headline)
+ ,file-variants
+ (string :tag " Headline"))
+ (list :tag "File & Outline path"
+ (const :format "" file+olp)
+ ,file-variants
+ (repeat :tag "Outline path" :inline t
+ (string :tag "Headline")))
+ (list :tag "File & Regexp"
+ (const :format "" file+regexp)
+ ,file-variants
+ (regexp :tag " Regexp"))
+ (list :tag "File & Date tree"
+ (const :format "" file+datetree)
+ ,file-variants)
+ (list :tag "File & Date tree, prompt for date"
+ (const :format "" file+datetree+prompt)
+ ,file-variants)
+ (list :tag "File & Week tree"
+ (const :format "" file+weektree)
+ ,file-variants)
+ (list :tag "File & Week tree, prompt for date"
+ (const :format "" file+weektree+prompt)
+ ,file-variants)
+ (list :tag "File & function"
+ (const :format "" file+function)
+ ,file-variants
+ (sexp :tag " Function"))
+ (list :tag "Current clocking task"
+ (const :format "" clock))
+ (list :tag "Function"
+ (const :format "" function)
+ (sexp :tag " Function")))
+ (choice :tag "Template "
+ (string)
+ (list :tag "File"
+ (const :format "" file)
+ (file :tag "Template file"))
+ (list :tag "Function"
+ (const :format "" function)
+ (function :tag "Template function")))
+ (plist :inline t
+ ;; Give the most common options as checkboxes
+ :options (((const :format "%v " :prepend) (const t))
+ ((const :format "%v " :immediate-finish) (const t))
+ ((const :format "%v " :jump-to-captured) (const t))
+ ((const :format "%v " :empty-lines) (const 1))
+ ((const :format "%v " :empty-lines-before) (const 1))
+ ((const :format "%v " :empty-lines-after) (const 1))
+ ((const :format "%v " :clock-in) (const t))
+ ((const :format "%v " :clock-keep) (const t))
+ ((const :format "%v " :clock-resume) (const t))
+ ((const :format "%v " :unnarrowed) (const t))
+ ((const :format "%v " :table-line-pos) (const t))
+ ((const :format "%v " :kill-buffer) (const t)))))))))
+
+(defcustom org-capture-before-finalize-hook nil
+ "Hook that is run right before a capture process is finalized.
+The capture buffer is still current when this hook runs and it is
+widened to the entire buffer."
+ :group 'org-capture
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-capture-after-finalize-hook nil
+ "Hook that is run right after a capture process is finalized.
+Suitable for window cleanup."
+ :group 'org-capture
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-capture-prepare-finalize-hook nil
+ "Hook that is run before the finalization starts.
+The capture buffer is current and still narrowed."
+ :group 'org-capture
+ :version "24.1"
+ :type 'hook)
+
+(defcustom org-capture-bookmark t
+ "When non-nil, add a bookmark pointing at the last stored
+position when capturing."
+ :group 'org-capture
+ :version "24.3"
+ :type 'boolean)
+
+;;; The property list for keeping information about the capture process
+
+(defvar org-capture-plist nil
+ "Plist for the current capture process, global, to avoid having to pass it.")
+
+(defvar org-capture-current-plist nil
+ "Local variable holding the plist in a capture buffer.
+This is used to store the plist for use when finishing a capture process
+because another such process might have changed the global variable by then.
+
+Each time a new capture buffer has been set up, the global `org-capture-plist'
+is copied to this variable, which is local in the indirect buffer.")
+
+(defvar org-capture-clock-keep nil
+ "Local variable to store the value of the :clock-keep parameter.
+This is needed in case org-capture-finalize is called interactively.")
+
+(defun org-capture-put (&rest stuff)
+ "Add properties to the capture property list `org-capture-plist'."
+ (while stuff
+ (setq org-capture-plist (plist-put org-capture-plist
+ (pop stuff) (pop stuff)))))
+(defun org-capture-get (prop &optional local)
+ "Get properties from the capture property list `org-capture-plist'.
+When LOCAL is set, use the local variable `org-capture-current-plist',
+this is necessary after initialization of the capture process,
+to avoid conflicts with other active capture processes."
+ (plist-get (if local org-capture-current-plist org-capture-plist) prop))
+
+(defun org-capture-member (prop &optional local)
+ "Is PROP a property in `org-capture-plist'.
+When LOCAL is set, use the local variable `org-capture-current-plist',
+this is necessary after initialization of the capture process,
+to avoid conflicts with other active capture processes."
+ (plist-get (if local org-capture-current-plist org-capture-plist) prop))
+
+;;; The minor mode
+
+(defvar org-capture-mode-map (make-sparse-keymap)
+ "Keymap for `org-capture-mode', a minor mode.
+Use this map to set additional keybindings for when Org mode is used
+for a capture buffer.")
+
+(defvar org-capture-mode-hook nil
+ "Hook for the minor `org-capture-mode'.")
+
+(define-minor-mode org-capture-mode
+ "Minor mode for special key bindings in a capture buffer.
+
+Turning on this mode runs the normal hook `org-capture-mode-hook'."
+ nil " Rem" org-capture-mode-map
+ (setq-local
+ header-line-format
+ (substitute-command-keys
+ "\\<org-capture-mode-map>Capture buffer. Finish \
+`\\[org-capture-finalize]', refile `\\[org-capture-refile]', \
+abort `\\[org-capture-kill]'.")))
+(define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize)
+(define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill)
+(define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile)
+
+;;; The main commands
+
+(defvar org-capture-initial nil)
+(defvar org-capture-entry nil)
+
+;;;###autoload
+(defun org-capture-string (string &optional keys)
+ "Capture STRING with the template selected by KEYS."
+ (interactive "sInitial text: \n")
+ (let ((org-capture-initial string)
+ (org-capture-entry (org-capture-select-template keys)))
+ (org-capture)))
+
+(defcustom org-capture-templates-contexts nil
+ "Alist of capture templates and valid contexts.
+
+For example, if you have a capture template \"c\" and you want
+this template to be accessible only from `message-mode' buffers,
+use this:
+
+ \\='((\"c\" ((in-mode . \"message-mode\"))))
+
+Here are the available contexts definitions:
+
+ in-file: command displayed only in matching files
+ in-mode: command displayed only in matching modes
+ not-in-file: command not displayed in matching files
+ not-in-mode: command not displayed in matching modes
+ in-buffer: command displayed only in matching buffers
+not-in-buffer: command not displayed in matching buffers
+ [function]: a custom function taking no argument
+
+If you define several checks, the agenda command will be
+accessible if there is at least one valid check.
+
+You can also bind a key to another agenda custom command
+depending on contextual rules.
+
+ \\='((\"c\" \"d\" ((in-mode . \"message-mode\"))))
+
+Here it means: in `message-mode buffers', use \"c\" as the
+key for the capture template otherwise associated with \"d\".
+\(The template originally associated with \"d\" is not displayed
+to avoid duplicates.)"
+ :version "24.3"
+ :group 'org-capture
+ :type '(repeat (list :tag "Rule"
+ (string :tag " Capture key")
+ (string :tag "Replace by template")
+ (repeat :tag "Available when"
+ (choice
+ (cons :tag "Condition"
+ (choice
+ (const :tag "In file" in-file)
+ (const :tag "Not in file" not-in-file)
+ (const :tag "In buffer" in-buffer)
+ (const :tag "Not in buffer" not-in-buffer)
+ (const :tag "In mode" in-mode)
+ (const :tag "Not in mode" not-in-mode))
+ (regexp))
+ (function :tag "Custom function"))))))
+
+(defcustom org-capture-use-agenda-date nil
+ "Non-nil means use the date at point when capturing from agendas.
+When nil, you can still capture using the date at point with
+`\\[org-agenda-capture]'."
+ :group 'org-capture
+ :version "24.3"
+ :type 'boolean)
+
+;;;###autoload
+(defun org-capture (&optional goto keys)
+ "Capture something.
+\\<org-capture-mode-map>
+This will let you select a template from `org-capture-templates', and
+then file the newly captured information. The text is immediately
+inserted at the target location, and an indirect buffer is shown where
+you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the \
+previous
+state of Emacs, so that you can continue your work.
+
+When called interactively with a `\\[universal-argument]' prefix argument \
+GOTO, don't
+capture anything, just go to the file/headline where the selected
+template stores its notes.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \
+the last note stored.
+
+When called with a `C-0' (zero) prefix, insert a template at point.
+
+ELisp programs can set KEYS to a string associated with a template
+in `org-capture-templates'. In this case, interactive selection
+will be bypassed.
+
+If `org-capture-use-agenda-date' is non-nil, capturing from the
+agenda will use the date at point as the default date. Then, a
+`C-1' prefix will tell the capture process to use the HH:MM time
+of the day at point (if any) or the current HH:MM time."
+ (interactive "P")
+ (when (and org-capture-use-agenda-date
+ (eq major-mode 'org-agenda-mode))
+ (setq org-overriding-default-time
+ (org-get-cursor-date (equal goto 1))))
+ (cond
+ ((equal goto '(4)) (org-capture-goto-target))
+ ((equal goto '(16)) (org-capture-goto-last-stored))
+ (t
+ ;; FIXME: Are these needed?
+ (let* ((orig-buf (current-buffer))
+ (annotation (if (and (boundp 'org-capture-link-is-already-stored)
+ org-capture-link-is-already-stored)
+ (plist-get org-store-link-plist :annotation)
+ (ignore-errors (org-store-link nil))))
+ (entry (or org-capture-entry (org-capture-select-template keys)))
+ initial)
+ (setq initial (or org-capture-initial
+ (and (org-region-active-p)
+ (buffer-substring (point) (mark)))))
+ (when (stringp initial)
+ (remove-text-properties 0 (length initial) '(read-only t) initial))
+ (when (stringp annotation)
+ (remove-text-properties 0 (length annotation)
+ '(read-only t) annotation))
+ (cond
+ ((equal entry "C")
+ (customize-variable 'org-capture-templates))
+ ((equal entry "q")
+ (user-error "Abort"))
+ (t
+ (org-capture-set-plist entry)
+ (org-capture-get-template)
+ (org-capture-put :original-buffer orig-buf
+ :original-file (or (buffer-file-name orig-buf)
+ (and (featurep 'dired)
+ (car (rassq orig-buf
+ dired-buffers))))
+ :original-file-nondirectory
+ (and (buffer-file-name orig-buf)
+ (file-name-nondirectory
+ (buffer-file-name orig-buf)))
+ :annotation annotation
+ :initial initial
+ :return-to-wconf (current-window-configuration)
+ :default-time
+ (or org-overriding-default-time
+ (org-current-time)))
+ (org-capture-set-target-location)
+ (condition-case error
+ (org-capture-put :template (org-capture-fill-template))
+ ((error quit)
+ (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
+ (error "Capture abort: %s" error)))
+
+ (setq org-capture-clock-keep (org-capture-get :clock-keep))
+ (if (equal goto 0)
+ ;;insert at point
+ (org-capture-insert-template-here)
+ (condition-case error
+ (org-capture-place-template
+ (eq (car (org-capture-get :target)) 'function))
+ ((error quit)
+ (if (and (buffer-base-buffer (current-buffer))
+ (string-prefix-p "CAPTURE-" (buffer-name)))
+ (kill-buffer (current-buffer)))
+ (set-window-configuration (org-capture-get :return-to-wconf))
+ (error "Capture template `%s': %s"
+ (org-capture-get :key)
+ (nth 1 error))))
+ (if (and (derived-mode-p 'org-mode)
+ (org-capture-get :clock-in))
+ (condition-case nil
+ (progn
+ (if (org-clock-is-active)
+ (org-capture-put :interrupted-clock
+ (copy-marker org-clock-marker)))
+ (org-clock-in)
+ (setq-local org-capture-clock-was-started t))
+ (error
+ "Could not start the clock in this capture buffer")))
+ (if (org-capture-get :immediate-finish)
+ (org-capture-finalize)))))))))
+
+(defun org-capture-get-template ()
+ "Get the template from a file or a function if necessary."
+ (let ((txt (org-capture-get :template)) file)
+ (cond
+ ((and (listp txt) (eq (car txt) 'file))
+ (if (file-exists-p
+ (setq file (expand-file-name (nth 1 txt) org-directory)))
+ (setq txt (org-file-contents file))
+ (setq txt (format "* Template file %s not found" (nth 1 txt)))))
+ ((and (listp txt) (eq (car txt) 'function))
+ (if (fboundp (nth 1 txt))
+ (setq txt (funcall (nth 1 txt)))
+ (setq txt (format "* Template function %s not found" (nth 1 txt)))))
+ ((not txt) (setq txt ""))
+ ((stringp txt))
+ (t (setq txt "* Invalid capture template")))
+ (org-capture-put :template txt)))
+
+(defun org-capture-finalize (&optional stay-with-capture)
+ "Finalize the capture process.
+With prefix argument STAY-WITH-CAPTURE, jump to the location of the
+captured item after finalizing."
+ (interactive "P")
+ (when (org-capture-get :jump-to-captured)
+ (setq stay-with-capture t))
+ (unless (and org-capture-mode
+ (buffer-base-buffer (current-buffer)))
+ (error "This does not seem to be a capture buffer for Org mode"))
+
+ (run-hooks 'org-capture-prepare-finalize-hook)
+
+ ;; Did we start the clock in this capture buffer?
+ (when (and org-capture-clock-was-started
+ org-clock-marker (marker-buffer org-clock-marker)
+ (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
+ (> org-clock-marker (point-min))
+ (< org-clock-marker (point-max)))
+ ;; Looks like the clock we started is still running. Clock out.
+ (when (not org-capture-clock-keep) (let (org-log-note-clock-out) (org-clock-out)))
+ (when (and (not org-capture-clock-keep)
+ (org-capture-get :clock-resume 'local)
+ (markerp (org-capture-get :interrupted-clock 'local))
+ (buffer-live-p (marker-buffer
+ (org-capture-get :interrupted-clock 'local))))
+ (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
+ (org-with-point-at clock-in-task
+ (org-clock-in)))
+ (message "Interrupted clock has been resumed")))
+
+ (let ((beg (point-min))
+ (end (point-max))
+ (abort-note nil))
+ ;; Store the size of the capture buffer
+ (org-capture-put :captured-entry-size (- (point-max) (point-min)))
+ (widen)
+ ;; Store the insertion point in the target buffer
+ (org-capture-put :insertion-point (point))
+
+ (if org-note-abort
+ (let ((m1 (org-capture-get :begin-marker 'local))
+ (m2 (org-capture-get :end-marker 'local)))
+ (if (and m1 m2 (= m1 beg) (= m2 end))
+ (progn
+ (setq m2 (if (cdr (assq 'heading org-blank-before-new-entry))
+ m2 (1+ m2))
+ m2 (if (< (point-max) m2) (point-max) m2))
+ (setq abort-note 'clean)
+ (kill-region m1 m2))
+ (setq abort-note 'dirty)))
+
+ ;; Postprocessing: Update Statistics cookies, do the sorting
+ (when (derived-mode-p 'org-mode)
+ (save-excursion
+ (when (ignore-errors (org-back-to-heading))
+ (org-update-parent-todo-statistics)
+ (org-update-checkbox-count)))
+ ;; FIXME Here we should do the sorting
+ ;; If we have added a table line, maybe recompute?
+ (when (and (eq (org-capture-get :type 'local) 'table-line)
+ (org-at-table-p))
+ (if (org-table-get-stored-formulas)
+ (org-table-recalculate 'all) ;; FIXME: Should we iterate???
+ (org-table-align))))
+ ;; Store this place as the last one where we stored something
+ ;; Do the marking in the base buffer, so that it makes sense after
+ ;; the indirect buffer has been killed.
+ (org-capture-store-last-position)
+
+ ;; Run the hook
+ (run-hooks 'org-capture-before-finalize-hook))
+
+ (when (org-capture-get :decrypted)
+ (save-excursion
+ (goto-char (org-capture-get :decrypted))
+ (org-encrypt-entry)))
+
+ ;; Kill the indirect buffer
+ (save-buffer)
+ (let ((return-wconf (org-capture-get :return-to-wconf 'local))
+ (new-buffer (org-capture-get :new-buffer 'local))
+ (kill-buffer (org-capture-get :kill-buffer 'local))
+ (base-buffer (buffer-base-buffer (current-buffer))))
+
+ ;; Kill the indirect buffer
+ (kill-buffer (current-buffer))
+
+ ;; Narrow back the target buffer to its previous state
+ (with-current-buffer (org-capture-get :buffer)
+ (let ((reg (org-capture-get :initial-target-region))
+ (pos (org-capture-get :initial-target-position))
+ (ipt (org-capture-get :insertion-point))
+ (size (org-capture-get :captured-entry-size)))
+ (if (not reg)
+ (widen)
+ (cond ((< ipt (car reg))
+ ;; insertion point is before the narrowed region
+ (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
+ ((> ipt (cdr reg))
+ ;; insertion point is after the narrowed region
+ (narrow-to-region (car reg) (cdr reg)))
+ (t
+ ;; insertion point is within the narrowed region
+ (narrow-to-region (car reg) (+ size (cdr reg)))))
+ ;; now place back the point at its original position
+ (if (< ipt (car reg))
+ (goto-char (+ size pos))
+ (goto-char (if (< ipt pos) (+ size pos) pos))))))
+
+ ;; Kill the target buffer if that is desired
+ (when (and base-buffer new-buffer kill-buffer)
+ (with-current-buffer base-buffer (save-buffer))
+ (kill-buffer base-buffer))
+
+ ;; Restore the window configuration before capture
+ (set-window-configuration return-wconf))
+
+ (run-hooks 'org-capture-after-finalize-hook)
+ ;; Special cases
+ (cond
+ (abort-note
+ (cl-case abort-note
+ (clean
+ (message "Capture process aborted and target buffer cleaned up"))
+ (dirty
+ (error "Capture process aborted, but target buffer could not be \
+cleaned up correctly"))))
+ (stay-with-capture
+ (org-capture-goto-last-stored)))
+ ;; Return if we did store something
+ (not abort-note)))
+
+(defun org-capture-refile ()
+ "Finalize the current capture and then refile the entry.
+Refiling is done from the base buffer, because the indirect buffer is then
+already gone. Any prefix argument will be passed to the refile command."
+ (interactive)
+ (unless (eq (org-capture-get :type 'local) 'entry)
+ (user-error "Refiling from a capture buffer makes only sense \
+for `entry'-type templates"))
+ (let* ((base (or (buffer-base-buffer) (current-buffer)))
+ (pos (make-marker))
+ (org-capture-is-refiling t)
+ (kill-buffer (org-capture-get :kill-buffer 'local)))
+ ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
+ ;; empty lines) around entry, use a marker to refer to the
+ ;; headline to be refiled. Place the marker in the base buffer,
+ ;; as the current indirect one is going to be killed.
+ (set-marker pos (save-excursion (org-back-to-heading t) (point)) base)
+ (org-capture-put :kill-buffer nil)
+ (unwind-protect
+ (progn
+ (org-capture-finalize)
+ (save-window-excursion
+ (with-current-buffer base
+ (org-with-wide-buffer
+ (goto-char pos)
+ (call-interactively 'org-refile))))
+ (when kill-buffer (kill-buffer base)))
+ (set-marker pos nil))))
+
+(defun org-capture-kill ()
+ "Abort the current capture process."
+ (interactive)
+ ;; FIXME: This does not do the right thing, we need to remove the
+ ;; new stuff by hand it is easy: undo, then kill the buffer
+ (let ((org-note-abort t)
+ (org-capture-before-finalize-hook nil))
+ (org-capture-finalize)))
+
+(defun org-capture-goto-last-stored ()
+ "Go to the location where the last capture note was stored."
+ (interactive)
+ (org-goto-marker-or-bmk org-capture-last-stored-marker
+ (plist-get org-bookmark-names-plist
+ :last-capture))
+ (message "This is the last note stored by a capture process"))
+
+;;; Supporting functions for handling the process
+
+(defun org-capture-put-target-region-and-position ()
+ "Store the initial region with `org-capture-put'."
+ (org-capture-put
+ :initial-target-region
+ ;; Check if the buffer is currently narrowed
+ (when (org-buffer-narrowed-p)
+ (cons (point-min) (point-max))))
+ ;; store the current point
+ (org-capture-put :initial-target-position (point)))
+
+(defvar org-time-was-given) ; dynamically scoped parameter
+(defun org-capture-set-target-location (&optional target)
+ "Find TARGET buffer and position.
+Store them in the capture property list."
+ (let ((target-entry-p t) decrypted-hl-pos)
+ (setq target (or target (org-capture-get :target)))
+ (save-excursion
+ (cond
+ ((eq (car target) 'file)
+ (set-buffer (org-capture-target-buffer (nth 1 target)))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (setq target-entry-p nil))
+
+ ((eq (car target) 'id)
+ (let ((loc (org-id-find (nth 1 target))))
+ (if (not loc)
+ (error "Cannot find target ID \"%s\"" (nth 1 target))
+ (set-buffer (org-capture-target-buffer (car loc)))
+ (widen)
+ (org-capture-put-target-region-and-position)
+ (goto-char (cdr loc)))))
+
+ ((eq (car target) 'file+headline)
+ (set-buffer (org-capture-target-buffer (nth 1 target)))
+ (unless (derived-mode-p 'org-mode)
+ (error
+ "Target buffer \"%s\" for file+headline should be in Org mode"
+ (current-buffer)))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (let ((hd (nth 2 target)))
+ (goto-char (point-min))
+ (if (re-search-forward
+ (format org-complex-heading-regexp-format (regexp-quote hd))
+ nil t)
+ (goto-char (point-at-bol))
+ (goto-char (point-max))
+ (or (bolp) (insert "\n"))
+ (insert "* " hd "\n")
+ (beginning-of-line 0))))
+
+ ((eq (car target) 'file+olp)
+ (let ((m (org-find-olp
+ (cons (org-capture-expand-file (nth 1 target))
+ (cddr target)))))
+ (set-buffer (marker-buffer m))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (goto-char m)))
+
+ ((eq (car target) 'file+regexp)
+ (set-buffer (org-capture-target-buffer (nth 1 target)))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (goto-char (point-min))
+ (if (re-search-forward (nth 2 target) nil t)
+ (progn
+ (goto-char (if (org-capture-get :prepend)
+ (match-beginning 0) (match-end 0)))
+ (org-capture-put :exact-position (point))
+ (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
+ (error "No match for target regexp in file %s" (nth 1 target))))
+
+ ((memq (car target) '(file+datetree file+datetree+prompt file+weektree file+weektree+prompt))
+ (require 'org-datetree)
+ (set-buffer (org-capture-target-buffer (nth 1 target)))
+ (unless (derived-mode-p 'org-mode)
+ (error "Target buffer \"%s\" for %s should be in Org mode"
+ (current-buffer)
+ (car target)))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ ;; Make a date/week tree entry, with the current date (or
+ ;; yesterday, if we are extending dates for a couple of hours)
+ (funcall
+ (cond
+ ((memq (car target) '(file+weektree file+weektree+prompt))
+ #'org-datetree-find-iso-week-create)
+ (t #'org-datetree-find-date-create))
+ (calendar-gregorian-from-absolute
+ (cond
+ (org-overriding-default-time
+ ;; use the overriding default time
+ (time-to-days org-overriding-default-time))
+
+ ((memq (car target) '(file+datetree+prompt file+weektree+prompt))
+ ;; prompt for date
+ (let ((prompt-time (org-read-date
+ nil t nil "Date for tree entry:"
+ (current-time))))
+ (org-capture-put
+ :default-time
+ (cond ((and (or (not (boundp 'org-time-was-given))
+ (not org-time-was-given))
+ (not (= (time-to-days prompt-time) (org-today))))
+ ;; Use 00:00 when no time is given for another date than today?
+ (apply #'encode-time
+ (append '(0 0 0)
+ (cl-cdddr (decode-time prompt-time)))))
+ ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)" org-read-date-final-answer)
+ ;; Replace any time range by its start
+ (apply 'encode-time
+ (org-read-date-analyze
+ (replace-match "\\1 \\2" nil nil org-read-date-final-answer)
+ prompt-time (decode-time prompt-time))))
+ (t prompt-time)))
+ (time-to-days prompt-time)))
+ (t
+ ;; current date, possibly corrected for late night workers
+ (org-today))))))
+
+ ((eq (car target) 'file+function)
+ (set-buffer (org-capture-target-buffer (nth 1 target)))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (funcall (nth 2 target))
+ (org-capture-put :exact-position (point))
+ (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
+
+ ((eq (car target) 'function)
+ (funcall (nth 1 target))
+ (org-capture-put :exact-position (point))
+ (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
+
+ ((eq (car target) 'clock)
+ (if (and (markerp org-clock-hd-marker)
+ (marker-buffer org-clock-hd-marker))
+ (progn (set-buffer (marker-buffer org-clock-hd-marker))
+ (org-capture-put-target-region-and-position)
+ (widen)
+ (goto-char org-clock-hd-marker))
+ (error "No running clock that could be used as capture target")))
+
+ (t (error "Invalid capture target specification")))
+
+ (when (and (featurep 'org-crypt) (org-at-encrypted-entry-p))
+ (org-decrypt-entry)
+ (setq decrypted-hl-pos
+ (save-excursion (and (org-back-to-heading t) (point)))))
+
+ (org-capture-put :buffer (current-buffer) :pos (point)
+ :target-entry-p target-entry-p
+ :decrypted decrypted-hl-pos))))
+
+(defun org-capture-expand-file (file)
+ "Expand functions, symbols and file names for FILE.
+When FILE is a function, call it. When it is a form, evaluate
+it. When it is a variable, retrieve the value. When it is
+a string, treat it as a file name, possibly expanding it
+according to `org-directory', and return it. If it is the empty
+string, however, return `org-default-notes-file'. In any other
+case, raise an error."
+ (cond
+ ((equal file "") org-default-notes-file)
+ ((stringp file) (expand-file-name file org-directory))
+ ((functionp file) (funcall file))
+ ((and (symbolp file) (boundp file)) (symbol-value file))
+ ((consp file) (eval file))
+ (t file)))
+
+(defun org-capture-target-buffer (file)
+ "Get a buffer for FILE.
+FILE is a generalized file location, as handled by
+`org-capture-expand-file'."
+ (let ((file (or (org-string-nw-p (org-capture-expand-file file))
+ org-default-notes-file
+ (error "No notes file specified, and no default available"))))
+ (or (org-find-base-buffer-visiting file)
+ (progn (org-capture-put :new-buffer t)
+ (find-file-noselect file)))))
+
+(defun org-capture-place-template (&optional inhibit-wconf-store)
+ "Insert the template at the target location, and display the buffer.
+When `inhibit-wconf-store', don't store the window configuration, as it
+may have been stored before."
+ (unless inhibit-wconf-store
+ (org-capture-put :return-to-wconf (current-window-configuration)))
+ (delete-other-windows)
+ (org-switch-to-buffer-other-window
+ (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
+ (widen)
+ (outline-show-all)
+ (goto-char (org-capture-get :pos))
+ (setq-local outline-level 'org-outline-level)
+ (pcase (org-capture-get :type)
+ ((or `nil `entry) (org-capture-place-entry))
+ (`table-line (org-capture-place-table-line))
+ (`plain (org-capture-place-plain-text))
+ (`item (org-capture-place-item))
+ (`checkitem (org-capture-place-item)))
+ (org-capture-mode 1)
+ (setq-local org-capture-current-plist org-capture-plist))
+
+(defun org-capture-place-entry ()
+ "Place the template as a new Org entry."
+ (let ((reversed? (org-capture-get :prepend))
+ level)
+ (when (org-capture-get :exact-position)
+ (goto-char (org-capture-get :exact-position)))
+ (cond
+ ;; Insert as a child of the current entry.
+ ((org-capture-get :target-entry-p)
+ (setq level (org-get-valid-level
+ (if (org-at-heading-p) (org-outline-level) 1)
+ 1))
+ (if reversed? (outline-next-heading) (org-end-of-subtree t)))
+ ;; Insert as a top-level entry at the beginning of the file.
+ (reversed?
+ (goto-char (point-min))
+ (unless (org-at-heading-p) (outline-next-heading)))
+ ;; Otherwise, insert as a top-level entry at the end of the file.
+ (t (goto-char (point-max))))
+ (unless (bolp) (insert "\n"))
+ (org-capture-empty-lines-before)
+ (let ((beg (point))
+ (template (org-capture-get :template)))
+ (org-capture-verify-tree template)
+ (org-paste-subtree level template 'for-yank)
+ (org-capture-empty-lines-after)
+ (org-capture-position-for-last-stored beg)
+ (unless (org-at-heading-p) (outline-next-heading))
+ (let ((end (point)))
+ (org-capture-mark-kill-region beg end)
+ (org-capture-narrow beg end)
+ (when (or (re-search-backward "%\\?" beg t)
+ (re-search-forward "%\\?" end t))
+ (replace-match ""))))))
+
+(defun org-capture-place-item ()
+ "Place the template as a new plain list item."
+ (let* ((txt (org-capture-get :template))
+ (target-entry-p (org-capture-get :target-entry-p))
+ (ind 0)
+ beg end)
+ (if (org-capture-get :exact-position)
+ (goto-char (org-capture-get :exact-position))
+ (cond
+ ((not target-entry-p)
+ ;; Insert as top-level entry, either at beginning or at end of file
+ (setq beg (point-min) end (point-max)))
+ (t
+ (setq beg (1+ (point-at-eol))
+ end (save-excursion (outline-next-heading) (point)))))
+ (setq ind nil)
+ (if (org-capture-get :prepend)
+ (progn
+ (goto-char beg)
+ (when (org-list-search-forward (org-item-beginning-re) end t)
+ (goto-char (match-beginning 0))
+ (setq ind (org-get-indentation))))
+ (goto-char end)
+ (when (org-list-search-backward (org-item-beginning-re) beg t)
+ (setq ind (org-get-indentation))
+ (org-end-of-item)))
+ (unless ind (goto-char end)))
+ ;; Remove common indentation
+ (setq txt (org-remove-indentation txt))
+ ;; Make sure this is indeed an item
+ (unless (string-match (concat "\\`" (org-item-re)) txt)
+ (setq txt (concat "- "
+ (mapconcat 'identity (split-string txt "\n")
+ "\n "))))
+ ;; Prepare surrounding empty lines.
+ (org-capture-empty-lines-before)
+ (setq beg (point))
+ (unless (eolp) (save-excursion (insert "\n")))
+ (unless ind
+ (org-indent-line)
+ (setq ind (org-get-indentation))
+ (delete-region beg (point)))
+ ;; Set the correct indentation, depending on context
+ (setq ind (make-string ind ?\ ))
+ (setq txt (concat ind
+ (mapconcat 'identity (split-string txt "\n")
+ (concat "\n" ind))
+ "\n"))
+ ;; Insert item.
+ (insert txt)
+ (org-capture-empty-lines-after)
+ (org-capture-position-for-last-stored beg)
+ (forward-char 1)
+ (setq end (point))
+ (org-capture-mark-kill-region beg (1- end))
+ (org-capture-narrow beg (1- end))
+ (if (or (re-search-backward "%\\?" beg t)
+ (re-search-forward "%\\?" end t))
+ (replace-match ""))))
+
+(defun org-capture-place-table-line ()
+ "Place the template as a table line."
+ (require 'org-table)
+ (let* ((txt (org-capture-get :template))
+ (target-entry-p (org-capture-get :target-entry-p))
+ (table-line-pos (org-capture-get :table-line-pos))
+ beg end)
+ (cond
+ ((org-capture-get :exact-position)
+ (goto-char (org-capture-get :exact-position)))
+ ((not target-entry-p)
+ ;; Table is not necessarily under a heading
+ (setq beg (point-min) end (point-max)))
+ (t
+ ;; WE are at a heading, limit search to the body
+ (setq beg (1+ (point-at-eol))
+ end (save-excursion (outline-next-heading) (point)))))
+ (if (re-search-forward org-table-dataline-regexp end t)
+ (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
+ (goto-char e)
+ (if (looking-at "[ \t]*#\\+tblfm:")
+ (forward-line 1))
+ (narrow-to-region b (point)))
+ (goto-char end)
+ (insert "\n| |\n|----|\n| |\n")
+ (narrow-to-region (1+ end) (point)))
+ ;; We are narrowed to the table, or to an empty line if there was no table
+
+ ;; Check if the template is good
+ (if (not (string-match org-table-dataline-regexp txt))
+ (setq txt "| %?Bad template |\n"))
+ (if (functionp table-line-pos)
+ (setq table-line-pos (funcall table-line-pos))
+ (setq table-line-pos (eval table-line-pos)))
+ (cond
+ ((and table-line-pos
+ (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
+ (goto-char (point-min))
+ ;; we have a complex line specification
+ (let ((ll (ignore-errors
+ (save-match-data (org-table-analyze))
+ (aref org-table-hlines
+ (- (match-end 1) (match-beginning 1)))))
+ (delta (string-to-number (match-string 2 table-line-pos))))
+ ;; The user wants a special position in the table
+ (unless ll
+ (error "Invalid table line specification \"%s\"" table-line-pos))
+ (goto-char org-table-current-begin-pos)
+ (forward-line (+ ll delta (if (< delta 0) 0 -1)))
+ (org-table-insert-row 'below)
+ (beginning-of-line 1)
+ (delete-region (point) (1+ (point-at-eol)))
+ (setq beg (point))
+ (insert txt)
+ (setq end (point))))
+ ((org-capture-get :prepend)
+ (goto-char (point-min))
+ (re-search-forward org-table-hline-regexp nil t)
+ (beginning-of-line 1)
+ (re-search-forward org-table-dataline-regexp nil t)
+ (beginning-of-line 1)
+ (setq beg (point))
+ (org-table-insert-row)
+ (beginning-of-line 1)
+ (delete-region (point) (1+ (point-at-eol)))
+ (insert txt)
+ (setq end (point)))
+ (t
+ (goto-char (point-max))
+ (re-search-backward org-table-dataline-regexp nil t)
+ (beginning-of-line 1)
+ (org-table-insert-row 'below)
+ (beginning-of-line 1)
+ (delete-region (point) (1+ (point-at-eol)))
+ (setq beg (point))
+ (insert txt)
+ (setq end (point))))
+ (goto-char beg)
+ (org-capture-position-for-last-stored 'table-line)
+ (if (or (re-search-backward "%\\?" beg t)
+ (re-search-forward "%\\?" end t))
+ (replace-match ""))
+ (org-table-align)))
+
+(defun org-capture-place-plain-text ()
+ "Place the template plainly.
+If the target locator points at an Org node, place the template into
+the text of the entry, before the first child. If not, place the
+template at the beginning or end of the file.
+Of course, if exact position has been required, just put it there."
+ (let* ((txt (org-capture-get :template))
+ beg end)
+ (cond
+ ((org-capture-get :exact-position)
+ (goto-char (org-capture-get :exact-position)))
+ ((and (org-capture-get :target-entry-p)
+ (bolp)
+ (looking-at org-outline-regexp))
+ ;; we should place the text into this entry
+ (if (org-capture-get :prepend)
+ ;; Skip meta data and drawers
+ (org-end-of-meta-data t)
+ ;; go to ent of the entry text, before the next headline
+ (outline-next-heading)))
+ (t
+ ;; beginning or end of file
+ (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
+ (or (bolp) (newline))
+ (org-capture-empty-lines-before)
+ (setq beg (point))
+ (insert txt)
+ (org-capture-empty-lines-after)
+ (org-capture-position-for-last-stored beg)
+ (setq end (point))
+ (org-capture-mark-kill-region beg (1- end))
+ (org-capture-narrow beg (1- end))
+ (if (or (re-search-backward "%\\?" beg t)
+ (re-search-forward "%\\?" end t))
+ (replace-match ""))))
+
+(defun org-capture-mark-kill-region (beg end)
+ "Mark the region that will have to be killed when aborting capture."
+ (let ((m1 (move-marker (make-marker) beg))
+ (m2 (move-marker (make-marker) end)))
+ (org-capture-put :begin-marker m1)
+ (org-capture-put :end-marker m2)))
+
+(defun org-capture-position-for-last-stored (where)
+ "Memorize the position that should later become the position of last capture."
+ (cond
+ ((integerp where)
+ (org-capture-put :position-for-last-stored
+ (move-marker (make-marker) where
+ (or (buffer-base-buffer (current-buffer))
+ (current-buffer)))))
+ ((eq where 'table-line)
+ (org-capture-put :position-for-last-stored
+ (list 'table-line
+ (org-table-current-dline))))
+ (t (error "This should not happen"))))
+
+(defun org-capture-store-last-position ()
+ "Store the last-captured position."
+ (let* ((where (org-capture-get :position-for-last-stored 'local))
+ (pos (cond
+ ((markerp where)
+ (prog1 (marker-position where)
+ (move-marker where nil)))
+ ((and (listp where) (eq (car where) 'table-line))
+ (if (org-at-table-p)
+ (save-excursion
+ (org-table-goto-line (nth 1 where))
+ (point-at-bol))
+ (point))))))
+ (with-current-buffer (buffer-base-buffer (current-buffer))
+ (org-with-point-at pos
+ (when org-capture-bookmark
+ (let ((bookmark (plist-get org-bookmark-names-plist :last-capture)))
+ (when bookmark (with-demoted-errors (bookmark-set bookmark)))))
+ (move-marker org-capture-last-stored-marker (point))))))
+
+(defun org-capture-narrow (beg end)
+ "Narrow, unless configuration says not to narrow."
+ (unless (org-capture-get :unnarrowed)
+ (narrow-to-region beg end)
+ (goto-char beg)))
+
+(defun org-capture-empty-lines-before (&optional n)
+ "Set the correct number of empty lines before the insertion point.
+Point will be after the empty lines, so insertion can directly be done."
+ (setq n (or n (org-capture-get :empty-lines-before)
+ (org-capture-get :empty-lines) 0))
+ (let ((pos (point)))
+ (org-back-over-empty-lines)
+ (delete-region (point) pos)
+ (if (> n 0) (newline n))))
+
+(defun org-capture-empty-lines-after (&optional n)
+ "Set the correct number of empty lines after the inserted string.
+Point will remain at the first line after the inserted text."
+ (setq n (or n (org-capture-get :empty-lines-after)
+ (org-capture-get :empty-lines) 0))
+ (org-back-over-empty-lines)
+ (while (looking-at "[ \t]*\n") (replace-match ""))
+ (let ((pos (point)))
+ (if (> n 0) (newline n))
+ (goto-char pos)))
+
+(defvar org-clock-marker) ; Defined in org.el
+
+(defun org-capture-insert-template-here ()
+ "Insert the capture template at point."
+ (let* ((template (org-capture-get :template))
+ (type (org-capture-get :type))
+ beg end pp)
+ (unless (bolp) (insert "\n"))
+ (setq beg (point))
+ (cond
+ ((and (eq type 'entry) (derived-mode-p 'org-mode))
+ (org-capture-verify-tree (org-capture-get :template))
+ (org-paste-subtree nil template t))
+ ((and (memq type '(item checkitem))
+ (derived-mode-p 'org-mode)
+ (save-excursion (skip-chars-backward " \t\n")
+ (setq pp (point))
+ (org-in-item-p)))
+ (goto-char pp)
+ (org-insert-item)
+ (skip-chars-backward " ")
+ (skip-chars-backward "-+*0123456789).")
+ (delete-region (point) (point-at-eol))
+ (setq beg (point))
+ (org-remove-indentation template)
+ (insert template)
+ (org-capture-empty-lines-after)
+ (goto-char beg)
+ (org-list-repair)
+ (org-end-of-item))
+ (t
+ (insert template)
+ (org-capture-empty-lines-after)
+ (skip-chars-forward " \t\n")
+ (unless (eobp) (beginning-of-line))))
+ (setq end (point))
+ (goto-char beg)
+ (when (re-search-forward "%\\?" end t)
+ (replace-match ""))))
+
+(defun org-capture-set-plist (entry)
+ "Initialize the property list from the template definition."
+ (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
+ (org-capture-put :key (car entry) :description (nth 1 entry)
+ :target (nth 3 entry))
+ (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
+ (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
+ ;; The template may be empty or omitted for special types.
+ ;; Here we insert the default templates for such cases.
+ (cond
+ ((eq type 'item) (setq txt "- %?"))
+ ((eq type 'checkitem) (setq txt "- [ ] %?"))
+ ((eq type 'table-line) (setq txt "| %? |"))
+ ((member type '(nil entry)) (setq txt "* %?\n %a"))))
+ (org-capture-put :template txt :type type)))
+
+(defun org-capture-goto-target (&optional template-key)
+ "Go to the target location of a capture template.
+The user is queried for the template."
+ (interactive)
+ (let ((entry (org-capture-select-template template-key)))
+ (unless entry (error "No capture template selected"))
+ (org-capture-set-plist entry)
+ (org-capture-set-target-location)
+ (pop-to-buffer-same-window (org-capture-get :buffer))
+ (goto-char (org-capture-get :pos))))
+
+(defun org-capture-get-indirect-buffer (&optional buffer prefix)
+ "Make an indirect buffer for a capture process.
+Use PREFIX as a prefix for the name of the indirect buffer."
+ (setq buffer (or buffer (current-buffer)))
+ (let ((n 1) (base (buffer-name buffer)) bname)
+ (setq bname (concat prefix "-" base))
+ (while (buffer-live-p (get-buffer bname))
+ (setq bname (concat prefix "-" (number-to-string (cl-incf n)) "-" base)))
+ (condition-case nil
+ (make-indirect-buffer buffer bname 'clone)
+ (error
+ (let ((buf (make-indirect-buffer buffer bname)))
+ (with-current-buffer buf (org-mode))
+ buf)))))
+
+(defun org-capture-verify-tree (tree)
+ "Throw error if TREE is not a valid tree."
+ (unless (org-kill-is-subtree-p tree)
+ (error "Template is not a valid Org entry or tree")))
+
+(defun org-mks (table title &optional prompt specials)
+ "Select a member of an alist with multiple keys.
+
+TABLE is the alist which should contain entries where the car is a string.
+There should be two types of entries.
+
+1. prefix descriptions like (\"a\" \"Description\")
+ This indicates that `a' is a prefix key for multi-letter selection, and
+ that there are entries following with keys like \"ab\", \"ax\"...
+
+2. Select-able members must have more than two elements, with the first
+ being the string of keys that lead to selecting it, and the second a
+ short description string of the item.
+
+The command will then make a temporary buffer listing all entries
+that can be selected with a single key, and all the single key
+prefixes. When you press the key for a single-letter entry, it is selected.
+When you press a prefix key, the commands (and maybe further prefixes)
+under this key will be shown and offered for selection.
+
+TITLE will be placed over the selection in the temporary buffer,
+PROMPT will be used when prompting for a key. SPECIAL is an
+alist with (\"key\" \"description\") entries. When one of these
+is selected, only the bare key is returned."
+ (save-window-excursion
+ (let ((inhibit-quit t)
+ (buffer (org-switch-to-buffer-other-window "*Org Select*"))
+ (prompt (or prompt "Select: "))
+ current)
+ (unwind-protect
+ (catch 'exit
+ (while t
+ (erase-buffer)
+ (insert title "\n\n")
+ (let ((des-keys nil)
+ (allowed-keys '("\C-g"))
+ (cursor-type nil))
+ ;; Populate allowed keys and descriptions keys
+ ;; available with CURRENT selector.
+ (let ((re (format "\\`%s\\(.\\)\\'"
+ (if current (regexp-quote current) "")))
+ (prefix (if current (concat current " ") "")))
+ (dolist (entry table)
+ (pcase entry
+ ;; Description.
+ (`(,(and key (pred (string-match re))) ,desc)
+ (let ((k (match-string 1 key)))
+ (push k des-keys)
+ (push k allowed-keys)
+ (insert prefix "[" k "]" "..." " " desc "..." "\n")))
+ ;; Usable entry.
+ (`(,(and key (pred (string-match re))) ,desc . ,_)
+ (let ((k (match-string 1 key)))
+ (insert prefix "[" k "]" " " desc "\n")
+ (push k allowed-keys)))
+ (_ nil))))
+ ;; Insert special entries, if any.
+ (when specials
+ (insert "----------------------------------------------------\
+---------------------------\n")
+ (pcase-dolist (`(,key ,description) specials)
+ (insert (format "[%s] %s\n" key description))
+ (push key allowed-keys)))
+ ;; Display UI and let user select an entry or
+ ;; a sub-level prefix.
+ (goto-char (point-min))
+ (unless (pos-visible-in-window-p (point-max))
+ (org-fit-window-to-buffer))
+ (message prompt)
+ (let ((pressed (char-to-string (read-char-exclusive))))
+ (while (not (member pressed allowed-keys))
+ (message "Invalid key `%s'" pressed) (sit-for 1)
+ (message prompt)
+ (setq pressed (char-to-string (read-char-exclusive))))
+ (setq current (concat current pressed))
+ (cond
+ ((equal pressed "\C-g") (user-error "Abort"))
+ ;; Selection is a prefix: open a new menu.
+ ((member pressed des-keys))
+ ;; Selection matches an association: return it.
+ ((let ((entry (assoc current table)))
+ (and entry (throw 'exit entry))))
+ ;; Selection matches a special entry: return the
+ ;; selection prefix.
+ ((assoc current specials) (throw 'exit current))
+ (t (error "No entry available")))))))
+ (when buffer (kill-buffer buffer))))))
+
+;;; The template code
+(defun org-capture-select-template (&optional keys)
+ "Select a capture template.
+Lisp programs can force the template by setting KEYS to a string."
+ (let ((org-capture-templates
+ (or (org-contextualize-keys
+ org-capture-templates org-capture-templates-contexts)
+ '(("t" "Task" entry (file+headline "" "Tasks")
+ "* TODO %?\n %u\n %a")))))
+ (if keys
+ (or (assoc keys org-capture-templates)
+ (error "No capture template referred to by \"%s\" keys" keys))
+ (org-mks org-capture-templates
+ "Select a capture template\n========================="
+ "Template key: "
+ '(("C" "Customize org-capture-templates")
+ ("q" "Abort"))))))
+
+(defvar org-capture--clipboards nil
+ "List various clipboards values.")
+
+(defun org-capture-fill-template (&optional template initial annotation)
+ "Fill a template and return the filled template as a string.
+The template may still contain \"%?\" for cursor positioning."
+ (let* ((template (or template (org-capture-get :template)))
+ (buffer (org-capture-get :buffer))
+ (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
+ (time (let* ((c (or (org-capture-get :default-time) (current-time)))
+ (d (decode-time c)))
+ (if (< (nth 2 d) org-extend-today-until)
+ (encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
+ c)))
+ (v-t (format-time-string (org-time-stamp-format nil) time))
+ (v-T (format-time-string (org-time-stamp-format t) time))
+ (v-u (format-time-string (org-time-stamp-format nil t) time))
+ (v-U (format-time-string (org-time-stamp-format t t) time))
+ (v-c (and kill-ring (current-kill 0)))
+ (v-x (or (org-get-x-clipboard 'PRIMARY)
+ (org-get-x-clipboard 'CLIPBOARD)
+ (org-get-x-clipboard 'SECONDARY)))
+ ;; `initial' and `annotation' might have been passed. But if
+ ;; the property list has them, we prefer those values.
+ (v-i (or (plist-get org-store-link-plist :initial)
+ (and (stringp initial) (org-no-properties initial))
+ (org-capture-get :initial)
+ ""))
+ (v-a
+ (let ((a (or (plist-get org-store-link-plist :annotation)
+ annotation
+ (org-capture-get :annotation)
+ "")))
+ ;; Is the link empty? Then we do not want it...
+ (if (equal a "[[]]") "" a)))
+ (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
+ (v-A (if (and v-a (string-match l-re v-a))
+ (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
+ v-a))
+ (v-l (if (and v-a (string-match l-re v-a))
+ (replace-match "\\1" nil nil v-a)
+ v-a))
+ (v-n user-full-name)
+ (v-k (and (marker-buffer org-clock-marker)
+ (org-no-properties org-clock-heading)))
+ (v-K (if (marker-buffer org-clock-marker)
+ (org-make-link-string
+ (buffer-file-name (marker-buffer org-clock-marker))
+ org-clock-heading)))
+ (v-f (or (org-capture-get :original-file-nondirectory) ""))
+ (v-F (or (org-capture-get :original-file) ""))
+ (org-capture--clipboards
+ (delq nil
+ (list v-i
+ (org-get-x-clipboard 'PRIMARY)
+ (org-get-x-clipboard 'CLIPBOARD)
+ (org-get-x-clipboard 'SECONDARY)
+ v-c))))
+
+ (setq org-store-link-plist (plist-put org-store-link-plist :annotation v-a))
+ (setq org-store-link-plist (plist-put org-store-link-plist :initial v-i))
+
+ (unless template
+ (setq template "")
+ (message "no template") (ding)
+ (sit-for 1))
+ (save-window-excursion
+ (org-switch-to-buffer-other-window (get-buffer-create "*Capture*"))
+ (erase-buffer)
+ (setq buffer-file-name nil)
+ (setq mark-active nil)
+ (insert template)
+ (goto-char (point-min))
+
+ ;; %[] insert contents of a file.
+ (save-excursion
+ (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
+ (let ((filename (expand-file-name (match-string 1)))
+ (beg (copy-marker (match-beginning 0)))
+ (end (copy-marker (match-end 0))))
+ (unless (org-capture-escaped-%)
+ (delete-region beg end)
+ (set-marker beg nil)
+ (set-marker end nil)
+ (condition-case error
+ (insert-file-contents filename)
+ (error
+ (insert (format "%%![couldn not insert %s: %s]"
+ filename
+ error))))))))
+
+ ;; Mark %() embedded elisp for later evaluation.
+ (org-capture-expand-embedded-elisp 'mark)
+
+ ;; Expand non-interactive templates.
+ (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)"))
+ (save-excursion
+ (while (re-search-forward regexp nil t)
+ ;; `org-capture-escaped-%' may modify buffer and cripple
+ ;; match-data. Use markers instead. Ditto for other
+ ;; templates.
+ (let ((pos (copy-marker (match-beginning 0)))
+ (end (copy-marker (match-end 0)))
+ (value (match-string 1))
+ (time-string (match-string 2)))
+ (unless (org-capture-escaped-%)
+ (delete-region pos end)
+ (set-marker pos nil)
+ (set-marker end nil)
+ (let* ((inside-sexp? (org-capture-inside-embedded-elisp-p))
+ (replacement
+ (pcase (string-to-char value)
+ (?< (format-time-string time-string))
+ (?:
+ (or (plist-get org-store-link-plist (intern value))
+ ""))
+ (?i
+ (if inside-sexp? v-i
+ ;; Outside embedded Lisp, repeat leading
+ ;; characters before initial place holder
+ ;; every line.
+ (let ((lead (buffer-substring-no-properties
+ (line-beginning-position) (point))))
+ (replace-regexp-in-string "\n\\(.\\)"
+ (concat lead "\\1")
+ v-i nil nil 1))))
+ (?a v-a)
+ (?A v-A)
+ (?c v-c)
+ (?f v-f)
+ (?F v-F)
+ (?k v-k)
+ (?K v-K)
+ (?l v-l)
+ (?n v-n)
+ (?t v-t)
+ (?T v-T)
+ (?u v-u)
+ (?U v-U)
+ (?x v-x))))
+ (insert
+ (if inside-sexp?
+ ;; Escape sensitive characters.
+ (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement)
+ replacement))))))))
+
+ ;; Expand %() embedded Elisp. Limit to Sexp originally marked.
+ (org-capture-expand-embedded-elisp)
+
+ ;; Expand interactive templates. This is the last step so that
+ ;; template is mostly expanded when prompting happens. Turn on
+ ;; Org mode and set local variables. This is to support
+ ;; completion in interactive prompts.
+ (let ((org-inhibit-startup t)) (org-mode))
+ (org-clone-local-variables buffer "\\`org-")
+ (let (strings) ; Stores interactive answers.
+ (save-excursion
+ (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
+ (while (re-search-forward regexp nil t)
+ (let* ((items (and (match-end 1)
+ (save-match-data
+ (split-string (match-string-no-properties 1)
+ "|"))))
+ (key (match-string 2))
+ (beg (copy-marker (match-beginning 0)))
+ (end (copy-marker (match-end 0)))
+ (prompt (nth 0 items))
+ (default (nth 1 items))
+ (completions (nthcdr 2 items)))
+ (unless (org-capture-escaped-%)
+ (delete-region beg end)
+ (set-marker beg nil)
+ (set-marker end nil)
+ (pcase key
+ ((or "G" "g")
+ (let* ((org-last-tags-completion-table
+ (org-global-tags-completion-table
+ (cond ((equal key "G") (org-agenda-files))
+ (file (list file))
+ (t nil))))
+ (org-add-colon-after-tag-completion t)
+ (ins (mapconcat
+ #'identity
+ (org-split-string
+ (completing-read
+ (if prompt (concat prompt ": ") "Tags: ")
+ 'org-tags-completion-function nil nil nil
+ 'org-tags-history)
+ "[^[:alnum:]_@#%]+")
+ ":")))
+ (when (org-string-nw-p ins)
+ (unless (eq (char-before) ?:) (insert ":"))
+ (insert ins)
+ (unless (eq (char-after) ?:) (insert ":"))
+ (and (org-at-heading-p)
+ (let ((org-ignore-region t))
+ (org-set-tags nil 'align))))))
+ ((or "C" "L")
+ (let ((insert-fun (if (equal key "C") #'insert
+ (lambda (s) (org-insert-link 0 s)))))
+ (pcase org-capture--clipboards
+ (`nil nil)
+ (`(,value) (funcall insert-fun value))
+ (`(,first-value . ,_)
+ (funcall insert-fun
+ (read-string "Clipboard/kill value: "
+ first-value
+ 'org-capture--clipboards
+ first-value)))
+ (_ (error "Invalid `org-capture--clipboards' value: %S"
+ org-capture--clipboards)))))
+ ("p" (org-set-property prompt nil))
+ ((guard key)
+ ;; These are the date/time related ones.
+ (let* ((upcase? (equal (upcase key) key))
+ (org-time-was-given upcase?)
+ (org-end-time-was-given)
+ (time (org-read-date upcase? t nil prompt)))
+ (org-insert-time-stamp
+ time org-time-was-given
+ (member key '("u" "U"))
+ nil nil (list org-end-time-was-given))))
+ (_
+ (push (org-completing-read
+ (concat (or prompt "Enter string")
+ (and default (format " [%s]" default))
+ ": ")
+ completions nil nil nil nil default)
+ strings)
+ (insert (car strings)))))))))
+
+ ;; Replace %n escapes with nth %^{...} string.
+ (setq strings (nreverse strings))
+ (save-excursion
+ (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
+ (unless (org-capture-escaped-%)
+ (replace-match
+ (nth (1- (string-to-number (match-string 1))) strings)
+ nil t)))))
+
+ ;; Make sure there are no empty lines before the text, and that
+ ;; it ends with a newline character.
+ (skip-chars-forward " \t\n")
+ (delete-region (point-min) (line-beginning-position))
+ (goto-char (point-max))
+ (skip-chars-backward " \t\n")
+ (delete-region (point) (point-max))
+ (insert "\n")
+
+ ;; Return the expanded template and kill the capture buffer.
+ (untabify (point-min) (point-max))
+ (set-buffer-modified-p nil)
+ (prog1 (buffer-substring-no-properties (point-min) (point-max))
+ (kill-buffer (current-buffer))))))
+
+(defun org-capture-escaped-% ()
+ "Non-nil if % was escaped.
+If yes, unescape it now. Assume match-data contains the
+placeholder to check."
+ (save-excursion
+ (goto-char (match-beginning 0))
+ (let ((n (abs (skip-chars-backward "\\\\"))))
+ (delete-char (/ (1+ n) 2))
+ (= (% n 2) 1))))
+
+(defun org-capture-expand-embedded-elisp (&optional mark)
+ "Evaluate embedded elisp %(sexp) and replace with the result.
+When optional MARK argument is non-nil, mark Sexp with a text
+property (`org-embedded-elisp') for later evaluation. Only
+marked Sexp are evaluated when this argument is nil."
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "%(" nil t)
+ (cond
+ ((get-text-property (match-beginning 0) 'org-embedded-elisp)
+ (goto-char (match-beginning 0))
+ (let ((template-start (point)))
+ (forward-char 1)
+ (let* ((sexp (read (current-buffer)))
+ (result (org-eval
+ (org-capture--expand-keyword-in-embedded-elisp
+ sexp))))
+ (delete-region template-start (point))
+ (cond
+ ((not result) nil)
+ ((stringp result) (insert result))
+ (t (error
+ "Capture template sexp `%s' must evaluate to string or nil"
+ sexp))))))
+ ((not mark) nil)
+ ;; Only mark valid and non-escaped sexp.
+ ((org-capture-escaped-%) nil)
+ (t
+ (let ((end (with-syntax-table emacs-lisp-mode-syntax-table
+ (ignore-errors (scan-sexps (1- (point)) 1)))))
+ (when end
+ (put-text-property (- (point) 2) end 'org-embedded-elisp t))))))))
+
+(defun org-capture--expand-keyword-in-embedded-elisp (attr)
+ "Recursively replace capture link keywords in ATTR sexp.
+Such keywords are prefixed with \"%:\". See
+`org-capture-template' for more information."
+ (cond ((consp attr)
+ (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
+ ((symbolp attr)
+ (let* ((attr-symbol (symbol-name attr))
+ (key (and (string-match "%\\(:.*\\)" attr-symbol)
+ (intern (match-string 1 attr-symbol)))))
+ (or (plist-get org-store-link-plist key)
+ attr)))
+ (t attr)))
+
+(defun org-capture-inside-embedded-elisp-p ()
+ "Non-nil if point is inside of embedded elisp %(sexp).
+Assume sexps have been marked with
+`org-capture-expand-embedded-elisp' beforehand."
+ (get-text-property (point) 'org-embedded-elisp))
+
+;;;###autoload
+(defun org-capture-import-remember-templates ()
+ "Set `org-capture-templates' to be similar to `org-remember-templates'."
+ (interactive)
+ (when (and (yes-or-no-p
+ "Import old remember templates into org-capture-templates? ")
+ (yes-or-no-p
+ "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
+ (require 'org-remember)
+ (setq org-capture-templates
+ (mapcar
+ (lambda (entry)
+ (let ((desc (car entry))
+ (key (char-to-string (nth 1 entry)))
+ (template (nth 2 entry))
+ (file (or (nth 3 entry) org-default-notes-file))
+ (position (or (nth 4 entry) org-remember-default-headline))
+ (type 'entry)
+ (prepend org-reverse-note-order)
+ immediate target jump-to-captured)
+ (cond
+ ((member position '(top bottom))
+ (setq target (list 'file file)
+ prepend (eq position 'top)))
+ ((eq position 'date-tree)
+ (setq target (list 'file+datetree file)
+ prepend nil))
+ (t (setq target (list 'file+headline file position))))
+
+ (when (string-match "%!" template)
+ (setq template (replace-match "" t t template)
+ immediate t))
+
+ (when (string-match "%&" template)
+ (setq jump-to-captured t))
+
+ (append (list key desc type target template)
+ (if prepend '(:prepend t))
+ (if immediate '(:immediate-finish t))
+ (if jump-to-captured '(:jump-to-captured t)))))
+
+ org-remember-templates))))
+;;; The function was made obsolete by commit 65399674d5 of
+;;; 2013-02-22. This make-obsolete call was added 2016-09-01.
+(make-obsolete 'org-capture-import-remember-templates "use the `org-capture-templates' variable instead." "Org 9.0")
+
+(provide 'org-capture)
+
+;;; org-capture.el ends here
diff --git a/lisp/org-clock.el b/lisp/org-clock.el
new file mode 100644
index 0000000..cb6a6c9
--- /dev/null
+++ b/lisp/org-clock.el
@@ -0,0 +1,2981 @@
+;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the time clocking code for Org mode
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+
+(declare-function calendar-iso-to-absolute "cal-iso" (date))
+(declare-function notifications-notify "notifications" (&rest params))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-table-goto-line "org-table" (n))
+
+(defvar org-frame-title-format-backup frame-title-format)
+(defvar org-time-stamp-formats)
+(defvar org-ts-what)
+
+
+(defgroup org-clock nil
+ "Options concerning clocking working time in Org mode."
+ :tag "Org Clock"
+ :group 'org-progress)
+
+(defcustom org-clock-into-drawer t
+ "Non-nil when clocking info should be wrapped into a drawer.
+
+When non-nil, clocking info will be inserted into the same drawer
+as log notes (see variable `org-log-into-drawer'), if it exists,
+or \"LOGBOOK\" otherwise. If necessary, the drawer will be
+created.
+
+When an integer, the drawer is created only when the number of
+clocking entries in an item reaches or exceeds this value.
+
+When a string, it becomes the name of the drawer, ignoring the
+log notes drawer altogether.
+
+Do not check directly this variable in a Lisp program. Call
+function `org-clock-into-drawer' instead."
+ :group 'org-todo
+ :group 'org-clock
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Only when drawer exists" nil)
+ (integer :tag "When at least N clock entries")
+ (const :tag "Into LOGBOOK drawer" "LOGBOOK")
+ (string :tag "Into Drawer named...")))
+
+(defun org-clock-into-drawer ()
+ "Value of `org-clock-into-drawer'. but let properties overrule.
+
+If the current entry has or inherits a CLOCK_INTO_DRAWER
+property, it will be used instead of the default value.
+
+Return value is either a string, an integer, or nil."
+ (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit t)))
+ (cond ((equal p "nil") nil)
+ ((equal p "t") (or (org-log-into-drawer) "LOGBOOK"))
+ ((org-string-nw-p p)
+ (if (string-match-p "\\`[0-9]+\\'" p) (string-to-number p) p))
+ ((org-string-nw-p org-clock-into-drawer))
+ ((integerp org-clock-into-drawer) org-clock-into-drawer)
+ ((not org-clock-into-drawer) nil)
+ ((org-log-into-drawer))
+ (t "LOGBOOK"))))
+
+(defcustom org-clock-out-when-done t
+ "When non-nil, clock will be stopped when the clocked entry is marked DONE.
+\\<org-mode-map>\
+DONE here means any DONE-like state.
+A nil value means clock will keep running until stopped explicitly with
+`\\[org-clock-out]', or until the clock is started in a different item.
+Instead of t, this can also be a list of TODO states that should trigger
+clocking out."
+ :group 'org-clock
+ :type '(choice
+ (const :tag "No" nil)
+ (const :tag "Yes, when done" t)
+ (repeat :tag "State list"
+ (string :tag "TODO keyword"))))
+
+(defcustom org-clock-rounding-minutes 0
+ "Rounding minutes when clocking in or out.
+The default value is 0 so that no rounding is done.
+When set to a non-integer value, use the car of
+`org-time-stamp-rounding-minutes', like for setting a time-stamp.
+
+E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
+and you clock in: then the clock starts at 14:45. If you clock
+out within the next 5 minutes, the clock line will be removed;
+if you clock out 8 minutes after your clocked in, the clock
+out time will be 14:50."
+ :group 'org-clock
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (integer :tag "Minutes (0 for no rounding)")
+ (symbol :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp)))
+
+(defcustom org-clock-out-remove-zero-time-clocks nil
+ "Non-nil means remove the clock line when the resulting time is zero."
+ :group 'org-clock
+ :type 'boolean)
+
+(defcustom org-clock-in-switch-to-state nil
+ "Set task to a special todo state while clocking it.
+The value should be the state to which the entry should be
+switched. If the value is a function, it must take one
+parameter (the current TODO state of the item) and return the
+state to switch it to."
+ :group 'org-clock
+ :group 'org-todo
+ :type '(choice
+ (const :tag "Don't force a state" nil)
+ (string :tag "State")
+ (symbol :tag "Function")))
+
+(defcustom org-clock-out-switch-to-state nil
+ "Set task to a special todo state after clocking out.
+The value should be the state to which the entry should be
+switched. If the value is a function, it must take one
+parameter (the current TODO state of the item) and return the
+state to switch it to."
+ :group 'org-clock
+ :group 'org-todo
+ :type '(choice
+ (const :tag "Don't force a state" nil)
+ (string :tag "State")
+ (symbol :tag "Function")))
+
+(defcustom org-clock-history-length 5
+ "Number of clock tasks to remember in history."
+ :group 'org-clock
+ :type 'integer)
+
+(defcustom org-clock-goto-may-find-recent-task t
+ "Non-nil means `org-clock-goto' can go to recent task if no active clock."
+ :group 'org-clock
+ :type 'boolean)
+
+(defcustom org-clock-heading-function nil
+ "When non-nil, should be a function to create `org-clock-heading'.
+This is the string shown in the mode line when a clock is running.
+The function is called with point at the beginning of the headline."
+ :group 'org-clock
+ :type '(choice (const nil) (function)))
+
+(defcustom org-clock-string-limit 0
+ "Maximum length of clock strings in the mode line. 0 means no limit."
+ :group 'org-clock
+ :type 'integer)
+
+(defcustom org-clock-in-resume nil
+ "If non-nil, resume clock when clocking into task with open clock.
+When clocking into a task with a clock entry which has not been closed,
+the clock can be resumed from that point."
+ :group 'org-clock
+ :type 'boolean)
+
+(defcustom org-clock-persist nil
+ "When non-nil, save the running clock when Emacs is closed.
+The clock is resumed when Emacs restarts.
+When this is t, both the running clock, and the entire clock
+history are saved. When this is the symbol `clock', only the
+running clock is saved. When this is the symbol `history', only
+the clock history is saved.
+
+When Emacs restarts with saved clock information, the file containing
+the running clock as well as all files mentioned in the clock history
+will be visited.
+
+All this depends on running `org-clock-persistence-insinuate' in your
+Emacs initialization file."
+ :group 'org-clock
+ :type '(choice
+ (const :tag "Just the running clock" clock)
+ (const :tag "Just the history" history)
+ (const :tag "Clock and history" t)
+ (const :tag "No persistence" nil)))
+
+(defcustom org-clock-persist-file (convert-standard-filename
+ (concat user-emacs-directory "org-clock-save.el"))
+ "File to save clock data to."
+ :group 'org-clock
+ :type 'string)
+
+(defcustom org-clock-persist-query-save nil
+ "When non-nil, ask before saving the current clock on exit."
+ :group 'org-clock
+ :type 'boolean)
+
+(defcustom org-clock-persist-query-resume t
+ "When non-nil, ask before resuming any stored clock during load."
+ :group 'org-clock
+ :type 'boolean)
+
+(defcustom org-clock-sound nil
+ "Sound to use for notifications.
+Possible values are:
+
+nil No sound played
+t Standard Emacs beep
+file name Play this sound file, fall back to beep"
+ :group 'org-clock
+ :type '(choice
+ (const :tag "No sound" nil)
+ (const :tag "Standard beep" t)
+ (file :tag "Play sound file")))
+
+(defcustom org-clock-mode-line-total 'auto
+ "Default setting for the time included for the mode line clock.
+This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
+Allowed values are:
+
+current Only the time in the current instance of the clock
+today All time clocked into this task today
+repeat All time clocked into this task since last repeat
+all All time ever recorded for this task
+auto Automatically, either `all', or `repeat' for repeating tasks"
+ :group 'org-clock
+ :type '(choice
+ (const :tag "Current clock" current)
+ (const :tag "Today's task time" today)
+ (const :tag "Since last repeat" repeat)
+ (const :tag "All task time" all)
+ (const :tag "Automatically, `all' or since `repeat'" auto)))
+
+(defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
+(defcustom org-clock-task-overrun-text nil
+ "Extra mode line text to indicate that the clock is overrun.
+The can be nil to indicate that instead of adding text, the clock time
+should get a different face (`org-mode-line-clock-overrun').
+When this is a string, it is prepended to the clock string as an indication,
+also using the face `org-mode-line-clock-overrun'."
+ :group 'org-clock
+ :version "24.1"
+ :type '(choice
+ (const :tag "Just mark the time string" nil)
+ (string :tag "Text to prepend")))
+
+(defcustom org-show-notification-handler nil
+ "Function or program to send notification with.
+The function or program will be called with the notification
+string as argument."
+ :group 'org-clock
+ :type '(choice
+ (const nil)
+ (string :tag "Program")
+ (function :tag "Function")))
+
+(defgroup org-clocktable nil
+ "Options concerning the clock table in Org mode."
+ :tag "Org Clock Table"
+ :group 'org-clock)
+
+(defcustom org-clocktable-defaults
+ (list
+ :maxlevel 2
+ :lang (or (bound-and-true-p org-export-default-language) "en")
+ :scope 'file
+ :block nil
+ :wstart 1
+ :mstart 1
+ :tstart nil
+ :tend nil
+ :step nil
+ :stepskip0 nil
+ :fileskip0 nil
+ :tags nil
+ :emphasize nil
+ :link nil
+ :narrow '40!
+ :indent t
+ :formula nil
+ :timestamp nil
+ :level nil
+ :tcolumns nil
+ :formatter nil)
+ "Default properties for clock tables."
+ :group 'org-clock
+ :version "24.1"
+ :type 'plist)
+
+(defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
+ "Function to turn clocking data into a table.
+For more information, see `org-clocktable-write-default'."
+ :group 'org-clocktable
+ :version "24.1"
+ :type 'function)
+
+;; FIXME: translate es and nl last string "Clock summary at"
+(defcustom org-clock-clocktable-language-setup
+ '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
+ ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
+ ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
+ ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
+ ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
+ "Gesamtdauer" "Dateizeit" "Erstellt am"))
+ "Terms used in clocktable, translated to different languages."
+ :group 'org-clocktable
+ :version "24.1"
+ :type 'alist)
+
+(defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
+ "Default properties for new clocktables.
+These will be inserted into the BEGIN line, to make it easy for users to
+play with them."
+ :group 'org-clocktable
+ :type 'plist)
+
+(defcustom org-clock-idle-time nil
+ "When non-nil, resolve open clocks if the user is idle more than X minutes."
+ :group 'org-clock
+ :type '(choice
+ (const :tag "Never" nil)
+ (integer :tag "After N minutes")))
+
+(defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
+ "When to automatically resolve open clocks found in Org buffers."
+ :group 'org-clock
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (const :tag "When no clock is running" when-no-clock-is-running)))
+
+(defcustom org-clock-report-include-clocking-task nil
+ "When non-nil, include the current clocking task time in clock reports."
+ :group 'org-clock
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-clock-resolve-expert nil
+ "Non-nil means do not show the splash buffer with the clock resolver."
+ :group 'org-clock
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-clock-continuously nil
+ "Non-nil means to start clocking from the last clock-out time, if any."
+ :type 'boolean
+ :version "24.1"
+ :group 'org-clock)
+
+(defcustom org-clock-total-time-cell-format "*%s*"
+ "Format string for the total time cells."
+ :group 'org-clock
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-clock-file-time-cell-format "*%s*"
+ "Format string for the file time cells."
+ :group 'org-clock
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-clock-clocked-in-display 'mode-line
+ "When clocked in for a task, Org can display the current
+task and accumulated time in the mode line and/or frame title.
+Allowed values are:
+
+both displays in both mode line and frame title
+mode-line displays only in mode line (default)
+frame-title displays only in frame title
+nil current clock is not displayed"
+ :group 'org-clock
+ :type '(choice
+ (const :tag "Mode line" mode-line)
+ (const :tag "Frame title" frame-title)
+ (const :tag "Both" both)
+ (const :tag "None" nil)))
+
+(defcustom org-clock-frame-title-format '(t org-mode-line-string)
+ "The value for `frame-title-format' when clocking in.
+
+When `org-clock-clocked-in-display' is set to `frame-title'
+or `both', clocking in will replace `frame-title-format' with
+this value. Clocking out will restore `frame-title-format'.
+
+`org-frame-title-string' is a format string using the same
+specifications than `frame-title-format', which see."
+ :version "24.1"
+ :group 'org-clock
+ :type 'sexp)
+
+(defcustom org-clock-x11idle-program-name "x11idle"
+ "Name of the program which prints X11 idle time in milliseconds.
+
+You can find x11idle.c in the contrib/scripts directory of the
+Org git distribution. Or, you can do:
+
+ sudo apt-get install xprintidle
+
+if you are using Debian."
+ :group 'org-clock
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-clock-goto-before-context 2
+ "Number of lines of context to display before currently clocked-in entry.
+This applies when using `org-clock-goto'."
+ :group 'org-clock
+ :type 'integer)
+
+(defcustom org-clock-display-default-range 'thisyear
+ "Default range when displaying clocks with `org-clock-display'."
+ :group 'org-clock
+ :type '(choice (const today)
+ (const yesterday)
+ (const thisweek)
+ (const lastweek)
+ (const thismonth)
+ (const lastmonth)
+ (const thisyear)
+ (const lastyear)
+ (const untilnow)
+ (const :tag "Select range interactively" interactive)))
+
+(defvar org-clock-in-prepare-hook nil
+ "Hook run when preparing the clock.
+This hook is run before anything happens to the task that
+you want to clock in. For example, you can use this hook
+to add an effort property.")
+(defvar org-clock-in-hook nil
+ "Hook run when starting the clock.")
+(defvar org-clock-out-hook nil
+ "Hook run when stopping the current clock.")
+
+(defvar org-clock-cancel-hook nil
+ "Hook run when canceling the current clock.")
+(defvar org-clock-goto-hook nil
+ "Hook run when selecting the currently clocked-in entry.")
+(defvar org-clock-has-been-used nil
+ "Has the clock been used during the current Emacs session?")
+
+(defvar org-clock-stored-history nil
+ "Clock history, populated by `org-clock-load'")
+(defvar org-clock-stored-resume-clock nil
+ "Clock to resume, saved by `org-clock-load'")
+
+(defconst org-clock--oldest-date
+ (let* ((dichotomy
+ (lambda (min max pred)
+ (if (funcall pred min) min
+ (cl-incf min)
+ (while (> (- max min) 1)
+ (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
+ (if (funcall pred mean) (setq max mean) (setq min mean)))))
+ max))
+ (high
+ (funcall dichotomy
+ most-negative-fixnum
+ 0
+ (lambda (m) (ignore-errors (decode-time (list m 0))))))
+ (low
+ (funcall dichotomy
+ most-negative-fixnum
+ 0
+ (lambda (m) (ignore-errors (decode-time (list high m)))))))
+ (list high low))
+ "Internal time for oldest date representable on the system.")
+
+;;; The clock for measuring work time.
+
+(defvar org-mode-line-string "")
+(put 'org-mode-line-string 'risky-local-variable t)
+
+(defvar org-clock-mode-line-timer nil)
+(defvar org-clock-idle-timer nil)
+(defvar org-clock-heading) ; defined in org.el
+(defvar org-clock-start-time "")
+
+(defvar org-clock-leftover-time nil
+ "If non-nil, user canceled a clock; this is when leftover time started.")
+
+(defvar org-clock-effort ""
+ "Effort estimate of the currently clocking task.")
+
+(defvar org-clock-total-time nil
+ "Holds total time, spent previously on currently clocked item.
+This does not include the time in the currently running clock.")
+
+(defvar org-clock-history nil
+ "List of marker pointing to recent clocked tasks.")
+
+(defvar org-clock-default-task (make-marker)
+ "Marker pointing to the default task that should clock time.
+The clock can be made to switch to this task after clocking out
+of a different task.")
+
+(defvar org-clock-interrupted-task (make-marker)
+ "Marker pointing to the task that has been interrupted by the current clock.")
+
+(defvar org-clock-mode-line-map (make-sparse-keymap))
+(define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
+(define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
+
+(defun org-clock-menu ()
+ (interactive)
+ (popup-menu
+ '("Clock"
+ ["Clock out" org-clock-out t]
+ ["Change effort estimate" org-clock-modify-effort-estimate t]
+ ["Go to clock entry" org-clock-goto t]
+ ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
+
+(defun org-clock-history-push (&optional pos buffer)
+ "Push a marker to the clock history."
+ (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
+ (let ((m (move-marker (make-marker)
+ (or pos (point)) (org-base-buffer
+ (or buffer (current-buffer)))))
+ n l)
+ (while (setq n (member m org-clock-history))
+ (move-marker (car n) nil))
+ (setq org-clock-history
+ (delq nil
+ (mapcar (lambda (x) (if (marker-buffer x) x nil))
+ org-clock-history)))
+ (when (>= (setq l (length org-clock-history)) org-clock-history-length)
+ (setq org-clock-history
+ (nreverse
+ (nthcdr (- l org-clock-history-length -1)
+ (nreverse org-clock-history)))))
+ (push m org-clock-history)))
+
+(defun org-clock-save-markers-for-cut-and-paste (beg end)
+ "Save relative positions of markers in region."
+ (org-check-and-save-marker org-clock-marker beg end)
+ (org-check-and-save-marker org-clock-hd-marker beg end)
+ (org-check-and-save-marker org-clock-default-task beg end)
+ (org-check-and-save-marker org-clock-interrupted-task beg end)
+ (dolist (m org-clock-history)
+ (org-check-and-save-marker m beg end)))
+
+(defun org-clock-drawer-name ()
+ "Return clock drawer's name for current entry, or nil."
+ (let ((drawer (org-clock-into-drawer)))
+ (cond ((integerp drawer)
+ (let ((log-drawer (org-log-into-drawer)))
+ (if (stringp log-drawer) log-drawer "LOGBOOK")))
+ ((stringp drawer) drawer)
+ (t nil))))
+
+(defun org-clocking-buffer ()
+ "Return the clocking buffer if we are currently clocking a task or nil."
+ (marker-buffer org-clock-marker))
+
+(defun org-clocking-p ()
+ "Return t when clocking a task."
+ (not (equal (org-clocking-buffer) nil)))
+
+(defvar org-clock-before-select-task-hook nil
+ "Hook called in task selection just before prompting the user.")
+
+(defun org-clock-select-task (&optional prompt)
+ "Select a task that was recently associated with clocking."
+ (interactive)
+ (let (och chl sel-list rpl (i 0) s)
+ ;; Remove successive dups from the clock history to consider
+ (dolist (c org-clock-history)
+ (unless (equal c (car och)) (push c och)))
+ (setq och (reverse och) chl (length och))
+ (if (zerop chl)
+ (user-error "No recent clock")
+ (save-window-excursion
+ (org-switch-to-buffer-other-window
+ (get-buffer-create "*Clock Task Select*"))
+ (erase-buffer)
+ (when (marker-buffer org-clock-default-task)
+ (insert (org-add-props "Default Task\n" nil 'face 'bold))
+ (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
+ (push s sel-list))
+ (when (marker-buffer org-clock-interrupted-task)
+ (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
+ (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
+ (push s sel-list))
+ (when (org-clocking-p)
+ (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
+ (setq s (org-clock-insert-selection-line ?c org-clock-marker))
+ (push s sel-list))
+ (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
+ (dolist (m och)
+ (when (marker-buffer m)
+ (setq i (1+ i)
+ s (org-clock-insert-selection-line
+ (if (< i 10)
+ (+ i ?0)
+ (+ i (- ?A 10))) m))
+ (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
+ (push s sel-list)))
+ (run-hooks 'org-clock-before-select-task-hook)
+ (goto-char (point-min))
+ ;; Set min-height relatively to circumvent a possible but in
+ ;; `fit-window-to-buffer'
+ (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
+ (message (or prompt "Select task for clocking:"))
+ (setq cursor-type nil rpl (read-char-exclusive))
+ (kill-buffer)
+ (cond
+ ((eq rpl ?q) nil)
+ ((eq rpl ?x) nil)
+ ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
+ (t (user-error "Invalid task choice %c" rpl)))))))
+
+(defun org-clock-insert-selection-line (i marker)
+ "Insert a line for the clock selection menu.
+And return a cons cell with the selection character integer and the marker
+pointing to it."
+ (when (marker-buffer marker)
+ (let (cat task heading prefix)
+ (with-current-buffer (org-base-buffer (marker-buffer marker))
+ (org-with-wide-buffer
+ (ignore-errors
+ (goto-char marker)
+ (setq cat (org-get-category)
+ heading (org-get-heading 'notags)
+ prefix (save-excursion
+ (org-back-to-heading t)
+ (looking-at org-outline-regexp)
+ (match-string 0))
+ task (substring
+ (org-fontify-like-in-org-mode
+ (concat prefix heading)
+ org-odd-levels-only)
+ (length prefix))))))
+ (when (and cat task)
+ (insert (format "[%c] %-12s %s\n" i cat task))
+ (cons i marker)))))
+
+(defvar org-clock-task-overrun nil
+ "Internal flag indicating if the clock has overrun the planned time.")
+(defvar org-clock-update-period 60
+ "Number of seconds between mode line clock string updates.")
+
+(defun org-clock-get-clock-string ()
+ "Form a clock-string, that will be shown in the mode line.
+If an effort estimate was defined for the current item, use
+01:30/01:50 format (clocked/estimated).
+If not, show simply the clocked time like 01:50."
+ (let ((clocked-time (org-clock-get-clocked-time)))
+ (if org-clock-effort
+ (let* ((effort-in-minutes
+ (org-duration-string-to-minutes org-clock-effort))
+ (work-done-str
+ (propertize
+ (org-minutes-to-clocksum-string clocked-time)
+ 'face (if (and org-clock-task-overrun (not org-clock-task-overrun-text))
+ 'org-mode-line-clock-overrun 'org-mode-line-clock)))
+ (effort-str (org-minutes-to-clocksum-string effort-in-minutes))
+ (clockstr (propertize
+ (concat " [%s/" effort-str
+ "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
+ 'face 'org-mode-line-clock)))
+ (format clockstr work-done-str))
+ (propertize (concat " [" (org-minutes-to-clocksum-string clocked-time)
+ "]" (format " (%s)" org-clock-heading))
+ 'face 'org-mode-line-clock))))
+
+(defun org-clock-get-last-clock-out-time ()
+ "Get the last clock-out time for the current subtree."
+ (save-excursion
+ (let ((end (save-excursion (org-end-of-subtree))))
+ (when (re-search-forward (concat org-clock-string
+ ".*\\]--\\(\\[[^]]+\\]\\)") end t)
+ (org-time-string-to-time (match-string 1))))))
+
+(defun org-clock-update-mode-line ()
+ (if org-clock-effort
+ (org-clock-notify-once-if-expired)
+ (setq org-clock-task-overrun nil))
+ (setq org-mode-line-string
+ (propertize
+ (let ((clock-string (org-clock-get-clock-string))
+ (help-text "Org mode clock is running.\nmouse-1 shows a \
+menu\nmouse-2 will jump to task"))
+ (if (and (> org-clock-string-limit 0)
+ (> (length clock-string) org-clock-string-limit))
+ (propertize
+ (substring clock-string 0 org-clock-string-limit)
+ 'help-echo (concat help-text ": " org-clock-heading))
+ (propertize clock-string 'help-echo help-text)))
+ 'local-map org-clock-mode-line-map
+ 'mouse-face 'mode-line-highlight))
+ (if (and org-clock-task-overrun org-clock-task-overrun-text)
+ (setq org-mode-line-string
+ (concat (propertize
+ org-clock-task-overrun-text
+ 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
+ (force-mode-line-update))
+
+(defun org-clock-get-clocked-time ()
+ "Get the clocked time for the current item in minutes.
+The time returned includes the time spent on this task in
+previous clocking intervals."
+ (let ((currently-clocked-time
+ (floor (- (float-time)
+ (float-time org-clock-start-time)) 60)))
+ (+ currently-clocked-time (or org-clock-total-time 0))))
+
+(defun org-clock-modify-effort-estimate (&optional value)
+ "Add to or set the effort estimate of the item currently being clocked.
+VALUE can be a number of minutes, or a string with format hh:mm or mm.
+When the string starts with a + or a - sign, the current value of the effort
+property will be changed by that amount. If the effort value is expressed
+as an `org-effort-durations' (e.g. \"3h\"), the modified value will be
+converted to a hh:mm duration.
+
+This command will update the \"Effort\" property of the currently
+clocked item, and the value displayed in the mode line."
+ (interactive)
+ (if (org-clock-is-active)
+ (let ((current org-clock-effort) sign)
+ (unless value
+ ;; Prompt user for a value or a change
+ (setq value
+ (read-string
+ (format "Set effort (hh:mm or mm%s): "
+ (if current
+ (format ", prefix + to add to %s" org-clock-effort)
+ "")))))
+ (when (stringp value)
+ ;; A string. See if it is a delta
+ (setq sign (string-to-char value))
+ (if (member sign '(?- ?+))
+ (setq current (org-duration-string-to-minutes current)
+ value (substring value 1))
+ (setq current 0))
+ (setq value (org-duration-string-to-minutes value))
+ (if (equal ?- sign)
+ (setq value (- current value))
+ (if (equal ?+ sign) (setq value (+ current value)))))
+ (setq value (max 0 value)
+ org-clock-effort (org-minutes-to-clocksum-string value))
+ (org-entry-put org-clock-marker "Effort" org-clock-effort)
+ (org-clock-update-mode-line)
+ (message "Effort is now %s" org-clock-effort))
+ (message "Clock is not currently active")))
+
+(defvar org-clock-notification-was-shown nil
+ "Shows if we have shown notification already.")
+
+(defun org-clock-notify-once-if-expired ()
+ "Show notification if we spent more time than we estimated before.
+Notification is shown only once."
+ (when (org-clocking-p)
+ (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort))
+ (clocked-time (org-clock-get-clocked-time)))
+ (if (setq org-clock-task-overrun
+ (if (or (null effort-in-minutes) (zerop effort-in-minutes))
+ nil
+ (>= clocked-time effort-in-minutes)))
+ (unless org-clock-notification-was-shown
+ (setq org-clock-notification-was-shown t)
+ (org-notify
+ (format-message "Task `%s' should be finished by now. (%s)"
+ org-clock-heading org-clock-effort)
+ org-clock-sound))
+ (setq org-clock-notification-was-shown nil)))))
+
+(defun org-notify (notification &optional play-sound)
+ "Send a NOTIFICATION and maybe PLAY-SOUND.
+If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
+ (org-show-notification notification)
+ (if play-sound (org-clock-play-sound play-sound)))
+
+(defun org-show-notification (notification)
+ "Show notification.
+Use `org-show-notification-handler' if defined,
+use libnotify if available, or fall back on a message."
+ (cond ((functionp org-show-notification-handler)
+ (funcall org-show-notification-handler notification))
+ ((stringp org-show-notification-handler)
+ (start-process "emacs-timer-notification" nil
+ org-show-notification-handler notification))
+ ((fboundp 'notifications-notify)
+ (notifications-notify
+ :title "Org mode message"
+ :body notification
+ ;; FIXME how to link to the Org icon?
+ ;; :app-icon "~/.emacs.d/icons/mail.png"
+ :urgency 'low))
+ ((executable-find "notify-send")
+ (start-process "emacs-timer-notification" nil
+ "notify-send" notification))
+ ;; Maybe the handler will send a message, so only use message as
+ ;; a fall back option
+ (t (message "%s" notification))))
+
+(defun org-clock-play-sound (&optional clock-sound)
+ "Play sound as configured by `org-clock-sound'.
+Use alsa's aplay tool if available.
+If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
+ (let ((org-clock-sound (or clock-sound org-clock-sound)))
+ (cond
+ ((not org-clock-sound))
+ ((eq org-clock-sound t) (beep t) (beep t))
+ ((stringp org-clock-sound)
+ (let ((file (expand-file-name org-clock-sound)))
+ (if (file-exists-p file)
+ (if (executable-find "aplay")
+ (start-process "org-clock-play-notification" nil
+ "aplay" file)
+ (condition-case nil
+ (play-sound-file file)
+ (error (beep t) (beep t))))))))))
+
+(defvar org-clock-mode-line-entry nil
+ "Information for the mode line about the running clock.")
+
+(defun org-find-open-clocks (file)
+ "Search through the given file and find all open clocks."
+ (let ((buf (or (get-file-buffer file)
+ (find-file-noselect file)))
+ (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$"))
+ clocks)
+ (with-current-buffer buf
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward org-clock-re nil t)
+ (push (cons (copy-marker (match-end 1) t)
+ (org-time-string-to-time (match-string 1))) clocks))))
+ clocks))
+
+(defsubst org-is-active-clock (clock)
+ "Return t if CLOCK is the currently active clock."
+ (and (org-clock-is-active)
+ (= org-clock-marker (car clock))))
+
+(defmacro org-with-clock-position (clock &rest forms)
+ "Evaluate FORMS with CLOCK as the current active clock."
+ `(with-current-buffer (marker-buffer (car ,clock))
+ (org-with-wide-buffer
+ (goto-char (car ,clock))
+ (beginning-of-line)
+ ,@forms)))
+(def-edebug-spec org-with-clock-position (form body))
+(put 'org-with-clock-position 'lisp-indent-function 1)
+
+(defmacro org-with-clock (clock &rest forms)
+ "Evaluate FORMS with CLOCK as the current active clock.
+This macro also protects the current active clock from being altered."
+ `(org-with-clock-position ,clock
+ (let ((org-clock-start-time (cdr ,clock))
+ (org-clock-total-time)
+ (org-clock-history)
+ (org-clock-effort)
+ (org-clock-marker (car ,clock))
+ (org-clock-hd-marker (save-excursion
+ (org-back-to-heading t)
+ (point-marker))))
+ ,@forms)))
+(def-edebug-spec org-with-clock (form body))
+(put 'org-with-clock 'lisp-indent-function 1)
+
+(defsubst org-clock-clock-in (clock &optional resume start-time)
+ "Clock in to the clock located by CLOCK.
+If necessary, clock-out of the currently active clock."
+ (org-with-clock-position clock
+ (let ((org-clock-in-resume (or resume org-clock-in-resume)))
+ (org-clock-in nil start-time))))
+
+(defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
+ "Clock out of the clock located by CLOCK."
+ (let ((temp (copy-marker (car clock)
+ (marker-insertion-type (car clock)))))
+ (if (org-is-active-clock clock)
+ (org-clock-out nil fail-quietly at-time)
+ (org-with-clock clock
+ (org-clock-out nil fail-quietly at-time)))
+ (setcar clock temp)))
+
+(defsubst org-clock-clock-cancel (clock)
+ "Cancel the clock located by CLOCK."
+ (let ((temp (copy-marker (car clock)
+ (marker-insertion-type (car clock)))))
+ (if (org-is-active-clock clock)
+ (org-clock-cancel)
+ (org-with-clock clock
+ (org-clock-cancel)))
+ (setcar clock temp)))
+
+(defvar org-clock-clocking-in nil)
+(defvar org-clock-resolving-clocks nil)
+(defvar org-clock-resolving-clocks-due-to-idleness nil)
+
+(defun org-clock-resolve-clock (clock resolve-to clock-out-time
+ &optional close-p restart-p fail-quietly)
+ "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
+`CLOCK' is a cons cell of the form (MARKER START-TIME)."
+ (let ((org-clock-resolving-clocks t))
+ (cond
+ ((null resolve-to)
+ (org-clock-clock-cancel clock)
+ (if (and restart-p (not org-clock-clocking-in))
+ (org-clock-clock-in clock)))
+
+ ((eq resolve-to 'now)
+ (if restart-p
+ (error "RESTART-P is not valid here"))
+ (if (or close-p org-clock-clocking-in)
+ (org-clock-clock-out clock fail-quietly)
+ (unless (org-is-active-clock clock)
+ (org-clock-clock-in clock t))))
+
+ ((not (time-less-p resolve-to (current-time)))
+ (error "RESOLVE-TO must refer to a time in the past"))
+
+ (t
+ (if restart-p
+ (error "RESTART-P is not valid here"))
+ (org-clock-clock-out clock fail-quietly (or clock-out-time
+ resolve-to))
+ (unless org-clock-clocking-in
+ (if close-p
+ (setq org-clock-leftover-time (and (null clock-out-time)
+ resolve-to))
+ (org-clock-clock-in clock nil (and clock-out-time
+ resolve-to))))))))
+
+(defun org-clock-jump-to-current-clock (&optional effective-clock)
+ (interactive)
+ (let ((drawer (org-clock-into-drawer))
+ (clock (or effective-clock (cons org-clock-marker
+ org-clock-start-time))))
+ (unless (marker-buffer (car clock))
+ (error "No clock is currently running"))
+ (org-with-clock clock (org-clock-goto))
+ (with-current-buffer (marker-buffer (car clock))
+ (goto-char (car clock))
+ (when drawer
+ (org-with-wide-buffer
+ (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
+ (regexp-quote (if (stringp drawer) drawer "LOGBOOK"))))
+ (beg (save-excursion (org-back-to-heading t) (point))))
+ (catch 'exit
+ (while (re-search-backward drawer-re beg t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'drawer)
+ (when (> (org-element-property :end element) (car clock))
+ (org-flag-drawer nil element))
+ (throw 'exit nil)))))))))))
+
+(defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
+ "Resolve an open Org clock.
+An open clock was found, with `dangling' possibly being non-nil.
+If this function was invoked with a prefix argument, non-dangling
+open clocks are ignored. The given clock requires some sort of
+user intervention to resolve it, either because a clock was left
+dangling or due to an idle timeout. The clock resolution can
+either be:
+
+ (a) deleted, the user doesn't care about the clock
+ (b) restarted from the current time (if no other clock is open)
+ (c) closed, giving the clock X minutes
+ (d) closed and then restarted
+ (e) resumed, as if the user had never left
+
+The format of clock is (CONS MARKER START-TIME), where MARKER
+identifies the buffer and position the clock is open at (and
+thus, the heading it's under), and START-TIME is when the clock
+was started."
+ (cl-assert clock)
+ (let* ((ch
+ (save-window-excursion
+ (save-excursion
+ (unless org-clock-resolving-clocks-due-to-idleness
+ (org-clock-jump-to-current-clock clock))
+ (unless org-clock-resolve-expert
+ (with-output-to-temp-buffer "*Org Clock*"
+ (princ (format-message "Select a Clock Resolution Command:
+
+i/q Ignore this question; the same as keeping all the idle time.
+
+k/K Keep X minutes of the idle time (default is all). If this
+ amount is less than the default, you will be clocked out
+ that many minutes after the time that idling began, and then
+ clocked back in at the present time.
+
+g/G Indicate that you \"got back\" X minutes ago. This is quite
+ different from `k': it clocks you out from the beginning of
+ the idle period and clock you back in X minutes ago.
+
+s/S Subtract the idle time from the current clock. This is the
+ same as keeping 0 minutes.
+
+C Cancel the open timer altogether. It will be as though you
+ never clocked in.
+
+j/J Jump to the current clock, to make manual adjustments.
+
+For all these options, using uppercase makes your final state
+to be CLOCKED OUT."))))
+ (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
+ (let (char-pressed)
+ (while (or (null char-pressed)
+ (and (not (memq char-pressed
+ '(?k ?K ?g ?G ?s ?S ?C
+ ?j ?J ?i ?q)))
+ (or (ding) t)))
+ (setq char-pressed
+ (read-char (concat (funcall prompt-fn clock)
+ " [jkKgGSscCiq]? ")
+ nil 45)))
+ (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
+ (default
+ (floor (/ (float-time
+ (time-subtract (current-time) last-valid)) 60)))
+ (keep
+ (and (memq ch '(?k ?K))
+ (read-number "Keep how many minutes? " default)))
+ (gotback
+ (and (memq ch '(?g ?G))
+ (read-number "Got back how many minutes ago? " default)))
+ (subtractp (memq ch '(?s ?S)))
+ (barely-started-p (< (- (float-time last-valid)
+ (float-time (cdr clock))) 45))
+ (start-over (and subtractp barely-started-p)))
+ (cond
+ ((memq ch '(?j ?J))
+ (if (eq ch ?J)
+ (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
+ (org-clock-jump-to-current-clock clock))
+ ((or (null ch)
+ (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
+ (message ""))
+ (t
+ (org-clock-resolve-clock
+ clock (cond
+ ((or (eq ch ?C)
+ ;; If the time on the clock was less than a minute before
+ ;; the user went away, and they've ask to subtract all the
+ ;; time...
+ start-over)
+ nil)
+ ((or subtractp
+ (and gotback (= gotback 0)))
+ last-valid)
+ ((or (and keep (= keep default))
+ (and gotback (= gotback default)))
+ 'now)
+ (keep
+ (time-add last-valid (seconds-to-time (* 60 keep))))
+ (gotback
+ (time-subtract (current-time)
+ (seconds-to-time (* 60 gotback))))
+ (t
+ (error "Unexpected, please report this as a bug")))
+ (and gotback last-valid)
+ (memq ch '(?K ?G ?S))
+ (and start-over
+ (not (memq ch '(?K ?G ?S ?C))))
+ fail-quietly)))))
+
+;;;###autoload
+(defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
+ "Resolve all currently open Org clocks.
+If `only-dangling-p' is non-nil, only ask to resolve dangling
+\(i.e., not currently open and valid) clocks."
+ (interactive "P")
+ (unless org-clock-resolving-clocks
+ (let ((org-clock-resolving-clocks t))
+ (dolist (file (org-files-list))
+ (let ((clocks (org-find-open-clocks file)))
+ (dolist (clock clocks)
+ (let ((dangling (or (not (org-clock-is-active))
+ (/= (car clock) org-clock-marker))))
+ (if (or (not only-dangling-p) dangling)
+ (org-clock-resolve
+ clock
+ (or prompt-fn
+ (function
+ (lambda (clock)
+ (format
+ "Dangling clock started %d mins ago"
+ (floor (- (float-time)
+ (float-time (cdr clock)))
+ 60)))))
+ (or last-valid
+ (cdr clock)))))))))))
+
+(defun org-emacs-idle-seconds ()
+ "Return the current Emacs idle time in seconds, or nil if not idle."
+ (let ((idle-time (current-idle-time)))
+ (if idle-time
+ (float-time idle-time)
+ 0)))
+
+(defun org-mac-idle-seconds ()
+ "Return the current Mac idle time in seconds."
+ (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
+
+(defvar org-x11idle-exists-p
+ ;; Check that x11idle exists
+ (and (eq window-system 'x)
+ (eq 0 (call-process-shell-command
+ (format "command -v %s" org-clock-x11idle-program-name)))
+ ;; Check that x11idle can retrieve the idle time
+ ;; FIXME: Why "..-shell-command" rather than just `call-process'?
+ (eq 0 (call-process-shell-command org-clock-x11idle-program-name))))
+
+(defun org-x11-idle-seconds ()
+ "Return the current X11 idle time in seconds."
+ (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000))
+
+(defun org-user-idle-seconds ()
+ "Return the number of seconds the user has been idle for.
+This routine returns a floating point number."
+ (cond
+ ((eq system-type 'darwin)
+ (org-mac-idle-seconds))
+ ((and (eq window-system 'x) org-x11idle-exists-p)
+ (org-x11-idle-seconds))
+ (t
+ (org-emacs-idle-seconds))))
+
+(defvar org-clock-user-idle-seconds)
+
+(defun org-resolve-clocks-if-idle ()
+ "Resolve all currently open Org clocks.
+This is performed after `org-clock-idle-time' minutes, to check
+if the user really wants to stay clocked in after being idle for
+so long."
+ (when (and org-clock-idle-time (not org-clock-resolving-clocks)
+ org-clock-marker (marker-buffer org-clock-marker))
+ (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
+ (org-clock-user-idle-start
+ (time-subtract (current-time)
+ (seconds-to-time org-clock-user-idle-seconds)))
+ (org-clock-resolving-clocks-due-to-idleness t))
+ (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
+ (org-clock-resolve
+ (cons org-clock-marker
+ org-clock-start-time)
+ (lambda (_)
+ (format "Clocked in & idle for %.1f mins"
+ (/ (float-time
+ (time-subtract (current-time)
+ org-clock-user-idle-start))
+ 60.0)))
+ org-clock-user-idle-start)))))
+
+(defvar org-clock-current-task nil "Task currently clocked in.")
+(defvar org-clock-out-time nil) ; store the time of the last clock-out
+(defvar org--msg-extra)
+
+;;;###autoload
+(defun org-clock-in (&optional select start-time)
+ "Start the clock on the current item.
+
+If necessary, clock-out of the currently active clock.
+
+With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
+recently clocked
+tasks to clock into.
+
+When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
+clock into the current task and mark it as
+the default task, a special task that will always be offered in the
+clocking selection, associated with the letter `d'.
+
+When SELECT is `\\[universal-argument] \\[universal-argument] \
+\\[universal-argument]', clock in by using the last clock-out
+time as the start time. See `org-clock-continuously' to make this
+the default behavior."
+ (interactive "P")
+ (setq org-clock-notification-was-shown nil)
+ (org-refresh-properties
+ org-effort-property '((effort . identity)
+ (effort-minutes . org-duration-string-to-minutes)))
+ (catch 'abort
+ (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
+ (org-clocking-p)))
+ ts selected-task target-pos (org--msg-extra "")
+ (leftover (and (not org-clock-resolving-clocks)
+ org-clock-leftover-time)))
+
+ (when (and org-clock-auto-clock-resolution
+ (or (not interrupting)
+ (eq t org-clock-auto-clock-resolution))
+ (not org-clock-clocking-in)
+ (not org-clock-resolving-clocks))
+ (setq org-clock-leftover-time nil)
+ (let ((org-clock-clocking-in t))
+ (org-resolve-clocks))) ; check if any clocks are dangling
+
+ (when (equal select '(64))
+ ;; Set start-time to `org-clock-out-time'
+ (let ((org-clock-continuously t))
+ (org-clock-in nil org-clock-out-time)))
+
+ (when (equal select '(4))
+ (setq selected-task (org-clock-select-task "Clock-in on task: "))
+ (if selected-task
+ (setq selected-task (copy-marker selected-task))
+ (error "Abort")))
+
+ (when (equal select '(16))
+ ;; Mark as default clocking task
+ (org-clock-mark-default-task))
+
+ (when interrupting
+ ;; We are interrupting the clocking of a different task.
+ ;; Save a marker to this task, so that we can go back.
+ ;; First check if we are trying to clock into the same task!
+ (when (save-excursion
+ (unless selected-task
+ (org-back-to-heading t))
+ (and (equal (marker-buffer org-clock-hd-marker)
+ (if selected-task
+ (marker-buffer selected-task)
+ (current-buffer)))
+ (= (marker-position org-clock-hd-marker)
+ (if selected-task
+ (marker-position selected-task)
+ (point)))
+ (equal org-clock-current-task (nth 4 (org-heading-components)))))
+ (message "Clock continues in \"%s\"" org-clock-heading)
+ (throw 'abort nil))
+ (move-marker org-clock-interrupted-task
+ (marker-position org-clock-marker)
+ (marker-buffer org-clock-marker))
+ (let ((org-clock-clocking-in t))
+ (org-clock-out nil t)))
+
+ ;; Clock in at which position?
+ (setq target-pos
+ (if (and (eobp) (not (org-at-heading-p)))
+ (point-at-bol 0)
+ (point)))
+ (save-excursion
+ (when (and selected-task (marker-buffer selected-task))
+ ;; There is a selected task, move to the correct buffer
+ ;; and set the new target position.
+ (set-buffer (org-base-buffer (marker-buffer selected-task)))
+ (setq target-pos (marker-position selected-task))
+ (move-marker selected-task nil))
+ (org-with-wide-buffer
+ (goto-char target-pos)
+ (org-back-to-heading t)
+ (or interrupting (move-marker org-clock-interrupted-task nil))
+ (run-hooks 'org-clock-in-prepare-hook)
+ (org-clock-history-push)
+ (setq org-clock-current-task (nth 4 (org-heading-components)))
+ (cond ((functionp org-clock-in-switch-to-state)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ (let ((newstate (funcall org-clock-in-switch-to-state
+ (match-string 2))))
+ (when newstate (org-todo newstate))))
+ ((and org-clock-in-switch-to-state
+ (not (looking-at (concat org-outline-regexp "[ \t]*"
+ org-clock-in-switch-to-state
+ "\\>"))))
+ (org-todo org-clock-in-switch-to-state)))
+ (setq org-clock-heading
+ (cond ((and org-clock-heading-function
+ (functionp org-clock-heading-function))
+ (funcall org-clock-heading-function))
+ ((nth 4 (org-heading-components))
+ (replace-regexp-in-string
+ "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
+ (match-string-no-properties 4)))
+ (t "???")))
+ (org-clock-find-position org-clock-in-resume)
+ (cond
+ ((and org-clock-in-resume
+ (looking-at
+ (concat "^[ \t]*" org-clock-string
+ " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
+ " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
+ (message "Matched %s" (match-string 1))
+ (setq ts (concat "[" (match-string 1) "]"))
+ (goto-char (match-end 1))
+ (setq org-clock-start-time
+ (apply 'encode-time
+ (org-parse-time-string (match-string 1))))
+ (setq org-clock-effort (org-entry-get (point) org-effort-property))
+ (setq org-clock-total-time (org-clock-sum-current-item
+ (org-clock-get-sum-start))))
+ ((eq org-clock-in-resume 'auto-restart)
+ ;; called from org-clock-load during startup,
+ ;; do not interrupt, but warn!
+ (message "Cannot restart clock because task does not contain unfinished clock")
+ (ding)
+ (sit-for 2)
+ (throw 'abort nil))
+ (t
+ (insert-before-markers "\n")
+ (backward-char 1)
+ (org-indent-line)
+ (when (and (save-excursion
+ (end-of-line 0)
+ (org-in-item-p)))
+ (beginning-of-line 1)
+ (indent-line-to (- (org-get-indentation) 2)))
+ (insert org-clock-string " ")
+ (setq org-clock-effort (org-entry-get (point) org-effort-property))
+ (setq org-clock-total-time (org-clock-sum-current-item
+ (org-clock-get-sum-start)))
+ (setq org-clock-start-time
+ (or (and org-clock-continuously org-clock-out-time)
+ (and leftover
+ (y-or-n-p
+ (format
+ "You stopped another clock %d mins ago; start this one from then? "
+ (/ (- (float-time
+ (org-current-time org-clock-rounding-minutes t))
+ (float-time leftover))
+ 60)))
+ leftover)
+ start-time
+ (org-current-time org-clock-rounding-minutes t)))
+ (setq ts (org-insert-time-stamp org-clock-start-time
+ 'with-hm 'inactive))))
+ (move-marker org-clock-marker (point) (buffer-base-buffer))
+ (move-marker org-clock-hd-marker
+ (save-excursion (org-back-to-heading t) (point))
+ (buffer-base-buffer))
+ (setq org-clock-has-been-used t)
+ ;; add to mode line
+ (when (or (eq org-clock-clocked-in-display 'mode-line)
+ (eq org-clock-clocked-in-display 'both))
+ (or global-mode-string (setq global-mode-string '("")))
+ (or (memq 'org-mode-line-string global-mode-string)
+ (setq global-mode-string
+ (append global-mode-string '(org-mode-line-string)))))
+ ;; add to frame title
+ (when (or (eq org-clock-clocked-in-display 'frame-title)
+ (eq org-clock-clocked-in-display 'both))
+ (setq frame-title-format org-clock-frame-title-format))
+ (org-clock-update-mode-line)
+ (when org-clock-mode-line-timer
+ (cancel-timer org-clock-mode-line-timer)
+ (setq org-clock-mode-line-timer nil))
+ (when org-clock-clocked-in-display
+ (setq org-clock-mode-line-timer
+ (run-with-timer org-clock-update-period
+ org-clock-update-period
+ 'org-clock-update-mode-line)))
+ (when org-clock-idle-timer
+ (cancel-timer org-clock-idle-timer)
+ (setq org-clock-idle-timer nil))
+ (setq org-clock-idle-timer
+ (run-with-timer 60 60 'org-resolve-clocks-if-idle))
+ (message "Clock starts at %s - %s" ts org--msg-extra)
+ (run-hooks 'org-clock-in-hook))))))
+
+;;;###autoload
+(defun org-clock-in-last (&optional arg)
+ "Clock in the last closed clocked item.
+When already clocking in, send an warning.
+With a universal prefix argument, select the task you want to
+clock in from the last clocked in tasks.
+With two universal prefix arguments, start clocking using the
+last clock-out time, if any.
+With three universal prefix arguments, interactively prompt
+for a todo state to switch to, overriding the existing value
+`org-clock-in-switch-to-state'."
+ (interactive "P")
+ (if (equal arg '(4)) (org-clock-in arg)
+ (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
+ (or org-clock-out-time
+ (org-current-time org-clock-rounding-minutes t))
+ (org-current-time org-clock-rounding-minutes t))))
+ (if (null org-clock-history)
+ (message "No last clock")
+ (let ((org-clock-in-switch-to-state
+ (if (and (not org-clock-current-task) (equal arg '(64)))
+ (completing-read "Switch to state: "
+ (and org-clock-history
+ (with-current-buffer
+ (marker-buffer (car org-clock-history))
+ org-todo-keywords-1)))
+ org-clock-in-switch-to-state))
+ (already-clocking org-clock-current-task))
+ (org-clock-clock-in (list (car org-clock-history)) nil start-time)
+ (or already-clocking
+ ;; Don't display a message if we are already clocking in
+ (message "Clocking back: %s (in %s)"
+ org-clock-current-task
+ (buffer-name (marker-buffer org-clock-marker)))))))))
+
+(defun org-clock-mark-default-task ()
+ "Mark current task as default task."
+ (interactive)
+ (save-excursion
+ (org-back-to-heading t)
+ (move-marker org-clock-default-task (point))))
+
+(defun org-clock-get-sum-start ()
+ "Return the time from which clock times should be counted.
+This is for the currently running clock as it is displayed
+in the mode line. This function looks at the properties
+LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
+corresponding variable `org-clock-mode-line-total' and then
+decides which time to use."
+ (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
+ (symbol-name org-clock-mode-line-total)))
+ (lr (org-entry-get nil "LAST_REPEAT")))
+ (cond
+ ((equal cmt "current")
+ (setq org--msg-extra "showing time in current clock instance")
+ (current-time))
+ ((equal cmt "today")
+ (setq org--msg-extra "showing today's task time.")
+ (let* ((dt (decode-time))
+ (hour (nth 2 dt))
+ (day (nth 3 dt)))
+ (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
+ (setf (nth 2 dt) org-extend-today-until)
+ (setq dt (append (list 0 0) (nthcdr 2 dt)))
+ (apply 'encode-time dt)))
+ ((or (equal cmt "all")
+ (and (or (not cmt) (equal cmt "auto"))
+ (not lr)))
+ (setq org--msg-extra "showing entire task time.")
+ nil)
+ ((or (equal cmt "repeat")
+ (and (or (not cmt) (equal cmt "auto"))
+ lr))
+ (setq org--msg-extra "showing task time since last repeat.")
+ (if (not lr)
+ nil
+ (org-time-string-to-time lr)))
+ (t nil))))
+
+(defun org-clock-find-position (find-unclosed)
+ "Find the location where the next clock line should be inserted.
+When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
+line and position cursor in that line."
+ (org-back-to-heading t)
+ (catch 'exit
+ (let* ((beg (line-beginning-position))
+ (end (save-excursion (outline-next-heading) (point)))
+ (org-clock-into-drawer (org-clock-into-drawer))
+ (drawer (org-clock-drawer-name)))
+ ;; Look for a running clock if FIND-UNCLOSED in non-nil.
+ (when find-unclosed
+ (let ((open-clock-re
+ (concat "^[ \t]*"
+ org-clock-string
+ " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
+ " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
+ (while (re-search-forward open-clock-re end t)
+ (let ((element (org-element-at-point)))
+ (when (and (eq (org-element-type element) 'clock)
+ (eq (org-element-property :status element) 'running))
+ (beginning-of-line)
+ (throw 'exit t))))))
+ ;; Look for an existing clock drawer.
+ (when drawer
+ (goto-char beg)
+ (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
+ (while (re-search-forward drawer-re end t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'drawer)
+ (let ((cend (org-element-property :contents-end element)))
+ (if (and (not org-log-states-order-reversed) cend)
+ (goto-char cend)
+ (forward-line))
+ (throw 'exit t)))))))
+ (goto-char beg)
+ (let ((clock-re (concat "^[ \t]*" org-clock-string))
+ (count 0)
+ positions)
+ ;; Count the CLOCK lines and store their positions.
+ (save-excursion
+ (while (re-search-forward clock-re end t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'clock)
+ (setq positions (cons (line-beginning-position) positions)
+ count (1+ count))))))
+ (cond
+ ((null positions)
+ ;; Skip planning line and property drawer, if any.
+ (org-end-of-meta-data)
+ (unless (bolp) (insert "\n"))
+ ;; Create a new drawer if necessary.
+ (when (and org-clock-into-drawer
+ (or (not (wholenump org-clock-into-drawer))
+ (< org-clock-into-drawer 2)))
+ (let ((beg (point)))
+ (insert ":" drawer ":\n:END:\n")
+ (org-indent-region beg (point))
+ (goto-char beg)
+ (org-flag-drawer t)
+ (forward-line))))
+ ;; When a clock drawer needs to be created because of the
+ ;; number of clock items or simply if it is missing, collect
+ ;; all clocks in the section and wrap them within the drawer.
+ ((if (wholenump org-clock-into-drawer)
+ (>= (1+ count) org-clock-into-drawer)
+ drawer)
+ ;; Skip planning line and property drawer, if any.
+ (org-end-of-meta-data)
+ (let ((beg (point)))
+ (insert
+ (mapconcat
+ (lambda (p)
+ (save-excursion
+ (goto-char p)
+ (org-trim (delete-and-extract-region
+ (save-excursion (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))
+ (line-beginning-position 2)))))
+ positions "\n")
+ "\n:END:\n")
+ (let ((end (point-marker)))
+ (goto-char beg)
+ (save-excursion (insert ":" drawer ":\n"))
+ (org-flag-drawer t)
+ (org-indent-region (point) end)
+ (forward-line)
+ (unless org-log-states-order-reversed
+ (goto-char end)
+ (beginning-of-line -1))
+ (set-marker end nil))))
+ (org-log-states-order-reversed (goto-char (car (last positions))))
+ (t (goto-char (car positions))))))))
+
+;;;###autoload
+(defun org-clock-out (&optional switch-to-state fail-quietly at-time)
+ "Stop the currently running clock.
+Throw an error if there is no running clock and FAIL-QUIETLY is nil.
+With a universal prefix, prompt for a state to switch the clocked out task
+to, overriding the existing value of `org-clock-out-switch-to-state'."
+ (interactive "P")
+ (catch 'exit
+ (when (not (org-clocking-p))
+ (setq global-mode-string
+ (delq 'org-mode-line-string global-mode-string))
+ (setq frame-title-format org-frame-title-format-backup)
+ (force-mode-line-update)
+ (if fail-quietly (throw 'exit t) (user-error "No active clock")))
+ (let ((org-clock-out-switch-to-state
+ (if switch-to-state
+ (completing-read "Switch to state: "
+ (with-current-buffer
+ (marker-buffer org-clock-marker)
+ org-todo-keywords-1)
+ nil t "DONE")
+ org-clock-out-switch-to-state))
+ (now (org-current-time org-clock-rounding-minutes))
+ ts te s h m remove)
+ (setq org-clock-out-time now)
+ (save-excursion ; Do not replace this with `with-current-buffer'.
+ (with-no-warnings (set-buffer (org-clocking-buffer)))
+ (save-restriction
+ (widen)
+ (goto-char org-clock-marker)
+ (beginning-of-line 1)
+ (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
+ (equal (match-string 1) org-clock-string))
+ (setq ts (match-string 2))
+ (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
+ (goto-char (match-end 0))
+ (delete-region (point) (point-at-eol))
+ (insert "--")
+ (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
+ (setq s (- (float-time
+ (apply #'encode-time (org-parse-time-string te nil t)))
+ (float-time
+ (apply #'encode-time (org-parse-time-string ts nil t))))
+ h (floor (/ s 3600))
+ s (- s (* 3600 h))
+ m (floor (/ s 60))
+ s (- s (* 60 s)))
+ (insert " => " (format "%2d:%02d" h m))
+ (move-marker org-clock-marker nil)
+ (move-marker org-clock-hd-marker nil)
+ ;; Possibly remove zero time clocks. However, do not add
+ ;; a note associated to the CLOCK line in this case.
+ (cond ((and org-clock-out-remove-zero-time-clocks
+ (= (+ h m) 0))
+ (setq remove t)
+ (delete-region (line-beginning-position)
+ (line-beginning-position 2)))
+ (org-log-note-clock-out
+ (org-add-log-setup
+ 'clock-out nil nil nil
+ (concat "# Task: " (org-get-heading t) "\n\n"))))
+ (when org-clock-mode-line-timer
+ (cancel-timer org-clock-mode-line-timer)
+ (setq org-clock-mode-line-timer nil))
+ (when org-clock-idle-timer
+ (cancel-timer org-clock-idle-timer)
+ (setq org-clock-idle-timer nil))
+ (setq global-mode-string
+ (delq 'org-mode-line-string global-mode-string))
+ (setq frame-title-format org-frame-title-format-backup)
+ (when org-clock-out-switch-to-state
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((org-inhibit-logging t)
+ (org-clock-out-when-done nil))
+ (cond
+ ((functionp org-clock-out-switch-to-state)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ (let ((newstate (funcall org-clock-out-switch-to-state
+ (match-string 2))))
+ (when newstate (org-todo newstate))))
+ ((and org-clock-out-switch-to-state
+ (not (looking-at (concat org-outline-regexp "[ \t]*"
+ org-clock-out-switch-to-state
+ "\\>"))))
+ (org-todo org-clock-out-switch-to-state))))))
+ (force-mode-line-update)
+ (message (concat "Clock stopped at %s after "
+ (org-minutes-to-clocksum-string (+ (* 60 h) m)) "%s")
+ te (if remove " => LINE REMOVED" ""))
+ (run-hooks 'org-clock-out-hook)
+ (unless (org-clocking-p)
+ (setq org-clock-current-task nil)))))))
+
+(add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
+
+(defun org-clock-remove-empty-clock-drawer ()
+ "Remove empty clock drawers in current subtree."
+ (save-excursion
+ (org-back-to-heading t)
+ (org-map-tree
+ (lambda ()
+ (let ((drawer (org-clock-drawer-name))
+ (case-fold-search t))
+ (when drawer
+ (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
+ (end (save-excursion (outline-next-heading))))
+ (while (re-search-forward re end t)
+ (org-remove-empty-drawer-at (point))))))))))
+
+(defun org-clock-timestamps-up (&optional n)
+ "Increase CLOCK timestamps at cursor.
+Optional argument N tells to change by that many units."
+ (interactive "P")
+ (org-clock-timestamps-change 'up n))
+
+(defun org-clock-timestamps-down (&optional n)
+ "Increase CLOCK timestamps at cursor.
+Optional argument N tells to change by that many units."
+ (interactive "P")
+ (org-clock-timestamps-change 'down n))
+
+(defun org-clock-timestamps-change (updown &optional n)
+ "Change CLOCK timestamps synchronously at cursor.
+UPDOWN tells whether to change `up' or `down'.
+Optional argument N tells to change by that many units."
+ (setq org-ts-what nil)
+ (when (org-at-timestamp-p t)
+ (let ((tschange (if (eq updown 'up) 'org-timestamp-up
+ 'org-timestamp-down))
+ ts1 begts1 ts2 begts2 updatets1 tdiff)
+ (save-excursion
+ (move-beginning-of-line 1)
+ (re-search-forward org-ts-regexp3 nil t)
+ (setq ts1 (match-string 0) begts1 (match-beginning 0))
+ (when (re-search-forward org-ts-regexp3 nil t)
+ (setq ts2 (match-string 0) begts2 (match-beginning 0))))
+ ;; Are we on the second timestamp?
+ (if (<= begts2 (point)) (setq updatets1 t))
+ (if (not ts2)
+ ;; fall back on org-timestamp-up if there is only one
+ (funcall tschange n)
+ ;; setq this so that (boundp 'org-ts-what is non-nil)
+ (funcall tschange n)
+ (let ((ts (if updatets1 ts2 ts1))
+ (begts (if updatets1 begts1 begts2)))
+ (setq tdiff
+ (time-subtract
+ (org-time-string-to-time org-last-changed-timestamp)
+ (org-time-string-to-time ts)))
+ (save-excursion
+ (goto-char begts)
+ (org-timestamp-change
+ (round (/ (float-time tdiff)
+ (cond ((eq org-ts-what 'minute) 60)
+ ((eq org-ts-what 'hour) 3600)
+ ((eq org-ts-what 'day) (* 24 3600))
+ ((eq org-ts-what 'month) (* 24 3600 31))
+ ((eq org-ts-what 'year) (* 24 3600 365.2)))))
+ org-ts-what 'updown)))))))
+
+;;;###autoload
+(defun org-clock-cancel ()
+ "Cancel the running clock by removing the start timestamp."
+ (interactive)
+ (when (not (org-clocking-p))
+ (setq global-mode-string
+ (delq 'org-mode-line-string global-mode-string))
+ (setq frame-title-format org-frame-title-format-backup)
+ (force-mode-line-update)
+ (error "No active clock"))
+ (save-excursion ; Do not replace this with `with-current-buffer'.
+ (with-no-warnings (set-buffer (org-clocking-buffer)))
+ (goto-char org-clock-marker)
+ (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
+ (line-beginning-position))
+ (progn (delete-region (1- (point-at-bol)) (point-at-eol))
+ (org-remove-empty-drawer-at (point)))
+ (message "Clock gone, cancel the timer anyway")
+ (sit-for 2)))
+ (move-marker org-clock-marker nil)
+ (move-marker org-clock-hd-marker nil)
+ (setq global-mode-string
+ (delq 'org-mode-line-string global-mode-string))
+ (setq frame-title-format org-frame-title-format-backup)
+ (force-mode-line-update)
+ (message "Clock canceled")
+ (run-hooks 'org-clock-cancel-hook))
+
+;;;###autoload
+(defun org-clock-goto (&optional select)
+ "Go to the currently clocked-in entry, or to the most recently clocked one.
+With prefix arg SELECT, offer recently clocked tasks for selection."
+ (interactive "@P")
+ (let* ((recent nil)
+ (m (cond
+ (select
+ (or (org-clock-select-task "Select task to go to: ")
+ (error "No task selected")))
+ ((org-clocking-p) org-clock-marker)
+ ((and org-clock-goto-may-find-recent-task
+ (car org-clock-history)
+ (marker-buffer (car org-clock-history)))
+ (setq recent t)
+ (car org-clock-history))
+ (t (error "No active or recent clock task")))))
+ (pop-to-buffer-same-window (marker-buffer m))
+ (if (or (< m (point-min)) (> m (point-max))) (widen))
+ (goto-char m)
+ (org-show-entry)
+ (org-back-to-heading t)
+ (org-cycle-hide-drawers 'children)
+ (recenter org-clock-goto-before-context)
+ (org-reveal)
+ (if recent
+ (message "No running clock, this is the most recently clocked task"))
+ (run-hooks 'org-clock-goto-hook)))
+
+(defvar-local org-clock-file-total-minutes nil
+ "Holds the file total time in minutes, after a call to `org-clock-sum'.")
+
+(defun org-clock-sum-today (&optional headline-filter)
+ "Sum the times for each subtree for today."
+ (let ((range (org-clock-special-range 'today)))
+ (org-clock-sum (car range) (cadr range)
+ headline-filter :org-clock-minutes-today)))
+
+(defun org-clock-sum-custom (&optional headline-filter range propname)
+ "Sum the times for each subtree for today."
+ (let ((r (or (and (symbolp range) (org-clock-special-range range))
+ (org-clock-special-range
+ (intern (completing-read
+ "Range: "
+ '("today" "yesterday" "thisweek" "lastweek"
+ "thismonth" "lastmonth" "thisyear" "lastyear"
+ "interactive")
+ nil t))))))
+ (org-clock-sum (car r) (cadr r)
+ headline-filter (or propname :org-clock-minutes-custom))))
+
+;;;###autoload
+(defun org-clock-sum (&optional tstart tend headline-filter propname)
+ "Sum the times for each subtree.
+Puts the resulting times in minutes as a text property on each headline.
+TSTART and TEND can mark a time range to be considered.
+HEADLINE-FILTER is a zero-arg function that, if specified, is called for
+each headline in the time range with point at the headline. Headlines for
+which HEADLINE-FILTER returns nil are excluded from the clock summation.
+PROPNAME lets you set a custom text property instead of :org-clock-minutes."
+ (org-with-silent-modifications
+ (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
+ org-clock-string
+ "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
+ (lmax 30)
+ (ltimes (make-vector lmax 0))
+ (t1 0)
+ (level 0)
+ ts te dt
+ time)
+ (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
+ (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
+ (if (consp tstart) (setq tstart (float-time tstart)))
+ (if (consp tend) (setq tend (float-time tend)))
+ (remove-text-properties (point-min) (point-max)
+ `(,(or propname :org-clock-minutes) t
+ :org-clock-force-headline-inclusion t))
+ (save-excursion
+ (goto-char (point-max))
+ (while (re-search-backward re nil t)
+ (cond
+ ((match-end 2)
+ ;; Two time stamps
+ (setq ts (match-string 2)
+ te (match-string 3)
+ ts (float-time
+ (apply #'encode-time (org-parse-time-string ts nil t)))
+ te (float-time
+ (apply #'encode-time (org-parse-time-string te nil t)))
+ ts (if tstart (max ts tstart) ts)
+ te (if tend (min te tend) te)
+ dt (- te ts)
+ t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
+ ((match-end 4)
+ ;; A naked time
+ (setq t1 (+ t1 (string-to-number (match-string 5))
+ (* 60 (string-to-number (match-string 4))))))
+ (t ;; A headline
+ ;; Add the currently clocking item time to the total
+ (when (and org-clock-report-include-clocking-task
+ (equal (org-clocking-buffer) (current-buffer))
+ (equal (marker-position org-clock-hd-marker) (point))
+ tstart
+ tend
+ (>= (float-time org-clock-start-time) tstart)
+ (<= (float-time org-clock-start-time) tend))
+ (let ((time (floor (- (float-time)
+ (float-time org-clock-start-time))
+ 60)))
+ (setq t1 (+ t1 time))))
+ (let* ((headline-forced
+ (get-text-property (point)
+ :org-clock-force-headline-inclusion))
+ (headline-included
+ (or (null headline-filter)
+ (save-excursion
+ (save-match-data (funcall headline-filter))))))
+ (setq level (- (match-end 1) (match-beginning 1)))
+ (when (>= level lmax)
+ (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
+ (when (or (> t1 0) (> (aref ltimes level) 0))
+ (when (or headline-included headline-forced)
+ (if headline-included
+ (cl-loop for l from 0 to level do
+ (aset ltimes l (+ (aref ltimes l) t1))))
+ (setq time (aref ltimes level))
+ (goto-char (match-beginning 0))
+ (put-text-property (point) (point-at-eol)
+ (or propname :org-clock-minutes) time)
+ (when headline-filter
+ (save-excursion
+ (save-match-data
+ (while (org-up-heading-safe)
+ (put-text-property
+ (point) (line-end-position)
+ :org-clock-force-headline-inclusion t))))))
+ (setq t1 0)
+ (cl-loop for l from level to (1- lmax) do
+ (aset ltimes l 0)))))))
+ (setq org-clock-file-total-minutes (aref ltimes 0))))))
+
+(defun org-clock-sum-current-item (&optional tstart)
+ "Return time, clocked on current item in total."
+ (save-excursion
+ (save-restriction
+ (org-narrow-to-subtree)
+ (org-clock-sum tstart)
+ org-clock-file-total-minutes)))
+
+;;;###autoload
+(defun org-clock-display (&optional arg)
+ "Show subtree times in the entire buffer.
+
+By default, show the total time for the range defined in
+`org-clock-display-default-range'. With `\\[universal-argument]' \
+prefix, show
+the total time for today instead.
+
+With `\\[universal-argument] \\[universal-argument]' prefix, \
+use a custom range, entered at prompt.
+
+With `\\[universal-argument] \ \\[universal-argument] \
+\\[universal-argument]' prefix, display the total time in the
+echo area.
+
+Use `\\[org-clock-remove-overlays]' to remove the subtree times."
+ (interactive "P")
+ (org-clock-remove-overlays)
+ (let* ((todayp (equal arg '(4)))
+ (customp (member arg '((16) today yesterday
+ thisweek lastweek thismonth
+ lastmonth thisyear lastyear
+ untilnow interactive)))
+ (prop (cond ((not arg) :org-clock-minutes-default)
+ (todayp :org-clock-minutes-today)
+ (customp :org-clock-minutes-custom)
+ (t :org-clock-minutes)))
+ time h m p)
+ (cond ((not arg) (org-clock-sum-custom
+ nil org-clock-display-default-range prop))
+ (todayp (org-clock-sum-today))
+ (customp (org-clock-sum-custom nil arg))
+ (t (org-clock-sum)))
+ (unless (eq arg '(64))
+ (save-excursion
+ (goto-char (point-min))
+ (while (or (and (equal (setq p (point)) (point-min))
+ (get-text-property p prop))
+ (setq p (next-single-property-change
+ (point) prop)))
+ (goto-char p)
+ (when (setq time (get-text-property p prop))
+ (org-clock-put-overlay time)))
+ (setq h (/ org-clock-file-total-minutes 60)
+ m (- org-clock-file-total-minutes (* 60 h)))
+ ;; Arrange to remove the overlays upon next change.
+ (when org-remove-highlights-with-change
+ (add-hook 'before-change-functions 'org-clock-remove-overlays
+ nil 'local))))
+ (message (concat (format "Total file time%s: "
+ (cond (todayp " for today")
+ (customp " (custom)")
+ (t "")))
+ (org-minutes-to-clocksum-string
+ org-clock-file-total-minutes)
+ " (%d hours and %d minutes)")
+ h m)))
+
+(defvar-local org-clock-overlays nil)
+
+(defun org-clock-put-overlay (time)
+ "Put an overlays on the current line, displaying TIME.
+This creates a new overlay and stores it in `org-clock-overlays', so that it
+will be easy to remove."
+ (let (ov tx)
+ (beginning-of-line)
+ (let ((case-fold-search nil))
+ (when (looking-at org-complex-heading-regexp)
+ (goto-char (match-beginning 4))))
+ (setq ov (make-overlay (point) (point-at-eol))
+ tx (concat (buffer-substring-no-properties (point) (match-end 4))
+ (org-add-props
+ (make-string
+ (max 0 (- (- 60 (current-column))
+ (- (match-end 4) (match-beginning 4))
+ (length (org-get-at-bol 'line-prefix))))
+ ?\·)
+ '(face shadow))
+ (org-add-props
+ (format " %9s " (org-minutes-to-clocksum-string time))
+ '(face org-clock-overlay))
+ ""))
+ (overlay-put ov 'display tx)
+ (push ov org-clock-overlays)))
+
+;;;###autoload
+(defun org-clock-remove-overlays (&optional _beg _end noremove)
+ "Remove the occur highlights from the buffer.
+If NOREMOVE is nil, remove this function from the
+`before-change-functions' in the current buffer."
+ (interactive)
+ (unless org-inhibit-highlight-removal
+ (mapc #'delete-overlay org-clock-overlays)
+ (setq org-clock-overlays nil)
+ (unless noremove
+ (remove-hook 'before-change-functions
+ 'org-clock-remove-overlays 'local))))
+
+(defvar org-state) ;; dynamically scoped into this function
+(defun org-clock-out-if-current ()
+ "Clock out if the current entry contains the running clock.
+This is used to stop the clock after a TODO entry is marked DONE,
+and is only done if the variable `org-clock-out-when-done' is not nil."
+ (when (and (org-clocking-p)
+ org-clock-out-when-done
+ (marker-buffer org-clock-marker)
+ (or (and (eq t org-clock-out-when-done)
+ (member org-state org-done-keywords))
+ (and (listp org-clock-out-when-done)
+ (member org-state org-clock-out-when-done)))
+ (equal (or (buffer-base-buffer (org-clocking-buffer))
+ (org-clocking-buffer))
+ (or (buffer-base-buffer (current-buffer))
+ (current-buffer)))
+ (< (point) org-clock-marker)
+ (> (save-excursion (outline-next-heading) (point))
+ org-clock-marker))
+ ;; Clock out, but don't accept a logging message for this.
+ (let ((org-log-note-clock-out nil)
+ (org-clock-out-switch-to-state nil))
+ (org-clock-out))))
+
+(add-hook 'org-after-todo-state-change-hook
+ 'org-clock-out-if-current)
+
+;;;###autoload
+(defun org-clock-get-clocktable (&rest props)
+ "Get a formatted clocktable with parameters according to PROPS.
+The table is created in a temporary buffer, fully formatted and
+fontified, and then returned."
+ ;; Set the defaults
+ (setq props (plist-put props :name "clocktable"))
+ (unless (plist-member props :maxlevel)
+ (setq props (plist-put props :maxlevel 2)))
+ (unless (plist-member props :scope)
+ (setq props (plist-put props :scope 'agenda)))
+ (with-temp-buffer
+ (org-mode)
+ (org-create-dblock props)
+ (org-update-dblock)
+ (org-font-lock-ensure)
+ (forward-line 2)
+ (buffer-substring (point) (progn
+ (re-search-forward "^[ \t]*#\\+END" nil t)
+ (point-at-bol)))))
+
+;;;###autoload
+(defun org-clock-report (&optional arg)
+ "Create a table containing a report about clocked time.
+If the cursor is inside an existing clocktable block, then the table
+will be updated. If not, a new clocktable will be inserted. The scope
+of the new clock will be subtree when called from within a subtree, and
+file elsewhere.
+
+When called with a prefix argument, move to the first clock table in the
+buffer and update it."
+ (interactive "P")
+ (org-clock-remove-overlays)
+ (when arg
+ (org-find-dblock "clocktable")
+ (org-show-entry))
+ (if (org-in-clocktable-p)
+ (goto-char (org-in-clocktable-p))
+ (let ((props (if (ignore-errors
+ (save-excursion (org-back-to-heading)))
+ (list :name "clocktable" :scope 'subtree)
+ (list :name "clocktable"))))
+ (org-create-dblock
+ (org-combine-plists org-clock-clocktable-default-properties props))))
+ (org-update-dblock))
+
+(defun org-day-of-week (day month year)
+ "Returns the day of the week as an integer."
+ (nth 6
+ (decode-time
+ (date-to-time
+ (format "%d-%02d-%02dT00:00:00" year month day)))))
+
+(defun org-quarter-to-date (quarter year)
+ "Get the date (week day year) of the first day of a given quarter."
+ (let (startday)
+ (cond
+ ((= quarter 1)
+ (setq startday (org-day-of-week 1 1 year))
+ (cond
+ ((= startday 0)
+ (list 52 7 (- year 1)))
+ ((= startday 6)
+ (list 52 6 (- year 1)))
+ ((<= startday 4)
+ (list 1 startday year))
+ ((> startday 4)
+ (list 53 startday (- year 1)))
+ )
+ )
+ ((= quarter 2)
+ (setq startday (org-day-of-week 1 4 year))
+ (cond
+ ((= startday 0)
+ (list 13 startday year))
+ ((< startday 4)
+ (list 14 startday year))
+ ((>= startday 4)
+ (list 13 startday year))
+ )
+ )
+ ((= quarter 3)
+ (setq startday (org-day-of-week 1 7 year))
+ (cond
+ ((= startday 0)
+ (list 26 startday year))
+ ((< startday 4)
+ (list 27 startday year))
+ ((>= startday 4)
+ (list 26 startday year))
+ )
+ )
+ ((= quarter 4)
+ (setq startday (org-day-of-week 1 10 year))
+ (cond
+ ((= startday 0)
+ (list 39 startday year))
+ ((<= startday 4)
+ (list 40 startday year))
+ ((> startday 4)
+ (list 39 startday year)))))))
+
+(defun org-clock-special-range (key &optional time as-strings wstart mstart)
+ "Return two times bordering a special time range.
+
+KEY is a symbol specifying the range and can be one of `today',
+`yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
+`thisyear', `lastyear' or `untilnow'. If set to `interactive',
+user is prompted for range boundaries. It can be a string or an
+integer.
+
+By default, a week starts Monday 0:00 and ends Sunday 24:00. The
+range is determined relative to TIME, which defaults to current
+time.
+
+The return value is a list containing two internal times, one for
+the beginning of the range and one for its end, like the ones
+returned by `current time' or `encode-time' and a string used to
+display information. If AS-STRINGS is non-nil, the returned
+times will be formatted strings.
+
+If WSTART is non-nil, use this number to specify the starting day
+of a week (monday is 1). If MSTART is non-nil, use this number
+to specify the starting day of a month (1 is the first day of the
+month). If you can combine both, the month starting day will
+have priority."
+ (let* ((tm (decode-time time))
+ (m (nth 1 tm))
+ (h (nth 2 tm))
+ (d (nth 3 tm))
+ (month (nth 4 tm))
+ (y (nth 5 tm))
+ (dow (nth 6 tm))
+ (skey (format "%s" key))
+ (shift 0)
+ (q (cond ((>= month 10) 4)
+ ((>= month 7) 3)
+ ((>= month 4) 2)
+ (t 1)))
+ m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
+ (cond
+ ((string-match "\\`[0-9]+\\'" skey)
+ (setq y (string-to-number skey) month 1 d 1 key 'year))
+ ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
+ (setq y (string-to-number (match-string 1 skey))
+ month (string-to-number (match-string 2 skey))
+ d 1
+ key 'month))
+ ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
+ (require 'cal-iso)
+ (let ((date (calendar-gregorian-from-absolute
+ (calendar-iso-to-absolute
+ (list (string-to-number (match-string 2 skey))
+ 1
+ (string-to-number (match-string 1 skey)))))))
+ (setq d (nth 1 date)
+ month (car date)
+ y (nth 2 date)
+ dow 1
+ key 'week)))
+ ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
+ (require 'cal-iso)
+ (setq q (string-to-number (match-string 2 skey)))
+ (let ((date (calendar-gregorian-from-absolute
+ (calendar-iso-to-absolute
+ (org-quarter-to-date
+ q (string-to-number (match-string 1 skey)))))))
+ (setq d (nth 1 date)
+ month (car date)
+ y (nth 2 date)
+ dow 1
+ key 'quarter)))
+ ((string-match
+ "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
+ skey)
+ (setq y (string-to-number (match-string 1 skey))
+ month (string-to-number (match-string 2 skey))
+ d (string-to-number (match-string 3 skey))
+ key 'day))
+ ((string-match "\\([-+][0-9]+\\)\\'" skey)
+ (setq shift (string-to-number (match-string 1 skey))
+ key (intern (substring skey 0 (match-beginning 1))))
+ (when (and (memq key '(quarter thisq)) (> shift 0))
+ (error "Looking forward with quarters isn't implemented"))))
+ (when (= shift 0)
+ (pcase key
+ (`yesterday (setq key 'today shift -1))
+ (`lastweek (setq key 'week shift -1))
+ (`lastmonth (setq key 'month shift -1))
+ (`lastyear (setq key 'year shift -1))
+ (`lastq (setq key 'quarter shift -1))))
+ ;; Prepare start and end times depending on KEY's type.
+ (pcase key
+ ((or `day `today) (setq m 0 h 0 h1 24 d (+ d shift)))
+ ((or `week `thisweek)
+ (let* ((ws (or wstart 1))
+ (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
+ (setq m 0 h 0 d (- d diff) d1 (+ 7 d))))
+ ((or `month `thismonth)
+ (setq h 0 m 0 d (or mstart 1) month (+ month shift) month1 (1+ month)))
+ ((or `quarter `thisq)
+ ;; Compute if this shift remains in this year. If not, compute
+ ;; how many years and quarters we have to shift (via floor*) and
+ ;; compute the shifted years, months and quarters.
+ (cond
+ ((< (+ (- q 1) shift) 0) ; Shift not in this year.
+ (let* ((interval (* -1 (+ (- q 1) shift)))
+ ;; Set tmp to ((years to shift) (quarters to shift)).
+ (tmp (cl-floor interval 4)))
+ ;; Due to the use of floor, 0 quarters actually means 4.
+ (if (= 0 (nth 1 tmp))
+ (setq shiftedy (- y (nth 0 tmp))
+ shiftedm 1
+ shiftedq 1)
+ (setq shiftedy (- y (+ 1 (nth 0 tmp)))
+ shiftedm (- 13 (* 3 (nth 1 tmp)))
+ shiftedq (- 5 (nth 1 tmp)))))
+ (setq m 0 h 0 d 1 month shiftedm month1 (+ 3 shiftedm) y shiftedy))
+ ((> (+ q shift) 0) ; Shift is within this year.
+ (setq shiftedq (+ q shift))
+ (setq shiftedy y)
+ (let ((qshift (* 3 (1- (+ q shift)))))
+ (setq m 0 h 0 d 1 month (+ 1 qshift) month1 (+ 4 qshift))))))
+ ((or `year `thisyear)
+ (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
+ ((or `interactive `untilnow)) ; Special cases, ignore them.
+ (_ (user-error "No such time block %s" key)))
+ ;; Format start and end times according to AS-STRINGS.
+ (let* ((start (pcase key
+ (`interactive (org-read-date nil t nil "Range start? "))
+ (`untilnow org-clock--oldest-date)
+ (_ (encode-time 0 m h d month y))))
+ (end (pcase key
+ (`interactive (org-read-date nil t nil "Range end? "))
+ (`untilnow (current-time))
+ (_ (encode-time 0
+ (or m1 m)
+ (or h1 h)
+ (or d1 d)
+ (or month1 month)
+ (or y1 y)))))
+ (text
+ (pcase key
+ ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
+ ((or `week `thisweek) (format-time-string "week %G-W%V" start))
+ ((or `month `thismonth) (format-time-string "%B %Y" start))
+ ((or `year `thisyear) (format-time-string "the year %Y" start))
+ ((or `quarter `thisq)
+ (concat (org-count-quarter shiftedq)
+ " quarter of " (number-to-string shiftedy)))
+ (`interactive "(Range interactively set)")
+ (`untilnow "now"))))
+ (if (not as-strings) (list start end text)
+ (let ((f (cdr org-time-stamp-formats)))
+ (list (format-time-string f start)
+ (format-time-string f end)
+ text))))))
+
+(defun org-count-quarter (n)
+ (cond
+ ((= n 1) "1st")
+ ((= n 2) "2nd")
+ ((= n 3) "3rd")
+ ((= n 4) "4th")))
+
+;;;###autoload
+(defun org-clocktable-shift (dir n)
+ "Try to shift the :block date of the clocktable at point.
+Point must be in the #+BEGIN: line of a clocktable, or this function
+will throw an error.
+DIR is a direction, a symbol `left', `right', `up', or `down'.
+Both `left' and `down' shift the block toward the past, `up' and `right'
+push it toward the future.
+N is the number of shift steps to take. The size of the step depends on
+the currently selected interval size."
+ (setq n (prefix-numeric-value n))
+ (and (memq dir '(left down)) (setq n (- n)))
+ (save-excursion
+ (goto-char (point-at-bol))
+ (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
+ (error "Line needs a :block definition before this command works")
+ (let* ((b (match-beginning 1)) (e (match-end 1))
+ (s (match-string 1))
+ block shift ins y mw d date wp m)
+ (cond
+ ((equal s "yesterday") (setq s "today-1"))
+ ((equal s "lastweek") (setq s "thisweek-1"))
+ ((equal s "lastmonth") (setq s "thismonth-1"))
+ ((equal s "lastyear") (setq s "thisyear-1"))
+ ((equal s "lastq") (setq s "thisq-1")))
+
+ (cond
+ ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
+ (setq block (match-string 1 s)
+ shift (if (match-end 2)
+ (string-to-number (match-string 2 s))
+ 0))
+ (setq shift (+ shift n))
+ (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
+ ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
+ ;; 1 1 2 3 3 4 4 5 6 6 5 2
+ (setq y (string-to-number (match-string 1 s))
+ wp (and (match-end 3) (match-string 3 s))
+ mw (and (match-end 4) (string-to-number (match-string 4 s)))
+ d (and (match-end 6) (string-to-number (match-string 6 s))))
+ (cond
+ (d (setq ins (format-time-string
+ "%Y-%m-%d"
+ (encode-time 0 0 0 (+ d n) m y))))
+ ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
+ (require 'cal-iso)
+ (setq date (calendar-gregorian-from-absolute
+ (calendar-iso-to-absolute (list (+ mw n) 1 y))))
+ (setq ins (format-time-string
+ "%G-W%V"
+ (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
+ ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
+ (require 'cal-iso)
+ ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
+ (if (> (+ mw n) 4)
+ (setq mw 0
+ y (+ 1 y))
+ ())
+ ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
+ (if (= (+ mw n) 0)
+ (setq mw 5
+ y (- y 1))
+ ())
+ (setq date (calendar-gregorian-from-absolute
+ (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
+ (setq ins (format-time-string
+ (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
+ (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
+ (mw
+ (setq ins (format-time-string
+ "%Y-%m"
+ (encode-time 0 0 0 1 (+ mw n) y))))
+ (y
+ (setq ins (number-to-string (+ y n))))))
+ (t (error "Cannot shift clocktable block")))
+ (when ins
+ (goto-char b)
+ (insert ins)
+ (delete-region (point) (+ (point) (- e b)))
+ (beginning-of-line 1)
+ (org-update-dblock)
+ t)))))
+
+;;;###autoload
+(defun org-dblock-write:clocktable (params)
+ "Write the standard clocktable."
+ (setq params (org-combine-plists org-clocktable-defaults params))
+ (catch 'exit
+ (let* ((scope (plist-get params :scope))
+ (files (pcase scope
+ (`agenda
+ (org-agenda-files t))
+ (`agenda-with-archives
+ (org-add-archive-files (org-agenda-files t)))
+ (`file-with-archives
+ (and buffer-file-name
+ (org-add-archive-files (list buffer-file-name))))
+ ((pred consp) scope)
+ (_ (or (buffer-file-name) (current-buffer)))))
+ (block (plist-get params :block))
+ (ts (plist-get params :tstart))
+ (te (plist-get params :tend))
+ (ws (plist-get params :wstart))
+ (ms (plist-get params :mstart))
+ (step (plist-get params :step))
+ (formatter (or (plist-get params :formatter)
+ org-clock-clocktable-formatter
+ 'org-clocktable-write-default))
+ cc)
+ ;; Check if we need to do steps
+ (when block
+ ;; Get the range text for the header
+ (setq cc (org-clock-special-range block nil t ws ms)
+ ts (car cc)
+ te (nth 1 cc)))
+ (when step
+ ;; Write many tables, in steps
+ (unless (or block (and ts te))
+ (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
+ (org-clocktable-steps params)
+ (throw 'exit nil))
+
+ (org-agenda-prepare-buffers (if (consp files) files (list files)))
+
+ (let ((origin (point))
+ (tables
+ (if (consp files)
+ (mapcar (lambda (file)
+ (with-current-buffer (find-buffer-visiting file)
+ (save-excursion
+ (save-restriction
+ (org-clock-get-table-data file params)))))
+ files)
+ ;; Get the right restriction for the scope.
+ (save-restriction
+ (cond
+ ((not scope)) ;use the restriction as it is now
+ ((eq scope 'file) (widen))
+ ((eq scope 'subtree) (org-narrow-to-subtree))
+ ((eq scope 'tree)
+ (while (org-up-heading-safe))
+ (org-narrow-to-subtree))
+ ((and (symbolp scope)
+ (string-match "\\`tree\\([0-9]+\\)\\'"
+ (symbol-name scope)))
+ (let ((level (string-to-number
+ (match-string 1 (symbol-name scope)))))
+ (catch 'exit
+ (while (org-up-heading-safe)
+ (looking-at org-outline-regexp)
+ (when (<= (org-reduced-level (funcall outline-level))
+ level)
+ (throw 'exit nil))))
+ (org-narrow-to-subtree))))
+ (list (org-clock-get-table-data nil params)))))
+ (multifile
+ ;; Even though `file-with-archives' can consist of
+ ;; multiple files, we consider this is one extended file
+ ;; instead.
+ (and (consp files) (not (eq scope 'file-with-archives)))))
+
+ (funcall formatter
+ origin
+ tables
+ (org-combine-plists params `(:multifile ,multifile)))))))
+
+(defun org-clocktable-write-default (ipos tables params)
+ "Write out a clock table at position IPOS in the current buffer.
+TABLES is a list of tables with clocking data as produced by
+`org-clock-get-table-data'. PARAMS is the parameter property list obtained
+from the dynamic block definition."
+ ;; This function looks quite complicated, mainly because there are a
+ ;; lot of options which can add or remove columns. I have massively
+ ;; commented this function, the I hope it is understandable. If
+ ;; someone wants to write their own special formatter, this maybe
+ ;; much easier because there can be a fixed format with a
+ ;; well-defined number of columns...
+ (let* ((hlchars '((1 . "*") (2 . "/")))
+ (lwords (assoc (or (plist-get params :lang)
+ (bound-and-true-p org-export-default-language)
+ "en")
+ org-clock-clocktable-language-setup))
+ (multifile (plist-get params :multifile))
+ (block (plist-get params :block))
+ (sort (plist-get params :sort))
+ (header (plist-get params :header))
+ (ws (or (plist-get params :wstart) 1))
+ (ms (or (plist-get params :mstart) 1))
+ (link (plist-get params :link))
+ (org-time-clocksum-use-effort-durations
+ (plist-get params :effort-durations))
+ (maxlevel (or (plist-get params :maxlevel) 3))
+ (emph (plist-get params :emphasize))
+ (compact? (plist-get params :compact))
+ (narrow (or (plist-get params :narrow) (and compact? '40!)))
+ (level? (and (not compact?) (plist-get params :level)))
+ (timestamp (plist-get params :timestamp))
+ (properties (plist-get params :properties))
+ (time-columns
+ (if (or compact? (< maxlevel 2)) 1
+ ;; Deepest headline level is a hard limit for the number
+ ;; of time columns.
+ (let ((levels
+ (cl-mapcan
+ (lambda (table)
+ (pcase table
+ (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
+ (mapcar #'car entries))))
+ tables)))
+ (min maxlevel
+ (or (plist-get params :tcolumns) 100)
+ (if (null levels) 1 (apply #'max levels))))))
+ (indent (or compact? (plist-get params :indent)))
+ (formula (plist-get params :formula))
+ (case-fold-search t)
+ range-text total-time recalc narrow-cut-p)
+
+ (when (and narrow (integerp narrow) link)
+ ;; We cannot have both integer narrow and link.
+ (message
+ "Using hard narrowing in clocktable to allow for links")
+ (setq narrow (intern (format "%d!" narrow))))
+
+ (when narrow
+ (cond
+ ((integerp narrow))
+ ((and (symbolp narrow)
+ (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
+ (setq narrow-cut-p t
+ narrow (string-to-number (substring (symbol-name narrow)
+ 0 -1))))
+ (t
+ (error "Invalid value %s of :narrow property in clock table"
+ narrow))))
+
+ (when block
+ ;; Get the range text for the header.
+ (setq range-text (nth 2 (org-clock-special-range block nil t ws ms))))
+
+ ;; Compute the total time.
+ (setq total-time (apply #'+ (mapcar #'cadr tables)))
+
+ ;; Now we need to output this tsuff.
+ (goto-char ipos)
+
+ ;; Insert the text *before* the actual table.
+ (insert-before-markers
+ (or header
+ ;; Format the standard header.
+ (concat
+ "#+CAPTION: "
+ (nth 9 lwords) " ["
+ (substring
+ (format-time-string (cdr org-time-stamp-formats))
+ 1 -1)
+ "]"
+ (if block (concat ", for " range-text ".") "")
+ "\n")))
+
+ ;; Insert the narrowing line
+ (when (and narrow (integerp narrow) (not narrow-cut-p))
+ (insert-before-markers
+ "|" ;table line starter
+ (if multifile "|" "") ;file column, maybe
+ (if level? "|" "") ;level column, maybe
+ (if timestamp "|" "") ;timestamp column, maybe
+ (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
+ (format "<%d>| |\n" narrow))) ; headline and time columns
+
+ ;; Insert the table header line
+ (insert-before-markers
+ "|" ;table line starter
+ (if multifile (concat (nth 1 lwords) "|") "") ;file column, maybe
+ (if level? (concat (nth 2 lwords) "|") "") ;level column, maybe
+ (if timestamp (concat (nth 3 lwords) "|") "") ;timestamp column, maybe
+ (if properties ;properties columns, maybe
+ (concat (mapconcat #'identity properties "|") "|")
+ "")
+ (concat (nth 4 lwords) "|") ;headline
+ (concat (nth 5 lwords) "|") ;time column
+ (make-string (max 0 (1- time-columns)) ?|) ;other time columns
+ (if (eq formula '%) "%|\n" "\n"))
+
+ ;; Insert the total time in the table
+ (insert-before-markers
+ "|-\n" ;a hline
+ "|" ;table line starter
+ (if multifile (concat "| " (nth 6 lwords) " ") "")
+ ;file column, maybe
+ (if level? "|" "") ;level column, maybe
+ (if timestamp "|" "") ;timestamp column, maybe
+ (make-string (length properties) ?|) ;properties columns, maybe
+ (concat (format org-clock-total-time-cell-format (nth 7 lwords))
+ "| ")
+ (format org-clock-total-time-cell-format
+ (org-minutes-to-clocksum-string (or total-time 0))) ;time
+ "|"
+ (make-string (max 0 (1- time-columns)) ?|)
+ (cond ((not (eq formula '%)) "")
+ ((or (not total-time) (= total-time 0)) "0.0|")
+ (t "100.0|"))
+ "\n")
+
+ ;; Now iterate over the tables and insert the data but only if any
+ ;; time has been collected.
+ (when (and total-time (> total-time 0))
+ (pcase-dolist (`(,file-name ,file-time ,entries) tables)
+ (when (or (and file-time (> file-time 0))
+ (not (plist-get params :fileskip0)))
+ (insert-before-markers "|-\n") ;hline at new file
+ ;; First the file time, if we have multiple files.
+ (when multifile
+ ;; Summarize the time collected from this file.
+ (insert-before-markers
+ (format (concat "| %s %s | %s%s"
+ (format org-clock-file-time-cell-format
+ (nth 8 lwords))
+ " | *%s*|\n")
+ (file-name-nondirectory file-name)
+ (if level? "| " "") ;level column, maybe
+ (if timestamp "| " "") ;timestamp column, maybe
+ (if properties ;properties columns, maybe
+ (make-string (length properties) ?|)
+ "")
+ (org-minutes-to-clocksum-string file-time)))) ;time
+
+ ;; Get the list of node entries and iterate over it
+ (when (> maxlevel 0)
+ (pcase-dolist (`(,level ,headline ,ts ,time ,props) entries)
+ (when narrow-cut-p
+ (setq headline
+ (if (and (string-match
+ (format "\\`%s\\'" org-bracket-link-regexp)
+ headline)
+ (match-end 3))
+ (format "[[%s][%s]]"
+ (match-string 1 headline)
+ (org-shorten-string (match-string 3 headline)
+ narrow))
+ (org-shorten-string headline narrow))))
+ (let ((hlc (if emph (or (cdr (assoc level hlchars)) "") "")))
+ (insert-before-markers
+ "|" ;start the table line
+ (if multifile "|" "") ;free space for file name column?
+ (if level? (format "%d|" level) "") ;level, maybe
+ (if timestamp (concat ts "|") "") ;timestamp, maybe
+ (if properties ;properties columns, maybe
+ (concat (mapconcat (lambda (p)
+ (or (cdr (assoc p props)) ""))
+ properties
+ "|")
+ "|")
+ "")
+ (if indent ;indentation
+ (org-clocktable-indent-string level)
+ "")
+ hlc headline hlc "|" ;headline
+ ;; Empty fields for higher levels.
+ (make-string (max 0 (1- (min time-columns level))) ?|)
+ hlc (org-minutes-to-clocksum-string time) hlc "|" ; time
+ (make-string (max 0 (- time-columns level)) ?|)
+ (if (eq formula '%)
+ (format "%.1f |" (* 100 (/ time (float total-time))))
+ "")
+ "\n")))))))
+ (delete-char -1)
+ (cond
+ ;; Possibly rescue old formula?
+ ((or (not formula) (eq formula '%))
+ (let ((contents (org-string-nw-p (plist-get params :content))))
+ (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
+ (setq recalc t)
+ (insert "\n" (match-string 1 contents))
+ (beginning-of-line 0))))
+ ;; Insert specified formula line.
+ ((stringp formula)
+ (insert "\n#+TBLFM: " formula)
+ (setq recalc t))
+ (t
+ (user-error "Invalid :formula parameter in clocktable")))
+ ;; Back to beginning, align the table, recalculate if necessary.
+ (goto-char ipos)
+ (skip-chars-forward "^|")
+ (org-table-align)
+ (when org-hide-emphasis-markers
+ ;; We need to align a second time.
+ (org-table-align))
+ (when sort
+ (save-excursion
+ (org-table-goto-line 3)
+ (org-table-goto-column (car sort))
+ (org-table-sort-lines nil (cdr sort))))
+ (when recalc (org-table-recalculate 'all))
+ total-time))
+
+(defun org-clocktable-indent-string (level)
+ "Return indentation string according to LEVEL.
+LEVEL is an integer. Indent by two spaces per level above 1."
+ (if (= level 1) ""
+ (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
+
+(defun org-clocktable-steps (params)
+ "Step through the range to make a number of clock tables."
+ (let* ((p1 (copy-sequence params))
+ (ts (plist-get p1 :tstart))
+ (te (plist-get p1 :tend))
+ (ws (plist-get p1 :wstart))
+ (ms (plist-get p1 :mstart))
+ (step0 (plist-get p1 :step))
+ (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
+ (stepskip0 (plist-get p1 :stepskip0))
+ (block (plist-get p1 :block))
+ cc step-time tsb)
+ (when block
+ (setq cc (org-clock-special-range block nil t ws ms)
+ ts (car cc)
+ te (nth 1 cc)))
+ (cond
+ ((numberp ts)
+ ;; If ts is a number, it's an absolute day number from
+ ;; org-agenda.
+ (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
+ (setq ts (float-time (encode-time 0 0 0 day month year)))))
+ (ts
+ (setq ts (float-time
+ (apply #'encode-time (org-parse-time-string ts nil t))))))
+ (cond
+ ((numberp te)
+ ;; Likewise for te.
+ (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
+ (setq te (float-time (encode-time 0 0 0 day month year)))))
+ (te
+ (setq te (float-time
+ (apply #'encode-time (org-parse-time-string te nil t))))))
+ (setq tsb
+ (if (eq step0 'week)
+ (- ts (* 86400 (- (nth 6 (decode-time (seconds-to-time ts))) ws)))
+ ts))
+ (setq p1 (plist-put p1 :header ""))
+ (setq p1 (plist-put p1 :step nil))
+ (setq p1 (plist-put p1 :block nil))
+ (while (< tsb te)
+ (or (bolp) (insert "\n"))
+ (setq p1 (plist-put p1 :tstart (format-time-string
+ (org-time-stamp-format nil t)
+ (seconds-to-time (max tsb ts)))))
+ (setq p1 (plist-put p1 :tend (format-time-string
+ (org-time-stamp-format nil t)
+ (seconds-to-time (min te (setq tsb (+ tsb step)))))))
+ (insert "\n" (if (eq step0 'day) "Daily report: "
+ "Weekly report starting on: ")
+ (plist-get p1 :tstart) "\n")
+ (setq step-time (org-dblock-write:clocktable p1))
+ (re-search-forward "^[ \t]*#\\+END:")
+ (when (and (equal step-time 0) stepskip0)
+ ;; Remove the empty table
+ (delete-region (point-at-bol)
+ (save-excursion
+ (re-search-backward "^\\(Daily\\|Weekly\\) report"
+ nil t)
+ (point))))
+ (end-of-line 0))))
+
+(defun org-clock-get-table-data (file params)
+ "Get the clocktable data for file FILE, with parameters PARAMS.
+FILE is only for identification - this function assumes that
+the correct buffer is current, and that the wanted restriction is
+in place.
+The return value will be a list with the file name and the total
+file time (in minutes) as 1st and 2nd elements. The third element
+of this list will be a list of headline entries. Each entry has the
+following structure:
+
+ (LEVEL HEADLINE TIMESTAMP TIME PROPERTIES)
+
+LEVEL: The level of the headline, as an integer. This will be
+ the reduced level, so 1,2,3,... even if only odd levels
+ are being used.
+HEADLINE: The text of the headline. Depending on PARAMS, this may
+ already be formatted like a link.
+TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
+ entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
+ in this sequence.
+TIME: The sum of all time spend in this tree, in minutes. This time
+ will of cause be restricted to the time block and tags match
+ specified in PARAMS.
+PROPERTIES: The list properties specified in the `:properties' parameter
+ along with their value, as an alist following the pattern
+ (NAME . VALUE)."
+ (let* ((maxlevel (or (plist-get params :maxlevel) 3))
+ (timestamp (plist-get params :timestamp))
+ (ts (plist-get params :tstart))
+ (te (plist-get params :tend))
+ (ws (plist-get params :wstart))
+ (ms (plist-get params :mstart))
+ (block (plist-get params :block))
+ (link (plist-get params :link))
+ (tags (plist-get params :tags))
+ (properties (plist-get params :properties))
+ (inherit-property-p (plist-get params :inherit-props))
+ (matcher (and tags (cdr (org-make-tags-matcher tags))))
+ cc st p tbl)
+
+ (setq org-clock-file-total-minutes nil)
+ (when block
+ (setq cc (org-clock-special-range block nil t ws ms)
+ ts (car cc)
+ te (nth 1 cc)))
+ (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
+ (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
+ (when (and ts (listp ts))
+ (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
+ (when (and te (listp te))
+ (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
+ ;; Now the times are strings we can parse.
+ (if ts (setq ts (org-matcher-time ts)))
+ (if te (setq te (org-matcher-time te)))
+ (save-excursion
+ (org-clock-sum ts te
+ (when matcher
+ `(lambda ()
+ (let* ((tags-list (org-get-tags-at))
+ (org-scanner-tags tags-list)
+ (org-trust-scanner-tags t))
+ (funcall ,matcher nil tags-list nil)))))
+ (goto-char (point-min))
+ (setq st t)
+ (while (or (and (bobp) (prog1 st (setq st nil))
+ (get-text-property (point) :org-clock-minutes)
+ (setq p (point-min)))
+ (setq p (next-single-property-change
+ (point) :org-clock-minutes)))
+ (goto-char p)
+ (let ((time (get-text-property p :org-clock-minutes)))
+ (when (and time (> time 0) (org-at-heading-p))
+ (let ((level (org-reduced-level (org-current-level))))
+ (when (<= level maxlevel)
+ (let* ((headline (replace-regexp-in-string
+ (format "\\`%s[ \t]+" org-comment-string) ""
+ (nth 4 (org-heading-components))))
+ (hdl
+ (if (not link) headline
+ (let ((search
+ (org-make-org-heading-search-string headline)))
+ (org-make-link-string
+ (if (not (buffer-file-name)) search
+ (format "file:%s::%s" (buffer-file-name) search))
+ ;; Prune statistics cookies. Replace
+ ;; links with their description, or
+ ;; a plain link if there is none.
+ (org-trim
+ (org-link-display-format
+ (replace-regexp-in-string
+ "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
+ headline)))))))
+ (tsp
+ (and timestamp
+ (let ((p (org-entry-properties (point) 'special)))
+ (or (cdr (assoc "SCHEDULED" p))
+ (cdr (assoc "DEADLINE" p))
+ (cdr (assoc "TIMESTAMP" p))
+ (cdr (assoc "TIMESTAMP_IA" p))))))
+ (props
+ (and properties
+ (delq nil
+ (mapcar
+ (lambda (p)
+ (let ((v (org-entry-get
+ (point) p inherit-property-p)))
+ (and v (cons p v))))
+ properties)))))
+ (push (list level hdl tsp time props) tbl)))))))
+ (list file org-clock-file-total-minutes (nreverse tbl)))))
+
+;; Saving and loading the clock
+
+(defvar org-clock-loaded nil
+ "Was the clock file loaded?")
+
+;;;###autoload
+(defun org-clock-update-time-maybe ()
+ "If this is a CLOCK line, update it and return t.
+Otherwise, return nil."
+ (interactive)
+ (save-excursion
+ (beginning-of-line 1)
+ (skip-chars-forward " \t")
+ (when (looking-at org-clock-string)
+ (let ((re (concat "[ \t]*" org-clock-string
+ " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
+ "\\([ \t]*=>.*\\)?\\)?"))
+ ts te h m s neg)
+ (cond
+ ((not (looking-at re))
+ nil)
+ ((not (match-end 2))
+ (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
+ (> org-clock-marker (point))
+ (<= org-clock-marker (point-at-eol)))
+ ;; The clock is running here
+ (setq org-clock-start-time
+ (apply 'encode-time
+ (org-parse-time-string (match-string 1))))
+ (org-clock-update-mode-line)))
+ (t
+ (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
+ (end-of-line 1)
+ (setq ts (match-string 1)
+ te (match-string 3))
+ (setq s (- (float-time
+ (apply #'encode-time (org-parse-time-string te nil t)))
+ (float-time
+ (apply #'encode-time (org-parse-time-string ts nil t))))
+ neg (< s 0)
+ s (abs s)
+ h (floor (/ s 3600))
+ s (- s (* 3600 h))
+ m (floor (/ s 60))
+ s (- s (* 60 s)))
+ (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
+ t))))))
+
+(defun org-clock-save ()
+ "Persist various clock-related data to disk.
+The details of what will be saved are regulated by the variable
+`org-clock-persist'."
+ (when (and org-clock-persist
+ (or org-clock-loaded
+ org-clock-has-been-used
+ (not (file-exists-p org-clock-persist-file))))
+ (with-temp-file org-clock-persist-file
+ (insert (format ";; %s - %s at %s\n"
+ (file-name-nondirectory org-clock-persist-file)
+ (system-name)
+ (format-time-string (org-time-stamp-format t))))
+ ;; Store clock to be resumed.
+ (when (and (memq org-clock-persist '(t clock))
+ (let ((b (org-base-buffer (org-clocking-buffer))))
+ (and (buffer-live-p b)
+ (buffer-file-name b)
+ (or (not org-clock-persist-query-save)
+ (y-or-n-p (format "Save current clock (%s) "
+ org-clock-heading))))))
+ (insert
+ (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
+ (buffer-file-name (org-base-buffer (org-clocking-buffer)))
+ (marker-position org-clock-marker))))
+ ;; Store clocked task history. Tasks are stored reversed to
+ ;; make reading simpler.
+ (when (and (memq org-clock-persist '(t history))
+ org-clock-history)
+ (insert
+ (format "(setq org-clock-stored-history '(%s))\n"
+ (mapconcat
+ (lambda (m)
+ (let ((b (org-base-buffer (marker-buffer m))))
+ (when (and (buffer-live-p b)
+ (buffer-file-name b))
+ (format "(%S . %d)"
+ (buffer-file-name b)
+ (marker-position m)))))
+ (reverse org-clock-history)
+ " ")))))))
+
+(defun org-clock-load ()
+ "Load clock-related data from disk, maybe resuming a stored clock."
+ (when (and org-clock-persist (not org-clock-loaded))
+ (if (not (file-readable-p org-clock-persist-file))
+ (message "Not restoring clock data; %S not found" org-clock-persist-file)
+ (message "Restoring clock data")
+ ;; Load history.
+ (load-file org-clock-persist-file)
+ (setq org-clock-loaded t)
+ (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
+ org-clock-stored-history)
+ (org-clock-history-push position (find-file-noselect file)))
+ ;; Resume clock.
+ (pcase org-clock-stored-resume-clock
+ (`(,(and file (pred file-exists-p)) . ,position)
+ (with-current-buffer (find-file-noselect file)
+ (when (or (not org-clock-persist-query-resume)
+ (y-or-n-p (format "Resume clock (%s) "
+ (save-excursion
+ (goto-char position)
+ (org-get-heading t t)))))
+ (goto-char position)
+ (let ((org-clock-in-resume 'auto-restart)
+ (org-clock-auto-clock-resolution nil))
+ (org-clock-in)
+ (when (org-invisible-p) (org-show-context))))))
+ (_ nil)))))
+
+;; Suggested bindings
+(org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
+
+(provide 'org-clock)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-clock.el ends here
diff --git a/lisp/org-colview.el b/lisp/org-colview.el
new file mode 100644
index 0000000..ac8f36a
--- /dev/null
+++ b/lisp/org-colview.el
@@ -0,0 +1,1661 @@
+;;; org-colview.el --- Column View in Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the column view for Org.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+
+(declare-function org-agenda-redo "org-agenda" (&optional all))
+(declare-function org-agenda-do-context-action "org-agenda" ())
+(declare-function org-clock-sum-today "org-clock" (&optional headline-filter))
+(declare-function org-element-extract-element "org-element" (element))
+(declare-function org-element-interpret-data "org-element" (data))
+(declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
+(declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-restriction "org-element" (element))
+(declare-function org-element-type "org-element" (element))
+
+(defvar org-agenda-columns-add-appointments-to-effort-sum)
+(defvar org-agenda-columns-compute-summary-properties)
+(defvar org-agenda-columns-show-summaries)
+(defvar org-agenda-view-columns-initially)
+(defvar org-inlinetask-min-level)
+
+
+;;; Configuration
+
+(defcustom org-columns-modify-value-for-display-function nil
+ "Function that modifies values for display in column view.
+For example, it can be used to cut out a certain part from a time stamp.
+The function must take 2 arguments:
+
+column-title The title of the column (*not* the property name)
+value The value that should be modified.
+
+The function should return the value that should be displayed,
+or nil if the normal value should be used."
+ :group 'org-properties
+ :type '(choice (const nil) (function)))
+
+(defcustom org-columns-summary-types nil
+ "Alist between operators and summarize functions.
+
+Each association follows the pattern (LABEL . SUMMARIZE) where
+
+ LABEL is a string used in #+COLUMNS definition describing the
+ summary type. It can contain any character but \"}\". It is
+ case-sensitive.
+
+ SUMMARIZE is a function called with two arguments. The first
+ argument is a non-empty list of values, as non-empty strings.
+ The second one is a format string or nil. It has to return
+ a string summarizing the list of values.
+
+Note that the return value can become one value for an higher
+order summary, so the function is expected to handle its own
+output.
+
+Types defined in this variable take precedence over those defined
+in `org-columns-summary-types-default', which see."
+ :group 'org-properties
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type '(alist :key-type (string :tag " Label")
+ :value-type (function :tag "Summarize")))
+
+
+
+;;; Column View
+
+(defvar org-columns-overlays nil
+ "Holds the list of current column overlays.")
+
+(defvar org-columns--time 0.0
+ "Number of seconds since the epoch, as a floating point number.")
+
+(defvar-local org-columns-current-fmt nil
+ "Local variable, holds the currently active column format.")
+
+(defvar-local org-columns-current-fmt-compiled nil
+ "Local variable, holds the currently active column format.
+This is the compiled version of the format.")
+
+(defvar-local org-columns-current-maxwidths nil
+ "Currently active maximum column widths, as a vector.")
+
+(defvar org-columns-begin-marker (make-marker)
+ "Points to the position where last a column creation command was called.")
+
+(defvar org-columns-top-level-marker (make-marker)
+ "Points to the position where current columns region starts.")
+
+(defvar org-columns-map (make-sparse-keymap)
+ "The keymap valid in column display.")
+
+(defconst org-columns-summary-types-default
+ '(("+" . org-columns--summary-sum)
+ ("$" . org-columns--summary-currencies)
+ ("X" . org-columns--summary-checkbox)
+ ("X/" . org-columns--summary-checkbox-count)
+ ("X%" . org-columns--summary-checkbox-percent)
+ ("max" . org-columns--summary-max)
+ ("mean" . org-columns--summary-mean)
+ ("min" . org-columns--summary-min)
+ (":" . org-columns--summary-sum-times)
+ (":max" . org-columns--summary-max-time)
+ (":mean" . org-columns--summary-mean-time)
+ (":min" . org-columns--summary-min-time)
+ ("@max" . org-columns--summary-max-age)
+ ("@mean" . org-columns--summary-mean-age)
+ ("@min" . org-columns--summary-min-age)
+ ("est+" . org-columns--summary-estimate))
+ "Map operators to summarize functions.
+See `org-columns-summary-types' for details.")
+
+(defun org-columns-content ()
+ "Switch to contents view while in columns view."
+ (interactive)
+ (org-overview)
+ (org-content))
+
+(org-defkey org-columns-map "c" 'org-columns-content)
+(org-defkey org-columns-map "o" 'org-overview)
+(org-defkey org-columns-map "e" 'org-columns-edit-value)
+(org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
+(org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
+(org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
+(org-defkey org-columns-map "v" 'org-columns-show-value)
+(org-defkey org-columns-map "q" 'org-columns-quit)
+(org-defkey org-columns-map "r" 'org-columns-redo)
+(org-defkey org-columns-map "g" 'org-columns-redo)
+(org-defkey org-columns-map [left] 'backward-char)
+(org-defkey org-columns-map "\M-b" 'backward-char)
+(org-defkey org-columns-map "a" 'org-columns-edit-allowed)
+(org-defkey org-columns-map "s" 'org-columns-edit-attributes)
+(org-defkey org-columns-map "\M-f"
+ (lambda () (interactive) (goto-char (1+ (point)))))
+(org-defkey org-columns-map [right]
+ (lambda () (interactive) (goto-char (1+ (point)))))
+(org-defkey org-columns-map [down]
+ (lambda () (interactive)
+ (let ((col (current-column)))
+ (beginning-of-line 2)
+ (while (and (org-invisible-p2) (not (eobp)))
+ (beginning-of-line 2))
+ (move-to-column col)
+ (if (eq major-mode 'org-agenda-mode)
+ (org-agenda-do-context-action)))))
+(org-defkey org-columns-map [up]
+ (lambda () (interactive)
+ (let ((col (current-column)))
+ (beginning-of-line 0)
+ (while (and (org-invisible-p2) (not (bobp)))
+ (beginning-of-line 0))
+ (move-to-column col)
+ (if (eq major-mode 'org-agenda-mode)
+ (org-agenda-do-context-action)))))
+(org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
+(org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
+(org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
+(org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
+(org-defkey org-columns-map "<" 'org-columns-narrow)
+(org-defkey org-columns-map ">" 'org-columns-widen)
+(org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
+(org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
+(org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
+(org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
+(dotimes (i 10)
+ (org-defkey org-columns-map (number-to-string i)
+ `(lambda () (interactive)
+ (org-columns-next-allowed-value nil ,i))))
+
+(easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
+ '("Column"
+ ["Edit property" org-columns-edit-value t]
+ ["Next allowed value" org-columns-next-allowed-value t]
+ ["Previous allowed value" org-columns-previous-allowed-value t]
+ ["Show full value" org-columns-show-value t]
+ ["Edit allowed values" org-columns-edit-allowed t]
+ "--"
+ ["Edit column attributes" org-columns-edit-attributes t]
+ ["Increase column width" org-columns-widen t]
+ ["Decrease column width" org-columns-narrow t]
+ "--"
+ ["Move column right" org-columns-move-right t]
+ ["Move column left" org-columns-move-left t]
+ ["Add column" org-columns-new t]
+ ["Delete column" org-columns-delete t]
+ "--"
+ ["CONTENTS" org-columns-content t]
+ ["OVERVIEW" org-overview t]
+ ["Refresh columns display" org-columns-redo t]
+ "--"
+ ["Open link" org-columns-open-link t]
+ "--"
+ ["Quit" org-columns-quit t]))
+
+(defun org-columns--displayed-value (spec value)
+ "Return displayed value for specification SPEC in current entry.
+SPEC is a column format specification as stored in
+`org-columns-current-fmt-compiled'. VALUE is the real value to
+display, as a string."
+ (or (and (functionp org-columns-modify-value-for-display-function)
+ (funcall org-columns-modify-value-for-display-function
+ (nth 1 spec) ;column name
+ value))
+ (pcase spec
+ (`("ITEM" . ,_)
+ (concat (make-string (1- (org-current-level))
+ (if org-hide-leading-stars ?\s ?*))
+ "* "
+ (org-columns-compact-links value)))
+ (`(,_ ,_ ,_ ,_ nil) value)
+ ;; If PRINTF is set, assume we are displaying a number and
+ ;; obey to the format string.
+ (`(,_ ,_ ,_ ,_ ,printf) (format printf (string-to-number value)))
+ (_ (error "Invalid column specification format: %S" spec)))))
+
+(defun org-columns--collect-values (&optional compiled-fmt)
+ "Collect values for columns on the current line.
+
+Return a list of triplets (SPEC VALUE DISPLAYED) suitable for
+`org-columns--display-here'.
+
+This function assumes `org-columns-current-fmt-compiled' is
+initialized is set in the current buffer. However, it is
+possible to override it with optional argument COMPILED-FMT."
+ (let ((summaries (get-text-property (point) 'org-summaries)))
+ (mapcar
+ (lambda (spec)
+ (pcase spec
+ (`(,p . ,_)
+ (let* ((v (or (cdr (assoc spec summaries))
+ (org-entry-get (point) p 'selective t)
+ (and compiled-fmt ;assume `org-agenda-columns'
+ ;; Effort property is not defined. Try
+ ;; to use appointment duration.
+ org-agenda-columns-add-appointments-to-effort-sum
+ (string= p (upcase org-effort-property))
+ (get-text-property (point) 'duration)
+ (propertize (org-minutes-to-clocksum-string
+ (get-text-property (point) 'duration))
+ 'face 'org-warning))
+ "")))
+ (list spec v (org-columns--displayed-value spec v))))))
+ (or compiled-fmt org-columns-current-fmt-compiled))))
+
+(defun org-columns--set-widths (cache)
+ "Compute the maximum column widths from the format and CACHE.
+This function sets `org-columns-current-maxwidths' as a vector of
+integers greater than 0."
+ (setq org-columns-current-maxwidths
+ (apply #'vector
+ (mapcar
+ (lambda (spec)
+ (pcase spec
+ (`(,_ ,_ ,(and width (pred wholenump)) . ,_) width)
+ (`(,_ ,name . ,_)
+ ;; No width is specified in the columns format.
+ ;; Compute it by checking all possible values for
+ ;; PROPERTY.
+ (let ((width (length name)))
+ (dolist (entry cache width)
+ (let ((value (nth 2 (assoc spec (cdr entry)))))
+ (setq width (max (length value) width))))))))
+ org-columns-current-fmt-compiled))))
+
+(defun org-columns--new-overlay (beg end &optional string face)
+ "Create a new column overlay and add it to the list."
+ (let ((ov (make-overlay beg end)))
+ (overlay-put ov 'face (or face 'secondary-selection))
+ (org-overlay-display ov string face)
+ (push ov org-columns-overlays)
+ ov))
+
+(defun org-columns--summarize (operator)
+ "Return summary function associated to string OPERATOR."
+ (if (not operator) nil
+ (cdr (or (assoc operator org-columns-summary-types)
+ (assoc operator org-columns-summary-types-default)
+ (error "Unknown %S operator" operator)))))
+
+(defun org-columns--overlay-text (value fmt width property original)
+ "Return text "
+ (format fmt
+ (let ((v (org-columns-add-ellipses value width)))
+ (pcase property
+ ("PRIORITY"
+ (propertize v 'face (org-get-priority-face original)))
+ ("TAGS"
+ (if (not org-tags-special-faces-re)
+ (propertize v 'face 'org-tag)
+ (replace-regexp-in-string
+ org-tags-special-faces-re
+ (lambda (m) (propertize m 'face (org-get-tag-face m)))
+ v nil nil 1)))
+ ("TODO" (propertize v 'face (org-get-todo-face original)))
+ (_ v)))))
+
+(defun org-columns--display-here (columns &optional dateline)
+ "Overlay the current line with column display.
+COLUMNS is an alist (SPEC VALUE DISPLAYED). Optional argument
+DATELINE is non-nil when the face used should be
+`org-agenda-column-dateline'."
+ (save-excursion
+ (beginning-of-line)
+ (let* ((level-face (and (looking-at "\\(\\**\\)\\(\\* \\)")
+ (org-get-level-face 2)))
+ (ref-face (or level-face
+ (and (eq major-mode 'org-agenda-mode)
+ (org-get-at-bol 'face))
+ 'default))
+ (color (list :foreground (face-attribute ref-face :foreground)))
+ (font (list :height (face-attribute 'default :height)
+ :family (face-attribute 'default :family)))
+ (face (list color font 'org-column ref-face))
+ (face1 (list color font 'org-agenda-column-dateline ref-face)))
+ ;; Each column is an overlay on top of a character. So there has
+ ;; to be at least as many characters available on the line as
+ ;; columns to display.
+ (let ((columns (length org-columns-current-fmt-compiled))
+ (chars (- (line-end-position) (line-beginning-position))))
+ (when (> columns chars)
+ (save-excursion
+ (end-of-line)
+ (let ((inhibit-read-only t))
+ (insert (make-string (- columns chars) ?\s))))))
+ ;; Display columns. Create and install the overlay for the
+ ;; current column on the next character.
+ (let ((i 0)
+ (last (1- (length columns))))
+ (dolist (column columns)
+ (pcase column
+ (`(,spec ,original ,value)
+ (let* ((property (car spec))
+ (width (aref org-columns-current-maxwidths i))
+ (fmt (format (if (= i last) "%%-%d.%ds |"
+ "%%-%d.%ds | ")
+ width width))
+ (ov (org-columns--new-overlay
+ (point) (1+ (point))
+ (org-columns--overlay-text
+ value fmt width property original)
+ (if dateline face1 face))))
+ (overlay-put ov 'keymap org-columns-map)
+ (overlay-put ov 'org-columns-key property)
+ (overlay-put ov 'org-columns-value original)
+ (overlay-put ov 'org-columns-value-modified value)
+ (overlay-put ov 'org-columns-format fmt)
+ (overlay-put ov 'line-prefix "")
+ (overlay-put ov 'wrap-prefix "")
+ (forward-char))))
+ (cl-incf i)))
+ ;; Make the rest of the line disappear.
+ (let ((ov (org-columns--new-overlay (point) (line-end-position))))
+ (overlay-put ov 'invisible t)
+ (overlay-put ov 'keymap org-columns-map)
+ (overlay-put ov 'line-prefix "")
+ (overlay-put ov 'wrap-prefix ""))
+ (let ((ov (make-overlay (1- (line-end-position))
+ (line-beginning-position 2))))
+ (overlay-put ov 'keymap org-columns-map)
+ (push ov org-columns-overlays))
+ (org-with-silent-modifications
+ (let ((inhibit-read-only t))
+ (put-text-property
+ (line-end-position 0)
+ (line-beginning-position 2)
+ 'read-only
+ (substitute-command-keys
+ "Type \\<org-columns-map>`\\[org-columns-edit-value]' \
+to edit property")))))))
+
+(defun org-columns-add-ellipses (string width)
+ "Truncate STRING with WIDTH characters, with ellipses."
+ (cond
+ ((<= (length string) width) string)
+ ((<= width (length org-columns-ellipses))
+ (substring org-columns-ellipses 0 width))
+ (t (concat (substring string 0 (- width (length org-columns-ellipses)))
+ org-columns-ellipses))))
+
+(defvar org-columns-full-header-line-format nil
+ "The full header line format, will be shifted by horizontal scrolling." )
+(defvar org-previous-header-line-format nil
+ "The header line format before column view was turned on.")
+(defvar org-columns-inhibit-recalculation nil
+ "Inhibit recomputing of columns on column view startup.")
+(defvar org-columns-flyspell-was-active nil
+ "Remember the state of `flyspell-mode' before column view.
+Flyspell-mode can cause problems in columns view, so it is turned off
+for the duration of the command.")
+
+(defvar header-line-format)
+(defvar org-columns-previous-hscroll 0)
+
+(defun org-columns--display-here-title ()
+ "Overlay the newline before the current line with the table title."
+ (interactive)
+ (let ((title "")
+ (i 0))
+ (dolist (column org-columns-current-fmt-compiled)
+ (pcase column
+ (`(,property ,name . ,_)
+ (let* ((width (aref org-columns-current-maxwidths i))
+ (fmt (format "%%-%d.%ds | " width width)))
+ (setq title (concat title (format fmt (or name property)))))))
+ (cl-incf i))
+ (setq-local org-previous-header-line-format header-line-format)
+ (setq org-columns-full-header-line-format
+ (concat
+ (org-add-props " " nil 'display '(space :align-to 0))
+ (org-add-props (substring title 0 -1) nil 'face 'org-column-title)))
+ (setq org-columns-previous-hscroll -1)
+ (add-hook 'post-command-hook 'org-columns-hscroll-title nil 'local)))
+
+(defun org-columns-hscroll-title ()
+ "Set the `header-line-format' so that it scrolls along with the table."
+ (sit-for .0001) ; need to force a redisplay to update window-hscroll
+ (when (not (= (window-hscroll) org-columns-previous-hscroll))
+ (setq header-line-format
+ (concat (substring org-columns-full-header-line-format 0 1)
+ (substring org-columns-full-header-line-format
+ (1+ (window-hscroll))))
+ org-columns-previous-hscroll (window-hscroll))
+ (force-mode-line-update)))
+
+(defvar org-colview-initial-truncate-line-value nil
+ "Remember the value of `truncate-lines' across colview.")
+
+;;;###autoload
+(defun org-columns-remove-overlays ()
+ "Remove all currently active column overlays."
+ (interactive)
+ (when (marker-buffer org-columns-begin-marker)
+ (with-current-buffer (marker-buffer org-columns-begin-marker)
+ (when (local-variable-p 'org-previous-header-line-format)
+ (setq header-line-format org-previous-header-line-format)
+ (kill-local-variable 'org-previous-header-line-format)
+ (remove-hook 'post-command-hook 'org-columns-hscroll-title 'local))
+ (move-marker org-columns-begin-marker nil)
+ (move-marker org-columns-top-level-marker nil)
+ (org-with-silent-modifications
+ (mapc 'delete-overlay org-columns-overlays)
+ (setq org-columns-overlays nil)
+ (let ((inhibit-read-only t))
+ (remove-text-properties (point-min) (point-max) '(read-only t))))
+ (when org-columns-flyspell-was-active
+ (flyspell-mode 1))
+ (when (local-variable-p 'org-colview-initial-truncate-line-value)
+ (setq truncate-lines org-colview-initial-truncate-line-value)))))
+
+(defun org-columns-compact-links (s)
+ "Replace [[link][desc]] with [desc] or [link]."
+ (while (string-match org-bracket-link-regexp s)
+ (setq s (replace-match
+ (concat "[" (match-string (if (match-end 3) 3 1) s) "]")
+ t t s)))
+ s)
+
+(defun org-columns-show-value ()
+ "Show the full value of the property."
+ (interactive)
+ (let ((value (get-char-property (point) 'org-columns-value)))
+ (message "Value is: %s" (or value ""))))
+
+(defvar org-agenda-columns-active) ;; defined in org-agenda.el
+
+(defun org-columns-quit ()
+ "Remove the column overlays and in this way exit column editing."
+ (interactive)
+ (org-with-silent-modifications
+ (org-columns-remove-overlays)
+ (let ((inhibit-read-only t))
+ (remove-text-properties (point-min) (point-max) '(read-only t))))
+ (if (not (eq major-mode 'org-agenda-mode))
+ (setq org-columns-current-fmt nil)
+ (setq org-agenda-columns-active nil)
+ (message
+ "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
+
+(defun org-columns-check-computed ()
+ "Throw an error if current column value is computed."
+ (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
+ (and
+ (nth 3 spec)
+ (assoc spec (get-text-property (line-beginning-position) 'org-summaries))
+ (error "This value is computed from the entry's children"))))
+
+(defun org-columns-todo (&optional _arg)
+ "Change the TODO state during column view."
+ (interactive "P")
+ (org-columns-edit-value "TODO"))
+
+(defun org-columns-set-tags-or-toggle (&optional _arg)
+ "Toggle checkbox at point, or set tags for current headline."
+ (interactive "P")
+ (if (string-match "\\`\\[[ xX-]\\]\\'"
+ (get-char-property (point) 'org-columns-value))
+ (org-columns-next-allowed-value)
+ (org-columns-edit-value "TAGS")))
+
+(defvar org-agenda-overriding-columns-format nil
+ "When set, overrides any other format definition for the agenda.
+Don't set this, this is meant for dynamic scoping.")
+
+(defun org-columns-edit-value (&optional key)
+ "Edit the value of the property at point in column view.
+Where possible, use the standard interface for changing this line."
+ (interactive)
+ (org-columns-check-computed)
+ (let* ((col (current-column))
+ (bol (line-beginning-position))
+ (eol (line-end-position))
+ (pom (or (get-text-property bol 'org-hd-marker) (point)))
+ (key (or key (get-char-property (point) 'org-columns-key)))
+ (org-columns--time (float-time (current-time)))
+ (action
+ (pcase key
+ ("CLOCKSUM"
+ (error "This special column cannot be edited"))
+ ("ITEM"
+ (lambda () (org-with-point-at pom (org-edit-headline))))
+ ("TODO"
+ (lambda ()
+ (org-with-point-at pom (call-interactively #'org-todo))))
+ ("PRIORITY"
+ (lambda ()
+ (org-with-point-at pom
+ (call-interactively #'org-priority))))
+ ("TAGS"
+ (lambda ()
+ (org-with-point-at pom
+ (let ((org-fast-tag-selection-single-key
+ (if (eq org-fast-tag-selection-single-key 'expert)
+ t
+ org-fast-tag-selection-single-key)))
+ (call-interactively #'org-set-tags)))))
+ ("DEADLINE"
+ (lambda ()
+ (org-with-point-at pom (call-interactively #'org-deadline))))
+ ("SCHEDULED"
+ (lambda ()
+ (org-with-point-at pom (call-interactively #'org-schedule))))
+ ("BEAMER_ENV"
+ (lambda ()
+ (org-with-point-at pom
+ (call-interactively #'org-beamer-select-environment))))
+ (_
+ (let* ((allowed (org-property-get-allowed-values pom key 'table))
+ (value (get-char-property (point) 'org-columns-value))
+ (nval (org-trim
+ (if (null allowed) (read-string "Edit: " value)
+ (completing-read
+ "Value: " allowed nil
+ (not (get-text-property
+ 0 'org-unrestricted (caar allowed))))))))
+ (and (not (equal nval value))
+ (lambda () (org-entry-put pom key nval))))))))
+ (cond
+ ((null action))
+ ((eq major-mode 'org-agenda-mode)
+ (org-columns--call action)
+ ;; The following let preserves the current format, and makes
+ ;; sure that in only a single file things need to be updated.
+ (let* ((org-agenda-overriding-columns-format org-columns-current-fmt)
+ (buffer (marker-buffer pom))
+ (org-agenda-contributing-files
+ (list (with-current-buffer buffer
+ (buffer-file-name (buffer-base-buffer))))))
+ (org-agenda-columns)))
+ (t
+ (let ((inhibit-read-only t))
+ (org-with-silent-modifications
+ (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t)))
+ (org-columns--call action))
+ ;; Some properties can modify headline (e.g., "TODO"), and
+ ;; possible shuffle overlays. Make sure they are still all at
+ ;; the right place on the current line.
+ (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
+ (org-columns-update key)
+ (org-move-to-column col)))))
+
+(defun org-columns-edit-allowed ()
+ "Edit the list of allowed values for the current property."
+ (interactive)
+ (let* ((pom (or (org-get-at-bol 'org-marker)
+ (org-get-at-bol 'org-hd-marker)
+ (point)))
+ (key (get-char-property (point) 'org-columns-key))
+ (key1 (concat key "_ALL"))
+ (allowed (org-entry-get pom key1 t))
+ nval)
+ ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
+ ;; FIXME: Write back to #+PROPERTY setting if that is needed.
+ (setq nval (read-string "Allowed: " allowed))
+ (org-entry-put
+ (cond ((marker-position org-entry-property-inherited-from)
+ org-entry-property-inherited-from)
+ ((marker-position org-columns-top-level-marker)
+ org-columns-top-level-marker)
+ (t pom))
+ key1 nval)))
+
+(defun org-columns--call (fun)
+ "Call function FUN while preserving heading visibility.
+FUN is a function called with no argument."
+ (let ((hide-body (and (/= (line-end-position) (point-max))
+ (save-excursion
+ (move-beginning-of-line 2)
+ (org-at-heading-p t)))))
+ (unwind-protect (funcall fun)
+ (when hide-body (outline-hide-entry)))))
+
+(defun org-columns-previous-allowed-value ()
+ "Switch to the previous allowed value for this column."
+ (interactive)
+ (org-columns-next-allowed-value t))
+
+(defun org-columns-next-allowed-value (&optional previous nth)
+ "Switch to the next allowed value for this column.
+When PREVIOUS is set, go to the previous value. When NTH is
+an integer, select that value."
+ (interactive)
+ (org-columns-check-computed)
+ (let* ((column (current-column))
+ (key (get-char-property (point) 'org-columns-key))
+ (value (get-char-property (point) 'org-columns-value))
+ (pom (or (get-text-property (line-beginning-position) 'org-hd-marker)
+ (point)))
+ (allowed
+ (let ((all
+ (or (org-property-get-allowed-values pom key)
+ (pcase (nth column org-columns-current-fmt-compiled)
+ (`(,_ ,_ ,_ ,(or "X" "X/" "X%") ,_) '("[ ]" "[X]")))
+ (org-colview-construct-allowed-dates value))))
+ (if previous (reverse all) all))))
+ (when (equal key "ITEM") (error "Cannot edit item headline from here"))
+ (unless (or allowed (member key '("SCHEDULED" "DEADLINE" "CLOCKSUM")))
+ (error "Allowed values for this property have not been defined"))
+ (let* ((l (length allowed))
+ (new
+ (cond
+ ((member key '("SCHEDULED" "DEADLINE" "CLOCKSUM"))
+ (if previous 'earlier 'later))
+ ((integerp nth)
+ (when (> (abs nth) l)
+ (user-error "Only %d allowed values for property `%s'" l key))
+ (nth (mod (1- nth) l) allowed))
+ ((member value allowed)
+ (when (= l 1) (error "Only one allowed value for this property"))
+ (or (nth 1 (member value allowed)) (car allowed)))
+ (t (car allowed))))
+ (action (lambda () (org-entry-put pom key new))))
+ (cond
+ ((eq major-mode 'org-agenda-mode)
+ (org-columns--call action)
+ ;; The following let preserves the current format, and makes
+ ;; sure that in only a single file things need to be updated.
+ (let* ((org-agenda-overriding-columns-format org-columns-current-fmt)
+ (buffer (marker-buffer pom))
+ (org-agenda-contributing-files
+ (list (with-current-buffer buffer
+ (buffer-file-name (buffer-base-buffer))))))
+ (org-agenda-columns)))
+ (t
+ (let ((inhibit-read-only t))
+ (remove-text-properties (line-end-position 0) (line-end-position)
+ '(read-only t))
+ (org-columns--call action))
+ ;; Some properties can modify headline (e.g., "TODO"), and
+ ;; possible shuffle overlays. Make sure they are still all at
+ ;; the right place on the current line.
+ (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
+ (org-columns-update key)
+ (org-move-to-column column))))))
+
+(defun org-colview-construct-allowed-dates (s)
+ "Construct a list of three dates around the date in S.
+This respects the format of the time stamp in S, active or non-active,
+and also including time or not. S must be just a time stamp, no text
+around it."
+ (when (and s (string-match (concat "^" org-ts-regexp3 "$") s))
+ (let* ((time (org-parse-time-string s 'nodefaults))
+ (active (equal (string-to-char s) ?<))
+ (fmt (funcall (if (nth 1 time) 'cdr 'car) org-time-stamp-formats))
+ time-before time-after)
+ (unless active (setq fmt (concat "[" (substring fmt 1 -1) "]")))
+ (setf (car time) (or (car time) 0))
+ (setf (nth 1 time) (or (nth 1 time) 0))
+ (setf (nth 2 time) (or (nth 2 time) 0))
+ (setq time-before (copy-sequence time))
+ (setq time-after (copy-sequence time))
+ (setf (nth 3 time-before) (1- (nth 3 time)))
+ (setf (nth 3 time-after) (1+ (nth 3 time)))
+ (mapcar (lambda (x) (format-time-string fmt (apply 'encode-time x)))
+ (list time-before time time-after)))))
+
+(defun org-columns-open-link (&optional arg)
+ (interactive "P")
+ (let ((value (get-char-property (point) 'org-columns-value)))
+ (org-open-link-from-string value arg)))
+
+;;;###autoload
+(defun org-columns-get-format-and-top-level ()
+ (let ((fmt (org-columns-get-format)))
+ (org-columns-goto-top-level)
+ fmt))
+
+(defun org-columns-get-format (&optional fmt-string)
+ "Return columns format specifications.
+When optional argument FMT-STRING is non-nil, use it as the
+current specifications. This function also sets
+`org-columns-current-fmt-compiled' and
+`org-columns-current-fmt'."
+ (interactive)
+ (let ((format
+ (or fmt-string
+ (org-entry-get nil "COLUMNS" t)
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (catch :found
+ (let ((case-fold-search t))
+ (while (re-search-forward "^[ \t]*#\\+COLUMNS: .+$" nil t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (throw :found (org-element-property :value element)))))
+ nil)))
+ org-columns-default-format)))
+ (setq org-columns-current-fmt format)
+ (org-columns-compile-format format)
+ format))
+
+(defun org-columns-goto-top-level ()
+ "Move to the beginning of the column view area.
+Also sets `org-columns-top-level-marker' to the new position."
+ (goto-char
+ (move-marker
+ org-columns-top-level-marker
+ (cond ((org-before-first-heading-p) (point-min))
+ ((org-entry-get nil "COLUMNS" t) org-entry-property-inherited-from)
+ (t (org-back-to-heading) (point))))))
+
+;;;###autoload
+(defun org-columns (&optional global columns-fmt-string)
+ "Turn on column view on an Org mode file.
+
+Column view applies to the whole buffer if point is before the
+first headline. Otherwise, it applies to the first ancestor
+setting \"COLUMNS\" property. If there is none, it defaults to
+the current headline. With a `\\[universal-argument]' prefix \
+argument, turn on column
+view for the whole buffer unconditionally.
+
+When COLUMNS-FMT-STRING is non-nil, use it as the column format."
+ (interactive "P")
+ (org-columns-remove-overlays)
+ (when global (goto-char (point-min)))
+ (move-marker org-columns-begin-marker (point))
+ (org-columns-goto-top-level)
+ ;; Initialize `org-columns-current-fmt' and
+ ;; `org-columns-current-fmt-compiled'.
+ (let ((org-columns--time (float-time (current-time))))
+ (org-columns-get-format columns-fmt-string)
+ (unless org-columns-inhibit-recalculation (org-columns-compute-all))
+ (save-excursion
+ (save-restriction
+ (when (and (not global) (org-at-heading-p))
+ (narrow-to-region (point) (org-end-of-subtree t t)))
+ (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
+ (org-clock-sum))
+ (when (assoc "CLOCKSUM_T" org-columns-current-fmt-compiled)
+ (org-clock-sum-today))
+ (let ((cache
+ ;; Collect contents of columns ahead of time so as to
+ ;; compute their maximum width.
+ (org-map-entries
+ (lambda () (cons (point) (org-columns--collect-values)))
+ nil nil (and org-columns-skip-archived-trees 'archive))))
+ (when cache
+ (org-columns--set-widths cache)
+ (org-columns--display-here-title)
+ (when (setq-local org-columns-flyspell-was-active
+ (bound-and-true-p flyspell-mode))
+ (flyspell-mode 0))
+ (unless (local-variable-p 'org-colview-initial-truncate-line-value)
+ (setq-local org-colview-initial-truncate-line-value
+ truncate-lines))
+ (setq truncate-lines t)
+ (dolist (entry cache)
+ (goto-char (car entry))
+ (org-columns--display-here (cdr entry)))))))))
+
+(defun org-columns-new (&optional spec &rest attributes)
+ "Insert a new column, to the left of the current column.
+Interactively fill attributes for new column. When column format
+specification SPEC is provided, edit it instead.
+
+When optional argument attributes can be a list of columns
+specifications attributes to create the new column
+non-interactively. See `org-columns-compile-format' for
+details."
+ (interactive)
+ (let ((new (or attributes
+ (let ((prop
+ (completing-read
+ "Property: "
+ (mapcar #'list (org-buffer-property-keys t nil t))
+ nil nil (nth 0 spec))))
+ (list prop
+ (read-string (format "Column title [%s]: " prop)
+ (nth 1 spec))
+ ;; Use `read-string' instead of `read-number'
+ ;; to allow empty width.
+ (let ((w (read-string
+ "Column width: "
+ (and (nth 2 spec)
+ (number-to-string (nth 2 spec))))))
+ (and (org-string-nw-p w) (string-to-number w)))
+ (org-string-nw-p
+ (completing-read
+ "Summary: "
+ (delete-dups
+ (cons '("") ;Allow empty operator.
+ (mapcar (lambda (x) (list (car x)))
+ (append
+ org-columns-summary-types
+ org-columns-summary-types-default))))
+ nil t (nth 3 spec)))
+ (org-string-nw-p
+ (read-string "Format: " (nth 4 spec))))))))
+ (if spec
+ (progn (setcar spec (car new))
+ (setcdr spec (cdr new)))
+ (push new (nthcdr (current-column) org-columns-current-fmt-compiled)))
+ (org-columns-store-format)
+ (org-columns-redo)))
+
+(defun org-columns-delete ()
+ "Delete the column at point from columns view."
+ (interactive)
+ (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
+ (when (y-or-n-p (format "Are you sure you want to remove column %S? "
+ (nth 1 spec)))
+ (setq org-columns-current-fmt-compiled
+ (delq spec org-columns-current-fmt-compiled))
+ (org-columns-store-format)
+ ;; This may leave a now wrong value in a node property. However
+ ;; updating it may prove counter-intuitive. See comments in
+ ;; `org-columns-move-right' for details.
+ (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
+ (when (>= (current-column) (length org-columns-current-fmt-compiled))
+ (backward-char)))))
+
+(defun org-columns-edit-attributes ()
+ "Edit the attributes of the current column."
+ (interactive)
+ (org-columns-new (nth (current-column) org-columns-current-fmt-compiled)))
+
+(defun org-columns-widen (arg)
+ "Make the column wider by ARG characters."
+ (interactive "p")
+ (let* ((n (current-column))
+ (entry (nth n org-columns-current-fmt-compiled))
+ (width (aref org-columns-current-maxwidths n)))
+ (setq width (max 1 (+ width arg)))
+ (setcar (nthcdr 2 entry) width)
+ (org-columns-store-format)
+ (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))))
+
+(defun org-columns-narrow (arg)
+ "Make the column narrower by ARG characters."
+ (interactive "p")
+ (org-columns-widen (- arg)))
+
+(defun org-columns-move-right ()
+ "Swap this column with the one to the right."
+ (interactive)
+ (let* ((n (current-column))
+ (cell (nthcdr n org-columns-current-fmt-compiled))
+ e)
+ (when (>= n (1- (length org-columns-current-fmt-compiled)))
+ (error "Cannot shift this column further to the right"))
+ (setq e (car cell))
+ (setcar cell (car (cdr cell)))
+ (setcdr cell (cons e (cdr (cdr cell))))
+ (org-columns-store-format)
+ ;; Do not compute again properties, since we're just moving
+ ;; columns around. It can put a property value a bit off when
+ ;; switching between an non-computed and a computed value for the
+ ;; same property, e.g. from "%A %A{+}" to "%A{+} %A".
+ ;;
+ ;; In this case, the value needs to be updated since the first
+ ;; column related to a property determines how its value is
+ ;; computed. However, (correctly) updating the value could be
+ ;; surprising, so we leave it as-is nonetheless.
+ (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
+ (forward-char 1)))
+
+(defun org-columns-move-left ()
+ "Swap this column with the one to the left."
+ (interactive)
+ (let* ((n (current-column)))
+ (when (= n 0)
+ (error "Cannot shift this column further to the left"))
+ (backward-char 1)
+ (org-columns-move-right)
+ (backward-char 1)))
+
+(defun org-columns-store-format ()
+ "Store the text version of the current columns format.
+The format is stored either in the COLUMNS property of the node
+starting the current column display, or in a #+COLUMNS line of
+the current buffer."
+ (let ((fmt (org-columns-uncompile-format org-columns-current-fmt-compiled)))
+ (setq-local org-columns-current-fmt fmt)
+ (when (marker-position org-columns-top-level-marker)
+ (org-with-wide-buffer
+ (goto-char org-columns-top-level-marker)
+ (if (and (org-at-heading-p) (org-entry-get nil "COLUMNS"))
+ (org-entry-put nil "COLUMNS" fmt)
+ (goto-char (point-min))
+ (let ((case-fold-search t))
+ ;; Try to replace the first COLUMNS keyword available.
+ (catch :found
+ (while (re-search-forward "^[ \t]*#\\+COLUMNS:\\(.*\\)" nil t)
+ (let ((element (save-match-data (org-element-at-point))))
+ (when (and (eq (org-element-type element) 'keyword)
+ (equal (org-element-property :key element)
+ "COLUMNS"))
+ (replace-match (concat " " fmt) t t nil 1)
+ (throw :found nil))))
+ ;; No COLUMNS keyword in the buffer. Insert one at the
+ ;; beginning, right before the first heading, if any.
+ (goto-char (point-min))
+ (unless (org-at-heading-p t) (outline-next-heading))
+ (let ((inhibit-read-only t))
+ (insert-before-markers "#+COLUMNS: " fmt "\n"))))
+ (setq-local org-columns-default-format fmt))))))
+
+(defun org-columns-update (property)
+ "Recompute PROPERTY, and update the columns display for it."
+ (org-columns-compute property)
+ (org-with-wide-buffer
+ (let ((p (upcase property)))
+ (dolist (ov org-columns-overlays)
+ (let ((key (overlay-get ov 'org-columns-key)))
+ (when (and key (equal key p) (overlay-start ov))
+ (goto-char (overlay-start ov))
+ (let* ((spec (nth (current-column) org-columns-current-fmt-compiled))
+ (value
+ (or (cdr (assoc spec
+ (get-text-property (line-beginning-position)
+ 'org-summaries)))
+ (org-entry-get (point) key))))
+ (when value
+ (let ((displayed (org-columns--displayed-value spec value))
+ (format (overlay-get ov 'org-columns-format))
+ (width
+ (aref org-columns-current-maxwidths (current-column))))
+ (overlay-put ov 'org-columns-value value)
+ (overlay-put ov 'org-columns-value-modified displayed)
+ (overlay-put ov
+ 'display
+ (org-columns--overlay-text
+ displayed format width property value)))))))))))
+
+(defun org-columns-redo ()
+ "Construct the column display again."
+ (interactive)
+ (message "Recomputing columns...")
+ (org-with-wide-buffer
+ (when (marker-position org-columns-begin-marker)
+ (goto-char org-columns-begin-marker))
+ (org-columns-remove-overlays)
+ (if (derived-mode-p 'org-mode)
+ ;; Since we already know the columns format, provide it instead
+ ;; of computing again.
+ (call-interactively #'org-columns org-columns-current-fmt)
+ (org-agenda-redo)
+ (call-interactively #'org-agenda-columns)))
+ (message "Recomputing columns...done"))
+
+(defun org-columns-uncompile-format (compiled)
+ "Turn the compiled columns format back into a string representation.
+COMPILED is an alist, as returned by
+`org-columns-compile-format', which see."
+ (mapconcat
+ (lambda (spec)
+ (pcase spec
+ (`(,prop ,title ,width ,op ,printf)
+ (concat "%"
+ (and width (number-to-string width))
+ prop
+ (and title (not (equal prop title)) (format "(%s)" title))
+ (cond ((not op) nil)
+ (printf (format "{%s;%s}" op printf))
+ (t (format "{%s}" op)))))))
+ compiled " "))
+
+(defun org-columns-compile-format (fmt)
+ "Turn a column format string FMT into an alist of specifications.
+
+The alist has one entry for each column in the format. The elements of
+that list are:
+property the property name, as an upper-case string
+title the title field for the columns, as a string
+width the column width in characters, can be nil for automatic width
+operator the summary operator, as a string, or nil
+printf a printf format for computed values, as a string, or nil
+
+This function updates `org-columns-current-fmt-compiled'."
+ (setq org-columns-current-fmt-compiled nil)
+ (let ((start 0))
+ (while (string-match
+ "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\
+\\(?:{\\([^}]+\\)}\\)?\\s-*"
+ fmt start)
+ (setq start (match-end 0))
+ (let* ((width (and (match-end 1) (string-to-number (match-string 1 fmt))))
+ (prop (match-string-no-properties 2 fmt))
+ (title (or (match-string-no-properties 3 fmt) prop))
+ (operator (match-string-no-properties 4 fmt)))
+ (push (if (not operator) (list (upcase prop) title width nil nil)
+ (let (printf)
+ (when (string-match ";" operator)
+ (setq printf (substring operator (match-end 0)))
+ (setq operator (substring operator 0 (match-beginning 0))))
+ (list (upcase prop) title width operator printf)))
+ org-columns-current-fmt-compiled)))
+ (setq org-columns-current-fmt-compiled
+ (nreverse org-columns-current-fmt-compiled))))
+
+
+;;;; Column View Summary
+
+(defconst org-columns--duration-re
+ (concat "[0-9.]+ *" (regexp-opt (mapcar #'car org-effort-durations)))
+ "Regexp matching a duration.")
+
+(defun org-columns--time-to-seconds (s)
+ "Turn time string S into a number of seconds.
+A time is expressed as HH:MM, HH:MM:SS, or with units defined in
+`org-effort-durations'. Plain numbers are considered as hours."
+ (cond
+ ((string-match-p org-columns--duration-re s)
+ (* 60 (org-duration-string-to-minutes s)))
+ ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?\\'" s)
+ (+ (* 3600 (string-to-number (match-string 1 s)))
+ (* 60 (string-to-number (match-string 2 s)))
+ (if (match-end 3) (string-to-number (match-string 3 s)) 0)))
+ (t (* 3600 (string-to-number s)))))
+
+(defun org-columns--age-to-seconds (s)
+ "Turn age string S into a number of seconds.
+An age is either computed from a given time-stamp, or indicated
+as days/hours/minutes/seconds."
+ (cond
+ ((string-match-p org-ts-regexp s)
+ (floor
+ (- org-columns--time
+ (float-time (apply #'encode-time (org-parse-time-string s nil t))))))
+ ;; Match own output for computations in upper levels.
+ ((string-match "\\([0-9]+\\)d \\([0-9]+\\)h \\([0-9]+\\)m \\([0-9]+\\)s" s)
+ (+ (* 86400 (string-to-number (match-string 1 s)))
+ (* 3600 (string-to-number (match-string 2 s)))
+ (* 60 (string-to-number (match-string 3 s)))
+ (string-to-number (match-string 4 s))))
+ (t (user-error "Invalid age: %S" s))))
+
+(defun org-columns--summary-apply-times (fun times)
+ "Apply FUN to time values TIMES.
+If TIMES contains any time value expressed as a duration, return
+the result as a duration. If it contains any H:M:S, use that
+format instead. Otherwise, use H:M format."
+ (let* ((hms-flag nil)
+ (duration-flag nil)
+ (seconds
+ (apply fun
+ (mapcar
+ (lambda (time)
+ (cond
+ (duration-flag)
+ ((string-match-p org-columns--duration-re time)
+ (setq duration-flag t))
+ (hms-flag)
+ ((string-match-p "\\`[0-9]+:[0-9]+:[0-9]+\\'" time)
+ (setq hms-flag t)))
+ (org-columns--time-to-seconds time))
+ times))))
+ (cond (duration-flag (org-minutes-to-clocksum-string (/ seconds 60.0)))
+ (hms-flag (format-seconds "%h:%.2m:%.2s" seconds))
+ (t (format-seconds "%h:%.2m" seconds)))))
+
+(defun org-columns--compute-spec (spec &optional update)
+ "Update tree according to SPEC.
+SPEC is a column format specification. When optional argument
+UPDATE is non-nil, summarized values can replace existing ones in
+properties drawers."
+ (let* ((lmax (if (bound-and-true-p org-inlinetask-min-level)
+ org-inlinetask-min-level
+ 29)) ;Hard-code deepest level.
+ (lvals (make-vector (1+ lmax) nil))
+ (level 0)
+ (inminlevel lmax)
+ (last-level lmax)
+ (property (car spec))
+ (printf (nth 4 spec))
+ (summarize (org-columns--summarize (nth 3 spec))))
+ (org-with-wide-buffer
+ ;; Find the region to compute.
+ (goto-char org-columns-top-level-marker)
+ (goto-char (condition-case nil (org-end-of-subtree t) (error (point-max))))
+ ;; Walk the tree from the back and do the computations.
+ (while (re-search-backward
+ org-outline-regexp-bol org-columns-top-level-marker t)
+ (unless (or (= level 0) (eq level inminlevel))
+ (setq last-level level))
+ (setq level (org-reduced-level (org-outline-level)))
+ (let* ((pos (match-beginning 0))
+ (value (org-entry-get nil property))
+ (value-set (org-string-nw-p value)))
+ (cond
+ ((< level last-level)
+ ;; Collect values from lower levels and inline tasks here
+ ;; and summarize them using SUMMARIZE. Store them in text
+ ;; property `org-summaries', in alist whose key is SPEC.
+ (let* ((summary
+ (and summarize
+ (let ((values (append (and (/= last-level inminlevel)
+ (aref lvals last-level))
+ (aref lvals inminlevel))))
+ (and values (funcall summarize values printf))))))
+ ;; Leaf values are not summaries: do not mark them.
+ (when summary
+ (let* ((summaries-alist (get-text-property pos 'org-summaries))
+ (old (assoc spec summaries-alist)))
+ (if old (setcdr old summary)
+ (push (cons spec summary) summaries-alist)
+ (org-with-silent-modifications
+ (add-text-properties
+ pos (1+ pos) (list 'org-summaries summaries-alist)))))
+ ;; When PROPERTY exists in current node, even if empty,
+ ;; but its value doesn't match the one computed, use
+ ;; the latter instead.
+ ;;
+ ;; Ignore leading or trailing white spaces that might
+ ;; have been introduced in summary, since those are not
+ ;; significant in properties value.
+ (let ((new-value (org-trim summary)))
+ (when (and update value (not (equal value new-value)))
+ (org-entry-put (point) property new-value))))
+ ;; Add current to current level accumulator.
+ (when (or summary value-set)
+ (push (or summary value) (aref lvals level)))
+ ;; Clear accumulators for deeper levels.
+ (cl-loop for l from (1+ level) to lmax do (aset lvals l nil))))
+ (value-set (push value (aref lvals level)))
+ (t nil)))))))
+
+;;;###autoload
+(defun org-columns-compute (property)
+ "Summarize the values of PROPERTY hierarchically.
+Also update existing values for PROPERTY according to the first
+column specification."
+ (interactive)
+ (let ((main-flag t)
+ (upcase-prop (upcase property)))
+ (dolist (spec org-columns-current-fmt-compiled)
+ (pcase spec
+ (`(,(pred (equal upcase-prop)) . ,_)
+ (org-columns--compute-spec spec main-flag)
+ ;; Only the first summary can update the property value.
+ (when main-flag (setq main-flag nil)))))))
+
+(defun org-columns-compute-all ()
+ "Compute all columns that have operators defined."
+ (org-with-silent-modifications
+ (remove-text-properties (point-min) (point-max) '(org-summaries t)))
+ (let ((org-columns--time (float-time (current-time)))
+ seen)
+ (dolist (spec org-columns-current-fmt-compiled)
+ (let ((property (car spec)))
+ ;; Property value is updated only the first time a given
+ ;; property is encountered.
+ (org-columns--compute-spec spec (not (member property seen)))
+ (push property seen)))))
+
+(defun org-columns--summary-sum (values printf)
+ "Compute the sum of VALUES.
+When PRINTF is non-nil, use it to format the result."
+ (format (or printf "%s") (apply #'+ (mapcar #'string-to-number values))))
+
+(defun org-columns--summary-currencies (values _)
+ "Compute the sum of VALUES, with two decimals."
+ (format "%.2f" (apply #'+ (mapcar #'string-to-number values))))
+
+(defun org-columns--summary-checkbox (check-boxes _)
+ "Summarize CHECK-BOXES with a check-box."
+ (let ((done (cl-count "[X]" check-boxes :test #'equal))
+ (all (length check-boxes)))
+ (cond ((= done all) "[X]")
+ ((> done 0) "[-]")
+ (t "[ ]"))))
+
+(defun org-columns--summary-checkbox-count (check-boxes _)
+ "Summarize CHECK-BOXES with a check-box cookie."
+ (format "[%d/%d]"
+ (cl-count-if (lambda (b) (or (equal b "[X]")
+ (string-match-p "\\[\\([1-9]\\)/\\1\\]" b)))
+ check-boxes)
+ (length check-boxes)))
+
+(defun org-columns--summary-checkbox-percent (check-boxes _)
+ "Summarize CHECK-BOXES with a check-box percent."
+ (format "[%d%%]"
+ (round (* 100.0 (cl-count-if (lambda (b) (member b '("[X]" "[100%]")))
+ check-boxes))
+ (length check-boxes))))
+
+(defun org-columns--summary-min (values printf)
+ "Compute the minimum of VALUES.
+When PRINTF is non-nil, use it to format the result."
+ (format (or printf "%s")
+ (apply #'min (mapcar #'string-to-number values))))
+
+(defun org-columns--summary-max (values printf)
+ "Compute the maximum of VALUES.
+When PRINTF is non-nil, use it to format the result."
+ (format (or printf "%s")
+ (apply #'max (mapcar #'string-to-number values))))
+
+(defun org-columns--summary-mean (values printf)
+ "Compute the mean of VALUES.
+When PRINTF is non-nil, use it to format the result."
+ (format (or printf "%s")
+ (/ (apply #'+ (mapcar #'string-to-number values))
+ (float (length values)))))
+
+(defun org-columns--summary-sum-times (times _)
+ "Sum TIMES."
+ (org-columns--summary-apply-times #'+ times))
+
+(defun org-columns--summary-min-time (times _)
+ "Compute the minimum time among TIMES."
+ (org-columns--summary-apply-times #'min times))
+
+(defun org-columns--summary-max-time (times _)
+ "Compute the maximum time among TIMES."
+ (org-columns--summary-apply-times #'max times))
+
+(defun org-columns--summary-mean-time (times _)
+ "Compute the mean time among TIMES."
+ (org-columns--summary-apply-times
+ (lambda (&rest values) (/ (apply #'+ values) (float (length values))))
+ times))
+
+(defun org-columns--summary-min-age (ages _)
+ "Compute the minimum time among AGES."
+ (format-seconds
+ "%dd %.2hh %mm %ss"
+ (apply #'min (mapcar #'org-columns--age-to-seconds ages))))
+
+(defun org-columns--summary-max-age (ages _)
+ "Compute the maximum time among AGES."
+ (format-seconds
+ "%dd %.2hh %mm %ss"
+ (apply #'max (mapcar #'org-columns--age-to-seconds ages))))
+
+(defun org-columns--summary-mean-age (ages _)
+ "Compute the minimum time among AGES."
+ (format-seconds
+ "%dd %.2hh %mm %ss"
+ (/ (apply #'+ (mapcar #'org-columns--age-to-seconds ages))
+ (float (length ages)))))
+
+(defun org-columns--summary-estimate (estimates _)
+ "Combine a list of estimates, using mean and variance.
+The mean and variance of the result will be the sum of the means
+and variances (respectively) of the individual estimates."
+ (let ((mean 0)
+ (var 0))
+ (dolist (e estimates)
+ (pcase (mapcar #'string-to-number (split-string e "-"))
+ (`(,low ,high)
+ (let ((m (/ (+ low high) 2.0)))
+ (cl-incf mean m)
+ (cl-incf var (- (/ (+ (* low low) (* high high)) 2.0) (* m m)))))
+ (`(,value) (cl-incf mean value))))
+ (let ((sd (sqrt var)))
+ (format "%s-%s"
+ (format "%.0f" (- mean sd))
+ (format "%.0f" (+ mean sd))))))
+
+
+
+;;; Dynamic block for Column view
+
+(defun org-columns--capture-view (maxlevel skip-empty format local)
+ "Get the column view of the current buffer.
+
+MAXLEVEL sets the level limit. SKIP-EMPTY tells whether to skip
+empty rows, an empty row being one where all the column view
+specifiers but ITEM are empty. FORMAT is a format string for
+columns, or nil. When LOCAL is non-nil, only capture headings in
+current subtree.
+
+This function returns a list containing the title row and all
+other rows. Each row is a list of fields, as strings, or
+`hline'."
+ (org-columns (not local) format)
+ (goto-char org-columns-top-level-marker)
+ (let ((columns (length org-columns-current-fmt-compiled))
+ (has-item (assoc "ITEM" org-columns-current-fmt-compiled))
+ table)
+ (org-map-entries
+ (lambda ()
+ (when (get-char-property (point) 'org-columns-key)
+ (let (row)
+ (dotimes (i columns)
+ (let* ((col (+ (line-beginning-position) i))
+ (p (get-char-property col 'org-columns-key)))
+ (push (org-quote-vert
+ (get-char-property col
+ (if (string= p "ITEM")
+ 'org-columns-value
+ 'org-columns-value-modified)))
+ row)))
+ (unless (and skip-empty
+ (let ((r (delete-dups (remove "" row))))
+ (or (null r) (and has-item (= (length r) 1)))))
+ (push (cons (org-reduced-level (org-current-level)) (nreverse row))
+ table)))))
+ (and maxlevel (format "LEVEL<=%d" maxlevel))
+ (and local 'tree)
+ 'archive 'comment)
+ (org-columns-quit)
+ ;; Add column titles and a horizontal rule in front of the table.
+ (cons (mapcar #'cadr org-columns-current-fmt-compiled)
+ (cons 'hline (nreverse table)))))
+
+(defun org-columns--clean-item (item)
+ "Remove sensitive contents from string ITEM.
+This includes objects that may not be duplicated within
+a document, e.g., a target, or those forbidden in tables, e.g.,
+an inline src-block."
+ (let ((data (org-element-parse-secondary-string
+ item (org-element-restriction 'headline))))
+ (org-element-map data
+ '(footnote-reference inline-babel-call inline-src-block target
+ radio-target statistics-cookie)
+ #'org-element-extract-element)
+ (org-no-properties (org-element-interpret-data data))))
+
+;;;###autoload
+(defun org-dblock-write:columnview (params)
+ "Write the column view table.
+PARAMS is a property list of parameters:
+
+:id the :ID: property of the entry where the columns view
+ should be built. When the symbol `local', call locally.
+ When `global' call column view with the cursor at the beginning
+ of the buffer (usually this means that the whole buffer switches
+ to column view). When \"file:path/to/file.org\", invoke column
+ view at the start of that file. Otherwise, the ID is located
+ using `org-id-find'.
+:hlines When t, insert a hline before each item. When a number, insert
+ a hline before each level <= that number.
+:indent When non-nil, indent each ITEM field according to its level.
+:vlines When t, make each column a colgroup to enforce vertical lines.
+:maxlevel When set to a number, don't capture headlines below this level.
+:skip-empty-rows
+ When t, skip rows where all specifiers other than ITEM are empty.
+:width apply widths specified in columns format using <N> specifiers.
+:format When non-nil, specify the column view format to use."
+ (let ((table
+ (let ((id (plist-get params :id))
+ view-file view-pos)
+ (pcase id
+ (`global nil)
+ ((or `local `nil) (setq view-pos (point)))
+ ((and (let id-string (format "%s" id))
+ (guard (string-match "^file:\\(.*\\)" id-string)))
+ (setq view-file (match-string-no-properties 1 id-string))
+ (unless (file-exists-p view-file)
+ (user-error "No such file: %S" id-string)))
+ ((and (let idpos (org-find-entry-with-id id)) (guard idpos))
+ (setq view-pos idpos))
+ ((let `(,filename . ,position) (org-id-find id))
+ (setq view-file filename)
+ (setq view-pos position))
+ (_ (user-error "Cannot find entry with :ID: %s" id)))
+ (with-current-buffer (if view-file (get-file-buffer view-file)
+ (current-buffer))
+ (org-with-wide-buffer
+ (when view-pos (goto-char view-pos))
+ (org-columns--capture-view (plist-get params :maxlevel)
+ (plist-get params :skip-empty-rows)
+ (plist-get params :format)
+ view-pos))))))
+ (when table
+ ;; Prune level information from the table. Also normalize
+ ;; headings: remove stars, add indentation entities, if
+ ;; required, and possibly precede some of them with a horizontal
+ ;; rule.
+ (let ((item-index
+ (let ((p (assoc "ITEM" org-columns-current-fmt-compiled)))
+ (and p (cl-position p
+ org-columns-current-fmt-compiled
+ :test #'equal))))
+ (hlines (plist-get params :hlines))
+ (indent (plist-get params :indent))
+ new-table)
+ ;; Copy header and first rule.
+ (push (pop table) new-table)
+ (push (pop table) new-table)
+ (dolist (row table (setq table (nreverse new-table)))
+ (let ((level (car row)))
+ (when (and (not (eq (car new-table) 'hline))
+ (or (eq hlines t)
+ (and (numberp hlines) (<= level hlines))))
+ (push 'hline new-table))
+ (when item-index
+ (let ((item (org-columns--clean-item (nth item-index (cdr row)))))
+ (setf (nth item-index (cdr row))
+ (if (and indent (> level 1))
+ (concat "\\_" (make-string (* 2 (1- level)) ?\s) item)
+ item))))
+ (push (cdr row) new-table))))
+ (when (plist-get params :width)
+ (setq table
+ (append table
+ (list
+ (mapcar (lambda (spec)
+ (let ((w (nth 2 spec)))
+ (if w (format "<%d>" (max 3 w)) "")))
+ org-columns-current-fmt-compiled)))))
+ (when (plist-get params :vlines)
+ (setq table
+ (let ((size (length org-columns-current-fmt-compiled)))
+ (append (mapcar (lambda (x) (if (eq 'hline x) x (cons "" x)))
+ table)
+ (list (cons "/" (make-list size "<>")))))))
+ (let ((content-lines (org-split-string (plist-get params :content) "\n"))
+ recalc)
+ ;; Insert affiliated keywords before the table.
+ (when content-lines
+ (while (string-match-p "\\`[ \t]*#\\+" (car content-lines))
+ (insert (pop content-lines) "\n")))
+ (save-excursion
+ ;; Insert table at point.
+ (insert
+ (mapconcat (lambda (row)
+ (if (eq row 'hline) "|-|"
+ (format "|%s|" (mapconcat #'identity row "|"))))
+ table
+ "\n"))
+ ;; Insert TBLFM lines following table.
+ (let ((case-fold-search t))
+ (dolist (line content-lines)
+ (when (string-match-p "\\`[ \t]*#\\+TBLFM:" line)
+ (insert "\n" line)
+ (unless recalc (setq recalc t))))))
+ (when recalc (org-table-recalculate 'all t))
+ (org-table-align)))))
+
+;;;###autoload
+(defun org-columns-insert-dblock ()
+ "Create a dynamic block capturing a column view table."
+ (interactive)
+ (let ((id (completing-read
+ "Capture columns (local, global, entry with :ID: property) [local]: "
+ (append '(("global") ("local"))
+ (mapcar #'list (org-property-values "ID"))))))
+ (org-create-dblock
+ (list :name "columnview"
+ :hlines 1
+ :id (cond ((string= id "global") 'global)
+ ((member id '("" "local")) 'local)
+ (id)))))
+ (org-update-dblock))
+
+
+
+;;; Column view in the agenda
+
+;;;###autoload
+(defun org-agenda-columns ()
+ "Turn on or update column view in the agenda."
+ (interactive)
+ (org-columns-remove-overlays)
+ (move-marker org-columns-begin-marker (point))
+ (let* ((org-columns--time (float-time (current-time)))
+ (fmt
+ (cond
+ ((bound-and-true-p org-agenda-overriding-columns-format))
+ ((let ((m (org-get-at-bol 'org-hd-marker)))
+ (and m
+ (or (org-entry-get m "COLUMNS" t)
+ (with-current-buffer (marker-buffer m)
+ org-columns-default-format)))))
+ ((and (local-variable-p 'org-columns-current-fmt)
+ org-columns-current-fmt))
+ ((let ((m (next-single-property-change (point-min) 'org-hd-marker)))
+ (and m
+ (let ((m (get-text-property m 'org-hd-marker)))
+ (or (org-entry-get m "COLUMNS" t)
+ (with-current-buffer (marker-buffer m)
+ org-columns-default-format))))))
+ (t org-columns-default-format)))
+ (compiled-fmt (org-columns-compile-format fmt)))
+ (setq org-columns-current-fmt fmt)
+ (when org-agenda-columns-compute-summary-properties
+ (org-agenda-colview-compute org-columns-current-fmt-compiled))
+ (save-excursion
+ ;; Collect properties for each headline in current view.
+ (goto-char (point-min))
+ (let (cache)
+ (while (not (eobp))
+ (let ((m (org-get-at-bol 'org-hd-marker)))
+ (when m
+ (push (cons (line-beginning-position)
+ ;; `org-columns-current-fmt-compiled' is
+ ;; initialized but only set locally to the
+ ;; agenda buffer. Since current buffer is
+ ;; changing, we need to force the original
+ ;; compiled-fmt there.
+ (org-with-point-at m
+ (org-columns--collect-values compiled-fmt)))
+ cache)))
+ (forward-line))
+ (when cache
+ (org-columns--set-widths cache)
+ (org-columns--display-here-title)
+ (when (setq-local org-columns-flyspell-was-active
+ (bound-and-true-p flyspell-mode))
+ (flyspell-mode 0))
+ (dolist (entry cache)
+ (goto-char (car entry))
+ (org-columns--display-here (cdr entry)))
+ (when org-agenda-columns-show-summaries
+ (org-agenda-colview-summarize cache)))))))
+
+(defun org-agenda-colview-summarize (cache)
+ "Summarize the summarizable columns in column view in the agenda.
+This will add overlays to the date lines, to show the summary for each day."
+ (let ((fmt (mapcar
+ (lambda (spec)
+ (pcase spec
+ (`(,property ,title ,width . ,_)
+ (if (member property '("CLOCKSUM" "CLOCKSUM_T"))
+ (list property title width ":" nil)
+ spec))))
+ org-columns-current-fmt-compiled)))
+ ;; Ensure there's at least one summation column.
+ (when (cl-some (lambda (spec) (nth 3 spec)) fmt)
+ (goto-char (point-max))
+ (catch :complete
+ (while t
+ (when (or (get-text-property (point) 'org-date-line)
+ (eq (get-text-property (point) 'face)
+ 'org-agenda-structure))
+ ;; OK, this is a date line that should be used.
+ (let (entries)
+ (let (rest)
+ (dolist (c cache)
+ (if (> (car c) (point))
+ (push c entries)
+ (push c rest)))
+ (setq cache rest))
+ ;; ENTRIES contains entries below the current one.
+ ;; CACHE is the rest. Compute the summaries for the
+ ;; properties we want, set nil properties for the rest.
+ (when (setq entries (mapcar #'cdr entries))
+ (org-columns--display-here
+ (mapcar
+ (lambda (spec)
+ (pcase spec
+ (`("ITEM" . ,_)
+ ;; Replace ITEM with current date. Preserve
+ ;; properties for fontification.
+ (let ((date (buffer-substring
+ (line-beginning-position)
+ (line-end-position))))
+ (list spec date date)))
+ (`(,_ ,_ ,_ nil ,_) (list spec "" ""))
+ (`(,_ ,_ ,_ ,operator ,printf)
+ (let* ((summarize (org-columns--summarize operator))
+ (values
+ ;; Use real values for summary, not
+ ;; those prepared for display.
+ (delq nil
+ (mapcar
+ (lambda (e) (org-string-nw-p
+ (nth 1 (assoc spec e))))
+ entries)))
+ (final (if values
+ (funcall summarize values printf)
+ "")))
+ (unless (equal final "")
+ (put-text-property 0 (length final)
+ 'face 'bold final))
+ (list spec final final)))))
+ fmt)
+ 'dateline)
+ (setq-local org-agenda-columns-active t))))
+ (if (bobp) (throw :complete t) (forward-line -1)))))))
+
+(defun org-agenda-colview-compute (fmt)
+ "Compute the relevant columns in the contributing source buffers."
+ (let ((files org-agenda-contributing-files)
+ (org-columns-begin-marker (make-marker))
+ (org-columns-top-level-marker (make-marker)))
+ (dolist (f files)
+ (let ((b (find-buffer-visiting f)))
+ (with-current-buffer (or (buffer-base-buffer b) b)
+ (org-with-wide-buffer
+ (org-with-silent-modifications
+ (remove-text-properties (point-min) (point-max) '(org-summaries t)))
+ (goto-char (point-min))
+ (org-columns-get-format-and-top-level)
+ (dolist (spec fmt)
+ (let ((prop (car spec)))
+ (cond
+ ((equal prop "CLOCKSUM") (org-clock-sum))
+ ((equal prop "CLOCKSUM_T") (org-clock-sum-today))
+ ((and (nth 3 spec)
+ (let ((a (assoc prop org-columns-current-fmt-compiled)))
+ (equal (nth 3 a) (nth 3 spec))))
+ (org-columns-compute prop)))))))))))
+
+
+(provide 'org-colview)
+
+;;; org-colview.el ends here
diff --git a/lisp/org-compat.el b/lisp/org-compat.el
new file mode 100644
index 0000000..e1d4036
--- /dev/null
+++ b/lisp/org-compat.el
@@ -0,0 +1,507 @@
+;;; org-compat.el --- Compatibility Code for Older Emacsen -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains code needed for compatibility with older
+;; versions of GNU Emacs.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-macs)
+
+(declare-function org-at-table.el-p "org" (&optional table-type))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-type "org-element" (element))
+(declare-function org-link-set-parameters "org" (type &rest rest))
+(declare-function org-table-end (&optional table-type))
+(declare-function table--at-cell-p "table" (position &optional object at-column))
+
+(defvar org-table-any-border-regexp)
+(defvar org-table-dataline-regexp)
+(defvar org-table-tab-recognizes-table.el)
+(defvar org-table1-hline-regexp)
+
+;; As of Emacs 25.1, `outline-mode' functions are under the 'outline-'
+;; prefix, `find-tag' is replaced with `xref-find-definition' and
+;; `x-get-selection' with `gui-get-selection'.
+(when (< emacs-major-version 25)
+ (defalias 'outline-hide-entry 'hide-entry)
+ (defalias 'outline-hide-sublevels 'hide-sublevels)
+ (defalias 'outline-hide-subtree 'hide-subtree)
+ (defalias 'outline-show-all 'show-all)
+ (defalias 'outline-show-branches 'show-branches)
+ (defalias 'outline-show-children 'show-children)
+ (defalias 'outline-show-entry 'show-entry)
+ (defalias 'outline-show-subtree 'show-subtree)
+ (defalias 'xref-find-definitions 'find-tag)
+ (defalias 'format-message 'format)
+ (defalias 'gui-get-selection 'x-get-selection))
+
+
+;;; Obsolete aliases (remove them after the next major release).
+
+;;;; XEmacs compatibility, now removed.
+(define-obsolete-function-alias 'org-activate-mark 'activate-mark)
+(define-obsolete-function-alias 'org-add-hook 'add-hook "Org 9.0")
+(define-obsolete-function-alias 'org-bound-and-true-p 'bound-and-true-p "Org 9.0")
+(define-obsolete-function-alias 'org-decompose-region 'decompose-region "Org 9.0")
+(define-obsolete-function-alias 'org-defvaralias 'defvaralias "Org 9.0")
+(define-obsolete-function-alias 'org-detach-overlay 'delete-overlay "Org 9.0")
+(define-obsolete-function-alias 'org-file-equal-p 'file-equal-p "Org 9.0")
+(define-obsolete-function-alias 'org-float-time 'float-time "Org 9.0")
+(define-obsolete-function-alias 'org-indent-line-to 'indent-line-to "Org 9.0")
+(define-obsolete-function-alias 'org-indent-to-column 'indent-to-column "Org 9.0")
+(define-obsolete-function-alias 'org-looking-at-p 'looking-at-p "Org 9.0")
+(define-obsolete-function-alias 'org-looking-back 'looking-back "Org 9.0")
+(define-obsolete-function-alias 'org-match-string-no-properties 'match-string-no-properties "Org 9.0")
+(define-obsolete-function-alias 'org-propertize 'propertize "Org 9.0")
+(define-obsolete-function-alias 'org-select-frame-set-input-focus 'select-frame-set-input-focus "Org 9.0")
+
+(defmacro org-re (s)
+ "Replace posix classes in regular expression S."
+ (declare (debug (form))
+ (obsolete "you can safely remove it." "Org 9.0"))
+ s)
+
+;;;; Functions from cl-lib that Org used to have its own implementation of.
+(define-obsolete-function-alias 'org-count 'cl-count "Org 9.0")
+(define-obsolete-function-alias 'org-every 'cl-every "Org 9.0")
+(define-obsolete-function-alias 'org-find-if 'cl-find-if "Org 9.0")
+(define-obsolete-function-alias 'org-reduce 'cl-reduce "Org 9.0")
+(define-obsolete-function-alias 'org-remove-if 'cl-remove-if "Org 9.0")
+(define-obsolete-function-alias 'org-remove-if-not 'cl-remove-if-not "Org 9.0")
+(define-obsolete-function-alias 'org-some 'cl-some "Org 9.0")
+(define-obsolete-function-alias 'org-floor* 'cl-floor "Org 9.0")
+
+(defun org-sublist (list start end)
+ "Return a section of LIST, from START to END.
+Counting starts at 1."
+ (cl-subseq list (1- start) end))
+(make-obsolete 'org-sublist
+ "use cl-subseq (note the 0-based counting)."
+ "Org 9.0")
+
+
+;;;; Functions available since Emacs 24.3
+(define-obsolete-function-alias 'org-buffer-narrowed-p 'buffer-narrowed-p "Org 9.0")
+(define-obsolete-function-alias 'org-called-interactively-p 'called-interactively-p "Org 9.0")
+(define-obsolete-function-alias 'org-char-to-string 'char-to-string "Org 9.0")
+(define-obsolete-function-alias 'org-delete-directory 'delete-directory "Org 9.0")
+(define-obsolete-function-alias 'org-format-seconds 'format-seconds "Org 9.0")
+(define-obsolete-function-alias 'org-link-escape-browser 'url-encode-url "Org 9.0")
+(define-obsolete-function-alias 'org-no-warnings 'with-no-warnings "Org 9.0")
+(define-obsolete-function-alias 'org-number-sequence 'number-sequence "Org 9.0")
+(define-obsolete-function-alias 'org-pop-to-buffer-same-window 'pop-to-buffer-same-window "Org 9.0")
+(define-obsolete-function-alias 'org-string-match-p 'string-match-p "Org 9.0")
+
+;;;; Functions and variables from previous releases now obsolete.
+(define-obsolete-function-alias 'org-element-remove-indentation
+ 'org-remove-indentation "Org 9.0")
+(define-obsolete-variable-alias 'org-hierarchical-checkbox-statistics
+ 'org-checkbox-hierarchical-statistics "Org 8.0")
+(define-obsolete-variable-alias 'org-description-max-indent
+ 'org-list-description-max-indent "Org 8.0")
+(define-obsolete-variable-alias 'org-latex-create-formula-image-program
+ 'org-preview-latex-default-process "Org 9.0")
+(define-obsolete-variable-alias 'org-latex-preview-ltxpng-directory
+ 'org-preview-latex-image-directory "Org 9.0")
+(define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
+(define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 9.0")
+(define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp "Org 8.3")
+(define-obsolete-function-alias 'org-speed-command-default-hook
+ 'org-speed-command-activate "Org 8.0")
+(define-obsolete-function-alias 'org-babel-speed-command-hook
+ 'org-babel-speed-command-activate "Org 8.0")
+(define-obsolete-function-alias 'org-image-file-name-regexp
+ 'image-file-name-regexp "Org 9.0")
+(define-obsolete-function-alias 'org-get-legal-level
+ 'org-get-valid-level "Org 7.8")
+(define-obsolete-function-alias 'org-completing-read-no-i
+ 'completing-read "Org 9.0")
+(define-obsolete-function-alias 'org-icompleting-read
+ 'completing-read "Org 9.0")
+(define-obsolete-function-alias 'org-iread-file-name 'read-file-name "Org 9.0")
+(define-obsolete-function-alias 'org-days-to-time
+ 'org-time-stamp-to-now "Org 8.2")
+(define-obsolete-variable-alias 'org-agenda-ignore-drawer-properties
+ 'org-agenda-ignore-properties "Org 9.0")
+(define-obsolete-function-alias 'org-preview-latex-fragment
+ 'org-toggle-latex-fragment "Org 8.3")
+(define-obsolete-function-alias 'org-display-inline-modification-hook
+ 'org-display-inline-remove-overlay "Org 8.0")
+(define-obsolete-function-alias 'org-export-get-genealogy
+ 'org-element-lineage "Org 9.0")
+(define-obsolete-variable-alias 'org-latex-with-hyperref
+ 'org-latex-hyperref-template "Org 9.0")
+(define-obsolete-variable-alias 'org-link-to-org-use-id
+ 'org-id-link-to-org-use-id "Org 8.0")
+(define-obsolete-variable-alias 'hfy-optimisations 'hfy-optimizations "Org 9.0")
+(define-obsolete-variable-alias 'org-clock-modeline-total
+ 'org-clock-mode-line-total "Org 8.0")
+(define-obsolete-function-alias 'org-protocol-unhex-compound
+ 'org-link-unescape-compound "Org 7.8")
+(define-obsolete-function-alias 'org-protocol-unhex-string
+ 'org-link-unescape "Org 7.8")
+(define-obsolete-function-alias 'org-protocol-unhex-single-byte-sequence
+ 'org-link-unescape-single-byte-sequence "Org 7.8")
+(define-obsolete-variable-alias 'org-export-htmlized-org-css-url
+ 'org-org-htmlized-css-url "Org 8.2")
+(define-obsolete-variable-alias 'org-alphabetical-lists
+ 'org-list-allow-alphabetical "Org 8.0")
+(define-obsolete-function-alias 'org-list-parse-list 'org-list-to-lisp "Org 9.0")
+(define-obsolete-variable-alias 'org-agenda-menu-two-column
+ 'org-agenda-menu-two-columns "Org 8.0")
+(define-obsolete-variable-alias 'org-finalize-agenda-hook
+ 'org-agenda-finalize-hook "Org 8.0")
+(make-obsolete-variable 'org-agenda-ndays 'org-agenda-span "Org 7.8")
+(define-obsolete-function-alias 'org-agenda-post-command-hook
+ 'org-agenda-update-agenda-type "Org 8.0")
+(define-obsolete-function-alias 'org-agenda-todayp
+ 'org-agenda-today-p "Org 9.0")
+(define-obsolete-function-alias 'org-babel-examplize-region
+ 'org-babel-examplify-region "Org 9.0")
+(define-obsolete-function-alias 'org-babel-trim 'org-trim "Org 9.0")
+(define-obsolete-variable-alias 'org-html-style-include-scripts
+ 'org-html-head-include-scripts "Org 8.0")
+(define-obsolete-variable-alias 'org-html-style-include-default
+ 'org-html-head-include-default-style "Org 8.0")
+(define-obsolete-variable-alias 'org-html-style 'org-html-head "24.4")
+(define-obsolete-function-alias 'org-insert-columns-dblock
+ 'org-columns-insert-dblock "Org 9.0")
+(define-obsolete-function-alias 'org-activate-bracket-links
+ 'org-activate-links "Org 9.0")
+(define-obsolete-function-alias 'org-activate-plain-links 'ignore "Org 9.0")
+(define-obsolete-function-alias 'org-activate-angle-links 'ignore "Org 9.0")
+
+(defun org-in-fixed-width-region-p ()
+ "Non-nil if point in a fixed-width region."
+ (save-match-data
+ (eq 'fixed-width (org-element-type (org-element-at-point)))))
+(make-obsolete 'org-in-fixed-width-region-p
+ "use `org-element' library"
+ "Org 9.0")
+
+(defcustom org-read-date-minibuffer-setup-hook nil
+ "Hook to be used to set up keys for the date/time interface.
+Add key definitions to `minibuffer-local-map', which will be a
+temporary copy."
+ :group 'org-time
+ :type 'hook)
+(make-obsolete-variable
+ 'org-read-date-minibuffer-setup-hook
+ "set `org-read-date-minibuffer-local-map' instead." "Org 8.0")
+
+(defun org-compatible-face (inherits specs)
+ "Make a compatible face specification.
+If INHERITS is an existing face and if the Emacs version supports
+it, just inherit the face. If INHERITS is not given and SPECS
+is, use SPECS to define the face."
+ (declare (indent 1))
+ (if (facep inherits)
+ (list (list t :inherit inherits))
+ specs))
+(make-obsolete 'org-compatible-face "you can remove it." "Org 9.0")
+
+(defun org-add-link-type (type &optional follow export)
+ "Add a new TYPE link.
+FOLLOW and EXPORT are two functions.
+
+FOLLOW should take the link path as the single argument and do whatever
+is necessary to follow the link, for example find a file or display
+a mail message.
+
+EXPORT should format the link path for export to one of the export formats.
+It should be a function accepting three arguments:
+
+ path the path of the link, the text after the prefix (like \"http:\")
+ desc the description of the link, if any
+ format the export format, a symbol like `html' or `latex' or `ascii'.
+
+The function may use the FORMAT information to return different values
+depending on the format. The return value will be put literally into
+the exported file. If the return value is nil, this means Org should
+do what it normally does with links which do not have EXPORT defined.
+
+Org mode has a built-in default for exporting links. If you are happy with
+this default, there is no need to define an export function for the link
+type. For a simple example of an export function, see `org-bbdb.el'.
+
+If TYPE already exists, update it with the arguments.
+See `org-link-parameters' for documentation on the other parameters."
+ (org-link-set-parameters type :follow follow :export export)
+ (message "Created %s link." type))
+
+(make-obsolete 'org-add-link-type "use `org-link-set-parameters' instead." "Org 9.0")
+
+(defun org-table-recognize-table.el ()
+ "If there is a table.el table nearby, recognize it and move into it."
+ (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
+ (beginning-of-line)
+ (unless (or (looking-at org-table-dataline-regexp)
+ (not (looking-at org-table1-hline-regexp)))
+ (forward-line)
+ (when (looking-at org-table-any-border-regexp)
+ (forward-line -2)))
+ (if (re-search-forward "|" (org-table-end t) t)
+ (progn
+ (require 'table)
+ (if (table--at-cell-p (point)) t
+ (message "recognizing table.el table...")
+ (table-recognize-table)
+ (message "recognizing table.el table...done")))
+ (error "This should not happen"))))
+
+;; Not used by Org core since commit 6d1e3082, Feb 2010.
+(make-obsolete 'org-table-recognize-table.el
+ "please notify the org mailing list if you use this function."
+ "Org 9.0")
+
+(define-obsolete-function-alias
+ 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string "Org 8.0")
+
+(defun org-remove-angle-brackets (s)
+ (org-unbracket-string "<" ">" s))
+(make-obsolete 'org-remove-angle-brackets 'org-unbracket-string "Org 9.0")
+
+(defun org-remove-double-quotes (s)
+ (org-unbracket-string "\"" "\"" s))
+(make-obsolete 'org-remove-double-quotes 'org-unbracket-string "Org 9.0")
+
+(define-obsolete-function-alias 'org-babel-number-p
+ 'org-babel--string-to-number "Org 9.0")
+
+
+
+;;;; Obsolete link types
+
+(eval-after-load 'org
+ '(progn
+ (org-link-set-parameters "file+emacs") ;since Org 9.0
+ (org-link-set-parameters "file+sys"))) ;since Org 9.0
+
+
+
+;;; Miscellaneous functions
+
+(defun org-version-check (version feature level)
+ (let* ((v1 (mapcar 'string-to-number (split-string version "[.]")))
+ (v2 (mapcar 'string-to-number (split-string emacs-version "[.]")))
+ (rmaj (or (nth 0 v1) 99))
+ (rmin (or (nth 1 v1) 99))
+ (rbld (or (nth 2 v1) 99))
+ (maj (or (nth 0 v2) 0))
+ (min (or (nth 1 v2) 0))
+ (bld (or (nth 2 v2) 0)))
+ (if (or (< maj rmaj)
+ (and (= maj rmaj)
+ (< min rmin))
+ (and (= maj rmaj)
+ (= min rmin)
+ (< bld rbld)))
+ (if (eq level :predicate)
+ ;; just return if we have the version
+ nil
+ (let ((msg (format "Emacs %s or greater is recommended for %s"
+ version feature)))
+ (display-warning 'org msg level)
+ t))
+ t)))
+
+(defun org-get-x-clipboard (value)
+ "Get the value of the X or Windows clipboard."
+ (cond ((and (eq window-system 'x)
+ (fboundp 'gui-get-selection)) ;Silence byte-compiler.
+ (org-no-properties
+ (ignore-errors
+ (or (gui-get-selection value 'UTF8_STRING)
+ (gui-get-selection value 'COMPOUND_TEXT)
+ (gui-get-selection value 'STRING)
+ (gui-get-selection value 'TEXT)))))
+ ((and (eq window-system 'w32) (fboundp 'w32-get-clipboard-data))
+ (w32-get-clipboard-data))))
+
+(defun org-add-props (string plist &rest props)
+ "Add text properties to entire string, from beginning to end.
+PLIST may be a list of properties, PROPS are individual properties and values
+that will be added to PLIST. Returns the string that was modified."
+ (add-text-properties
+ 0 (length string) (if props (append plist props) plist) string)
+ string)
+(put 'org-add-props 'lisp-indent-function 2)
+
+(defun org-fit-window-to-buffer (&optional window max-height min-height
+ shrink-only)
+ "Fit WINDOW to the buffer, but only if it is not a side-by-side window.
+WINDOW defaults to the selected window. MAX-HEIGHT and MIN-HEIGHT are
+passed through to `fit-window-to-buffer'. If SHRINK-ONLY is set, call
+`shrink-window-if-larger-than-buffer' instead, the height limit is
+ignored in this case."
+ (cond ((if (fboundp 'window-full-width-p)
+ (not (window-full-width-p window))
+ ;; do nothing if another window would suffer
+ (> (frame-width) (window-width window))))
+ ((and (fboundp 'fit-window-to-buffer) (not shrink-only))
+ (fit-window-to-buffer window max-height min-height))
+ ((fboundp 'shrink-window-if-larger-than-buffer)
+ (shrink-window-if-larger-than-buffer window)))
+ (or window (selected-window)))
+
+;; `set-transient-map' is only in Emacs >= 24.4
+(defalias 'org-set-transient-map
+ (if (fboundp 'set-transient-map)
+ 'set-transient-map
+ 'set-temporary-overlay-map))
+
+;;; Region compatibility
+
+(defvar org-ignore-region nil
+ "Non-nil means temporarily disable the active region.")
+
+(defun org-region-active-p ()
+ "Non-nil when the region active.
+Unlike to `use-region-p', this function also checks
+`org-ignore-region'."
+ (and (not org-ignore-region) (use-region-p)))
+
+(defun org-cursor-to-region-beginning ()
+ (when (and (org-region-active-p)
+ (> (point) (region-beginning)))
+ (exchange-point-and-mark)))
+
+;;; Invisibility compatibility
+
+(defun org-remove-from-invisibility-spec (arg)
+ "Remove elements from `buffer-invisibility-spec'."
+ (if (fboundp 'remove-from-invisibility-spec)
+ (remove-from-invisibility-spec arg)
+ (if (consp buffer-invisibility-spec)
+ (setq buffer-invisibility-spec
+ (delete arg buffer-invisibility-spec)))))
+
+(defun org-in-invisibility-spec-p (arg)
+ "Is ARG a member of `buffer-invisibility-spec'?"
+ (if (consp buffer-invisibility-spec)
+ (member arg buffer-invisibility-spec)))
+
+(defun org-move-to-column (column &optional force _buffer)
+ "Move to column COLUMN.
+Pass COLUMN and FORCE to `move-to-column'."
+ (let ((buffer-invisibility-spec
+ (if (listp buffer-invisibility-spec)
+ (remove '(org-filtered) buffer-invisibility-spec)
+ buffer-invisibility-spec)))
+ (move-to-column column force)))
+
+(defmacro org-find-library-dir (library)
+ `(file-name-directory (or (locate-library ,library) "")))
+
+(defun org-count-lines (s)
+ "How many lines in string S?"
+ (let ((start 0) (n 1))
+ (while (string-match "\n" s start)
+ (setq start (match-end 0) n (1+ n)))
+ (if (and (> (length s) 0) (= (aref s (1- (length s))) ?\n))
+ (setq n (1- n)))
+ n))
+
+(defun org-kill-new (string &rest args)
+ (remove-text-properties 0 (length string) '(line-prefix t wrap-prefix t)
+ string)
+ (apply 'kill-new string args))
+
+;; `font-lock-ensure' is only available from 24.4.50 on
+(defalias 'org-font-lock-ensure
+ (if (fboundp 'font-lock-ensure)
+ #'font-lock-ensure
+ (lambda (&optional _beg _end)
+ (with-no-warnings (font-lock-fontify-buffer)))))
+
+;; `file-local-name' was added in Emacs 26.1.
+(defalias 'org-babel-local-file-name
+ (if (fboundp 'file-local-name)
+ 'file-local-name
+ (lambda (file)
+ "Return the local name component of FILE."
+ (or (file-remote-p file 'localname) file))))
+
+(defmacro org-no-popups (&rest body)
+ "Suppress popup windows.
+Let-bind some variables to nil around BODY to achieve the desired
+effect, which variables to use depends on the Emacs version."
+ (if (org-version-check "24.2.50" "" :predicate)
+ `(let (pop-up-frames display-buffer-alist)
+ ,@body)
+ `(let (pop-up-frames special-display-buffer-names special-display-regexps special-display-function)
+ ,@body)))
+
+;;;###autoload
+(defmacro org-check-version ()
+ "Try very hard to provide sensible version strings."
+ (let* ((org-dir (org-find-library-dir "org"))
+ (org-version.el (concat org-dir "org-version.el"))
+ (org-fixup.el (concat org-dir "../mk/org-fixup.el")))
+ (if (require 'org-version org-version.el 'noerror)
+ '(progn
+ (autoload 'org-release "org-version.el")
+ (autoload 'org-git-version "org-version.el"))
+ (if (require 'org-fixup org-fixup.el 'noerror)
+ '(org-fixup)
+ ;; provide fallback definitions and complain
+ (warn "Could not define org version correctly. Check installation!")
+ '(progn
+ (defun org-release () "N/A")
+ (defun org-git-version () "N/A !!check installation!!"))))))
+
+(defmacro org-with-silent-modifications (&rest body)
+ (if (fboundp 'with-silent-modifications)
+ `(with-silent-modifications ,@body)
+ `(org-unmodified ,@body)))
+(def-edebug-spec org-with-silent-modifications (body))
+
+;; Functions for Emacs < 24.4 compatibility
+(defun org-define-error (name message)
+ "Define NAME as a new error signal.
+MESSAGE is a string that will be output to the echo area if such
+an error is signaled without being caught by a `condition-case'.
+Implements `define-error' for older emacsen."
+ (if (fboundp 'define-error) (define-error name message)
+ (put name 'error-conditions
+ (copy-sequence (cons name (get 'error 'error-conditions))))))
+
+(unless (fboundp 'string-suffix-p)
+ ;; From Emacs subr.el.
+ (defun string-suffix-p (suffix string &optional ignore-case)
+ "Return non-nil if SUFFIX is a suffix of STRING.
+If IGNORE-CASE is non-nil, the comparison is done without paying
+attention to case differences."
+ (let ((start-pos (- (length string) (length suffix))))
+ (and (>= start-pos 0)
+ (eq t (compare-strings suffix nil nil
+ string start-pos nil ignore-case))))))
+
+(provide 'org-compat)
+
+;;; org-compat.el ends here
diff --git a/lisp/org-crypt.el b/lisp/org-crypt.el
new file mode 100644
index 0000000..3c431e4
--- /dev/null
+++ b/lisp/org-crypt.el
@@ -0,0 +1,275 @@
+;;; org-crypt.el --- Public Key Encryption for Org Entries -*- lexical-binding: t; -*-
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+
+;; Emacs Lisp Archive Entry
+;; Filename: org-crypt.el
+;; Keywords: org-mode
+;; Author: John Wiegley <johnw@gnu.org>
+;; Maintainer: Peter Jones <pjones@pmade.com>
+;; Description: Adds public key encryption to Org buffers
+;; URL: http://www.newartisans.com/software/emacs.html
+;; Compatibility: Emacs22
+
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Right now this is just a set of functions to play with. It depends
+;; on the epg library. Here's how you would use it:
+;;
+;; 1. To mark an entry for encryption, tag the heading with "crypt".
+;; You can change the tag to any complex tag matching string by
+;; setting the `org-crypt-tag-matcher' variable.
+;;
+;; 2. Set the encryption key to use in the `org-crypt-key' variable,
+;; or use `M-x org-set-property' to set the property CRYPTKEY to
+;; any address in your public keyring. The text of the entry (but
+;; not its properties or headline) will be encrypted for this user.
+;; For them to read it, the corresponding secret key must be
+;; located in the secret key ring of the account where you try to
+;; decrypt it. This makes it possible to leave secure notes that
+;; only the intended recipient can read in a shared-org-mode-files
+;; scenario.
+;; If the key is not set, org-crypt will default to symmetric encryption.
+;;
+;; 3. To later decrypt an entry, use `org-decrypt-entries' or
+;; `org-decrypt-entry'. It might be useful to bind this to a key,
+;; like C-c C-/. I hope that in the future, C-c C-r can be might
+;; overloaded to also decrypt an entry if it's encrypted, since
+;; that fits nicely with the meaning of "reveal".
+;;
+;; 4. To automatically encrypt all necessary entries when saving a
+;; file, call `org-crypt-use-before-save-magic' after loading
+;; org-crypt.el.
+
+;;; Thanks:
+
+;; - Carsten Dominik
+;; - Vitaly Ostanin
+
+(require 'org)
+
+;;; Code:
+
+(declare-function epg-decrypt-string "epg" (context cipher))
+(declare-function epg-list-keys "epg" (context &optional name mode))
+(declare-function epg-make-context "epg"
+ (&optional protocol armor textmode include-certs
+ cipher-algorithm digest-algorithm
+ compress-algorithm))
+(declare-function epg-encrypt-string "epg"
+ (context plain recipients &optional sign always-trust))
+(defvar epg-context)
+
+
+(defgroup org-crypt nil
+ "Org Crypt."
+ :tag "Org Crypt"
+ :group 'org)
+
+(defcustom org-crypt-tag-matcher "crypt"
+ "The tag matcher used to find headings whose contents should be encrypted.
+
+See the \"Match syntax\" section of the org manual for more details."
+ :type 'string
+ :group 'org-crypt)
+
+(defcustom org-crypt-key ""
+ "The default key to use when encrypting the contents of a heading.
+
+This setting can also be overridden in the CRYPTKEY property."
+ :type 'string
+ :group 'org-crypt)
+
+(defcustom org-crypt-disable-auto-save 'ask
+ "What org-decrypt should do if `auto-save-mode' is enabled.
+
+t : Disable auto-save-mode for the current buffer
+ prior to decrypting an entry.
+
+nil : Leave auto-save-mode enabled.
+ This may cause data to be written to disk unencrypted!
+
+`ask' : Ask user whether or not to disable auto-save-mode
+ for the current buffer.
+
+`encrypt': Leave auto-save-mode enabled for the current buffer,
+ but automatically re-encrypt all decrypted entries
+ *before* auto-saving.
+ NOTE: This only works for entries which have a tag
+ that matches `org-crypt-tag-matcher'."
+ :group 'org-crypt
+ :version "24.1"
+ :type '(choice (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (const :tag "Ask" ask)
+ (const :tag "Encrypt" encrypt)))
+
+(defun org-crypt-check-auto-save ()
+ "Check whether auto-save-mode is enabled for the current buffer.
+
+`auto-save-mode' may cause leakage when decrypting entries, so
+check whether it's enabled, and decide what to do about it.
+
+See `org-crypt-disable-auto-save'."
+ (when buffer-auto-save-file-name
+ (cond
+ ((or
+ (eq org-crypt-disable-auto-save t)
+ (and
+ (eq org-crypt-disable-auto-save 'ask)
+ (y-or-n-p "org-decrypt: auto-save-mode may cause leakage. Disable it for current buffer? ")))
+ (message "org-decrypt: Disabling auto-save-mode for %s"
+ (or (buffer-file-name) (current-buffer)))
+ ;; The argument to auto-save-mode has to be "-1", since
+ ;; giving a "nil" argument toggles instead of disabling.
+ (auto-save-mode -1))
+ ((eq org-crypt-disable-auto-save nil)
+ (message "org-decrypt: Decrypting entry with auto-save-mode enabled. This may cause leakage."))
+ ((eq org-crypt-disable-auto-save 'encrypt)
+ (message "org-decrypt: Enabling re-encryption on auto-save.")
+ (add-hook 'auto-save-hook
+ (lambda ()
+ (message "org-crypt: Re-encrypting all decrypted entries due to auto-save.")
+ (org-encrypt-entries))
+ nil t))
+ (t nil))))
+
+(defun org-crypt-key-for-heading ()
+ "Return the encryption key for the current heading."
+ (save-excursion
+ (org-back-to-heading t)
+ (or (org-entry-get nil "CRYPTKEY" 'selective)
+ org-crypt-key
+ (and (boundp 'epa-file-encrypt-to) epa-file-encrypt-to)
+ (message "No crypt key set, using symmetric encryption."))))
+
+(defun org-encrypt-string (str crypt-key)
+ "Return STR encrypted with CRYPT-KEY."
+ ;; Text and key have to be identical, otherwise we re-crypt.
+ (if (and (string= crypt-key (get-text-property 0 'org-crypt-key str))
+ (string= (sha1 str) (get-text-property 0 'org-crypt-checksum str)))
+ (get-text-property 0 'org-crypt-text str)
+ (setq-local epg-context (epg-make-context nil t t))
+ (epg-encrypt-string epg-context str (epg-list-keys epg-context crypt-key))))
+
+(defun org-encrypt-entry ()
+ "Encrypt the content of the current headline."
+ (interactive)
+ (require 'epg)
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (setq-local epg-context (epg-make-context nil t t))
+ (let ((start-heading (point)))
+ (org-end-of-meta-data)
+ (unless (looking-at-p "-----BEGIN PGP MESSAGE-----")
+ (let ((folded (org-invisible-p))
+ (crypt-key (org-crypt-key-for-heading))
+ (beg (point)))
+ (goto-char start-heading)
+ (org-end-of-subtree t t)
+ (org-back-over-empty-lines)
+ (let ((contents (delete-and-extract-region beg (point))))
+ (condition-case err
+ (insert (org-encrypt-string contents crypt-key))
+ ;; If encryption failed, make sure to insert back entry
+ ;; contents in the buffer.
+ (error (insert contents) (error (nth 1 err)))))
+ (when folded
+ (goto-char start-heading)
+ (outline-hide-subtree))
+ nil)))))
+
+(defun org-decrypt-entry ()
+ "Decrypt the content of the current headline."
+ (interactive)
+ (require 'epg)
+ (unless (org-before-first-heading-p)
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (let ((heading-point (point))
+ (heading-was-invisible-p
+ (save-excursion
+ (outline-end-of-heading)
+ (org-invisible-p))))
+ (org-end-of-meta-data)
+ (when (looking-at "-----BEGIN PGP MESSAGE-----")
+ (org-crypt-check-auto-save)
+ (setq-local epg-context (epg-make-context nil t t))
+ (let* ((end (save-excursion
+ (search-forward "-----END PGP MESSAGE-----")
+ (forward-line)
+ (point)))
+ (encrypted-text (buffer-substring-no-properties (point) end))
+ (decrypted-text
+ (decode-coding-string
+ (epg-decrypt-string
+ epg-context
+ encrypted-text)
+ 'utf-8)))
+ ;; Delete region starting just before point, because the
+ ;; outline property starts at the \n of the heading.
+ (delete-region (1- (point)) end)
+ ;; Store a checksum of the decrypted and the encrypted
+ ;; text value. This allows reusing the same encrypted text
+ ;; if the text does not change, and therefore avoid a
+ ;; re-encryption process.
+ (insert "\n" (propertize decrypted-text
+ 'org-crypt-checksum (sha1 decrypted-text)
+ 'org-crypt-key (org-crypt-key-for-heading)
+ 'org-crypt-text encrypted-text))
+ (when heading-was-invisible-p
+ (goto-char heading-point)
+ (org-flag-subtree t))
+ nil))))))
+
+(defun org-encrypt-entries ()
+ "Encrypt all top-level entries in the current buffer."
+ (interactive)
+ (let ((org--matcher-tags-todo-only nil))
+ (org-scan-tags
+ 'org-encrypt-entry
+ (cdr (org-make-tags-matcher org-crypt-tag-matcher))
+ org--matcher-tags-todo-only)))
+
+(defun org-decrypt-entries ()
+ "Decrypt all entries in the current buffer."
+ (interactive)
+ (let ((org--matcher-tags-todo-only nil))
+ (org-scan-tags
+ 'org-decrypt-entry
+ (cdr (org-make-tags-matcher org-crypt-tag-matcher))
+ org--matcher-tags-todo-only)))
+
+(defun org-at-encrypted-entry-p ()
+ "Is the current entry encrypted?"
+ (unless (org-before-first-heading-p)
+ (save-excursion
+ (org-back-to-heading t)
+ (search-forward "-----BEGIN PGP MESSAGE-----"
+ (save-excursion (outline-next-heading)) t))))
+
+(defun org-crypt-use-before-save-magic ()
+ "Add a hook to automatically encrypt entries before a file is saved to disk."
+ (add-hook
+ 'org-mode-hook
+ (lambda () (add-hook 'before-save-hook 'org-encrypt-entries nil t))))
+
+(add-hook 'org-reveal-start-hook 'org-decrypt-entry)
+
+(provide 'org-crypt)
+
+;;; org-crypt.el ends here
diff --git a/lisp/org-ctags.el b/lisp/org-ctags.el
new file mode 100644
index 0000000..98eb806
--- /dev/null
+++ b/lisp/org-ctags.el
@@ -0,0 +1,533 @@
+;;; org-ctags.el - Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+
+;; Author: Paul Sexton <eeeickythump@gmail.com>
+
+
+;; Keywords: org, wp
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;
+;; Synopsis
+;; ========
+;;
+;; Allows Org mode to make use of the Emacs `etags' system. Defines
+;; tag destinations in Org files as any text between <<double angled
+;; brackets>>. This allows the tags-generation program `exuberant
+;; ctags' to parse these files and create tag tables that record where
+;; these destinations are found. Plain [[links]] in org mode files
+;; which do not have <<matching destinations>> within the same file
+;; will then be interpreted as links to these 'tagged' destinations,
+;; allowing seamless navigation between multiple Org files. Topics
+;; can be created in any org mode file and will always be found by
+;; plain links from other files. Other file types recognized by ctags
+;; (source code files, latex files, etc) will also be available as
+;; destinations for plain links, and similarly, Org links will be
+;; available as tags from source files. Finally, the function
+;; `org-ctags-find-tag-interactive' lets you choose any known tag,
+;; using autocompletion, and quickly jump to it.
+;;
+;; Installation
+;; ============
+;;
+;; Install org mode
+;; Ensure org-ctags.el is somewhere in your emacs load path.
+;; Download and install Exuberant ctags -- "http://ctags.sourceforge.net/"
+;; Edit your .emacs file (see next section) and load emacs.
+
+;; To put in your init file (.emacs):
+;; ==================================
+;;
+;; Assuming you already have org mode installed and set up:
+;;
+;; (setq org-ctags-path-to-ctags "/path/to/ctags/executable")
+;; (add-hook 'org-mode-hook
+;; (lambda ()
+;; (define-key org-mode-map "\C-co" 'org-ctags-find-tag-interactive)))
+;;
+;; By default, with org-ctags loaded, org will first try and visit the tag
+;; with the same name as the link; then, if unsuccessful, ask the user if
+;; he/she wants to rebuild the 'TAGS' database and try again; then ask if
+;; the user wishes to append 'tag' as a new toplevel heading at the end of
+;; the buffer; and finally, defer to org's default behavior which is to
+;; search the entire text of the current buffer for 'tag'.
+;;
+;; This behavior can be modified by changing the value of
+;; ORG-CTAGS-OPEN-LINK-FUNCTIONS. For example I have the following in my
+;; .emacs, which describes the same behavior as the above paragraph with
+;; one difference:
+;;
+;; (setq org-ctags-open-link-functions
+;; '(org-ctags-find-tag
+;; org-ctags-ask-rebuild-tags-file-then-find-tag
+;; org-ctags-ask-append-topic
+;; org-ctags-fail-silently)) ; <-- prevents org default behavior
+;;
+;;
+;; Usage
+;; =====
+;;
+;; When you click on a link "[[foo]]" and org cannot find a matching "<<foo>>"
+;; in the current buffer, the tags facility will take over. The file TAGS in
+;; the active directory is examined to see if the tags facility knows about
+;; "<<foo>>" in any other files. If it does, the matching file will be opened
+;; and the cursor will jump to the position of "<<foo>>" in that file.
+;;
+;; User-visible functions:
+;; - `org-ctags-find-tag-interactive': type a tag (plain link) name and visit
+;; it. With autocompletion. Bound to ctrl-O in the above setup.
+;; - All the etags functions should work. These include:
+;;
+;; M-. `find-tag' -- finds the tag at point
+;;
+;; C-M-. find-tag based on regular expression
+;;
+;; M-x tags-search RET -- like C-M-. but searches through ENTIRE TEXT
+;; of ALL the files referenced in the TAGS file. A quick way to
+;; search through an entire 'project'.
+;;
+;; M-* "go back" from a tag jump. Like `org-mark-ring-goto'.
+;; You may need to bind this key yourself with (eg)
+;; (global-set-key (kbd "<M-kp-multiply>") 'pop-tag-mark)
+;;
+;; (see etags chapter in Emacs manual for more)
+;;
+;;
+;; Keeping the TAGS file up to date
+;; ================================
+;;
+;; Tags mode has no way of knowing that you have created new tags by
+;; typing in your Org buffer. New tags make it into the TAGS file in
+;; 3 ways:
+;;
+;; 1. You re-run (org-ctags-create-tags "directory") to rebuild the file.
+;; 2. You put the function `org-ctags-ask-rebuild-tags-file-then-find-tag' in
+;; your `org-open-link-functions' list, as is done in the setup
+;; above. This will cause the TAGS file to be rebuilt whenever a link
+;; cannot be found. This may be slow with large file collections however.
+;; 3. You run the following from the command line (all 1 line):
+;;
+;; ctags --langdef=orgmode --langmap=orgmode:.org
+;; --regex-orgmode="/<<([^>]+)>>/\1/d,definition/"
+;; -f /your/path/TAGS -e -R /your/path/*.org
+;;
+;; If you are paranoid, you might want to run (org-ctags-create-tags
+;; "/path/to/org/files") at startup, by including the following toplevel form
+;; in .emacs. However this can cause a pause of several seconds if ctags has
+;; to scan lots of files.
+;;
+;; (progn
+;; (message "-- rebuilding tags tables...")
+;; (mapc 'org-ctags-create-tags tags-table-list))
+
+;;; Code:
+
+(require 'org)
+
+(defgroup org-ctags nil
+ "Options concerning use of ctags within org mode."
+ :tag "Org-Ctags"
+ :group 'org-link)
+
+(defvar org-ctags-enabled-p t
+ "Activate ctags support in org mode?")
+
+(defvar org-ctags-tag-regexp "/<<([^>]+)>>/\\1/d,definition/"
+ "Regexp expression used by ctags external program.
+The regexp matches tag destinations in Org files.
+Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/
+See the ctags documentation for more information.")
+
+(defcustom org-ctags-path-to-ctags
+ (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags")
+ "Name of the ctags executable file."
+ :group 'org-ctags
+ :version "24.1"
+ :type 'file)
+
+(defcustom org-ctags-open-link-functions
+ '(org-ctags-find-tag
+ org-ctags-ask-rebuild-tags-file-then-find-tag
+ org-ctags-ask-append-topic)
+ "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active."
+ :group 'org-ctags
+ :version "24.1"
+ :type 'hook
+ :options '(org-ctags-find-tag
+ org-ctags-ask-rebuild-tags-file-then-find-tag
+ org-ctags-rebuild-tags-file-then-find-tag
+ org-ctags-ask-append-topic
+ org-ctags-append-topic
+ org-ctags-ask-visit-buffer-or-file
+ org-ctags-visit-buffer-or-file
+ org-ctags-fail-silently))
+
+
+(defvar org-ctags-tag-list nil
+ "List of all tags in the active TAGS file.
+Created as a local variable in each buffer.")
+
+(defcustom org-ctags-new-topic-template
+ "* <<%t>>\n\n\n\n\n\n"
+ "Text to insert when creating a new org file via opening a hyperlink.
+The following patterns are replaced in the string:
+ `%t' - replaced with the capitalized title of the hyperlink"
+ :group 'org-ctags
+ :version "24.1"
+ :type 'string)
+
+
+(add-hook 'org-mode-hook
+ (lambda ()
+ (when (and org-ctags-enabled-p
+ (buffer-file-name))
+ ;; Make sure this file's directory is added to default
+ ;; directories in which to search for tags.
+ (let ((tags-filename
+ (expand-file-name
+ (concat (file-name-directory (buffer-file-name))
+ "/TAGS"))))
+ (when (file-exists-p tags-filename)
+ (visit-tags-table tags-filename))))))
+
+
+(defadvice visit-tags-table (after org-ctags-load-tag-list activate compile)
+ (when (and org-ctags-enabled-p tags-file-name)
+ (setq-local org-ctags-tag-list
+ (org-ctags-all-tags-in-current-tags-table))))
+
+
+(defun org-ctags-enable ()
+ (put 'org-mode 'find-tag-default-function 'org-ctags-find-tag-at-point)
+ (setq org-ctags-enabled-p t)
+ (dolist (fn org-ctags-open-link-functions)
+ (add-hook 'org-open-link-functions fn t)))
+
+
+;;; General utility functions. ===============================================
+;; These work outside org-ctags mode.
+
+(defun org-ctags-get-filename-for-tag (tag)
+ "TAG is a string. Search the active TAGS file for a matching tag.
+If the tag is found, return a list containing the filename, line number, and
+buffer position where the tag is found."
+ (interactive "sTag: ")
+ (unless tags-file-name
+ (call-interactively (visit-tags-table)))
+ (save-excursion
+ (visit-tags-table-buffer 'same)
+ (when tags-file-name
+ (with-current-buffer (get-file-buffer tags-file-name)
+ (goto-char (point-min))
+ (cond
+ ((re-search-forward (format "^.*%s\\([0-9]+\\),\\([0-9]+\\)$"
+ (regexp-quote tag)) nil t)
+ (let ((line (string-to-number (match-string 1)))
+ (pos (string-to-number (match-string 2))))
+ (cond
+ ((re-search-backward " \n\\(.*\\),[0-9]+\n")
+ (list (match-string 1) line pos))
+ (t ; can't find a file name preceding the matched
+ ; tag??
+ (error "Malformed TAGS file: %s" (buffer-name))))))
+ (t ; tag not found
+ nil))))))
+
+
+(defun org-ctags-all-tags-in-current-tags-table ()
+ "Read all tags defined in the active TAGS file, into a list of strings.
+Return the list."
+ (interactive)
+ (let ((taglist nil))
+ (unless tags-file-name
+ (call-interactively (visit-tags-table)))
+ (save-excursion
+ (visit-tags-table-buffer 'same)
+ (with-current-buffer (get-file-buffer tags-file-name)
+ (goto-char (point-min))
+ (while (re-search-forward "^.*\\(.*\\)\\([0-9]+\\),\\([0-9]+\\)$"
+ nil t)
+ (push (substring-no-properties (match-string 1)) taglist)))
+ taglist)))
+
+
+(defun org-ctags-string-search-and-replace (search replace string)
+ "Replace all instances of SEARCH with REPLACE in STRING."
+ (replace-regexp-in-string (regexp-quote search) replace string t t))
+
+
+;;; Internal functions =======================================================
+
+
+(defun org-ctags-open-file (name &optional title)
+ "Visit or create a file called `NAME.org', and insert a new topic.
+The new topic will be titled NAME (or TITLE if supplied)."
+ (interactive "sFile name: ")
+ (condition-case v
+ (progn
+ (org-open-file name t)
+ (message "Opened file OK")
+ (goto-char (point-max))
+ (insert (org-ctags-string-search-and-replace
+ "%t" (capitalize (or title name))
+ org-ctags-new-topic-template))
+ (message "Inserted new file text OK")
+ (org-mode-restart))
+ (error (error "Error %S in org-ctags-open-file" v))))
+
+
+;;;; Misc interoperability with etags system =================================
+
+
+(defadvice xref-find-definitions
+ (before org-ctags-set-org-mark-before-finding-tag activate compile)
+ "Before trying to find a tag, save our current position on org mark ring."
+ (save-excursion
+ (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p)
+ (org-mark-ring-push))))
+
+
+
+(defun org-ctags-find-tag-at-point ()
+ "Determine default tag to search for, based on text at point.
+If there is no plausible default, return nil."
+ (let (from to bound)
+ (when (or (ignore-errors
+ ;; Look for hyperlink around `point'.
+ (save-excursion
+ (search-backward "[[") (setq from (+ 2 (point))))
+ (save-excursion
+ (goto-char from)
+ (search-forward "]") (setq to (- (point) 1)))
+ (and (> to from) (>= (point) from) (<= (point) to)))
+ (progn
+ ;; Look at text around `point'.
+ (save-excursion
+ (skip-syntax-backward "w_") (setq from (point)))
+ (save-excursion
+ (skip-syntax-forward "w_") (setq to (point)))
+ (> to from))
+ ;; Look between `line-beginning-position' and `point'.
+ (save-excursion
+ (and (setq bound (line-beginning-position))
+ (skip-syntax-backward "^w_" bound)
+ (> (setq to (point)) bound)
+ (skip-syntax-backward "w_")
+ (setq from (point))))
+ ;; Look between `point' and `line-end-position'.
+ (save-excursion
+ (and (setq bound (line-end-position))
+ (skip-syntax-forward "^w_" bound)
+ (< (setq from (point)) bound)
+ (skip-syntax-forward "w_")
+ (setq to (point)))))
+ (buffer-substring-no-properties from to))))
+
+
+;;; Functions for use with 'org-open-link-functions' hook =================
+
+
+(defun org-ctags-find-tag (name)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Look for a tag called `NAME' in the current TAGS table. If it is found,
+visit the file and location where the tag is found."
+ (interactive "sTag: ")
+ (let ((old-buf (current-buffer))
+ (old-pnt (point-marker))
+ (old-mark (copy-marker (mark-marker))))
+ (condition-case nil
+ (progn (xref-find-definitions name)
+ t)
+ (error
+ ;; only restore old location if find-tag raises error
+ (set-buffer old-buf)
+ (goto-char old-pnt)
+ (set-marker (mark-marker) old-mark)
+ nil))))
+
+
+(defun org-ctags-visit-buffer-or-file (name &optional create)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Visit buffer named `NAME.org'. If there is no such buffer, visit the file
+with the same name if it exists. If the file does not exist, then behavior
+depends on the value of CREATE.
+
+If CREATE is nil (default), then return nil. Do not create a new file.
+If CREATE is t, create the new file and visit it.
+If CREATE is the symbol `ask', then ask the user if they wish to create
+the new file."
+ (interactive)
+ (let ((filename (concat (substitute-in-file-name
+ (expand-file-name name))
+ ".org")))
+ (cond
+ ((get-buffer (concat name ".org"))
+ ;; Buffer is already open
+ (pop-to-buffer-same-window (get-buffer (concat name ".org"))))
+ ((file-exists-p filename)
+ ;; File exists but is not open --> open it
+ (message "Opening existing org file `%S'..."
+ filename)
+ (org-open-file filename t))
+ ((or (eql create t)
+ (and (eql create 'ask)
+ (y-or-n-p (format-message
+ "File `%s.org' not found; create?" name))))
+ (org-ctags-open-file filename name))
+ (t ;; File does not exist, and we don't want to create it.
+ nil))))
+
+
+(defun org-ctags-ask-visit-buffer-or-file (name)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is
+asked before creating a new file."
+ (org-ctags-visit-buffer-or-file name 'ask))
+
+
+(defun org-ctags-append-topic (name &optional narrowp)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Append a new toplevel heading to the end of the current buffer. The
+heading contains NAME surrounded by <<angular brackets>>, thus making
+the heading a destination for the tag `NAME'."
+ (interactive "sTopic: ")
+ (widen)
+ (goto-char (point-max))
+ (newline 2)
+ (message "Adding topic in buffer %s" (buffer-name))
+ (insert (org-ctags-string-search-and-replace
+ "%t" (capitalize name) org-ctags-new-topic-template))
+ (backward-char 4)
+ (end-of-line)
+ (forward-line 2)
+ (when narrowp
+ ;;(org-tree-to-indirect-buffer 1) ;; opens new frame
+ (org-narrow-to-subtree))
+ t)
+
+
+(defun org-ctags-ask-append-topic (name &optional narrowp)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Wrapper for org-ctags-append-topic, which first asks the user if they want
+to append a new topic."
+ (if (y-or-n-p (format-message
+ "Topic `%s' not found; append to end of buffer?" name))
+ (org-ctags-append-topic name narrowp)
+ nil))
+
+
+(defun org-ctags-rebuild-tags-file-then-find-tag (name)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first,
+to rebuild (update) the TAGS file."
+ (unless tags-file-name
+ (call-interactively (visit-tags-table)))
+ (when (buffer-file-name)
+ (org-ctags-create-tags))
+ (org-ctags-find-tag name))
+
+
+(defun org-ctags-ask-rebuild-tags-file-then-find-tag (name)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Wrapper for org-ctags-rebuild-tags-file-then-find-tag."
+ (if (and (buffer-file-name)
+ (y-or-n-p
+ (format-message
+ "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?"
+ name
+ (file-name-directory (buffer-file-name)))))
+ (org-ctags-rebuild-tags-file-then-find-tag name)
+ nil))
+
+
+(defun org-ctags-fail-silently (_name)
+ "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS.
+Put as the last function in the list if you want to prevent Org's
+default behavior of free text search."
+ t)
+
+
+;;; User-visible functions ===================================================
+
+
+(defun org-ctags-create-tags (&optional directory-name)
+ "(Re)create tags file in the directory of the active buffer.
+The file will contain tag definitions for all the files in the
+directory and its subdirectories which are recognized by ctags.
+This will include files ending in `.org' as well as most other
+source files (.C, .H, .EL, .LISP, etc). All the resulting tags
+end up in one file, called TAGS, located in the directory. This
+function may take several seconds to finish if the directory or
+its subdirectories contain large numbers of taggable files."
+ (interactive)
+ (cl-assert (buffer-file-name))
+ (let ((dir-name (or directory-name
+ (file-name-directory (buffer-file-name))))
+ (exitcode nil))
+ (save-excursion
+ (setq exitcode
+ (shell-command
+ (format (concat "%s --langdef=orgmode --langmap=orgmode:.org "
+ "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"")
+ org-ctags-path-to-ctags
+ org-ctags-tag-regexp
+ (expand-file-name (concat dir-name "/TAGS"))
+ (expand-file-name (concat dir-name "/*")))))
+ (cond
+ ((eql 0 exitcode)
+ (setq-local org-ctags-tag-list
+ (org-ctags-all-tags-in-current-tags-table)))
+ (t
+ ;; This seems to behave differently on Linux, so just ignore
+ ;; error codes for now
+ ;;(error "Calling ctags executable resulted in error code: %s"
+ ;; exitcode)
+ nil)))))
+
+
+(defvar org-ctags-find-tag-history nil
+ "History of tags visited by org-ctags-find-tag-interactive.")
+
+(defun org-ctags-find-tag-interactive ()
+ "Prompt for the name of a tag, with autocompletion, then visit the named tag.
+Uses `ido-mode' if available.
+If the user enters a string that does not match an existing tag, create
+a new topic."
+ (interactive)
+ (let* ((completing-read-fn (if (fboundp 'ido-completing-read)
+ 'ido-completing-read
+ 'completing-read))
+ (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list
+ nil 'confirm nil 'org-ctags-find-tag-history)))
+ (when tag
+ (cond
+ ((member tag org-ctags-tag-list)
+ ;; Existing tag
+ (push tag org-ctags-find-tag-history)
+ (xref-find-definitions tag))
+ (t
+ ;; New tag
+ (run-hook-with-args-until-success
+ 'org-open-link-functions tag))))))
+
+
+(org-ctags-enable)
+
+(provide 'org-ctags)
+
+;;; org-ctags.el ends here
diff --git a/lisp/org-datetree.el b/lisp/org-datetree.el
new file mode 100644
index 0000000..540753d
--- /dev/null
+++ b/lisp/org-datetree.el
@@ -0,0 +1,231 @@
+;;; org-datetree.el --- Create date entries in a tree -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains code to create entries in a tree where the top-level
+;; nodes represent years, the level 2 nodes represent the months, and the
+;; level 1 entries days.
+
+;;; Code:
+
+(require 'org)
+
+(defvar org-datetree-base-level 1
+ "The level at which years should be placed in the date tree.
+This is normally one, but if the buffer has an entry with a
+DATE_TREE (or WEEK_TREE for ISO week entries) property (any
+value), the date tree will become a subtree under that entry, so
+the base level will be properly adjusted.")
+
+(defcustom org-datetree-add-timestamp nil
+ "When non-nil, add a time stamp matching date of entry.
+Added time stamp is active unless value is `inactive'."
+ :group 'org-capture
+ :version "24.3"
+ :type '(choice
+ (const :tag "Do not add a time stamp" nil)
+ (const :tag "Add an inactive time stamp" inactive)
+ (const :tag "Add an active time stamp" active)))
+
+;;;###autoload
+(defun org-datetree-find-date-create (d &optional keep-restriction)
+ "Find or create an entry for date D.
+If KEEP-RESTRICTION is non-nil, do not widen the buffer.
+When it is nil, the buffer will be widened to make sure an existing date
+tree can be found."
+ (setq-local org-datetree-base-level 1)
+ (or keep-restriction (widen))
+ (save-restriction
+ (let ((prop (org-find-property "DATE_TREE")))
+ (when prop
+ (goto-char prop)
+ (setq-local org-datetree-base-level
+ (org-get-valid-level (org-current-level) 1))
+ (org-narrow-to-subtree)))
+ (goto-char (point-min))
+ (let ((year (calendar-extract-year d))
+ (month (calendar-extract-month d))
+ (day (calendar-extract-day d)))
+ (org-datetree--find-create
+ "^\\*+[ \t]+\\([12][0-9]\\{3\\}\\)\\(\\s-*?\
+\\([ \t]:[[:alnum:]:_@#%%]+:\\)?\\s-*$\\)"
+ year)
+ (org-datetree--find-create
+ "^\\*+[ \t]+%d-\\([01][0-9]\\) \\w+$"
+ year month)
+ (org-datetree--find-create
+ "^\\*+[ \t]+%d-%02d-\\([0123][0-9]\\) \\w+$"
+ year month day))))
+
+;;;###autoload
+(defun org-datetree-find-iso-week-create (d &optional keep-restriction)
+ "Find or create an ISO week entry for date D.
+Compared to `org-datetree-find-date-create' this function creates
+entries ordered by week instead of months.
+If KEEP-RESTRICTION is non-nil, do not widen the buffer. When it
+is nil, the buffer will be widened to make sure an existing date
+tree can be found."
+ (setq-local org-datetree-base-level 1)
+ (or keep-restriction (widen))
+ (save-restriction
+ (let ((prop (org-find-property "WEEK_TREE")))
+ (when prop
+ (goto-char prop)
+ (setq-local org-datetree-base-level
+ (org-get-valid-level (org-current-level) 1))
+ (org-narrow-to-subtree)))
+ (goto-char (point-min))
+ (require 'cal-iso)
+ (let* ((year (calendar-extract-year d))
+ (month (calendar-extract-month d))
+ (day (calendar-extract-day d))
+ (time (encode-time 0 0 0 day month year))
+ (iso-date (calendar-iso-from-absolute
+ (calendar-absolute-from-gregorian d)))
+ (weekyear (nth 2 iso-date))
+ (week (nth 0 iso-date)))
+ ;; ISO 8601 week format is %G-W%V(-%u)
+ (org-datetree--find-create
+ "^\\*+[ \t]+\\([12][0-9]\\{3\\}\\)\\(\\s-*?\
+\\([ \t]:[[:alnum:]:_@#%%]+:\\)?\\s-*$\\)"
+ weekyear nil nil
+ (format-time-string "%G" time))
+ (org-datetree--find-create
+ "^\\*+[ \t]+%d-W\\([0-5][0-9]\\)$"
+ weekyear week nil
+ (format-time-string "%G-W%V" time))
+ ;; For the actual day we use the regular date instead of ISO week.
+ (org-datetree--find-create
+ "^\\*+[ \t]+%d-%02d-\\([0123][0-9]\\) \\w+$"
+ year month day))))
+
+(defun org-datetree--find-create (regex year &optional month day insert)
+ "Find the datetree matched by REGEX for YEAR, MONTH, or DAY.
+REGEX is passed to `format' with YEAR, MONTH, and DAY as
+arguments. Match group 1 is compared against the specified date
+component. If INSERT is non-nil and there is no match then it is
+inserted into the buffer."
+ (when (or month day)
+ (org-narrow-to-subtree))
+ (let ((re (format regex year month day))
+ match)
+ (goto-char (point-min))
+ (while (and (setq match (re-search-forward re nil t))
+ (goto-char (match-beginning 1))
+ (< (string-to-number (match-string 1)) (or day month year))))
+ (cond
+ ((not match)
+ (goto-char (point-max))
+ (unless (bolp) (insert "\n"))
+ (org-datetree-insert-line year month day insert))
+ ((= (string-to-number (match-string 1)) (or day month year))
+ (beginning-of-line))
+ (t
+ (beginning-of-line)
+ (org-datetree-insert-line year month day insert)))))
+
+(defun org-datetree-insert-line (year &optional month day text)
+ (delete-region (save-excursion (skip-chars-backward " \t\n") (point)) (point))
+ (insert "\n" (make-string org-datetree-base-level ?*) " \n")
+ (backward-char)
+ (when month (org-do-demote))
+ (when day (org-do-demote))
+ (if text
+ (insert text)
+ (insert (format "%d" year))
+ (when month
+ (insert
+ (if day
+ (format-time-string "-%m-%d %A" (encode-time 0 0 0 day month year))
+ (format-time-string "-%m %B" (encode-time 0 0 0 1 month year))))))
+ (when (and day org-datetree-add-timestamp)
+ (save-excursion
+ (insert "\n")
+ (org-indent-line)
+ (org-insert-time-stamp
+ (encode-time 0 0 0 day month year)
+ nil
+ (eq org-datetree-add-timestamp 'inactive))))
+ (beginning-of-line))
+
+(defun org-datetree-file-entry-under (txt d)
+ "Insert a node TXT into the date tree under date D."
+ (org-datetree-find-date-create d)
+ (let ((level (org-get-valid-level (funcall outline-level) 1)))
+ (org-end-of-subtree t t)
+ (org-back-over-empty-lines)
+ (org-paste-subtree level txt)))
+
+(defun org-datetree-cleanup ()
+ "Make sure all entries in the current tree are under the correct date.
+It may be useful to restrict the buffer to the applicable portion
+before running this command, even though the command tries to be smart."
+ (interactive)
+ (goto-char (point-min))
+ (let ((dre (concat "\\<" org-deadline-string "\\>[ \t]*\\'"))
+ (sre (concat "\\<" org-scheduled-string "\\>[ \t]*\\'")))
+ (while (re-search-forward org-ts-regexp nil t)
+ (catch 'next
+ (let ((tmp (buffer-substring
+ (max (line-beginning-position)
+ (- (match-beginning 0) org-ds-keyword-length))
+ (match-beginning 0))))
+ (when (or (string-suffix-p "-" tmp)
+ (string-match dre tmp)
+ (string-match sre tmp))
+ (throw 'next nil))
+ (let* ((dct (decode-time (org-time-string-to-time (match-string 0))))
+ (date (list (nth 4 dct) (nth 3 dct) (nth 5 dct)))
+ (year (nth 2 date))
+ (month (car date))
+ (day (nth 1 date))
+ (pos (point))
+ (hdl-pos (progn (org-back-to-heading t) (point))))
+ (unless (org-up-heading-safe)
+ ;; No parent, we are not in a date tree.
+ (goto-char pos)
+ (throw 'next nil))
+ (unless (looking-at "\\*+[ \t]+[0-9]+-[0-1][0-9]-[0-3][0-9]")
+ ;; Parent looks wrong, we are not in a date tree.
+ (goto-char pos)
+ (throw 'next nil))
+ (when (looking-at (format "\\*+[ \t]+%d-%02d-%02d" year month day))
+ ;; At correct date already, do nothing.
+ (goto-char pos)
+ (throw 'next nil))
+ ;; OK, we need to refile this entry.
+ (goto-char hdl-pos)
+ (org-cut-subtree)
+ (save-excursion
+ (save-restriction
+ (org-datetree-file-entry-under (current-kill 0) date)))))))))
+
+(provide 'org-datetree)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-datetree.el ends here
diff --git a/lisp/org-docview.el b/lisp/org-docview.el
new file mode 100644
index 0000000..dfad893
--- /dev/null
+++ b/lisp/org-docview.el
@@ -0,0 +1,103 @@
+;;; org-docview.el --- Support for links to doc-view-mode buffers -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: Jan Böcker <jan.boecker at jboecker dot de>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to open files in doc-view-mode.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;; The links take the form
+;;
+;; docview:<file path>::<page number>
+;;
+;; for example: [[docview:~/.elisp/org/doc/org.pdf::1][Org-Mode Manual]]
+;;
+;; Autocompletion for inserting links is supported; you will be
+;; prompted for a file and a page number.
+;;
+;; If you use org-store-link in a doc-view mode buffer, the stored
+;; link will point to the current page.
+
+;;; Code:
+
+
+(require 'org)
+(require 'doc-view)
+
+(declare-function doc-view-goto-page "doc-view" (page))
+(declare-function image-mode-window-get "image-mode" (prop &optional winprops))
+
+(org-link-set-parameters "docview"
+ :follow #'org-docview-open
+ :export #'org-docview-export
+ :store #'org-docview-store-link)
+
+(defun org-docview-export (link description format)
+ "Export a docview link from Org files."
+ (let* ((path (if (string-match "\\(.+\\)::.+" link) (match-string 1 link)
+ link))
+ (desc (or description link)))
+ (when (stringp path)
+ (setq path (org-link-escape (expand-file-name path)))
+ (cond
+ ((eq format 'html) (format "<a href=\"%s\">%s</a>" path desc))
+ ((eq format 'latex) (format "\\href{%s}{%s}" path desc))
+ ((eq format 'ascii) (format "%s (%s)" desc path))
+ (t path)))))
+
+(defun org-docview-open (link)
+ (string-match "\\(.*?\\)\\(?:::\\([0-9]+\\)\\)?$" link)
+ (let ((path (match-string 1 link))
+ (page (and (match-beginning 2)
+ (string-to-number (match-string 2 link)))))
+ ;; Let Org mode open the file (in-emacs = 1) to ensure
+ ;; org-link-frame-setup is respected.
+ (org-open-file path 1)
+ (when page (doc-view-goto-page page))))
+
+(defun org-docview-store-link ()
+ "Store a link to a docview buffer."
+ (when (eq major-mode 'doc-view-mode)
+ ;; This buffer is in doc-view-mode
+ (let* ((path buffer-file-name)
+ (page (image-mode-window-get 'page))
+ (link (concat "docview:" path "::" (number-to-string page))))
+ (org-store-link-props
+ :type "docview"
+ :link link
+ :description path))))
+
+(defun org-docview-complete-link ()
+ "Use the existing file name completion for file.
+Links to get the file name, then ask the user for the page number
+and append it."
+ (concat (replace-regexp-in-string "^file:" "docview:" (org-file-complete-link))
+ "::"
+ (read-from-minibuffer "Page:" "1")))
+
+
+(provide 'org-docview)
+
+;;; org-docview.el ends here
diff --git a/lisp/org-element.el b/lisp/org-element.el
new file mode 100644
index 0000000..41b4a3a
--- /dev/null
+++ b/lisp/org-element.el
@@ -0,0 +1,6085 @@
+;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; See <http://orgmode.org/worg/dev/org-syntax.html> for details about
+;; Org syntax.
+;;
+;; Lisp-wise, a syntax object can be represented as a list.
+;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
+;; TYPE is a symbol describing the object.
+;; PROPERTIES is the property list attached to it. See docstring of
+;; appropriate parsing function to get an exhaustive list.
+;; CONTENTS is a list of syntax objects or raw strings contained
+;; in the current object, when applicable.
+;;
+;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
+;;
+;; The first part of this file defines constants for the Org syntax,
+;; while the second one provide accessors and setters functions.
+;;
+;; The next part implements a parser and an interpreter for each
+;; element and object type in Org syntax.
+;;
+;; The following part creates a fully recursive buffer parser. It
+;; also provides a tool to map a function to elements or objects
+;; matching some criteria in the parse tree. Functions of interest
+;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
+;; extent, `org-element-parse-secondary-string'.
+;;
+;; The penultimate part is the cradle of an interpreter for the
+;; obtained parse tree: `org-element-interpret-data'.
+;;
+;; The library ends by furnishing `org-element-at-point' function, and
+;; a way to give information about document structure around point
+;; with `org-element-context'. A cache mechanism is also provided for
+;; these functions.
+
+
+;;; Code:
+
+(require 'org)
+(require 'avl-tree)
+(require 'cl-lib)
+
+
+
+;;; Definitions And Rules
+;;
+;; Define elements, greater elements and specify recursive objects,
+;; along with the affiliated keywords recognized. Also set up
+;; restrictions on recursive objects combinations.
+;;
+;; `org-element-update-syntax' builds proper syntax regexps according
+;; to current setup.
+
+(defvar org-element-paragraph-separate nil
+ "Regexp to separate paragraphs in an Org buffer.
+In the case of lines starting with \"#\" and \":\", this regexp
+is not sufficient to know if point is at a paragraph ending. See
+`org-element-paragraph-parser' for more information.")
+
+(defvar org-element--object-regexp nil
+ "Regexp possibly matching the beginning of an object.
+This regexp allows false positives. Dedicated parser (e.g.,
+`org-export-bold-parser') will take care of further filtering.
+Radio links are not matched by this regexp, as they are treated
+specially in `org-element--object-lex'.")
+
+(defun org-element--set-regexps ()
+ "Build variable syntax regexps."
+ (setq org-element-paragraph-separate
+ (concat "^\\(?:"
+ ;; Headlines, inlinetasks.
+ org-outline-regexp "\\|"
+ ;; Footnote definitions.
+ "\\[fn:[-_[:word:]]+\\]" "\\|"
+ ;; Diary sexps.
+ "%%(" "\\|"
+ "[ \t]*\\(?:"
+ ;; Empty lines.
+ "$" "\\|"
+ ;; Tables (any type).
+ "|" "\\|"
+ "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
+ ;; Comments, keyword-like or block-like constructs.
+ ;; Blocks and keywords with dual values need to be
+ ;; double-checked.
+ "#\\(?: \\|$\\|\\+\\(?:"
+ "BEGIN_\\S-+" "\\|"
+ "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
+ "\\|"
+ ;; Drawers (any type) and fixed-width areas. Drawers
+ ;; need to be double-checked.
+ ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
+ ;; Horizontal rules.
+ "-\\{5,\\}[ \t]*$" "\\|"
+ ;; LaTeX environments.
+ "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
+ ;; Clock lines.
+ (regexp-quote org-clock-string) "\\|"
+ ;; Lists.
+ (let ((term (pcase org-plain-list-ordered-item-terminator
+ (?\) ")") (?. "\\.") (_ "[.)]")))
+ (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
+ (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
+ "\\(?:[ \t]\\|$\\)"))
+ "\\)\\)")
+ org-element--object-regexp
+ (mapconcat #'identity
+ (let ((link-types (regexp-opt (org-link-types))))
+ (list
+ ;; Sub/superscript.
+ "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
+ ;; Bold, code, italic, strike-through, underline
+ ;; and verbatim.
+ (concat "[*~=+_/]"
+ (format "[^%s]"
+ (nth 2 org-emphasis-regexp-components)))
+ ;; Plain links.
+ (concat "\\<" link-types ":")
+ ;; Objects starting with "[": regular link,
+ ;; footnote reference, statistics cookie,
+ ;; timestamp (inactive).
+ (concat "\\[\\(?:"
+ "fn:" "\\|"
+ "\\[" "\\|"
+ "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" "\\|"
+ "[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
+ "\\)")
+ ;; Objects starting with "@": export snippets.
+ "@@"
+ ;; Objects starting with "{": macro.
+ "{{{"
+ ;; Objects starting with "<" : timestamp
+ ;; (active, diary), target, radio target and
+ ;; angular links.
+ (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
+ ;; Objects starting with "$": latex fragment.
+ "\\$"
+ ;; Objects starting with "\": line break,
+ ;; entity, latex fragment.
+ "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
+ ;; Objects starting with raw text: inline Babel
+ ;; source block, inline Babel call.
+ "\\(?:call\\|src\\)_"))
+ "\\|")))
+
+(org-element--set-regexps)
+
+;;;###autoload
+(defun org-element-update-syntax ()
+ "Update parser internals."
+ (interactive)
+ (org-element--set-regexps)
+ (org-element-cache-reset 'all))
+
+(defconst org-element-all-elements
+ '(babel-call center-block clock comment comment-block diary-sexp drawer
+ dynamic-block example-block export-block fixed-width
+ footnote-definition headline horizontal-rule inlinetask item
+ keyword latex-environment node-property paragraph plain-list
+ planning property-drawer quote-block section
+ special-block src-block table table-row verse-block)
+ "Complete list of element types.")
+
+(defconst org-element-greater-elements
+ '(center-block drawer dynamic-block footnote-definition headline inlinetask
+ item plain-list property-drawer quote-block section
+ special-block table)
+ "List of recursive element types aka Greater Elements.")
+
+(defconst org-element-all-objects
+ '(bold code entity export-snippet footnote-reference inline-babel-call
+ inline-src-block italic line-break latex-fragment link macro
+ radio-target statistics-cookie strike-through subscript superscript
+ table-cell target timestamp underline verbatim)
+ "Complete list of object types.")
+
+(defconst org-element-recursive-objects
+ '(bold footnote-reference italic link subscript radio-target strike-through
+ superscript table-cell underline)
+ "List of recursive object types.")
+
+(defconst org-element-object-containers
+ (append org-element-recursive-objects '(paragraph table-row verse-block))
+ "List of object or element types that can directly contain objects.")
+
+(defconst org-element-affiliated-keywords
+ '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
+ "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
+ "List of affiliated keywords as strings.
+By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
+are affiliated keywords and need not to be in this list.")
+
+(defconst org-element-keyword-translation-alist
+ '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
+ ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
+ ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
+ "Alist of usual translations for keywords.
+The key is the old name and the value the new one. The property
+holding their value will be named after the translated name.")
+
+(defconst org-element-multiple-keywords '("CAPTION" "HEADER")
+ "List of affiliated keywords that can occur more than once in an element.
+
+Their value will be consed into a list of strings, which will be
+returned as the value of the property.
+
+This list is checked after translations have been applied. See
+`org-element-keyword-translation-alist'.
+
+By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
+allow multiple occurrences and need not to be in this list.")
+
+(defconst org-element-parsed-keywords '("CAPTION")
+ "List of affiliated keywords whose value can be parsed.
+
+Their value will be stored as a secondary string: a list of
+strings and objects.
+
+This list is checked after translations have been applied. See
+`org-element-keyword-translation-alist'.")
+
+(defconst org-element--parsed-properties-alist
+ (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
+ org-element-parsed-keywords)
+ "Alist of parsed keywords and associated properties.
+This is generated from `org-element-parsed-keywords', which
+see.")
+
+(defconst org-element-dual-keywords '("CAPTION" "RESULTS")
+ "List of affiliated keywords which can have a secondary value.
+
+In Org syntax, they can be written with optional square brackets
+before the colons. For example, RESULTS keyword can be
+associated to a hash value with the following:
+
+ #+RESULTS[hash-string]: some-source
+
+This list is checked after translations have been applied. See
+`org-element-keyword-translation-alist'.")
+
+(defconst org-element--affiliated-re
+ (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
+ (concat
+ ;; Dual affiliated keywords.
+ (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
+ (regexp-opt org-element-dual-keywords))
+ "\\|"
+ ;; Regular affiliated keywords.
+ (format "\\(?1:%s\\)"
+ (regexp-opt
+ (cl-remove-if
+ (lambda (k) (member k org-element-dual-keywords))
+ org-element-affiliated-keywords)))
+ "\\|"
+ ;; Export attributes.
+ "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
+ "Regexp matching any affiliated keyword.
+
+Keyword name is put in match group 1. Moreover, if keyword
+belongs to `org-element-dual-keywords', put the dual value in
+match group 2.
+
+Don't modify it, set `org-element-affiliated-keywords' instead.")
+
+(defconst org-element-object-restrictions
+ (let* ((standard-set (remq 'table-cell org-element-all-objects))
+ (standard-set-no-line-break (remq 'line-break standard-set)))
+ `((bold ,@standard-set)
+ (footnote-reference ,@standard-set)
+ (headline ,@standard-set-no-line-break)
+ (inlinetask ,@standard-set-no-line-break)
+ (italic ,@standard-set)
+ (item ,@standard-set-no-line-break)
+ (keyword ,@(remq 'footnote-reference standard-set))
+ ;; Ignore all links excepted plain links and angular links in
+ ;; a link description. Also ignore radio-targets and line
+ ;; breaks.
+ (link bold code entity export-snippet inline-babel-call inline-src-block
+ italic latex-fragment macro simple-link statistics-cookie
+ strike-through subscript superscript underline verbatim)
+ (paragraph ,@standard-set)
+ ;; Remove any variable object from radio target as it would
+ ;; prevent it from being properly recognized.
+ (radio-target bold code entity italic latex-fragment strike-through
+ subscript superscript underline superscript)
+ (strike-through ,@standard-set)
+ (subscript ,@standard-set)
+ (superscript ,@standard-set)
+ ;; Ignore inline babel call and inline src block as formulas are
+ ;; possible. Also ignore line breaks and statistics cookies.
+ (table-cell bold code entity export-snippet footnote-reference italic
+ latex-fragment link macro radio-target strike-through
+ subscript superscript target timestamp underline verbatim)
+ (table-row table-cell)
+ (underline ,@standard-set)
+ (verse-block ,@standard-set)))
+ "Alist of objects restrictions.
+
+key is an element or object type containing objects and value is
+a list of types that can be contained within an element or object
+of such type.
+
+For example, in a `radio-target' object, one can only find
+entities, latex-fragments, subscript, superscript and text
+markup.
+
+This alist also applies to secondary string. For example, an
+`headline' type element doesn't directly contain objects, but
+still has an entry since one of its properties (`:title') does.")
+
+(defconst org-element-secondary-value-alist
+ '((headline :title)
+ (inlinetask :title)
+ (item :tag))
+ "Alist between element types and locations of secondary values.")
+
+(defconst org-element--pair-round-table
+ (let ((table (make-syntax-table)))
+ (modify-syntax-entry ?\( "()" table)
+ (modify-syntax-entry ?\) ")(" table)
+ (dolist (char '(?\{ ?\} ?\[ ?\] ?\< ?\>) table)
+ (modify-syntax-entry char " " table)))
+ "Table used internally to pair only round brackets.
+Other brackets are treated as spaces.")
+
+(defconst org-element--pair-square-table
+ (let ((table (make-syntax-table)))
+ (modify-syntax-entry ?\[ "(]" table)
+ (modify-syntax-entry ?\] ")[" table)
+ (dolist (char '(?\{ ?\} ?\( ?\) ?\< ?\>) table)
+ (modify-syntax-entry char " " table)))
+ "Table used internally to pair only square brackets.
+Other brackets are treated as spaces.")
+
+(defconst org-element--pair-curly-table
+ (let ((table (make-syntax-table)))
+ (modify-syntax-entry ?\{ "(}" table)
+ (modify-syntax-entry ?\} "){" table)
+ (dolist (char '(?\[ ?\] ?\( ?\) ?\< ?\>) table)
+ (modify-syntax-entry char " " table)))
+ "Table used internally to pair only curly brackets.
+Other brackets are treated as spaces.")
+
+(defun org-element--parse-paired-brackets (char)
+ "Parse paired brackets at point.
+CHAR is the opening bracket to consider, as a character. Return
+contents between brackets, as a string, or nil. Also move point
+past the brackets."
+ (when (eq char (char-after))
+ (let ((syntax-table (pcase char
+ (?\{ org-element--pair-curly-table)
+ (?\[ org-element--pair-square-table)
+ (?\( org-element--pair-round-table)
+ (_ nil)))
+ (pos (point)))
+ (when syntax-table
+ (with-syntax-table syntax-table
+ (let ((end (ignore-errors (scan-lists pos 1 0))))
+ (when end
+ (goto-char end)
+ (buffer-substring-no-properties (1+ pos) (1- end)))))))))
+
+
+;;; Accessors and Setters
+;;
+;; Provide four accessors: `org-element-type', `org-element-property'
+;; `org-element-contents' and `org-element-restriction'.
+;;
+;; Setter functions allow modification of elements by side effect.
+;; There is `org-element-put-property', `org-element-set-contents'.
+;; These low-level functions are useful to build a parse tree.
+;;
+;; `org-element-adopt-elements', `org-element-set-element',
+;; `org-element-extract-element' and `org-element-insert-before' are
+;; high-level functions useful to modify a parse tree.
+;;
+;; `org-element-secondary-p' is a predicate used to know if a given
+;; object belongs to a secondary string. `org-element-class' tells if
+;; some parsed data is an element or an object, handling pseudo
+;; elements and objects. `org-element-copy' returns an element or
+;; object, stripping its parent property in the process.
+
+(defsubst org-element-type (element)
+ "Return type of ELEMENT.
+
+The function returns the type of the element or object provided.
+It can also return the following special value:
+ `plain-text' for a string
+ `org-data' for a complete document
+ nil in any other case."
+ (cond
+ ((not (consp element)) (and (stringp element) 'plain-text))
+ ((symbolp (car element)) (car element))))
+
+(defsubst org-element-property (property element)
+ "Extract the value from the PROPERTY of an ELEMENT."
+ (if (stringp element) (get-text-property 0 property element)
+ (plist-get (nth 1 element) property)))
+
+(defsubst org-element-contents (element)
+ "Extract contents from an ELEMENT."
+ (cond ((not (consp element)) nil)
+ ((symbolp (car element)) (nthcdr 2 element))
+ (t element)))
+
+(defsubst org-element-restriction (element)
+ "Return restriction associated to ELEMENT.
+ELEMENT can be an element, an object or a symbol representing an
+element or object type."
+ (cdr (assq (if (symbolp element) element (org-element-type element))
+ org-element-object-restrictions)))
+
+(defsubst org-element-put-property (element property value)
+ "In ELEMENT set PROPERTY to VALUE.
+Return modified element."
+ (if (stringp element) (org-add-props element nil property value)
+ (setcar (cdr element) (plist-put (nth 1 element) property value))
+ element))
+
+(defsubst org-element-set-contents (element &rest contents)
+ "Set ELEMENT's contents to CONTENTS.
+Return ELEMENT."
+ (cond ((null element) contents)
+ ((not (symbolp (car element))) contents)
+ ((cdr element) (setcdr (cdr element) contents) element)
+ (t (nconc element contents))))
+
+(defun org-element-secondary-p (object)
+ "Non-nil when OBJECT directly belongs to a secondary string.
+Return value is the property name, as a keyword, or nil."
+ (let* ((parent (org-element-property :parent object))
+ (properties (cdr (assq (org-element-type parent)
+ org-element-secondary-value-alist))))
+ (catch 'exit
+ (dolist (p properties)
+ (and (memq object (org-element-property p parent))
+ (throw 'exit p))))))
+
+(defun org-element-class (datum &optional parent)
+ "Return class for ELEMENT, as a symbol.
+Class is either `element' or `object'. Optional argument PARENT
+is the element or object containing DATUM. It defaults to the
+value of DATUM `:parent' property."
+ (let ((type (org-element-type datum))
+ (parent (or parent (org-element-property :parent datum))))
+ (cond
+ ;; Trivial cases.
+ ((memq type org-element-all-objects) 'object)
+ ((memq type org-element-all-elements) 'element)
+ ;; Special cases.
+ ((eq type 'org-data) 'element)
+ ((eq type 'plain-text) 'object)
+ ((not type) 'object)
+ ;; Pseudo object or elements. Make a guess about its class.
+ ;; Basically a pseudo object is contained within another object,
+ ;; a secondary string or a container element.
+ ((not parent) 'element)
+ (t
+ (let ((parent-type (org-element-type parent)))
+ (cond ((not parent-type) 'object)
+ ((memq parent-type org-element-object-containers) 'object)
+ ((org-element-secondary-p datum) 'object)
+ (t 'element)))))))
+
+(defsubst org-element-adopt-elements (parent &rest children)
+ "Append elements to the contents of another element.
+
+PARENT is an element or object. CHILDREN can be elements,
+objects, or a strings.
+
+The function takes care of setting `:parent' property for CHILD.
+Return parent element."
+ (if (not children) parent
+ ;; Link every child to PARENT. If PARENT is nil, it is a secondary
+ ;; string: parent is the list itself.
+ (dolist (child children)
+ (org-element-put-property child :parent (or parent children)))
+ ;; Add CHILDREN at the end of PARENT contents.
+ (when parent
+ (apply #'org-element-set-contents
+ parent
+ (nconc (org-element-contents parent) children)))
+ ;; Return modified PARENT element.
+ (or parent children)))
+
+(defun org-element-extract-element (element)
+ "Extract ELEMENT from parse tree.
+Remove element from the parse tree by side-effect, and return it
+with its `:parent' property stripped out."
+ (let ((parent (org-element-property :parent element))
+ (secondary (org-element-secondary-p element)))
+ (if secondary
+ (org-element-put-property
+ parent secondary
+ (delq element (org-element-property secondary parent)))
+ (apply #'org-element-set-contents
+ parent
+ (delq element (org-element-contents parent))))
+ ;; Return ELEMENT with its :parent removed.
+ (org-element-put-property element :parent nil)))
+
+(defun org-element-insert-before (element location)
+ "Insert ELEMENT before LOCATION in parse tree.
+LOCATION is an element, object or string within the parse tree.
+Parse tree is modified by side effect."
+ (let* ((parent (org-element-property :parent location))
+ (property (org-element-secondary-p location))
+ (siblings (if property (org-element-property property parent)
+ (org-element-contents parent)))
+ ;; Special case: LOCATION is the first element of an
+ ;; independent secondary string (e.g. :title property). Add
+ ;; ELEMENT in-place.
+ (specialp (and (not property)
+ (eq siblings parent)
+ (eq (car parent) location))))
+ ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
+ (cond (specialp)
+ ((or (null siblings) (eq (car siblings) location))
+ (push element siblings))
+ ((null location) (nconc siblings (list element)))
+ (t
+ (let ((index (cl-position location siblings)))
+ (unless index (error "No location found to insert element"))
+ (push element (cdr (nthcdr (1- index) siblings))))))
+ ;; Store SIBLINGS at appropriate place in parse tree.
+ (cond
+ (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
+ (property (org-element-put-property parent property siblings))
+ (t (apply #'org-element-set-contents parent siblings)))
+ ;; Set appropriate :parent property.
+ (org-element-put-property element :parent parent)))
+
+(defun org-element-set-element (old new)
+ "Replace element or object OLD with element or object NEW.
+The function takes care of setting `:parent' property for NEW."
+ ;; Ensure OLD and NEW have the same parent.
+ (org-element-put-property new :parent (org-element-property :parent old))
+ (if (or (memq (org-element-type old) '(plain-text nil))
+ (memq (org-element-type new) '(plain-text nil)))
+ ;; We cannot replace OLD with NEW since one of them is not an
+ ;; object or element. We take the long path.
+ (progn (org-element-insert-before new old)
+ (org-element-extract-element old))
+ ;; Since OLD is going to be changed into NEW by side-effect, first
+ ;; make sure that every element or object within NEW has OLD as
+ ;; parent.
+ (dolist (blob (org-element-contents new))
+ (org-element-put-property blob :parent old))
+ ;; Transfer contents.
+ (apply #'org-element-set-contents old (org-element-contents new))
+ ;; Overwrite OLD's properties with NEW's.
+ (setcar (cdr old) (nth 1 new))
+ ;; Transfer type.
+ (setcar old (car new))))
+
+(defun org-element-create (type &optional props &rest children)
+ "Create a new element of type TYPE.
+Optional argument PROPS, when non-nil, is a plist defining the
+properties of the element. CHILDREN can be elements, objects or
+strings."
+ (apply #'org-element-adopt-elements (list type props) children))
+
+(defun org-element-copy (datum)
+ "Return a copy of DATUM.
+DATUM is an element, object, string or nil. `:parent' property
+is cleared and contents are removed in the process."
+ (when datum
+ (let ((type (org-element-type datum)))
+ (pcase type
+ (`org-data (list 'org-data nil))
+ (`plain-text (substring-no-properties datum))
+ (`nil (copy-sequence datum))
+ (_
+ (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
+
+
+
+;;; Greater elements
+;;
+;; For each greater element type, we define a parser and an
+;; interpreter.
+;;
+;; A parser returns the element or object as the list described above.
+;; Most of them accepts no argument. Though, exceptions exist. Hence
+;; every element containing a secondary string (see
+;; `org-element-secondary-value-alist') will accept an optional
+;; argument to toggle parsing of these secondary strings. Moreover,
+;; `item' parser requires current list's structure as its first
+;; element.
+;;
+;; An interpreter accepts two arguments: the list representation of
+;; the element or object, and its contents. The latter may be nil,
+;; depending on the element or object considered. It returns the
+;; appropriate Org syntax, as a string.
+;;
+;; Parsing functions must follow the naming convention:
+;; org-element-TYPE-parser, where TYPE is greater element's type, as
+;; defined in `org-element-greater-elements'.
+;;
+;; Similarly, interpreting functions must follow the naming
+;; convention: org-element-TYPE-interpreter.
+;;
+;; With the exception of `headline' and `item' types, greater elements
+;; cannot contain other greater elements of their own type.
+;;
+;; Beside implementing a parser and an interpreter, adding a new
+;; greater element requires tweaking `org-element--current-element'.
+;; Moreover, the newly defined type must be added to both
+;; `org-element-all-elements' and `org-element-greater-elements'.
+
+
+;;;; Center Block
+
+(defun org-element-center-block-parser (limit affiliated)
+ "Parse a center block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `center-block' and CDR is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end',
+`:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the block."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((block-end-line (match-beginning 0)))
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ ;; Empty blocks have no contents.
+ (contents-begin (progn (forward-line)
+ (and (< (point) block-end-line)
+ (point))))
+ (contents-end (and contents-begin block-end-line))
+ (pos-before-blank (progn (goto-char block-end-line)
+ (forward-line)
+ (point)))
+ (end (save-excursion
+ (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'center-block
+ (nconc
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))))
+
+(defun org-element-center-block-interpreter (_ contents)
+ "Interpret a center-block element as Org syntax.
+CONTENTS is the contents of the element."
+ (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents))
+
+
+;;;; Drawer
+
+(defun org-element-drawer-parser (limit affiliated)
+ "Parse a drawer.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `drawer' and CDR is a plist containing
+`:drawer-name', `:begin', `:end', `:contents-begin',
+`:contents-end', `:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at beginning of drawer."
+ (let ((case-fold-search t))
+ (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
+ ;; Incomplete drawer: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (save-excursion
+ (let* ((drawer-end-line (match-beginning 0))
+ (name (progn (looking-at org-drawer-regexp)
+ (match-string-no-properties 1)))
+ (begin (car affiliated))
+ (post-affiliated (point))
+ ;; Empty drawers have no contents.
+ (contents-begin (progn (forward-line)
+ (and (< (point) drawer-end-line)
+ (point))))
+ (contents-end (and contents-begin drawer-end-line))
+ (pos-before-blank (progn (goto-char drawer-end-line)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'drawer
+ (nconc
+ (list :begin begin
+ :end end
+ :drawer-name name
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))))
+
+(defun org-element-drawer-interpreter (drawer contents)
+ "Interpret DRAWER element as Org syntax.
+CONTENTS is the contents of the element."
+ (format ":%s:\n%s:END:"
+ (org-element-property :drawer-name drawer)
+ contents))
+
+
+;;;; Dynamic Block
+
+(defun org-element-dynamic-block-parser (limit affiliated)
+ "Parse a dynamic block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `dynamic-block' and CDR is a plist
+containing `:block-name', `:begin', `:end', `:contents-begin',
+`:contents-end', `:arguments', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at beginning of dynamic block."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((block-end-line (match-beginning 0)))
+ (save-excursion
+ (let* ((name (progn (looking-at org-dblock-start-re)
+ (match-string-no-properties 1)))
+ (arguments (match-string-no-properties 3))
+ (begin (car affiliated))
+ (post-affiliated (point))
+ ;; Empty blocks have no contents.
+ (contents-begin (progn (forward-line)
+ (and (< (point) block-end-line)
+ (point))))
+ (contents-end (and contents-begin block-end-line))
+ (pos-before-blank (progn (goto-char block-end-line)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'dynamic-block
+ (nconc
+ (list :begin begin
+ :end end
+ :block-name name
+ :arguments arguments
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-dynamic-block-interpreter (dynamic-block contents)
+ "Interpret DYNAMIC-BLOCK element as Org syntax.
+CONTENTS is the contents of the element."
+ (format "#+BEGIN: %s%s\n%s#+END:"
+ (org-element-property :block-name dynamic-block)
+ (let ((args (org-element-property :arguments dynamic-block)))
+ (if args (concat " " args) ""))
+ contents))
+
+
+;;;; Footnote Definition
+
+(defconst org-element--footnote-separator
+ (concat org-outline-regexp-bol "\\|"
+ org-footnote-definition-re "\\|"
+ "^\\([ \t]*\n\\)\\{2,\\}")
+ "Regexp used as a footnote definition separator.")
+
+(defun org-element-footnote-definition-parser (limit affiliated)
+ "Parse a footnote definition.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `footnote-definition' and CDR is
+a plist containing `:label', `:begin' `:end', `:contents-begin',
+`:contents-end', `:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the footnote definition."
+ (save-excursion
+ (let* ((label (progn (looking-at org-footnote-definition-re)
+ (match-string-no-properties 1)))
+ (begin (car affiliated))
+ (post-affiliated (point))
+ (end
+ (save-excursion
+ (end-of-line)
+ (cond
+ ((not
+ (re-search-forward org-element--footnote-separator limit t))
+ limit)
+ ((eq ?\[ (char-after (match-beginning 0)))
+ ;; At a new footnote definition, make sure we end
+ ;; before any affiliated keyword above.
+ (forward-line -1)
+ (while (and (> (point) post-affiliated)
+ (looking-at-p org-element--affiliated-re))
+ (forward-line -1))
+ (line-beginning-position 2))
+ ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
+ (t (skip-chars-forward " \r\t\n" limit)
+ (if (= limit (point)) limit (line-beginning-position))))))
+ (contents-begin
+ (progn (search-forward "]")
+ (skip-chars-forward " \r\t\n" end)
+ (cond ((= (point) end) nil)
+ ((= (line-beginning-position) post-affiliated) (point))
+ (t (line-beginning-position)))))
+ (contents-end
+ (progn (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))))
+ (list 'footnote-definition
+ (nconc
+ (list :label label
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end (and contents-begin contents-end)
+ :post-blank (count-lines contents-end end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-footnote-definition-interpreter (footnote-definition contents)
+ "Interpret FOOTNOTE-DEFINITION element as Org syntax.
+CONTENTS is the contents of the footnote-definition."
+ (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
+ " "
+ contents))
+
+
+;;;; Headline
+
+(defun org-element--get-node-properties ()
+ "Return node properties associated to headline at point.
+Upcase property names. It avoids confusion between properties
+obtained through property drawer and default properties from the
+parser (e.g. `:end' and :END:). Return value is a plist."
+ (save-excursion
+ (forward-line)
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (when (looking-at org-property-drawer-re)
+ (forward-line)
+ (let ((end (match-end 0)) properties)
+ (while (< (line-end-position) end)
+ (looking-at org-property-re)
+ (push (match-string-no-properties 3) properties)
+ (push (intern (concat ":" (upcase (match-string 2)))) properties)
+ (forward-line))
+ properties))))
+
+(defun org-element--get-time-properties ()
+ "Return time properties associated to headline at point.
+Return value is a plist."
+ (save-excursion
+ (when (progn (forward-line) (looking-at org-planning-line-re))
+ (let ((end (line-end-position)) plist)
+ (while (re-search-forward org-keyword-time-not-clock-regexp end t)
+ (goto-char (match-end 1))
+ (skip-chars-forward " \t")
+ (let ((keyword (match-string 1))
+ (time (org-element-timestamp-parser)))
+ (cond ((equal keyword org-scheduled-string)
+ (setq plist (plist-put plist :scheduled time)))
+ ((equal keyword org-deadline-string)
+ (setq plist (plist-put plist :deadline time)))
+ (t (setq plist (plist-put plist :closed time))))))
+ plist))))
+
+(defun org-element-headline-parser (limit &optional raw-secondary-p)
+ "Parse a headline.
+
+Return a list whose CAR is `headline' and CDR is a plist
+containing `:raw-value', `:title', `:begin', `:end',
+`:pre-blank', `:contents-begin' and `:contents-end', `:level',
+`:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled',
+`:deadline', `:closed', `:archivedp', `:commentedp'
+`:footnote-section-p', `:post-blank' and `:post-affiliated'
+keywords.
+
+The plist also contains any property set in the property drawer,
+with its name in upper cases and colons added at the
+beginning (e.g., `:CUSTOM_ID').
+
+LIMIT is a buffer position bounding the search.
+
+When RAW-SECONDARY-P is non-nil, headline's title will not be
+parsed as a secondary string, but as a plain string instead.
+
+Assume point is at beginning of the headline."
+ (save-excursion
+ (let* ((begin (point))
+ (level (prog1 (org-reduced-level (skip-chars-forward "*"))
+ (skip-chars-forward " \t")))
+ (todo (and org-todo-regexp
+ (let (case-fold-search) (looking-at org-todo-regexp))
+ (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")
+ (match-string 0))))
+ (todo-type
+ (and todo (if (member todo org-done-keywords) 'done 'todo)))
+ (priority (and (looking-at "\\[#.\\][ \t]*")
+ (progn (goto-char (match-end 0))
+ (aref (match-string 0) 2))))
+ (commentedp
+ (and (let (case-fold-search) (looking-at org-comment-string))
+ (goto-char (match-end 0))))
+ (title-start (point))
+ (tags (when (re-search-forward
+ "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
+ (line-end-position)
+ 'move)
+ (goto-char (match-beginning 0))
+ (org-split-string (match-string 1) ":")))
+ (title-end (point))
+ (raw-value (org-trim
+ (buffer-substring-no-properties title-start title-end)))
+ (archivedp (member org-archive-tag tags))
+ (footnote-section-p (and org-footnote-section
+ (string= org-footnote-section raw-value)))
+ (standard-props (org-element--get-node-properties))
+ (time-props (org-element--get-time-properties))
+ (end (min (save-excursion (org-end-of-subtree t t)) limit))
+ (contents-begin (save-excursion
+ (forward-line)
+ (skip-chars-forward " \r\t\n" end)
+ (and (/= (point) end) (line-beginning-position))))
+ (contents-end (and contents-begin
+ (progn (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2)))))
+ (let ((headline
+ (list 'headline
+ (nconc
+ (list :raw-value raw-value
+ :begin begin
+ :end end
+ :pre-blank
+ (if (not contents-begin) 0
+ (1- (count-lines begin contents-begin)))
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :level level
+ :priority priority
+ :tags tags
+ :todo-keyword todo
+ :todo-type todo-type
+ :post-blank
+ (if contents-end
+ (count-lines contents-end end)
+ (1- (count-lines begin end)))
+ :footnote-section-p footnote-section-p
+ :archivedp archivedp
+ :commentedp commentedp
+ :post-affiliated begin)
+ time-props
+ standard-props))))
+ (org-element-put-property
+ headline :title
+ (if raw-secondary-p raw-value
+ (org-element--parse-objects
+ (progn (goto-char title-start)
+ (skip-chars-forward " \t")
+ (point))
+ (progn (goto-char title-end)
+ (skip-chars-backward " \t")
+ (point))
+ nil
+ (org-element-restriction 'headline)
+ headline)))))))
+
+(defun org-element-headline-interpreter (headline contents)
+ "Interpret HEADLINE element as Org syntax.
+CONTENTS is the contents of the element."
+ (let* ((level (org-element-property :level headline))
+ (todo (org-element-property :todo-keyword headline))
+ (priority (org-element-property :priority headline))
+ (title (org-element-interpret-data
+ (org-element-property :title headline)))
+ (tags (let ((tag-list (org-element-property :tags headline)))
+ (and tag-list
+ (format ":%s:" (mapconcat #'identity tag-list ":")))))
+ (commentedp (org-element-property :commentedp headline))
+ (pre-blank (or (org-element-property :pre-blank headline) 0))
+ (heading
+ (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
+ ?*)
+ (and todo (concat " " todo))
+ (and commentedp (concat " " org-comment-string))
+ (and priority (format " [#%c]" priority))
+ " "
+ (if (and org-footnote-section
+ (org-element-property :footnote-section-p headline))
+ org-footnote-section
+ title))))
+ (concat
+ heading
+ ;; Align tags.
+ (when tags
+ (cond
+ ((zerop org-tags-column) (format " %s" tags))
+ ((< org-tags-column 0)
+ (concat
+ (make-string
+ (max (- (+ org-tags-column (length heading) (length tags))) 1)
+ ?\s)
+ tags))
+ (t
+ (concat
+ (make-string (max (- org-tags-column (length heading)) 1) ?\s)
+ tags))))
+ (make-string (1+ pre-blank) ?\n)
+ contents)))
+
+
+;;;; Inlinetask
+
+(defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
+ "Parse an inline task.
+
+Return a list whose CAR is `inlinetask' and CDR is a plist
+containing `:title', `:begin', `:end', `:pre-blank',
+`:contents-begin' and `:contents-end', `:level', `:priority',
+`:raw-value', `:tags', `:todo-keyword', `:todo-type',
+`:scheduled', `:deadline', `:closed', `:post-blank' and
+`:post-affiliated' keywords.
+
+The plist also contains any property set in the property drawer,
+with its name in upper cases and colons added at the
+beginning (e.g., `:CUSTOM_ID').
+
+When optional argument RAW-SECONDARY-P is non-nil, inline-task's
+title will not be parsed as a secondary string, but as a plain
+string instead.
+
+Assume point is at beginning of the inline task."
+ (save-excursion
+ (let* ((begin (point))
+ (level (prog1 (org-reduced-level (skip-chars-forward "*"))
+ (skip-chars-forward " \t")))
+ (todo (and org-todo-regexp
+ (let (case-fold-search) (looking-at org-todo-regexp))
+ (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")
+ (match-string 0))))
+ (todo-type (and todo
+ (if (member todo org-done-keywords) 'done 'todo)))
+ (priority (and (looking-at "\\[#.\\][ \t]*")
+ (progn (goto-char (match-end 0))
+ (aref (match-string 0) 2))))
+ (title-start (point))
+ (tags (when (re-search-forward
+ "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
+ (line-end-position)
+ 'move)
+ (goto-char (match-beginning 0))
+ (org-split-string (match-string 1) ":")))
+ (title-end (point))
+ (raw-value (org-trim
+ (buffer-substring-no-properties title-start title-end)))
+ (task-end (save-excursion
+ (end-of-line)
+ (and (re-search-forward org-outline-regexp-bol limit t)
+ (looking-at-p "[ \t]*END[ \t]*$")
+ (line-beginning-position))))
+ (standard-props (and task-end (org-element--get-node-properties)))
+ (time-props (and task-end (org-element--get-time-properties)))
+ (contents-begin (and task-end
+ (< (point) task-end)
+ (progn
+ (forward-line)
+ (skip-chars-forward " \t\n")
+ (line-beginning-position))))
+ (contents-end (and contents-begin task-end))
+ (end (progn (when task-end (goto-char task-end))
+ (forward-line)
+ (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position))))
+ (inlinetask
+ (list 'inlinetask
+ (nconc
+ (list :raw-value raw-value
+ :begin begin
+ :end end
+ :pre-blank
+ (if (not contents-begin) 0
+ (1- (count-lines begin contents-begin)))
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :level level
+ :priority priority
+ :tags tags
+ :todo-keyword todo
+ :todo-type todo-type
+ :post-blank (1- (count-lines (or task-end begin) end))
+ :post-affiliated begin)
+ time-props
+ standard-props))))
+ (org-element-put-property
+ inlinetask :title
+ (if raw-secondary-p raw-value
+ (org-element--parse-objects
+ (progn (goto-char title-start)
+ (skip-chars-forward " \t")
+ (point))
+ (progn (goto-char title-end)
+ (skip-chars-backward " \t")
+ (point))
+ nil
+ (org-element-restriction 'inlinetask)
+ inlinetask))))))
+
+(defun org-element-inlinetask-interpreter (inlinetask contents)
+ "Interpret INLINETASK element as Org syntax.
+CONTENTS is the contents of inlinetask."
+ (let* ((level (org-element-property :level inlinetask))
+ (todo (org-element-property :todo-keyword inlinetask))
+ (priority (org-element-property :priority inlinetask))
+ (title (org-element-interpret-data
+ (org-element-property :title inlinetask)))
+ (tags (let ((tag-list (org-element-property :tags inlinetask)))
+ (and tag-list
+ (format ":%s:" (mapconcat 'identity tag-list ":")))))
+ (task (concat (make-string level ?*)
+ (and todo (concat " " todo))
+ (and priority (format " [#%c]" priority))
+ (and title (concat " " title)))))
+ (concat task
+ ;; Align tags.
+ (when tags
+ (cond
+ ((zerop org-tags-column) (format " %s" tags))
+ ((< org-tags-column 0)
+ (concat
+ (make-string
+ (max (- (+ org-tags-column (length task) (length tags))) 1)
+ ? )
+ tags))
+ (t
+ (concat
+ (make-string (max (- org-tags-column (length task)) 1) ? )
+ tags))))
+ ;; Prefer degenerate inlinetasks when there are no
+ ;; contents.
+ (when contents
+ (concat "\n"
+ contents
+ (make-string level ?*) " END")))))
+
+
+;;;; Item
+
+(defun org-element-item-parser (_ struct &optional raw-secondary-p)
+ "Parse an item.
+
+STRUCT is the structure of the plain list.
+
+Return a list whose CAR is `item' and CDR is a plist containing
+`:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
+`:checkbox', `:counter', `:tag', `:structure', `:post-blank' and
+`:post-affiliated' keywords.
+
+When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
+any, will not be parsed as a secondary string, but as a plain
+string instead.
+
+Assume point is at the beginning of the item."
+ (save-excursion
+ (beginning-of-line)
+ (looking-at org-list-full-item-re)
+ (let* ((begin (point))
+ (bullet (match-string-no-properties 1))
+ (checkbox (let ((box (match-string 3)))
+ (cond ((equal "[ ]" box) 'off)
+ ((equal "[X]" box) 'on)
+ ((equal "[-]" box) 'trans))))
+ (counter (let ((c (match-string 2)))
+ (save-match-data
+ (cond
+ ((not c) nil)
+ ((string-match "[A-Za-z]" c)
+ (- (string-to-char (upcase (match-string 0 c)))
+ 64))
+ ((string-match "[0-9]+" c)
+ (string-to-number (match-string 0 c)))))))
+ (end (progn (goto-char (nth 6 (assq (point) struct)))
+ (if (bolp) (point) (line-beginning-position 2))))
+ (contents-begin
+ (progn (goto-char
+ ;; Ignore tags in un-ordered lists: they are just
+ ;; a part of item's body.
+ (if (and (match-beginning 4)
+ (save-match-data (string-match "[.)]" bullet)))
+ (match-beginning 4)
+ (match-end 0)))
+ (skip-chars-forward " \r\t\n" end)
+ (cond ((= (point) end) nil)
+ ;; If first line isn't empty, contents really
+ ;; start at the text after item's meta-data.
+ ((= (line-beginning-position) begin) (point))
+ (t (line-beginning-position)))))
+ (contents-end (and contents-begin
+ (progn (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))))
+ (item
+ (list 'item
+ (list :bullet bullet
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :checkbox checkbox
+ :counter counter
+ :structure struct
+ :post-blank (count-lines (or contents-end begin) end)
+ :post-affiliated begin))))
+ (org-element-put-property
+ item :tag
+ (let ((raw (org-list-get-tag begin struct)))
+ (when raw
+ (if raw-secondary-p raw
+ (org-element--parse-objects
+ (match-beginning 4) (match-end 4) nil
+ (org-element-restriction 'item)
+ item))))))))
+
+(defun org-element-item-interpreter (item contents)
+ "Interpret ITEM element as Org syntax.
+CONTENTS is the contents of the element."
+ (let* ((bullet (let ((bullet (org-element-property :bullet item)))
+ (org-list-bullet-string
+ (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ")
+ ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
+ (t "1.")))))
+ (checkbox (org-element-property :checkbox item))
+ (counter (org-element-property :counter item))
+ (tag (let ((tag (org-element-property :tag item)))
+ (and tag (org-element-interpret-data tag))))
+ ;; Compute indentation.
+ (ind (make-string (length bullet) 32))
+ (item-starts-with-par-p
+ (eq (org-element-type (car (org-element-contents item)))
+ 'paragraph)))
+ ;; Indent contents.
+ (concat
+ bullet
+ (and counter (format "[@%d] " counter))
+ (pcase checkbox
+ (`on "[X] ")
+ (`off "[ ] ")
+ (`trans "[-] ")
+ (_ nil))
+ (and tag (format "%s :: " tag))
+ (when contents
+ (let ((contents (replace-regexp-in-string
+ "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
+ (if item-starts-with-par-p (org-trim contents)
+ (concat "\n" contents)))))))
+
+
+;;;; Plain List
+
+(defun org-element--list-struct (limit)
+ ;; Return structure of list at point. Internal function. See
+ ;; `org-list-struct' for details.
+ (let ((case-fold-search t)
+ (top-ind limit)
+ (item-re (org-item-re))
+ (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
+ items struct)
+ (save-excursion
+ (catch 'exit
+ (while t
+ (cond
+ ;; At limit: end all items.
+ ((>= (point) limit)
+ (throw 'exit
+ (let ((end (progn (skip-chars-backward " \r\t\n")
+ (forward-line)
+ (point))))
+ (dolist (item items (sort (nconc items struct)
+ 'car-less-than-car))
+ (setcar (nthcdr 6 item) end)))))
+ ;; At list end: end all items.
+ ((looking-at org-list-end-re)
+ (throw 'exit (dolist (item items (sort (nconc items struct)
+ 'car-less-than-car))
+ (setcar (nthcdr 6 item) (point)))))
+ ;; At a new item: end previous sibling.
+ ((looking-at item-re)
+ (let ((ind (save-excursion (skip-chars-forward " \t")
+ (current-column))))
+ (setq top-ind (min top-ind ind))
+ (while (and items (<= ind (nth 1 (car items))))
+ (let ((item (pop items)))
+ (setcar (nthcdr 6 item) (point))
+ (push item struct)))
+ (push (progn (looking-at org-list-full-item-re)
+ (let ((bullet (match-string-no-properties 1)))
+ (list (point)
+ ind
+ bullet
+ (match-string-no-properties 2) ; counter
+ (match-string-no-properties 3) ; checkbox
+ ;; Description tag.
+ (and (save-match-data
+ (string-match "[-+*]" bullet))
+ (match-string-no-properties 4))
+ ;; Ending position, unknown so far.
+ nil)))
+ items))
+ (forward-line 1))
+ ;; Skip empty lines.
+ ((looking-at "^[ \t]*$") (forward-line))
+ ;; Skip inline tasks and blank lines along the way.
+ ((and inlinetask-re (looking-at inlinetask-re))
+ (forward-line)
+ (let ((origin (point)))
+ (when (re-search-forward inlinetask-re limit t)
+ (if (looking-at-p "END[ \t]*$") (forward-line)
+ (goto-char origin)))))
+ ;; At some text line. Check if it ends any previous item.
+ (t
+ (let ((ind (save-excursion (skip-chars-forward " \t")
+ (current-column))))
+ (when (<= ind top-ind)
+ (skip-chars-backward " \r\t\n")
+ (forward-line))
+ (while (<= ind (nth 1 (car items)))
+ (let ((item (pop items)))
+ (setcar (nthcdr 6 item) (line-beginning-position))
+ (push item struct)
+ (unless items
+ (throw 'exit (sort struct #'car-less-than-car))))))
+ ;; Skip blocks (any type) and drawers contents.
+ (cond
+ ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
+ (re-search-forward
+ (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
+ limit t)))
+ ((and (looking-at org-drawer-regexp)
+ (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
+ (forward-line))))))))
+
+(defun org-element-plain-list-parser (limit affiliated structure)
+ "Parse a plain list.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value. STRUCTURE is the structure of the plain list being
+parsed.
+
+Return a list whose CAR is `plain-list' and CDR is a plist
+containing `:type', `:begin', `:end', `:contents-begin' and
+`:contents-end', `:structure', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at the beginning of the list."
+ (save-excursion
+ (let* ((struct (or structure (org-element--list-struct limit)))
+ (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
+ ((nth 5 (assq (point) struct)) 'descriptive)
+ (t 'unordered)))
+ (contents-begin (point))
+ (begin (car affiliated))
+ (contents-end (let* ((item (assq contents-begin struct))
+ (ind (nth 1 item))
+ (pos (nth 6 item)))
+ (while (and (setq item (assq pos struct))
+ (= (nth 1 item) ind))
+ (setq pos (nth 6 item)))
+ pos))
+ (end (progn (goto-char contents-end)
+ (skip-chars-forward " \r\t\n" limit)
+ (if (= (point) limit) limit (line-beginning-position)))))
+ ;; Return value.
+ (list 'plain-list
+ (nconc
+ (list :type type
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :structure struct
+ :post-blank (count-lines contents-end end)
+ :post-affiliated contents-begin)
+ (cdr affiliated))))))
+
+(defun org-element-plain-list-interpreter (_ contents)
+ "Interpret plain-list element as Org syntax.
+CONTENTS is the contents of the element."
+ (with-temp-buffer
+ (insert contents)
+ (goto-char (point-min))
+ (org-list-repair)
+ (buffer-string)))
+
+
+;;;; Property Drawer
+
+(defun org-element-property-drawer-parser (limit)
+ "Parse a property drawer.
+
+LIMIT bounds the search.
+
+Return a list whose car is `property-drawer' and cdr is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end',
+`:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the property drawer."
+ (save-excursion
+ (let ((case-fold-search t)
+ (begin (point))
+ (contents-begin (line-beginning-position 2)))
+ (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
+ (let ((contents-end (and (> (match-beginning 0) contents-begin)
+ (match-beginning 0)))
+ (before-blank (progn (forward-line) (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'property-drawer
+ (list :begin begin
+ :end end
+ :contents-begin (and contents-end contents-begin)
+ :contents-end contents-end
+ :post-blank (count-lines before-blank end)
+ :post-affiliated begin))))))
+
+(defun org-element-property-drawer-interpreter (_ contents)
+ "Interpret property-drawer element as Org syntax.
+CONTENTS is the properties within the drawer."
+ (format ":PROPERTIES:\n%s:END:" contents))
+
+
+;;;; Quote Block
+
+(defun org-element-quote-block-parser (limit affiliated)
+ "Parse a quote block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `quote-block' and CDR is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end',
+`:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the block."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((block-end-line (match-beginning 0)))
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ ;; Empty blocks have no contents.
+ (contents-begin (progn (forward-line)
+ (and (< (point) block-end-line)
+ (point))))
+ (contents-end (and contents-begin block-end-line))
+ (pos-before-blank (progn (goto-char block-end-line)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'quote-block
+ (nconc
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-quote-block-interpreter (_ contents)
+ "Interpret quote-block element as Org syntax.
+CONTENTS is the contents of the element."
+ (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents))
+
+
+;;;; Section
+
+(defun org-element-section-parser (_)
+ "Parse a section.
+
+Return a list whose CAR is `section' and CDR is a plist
+containing `:begin', `:end', `:contents-begin', `contents-end',
+`:post-blank' and `:post-affiliated' keywords."
+ (save-excursion
+ ;; Beginning of section is the beginning of the first non-blank
+ ;; line after previous headline.
+ (let ((begin (point))
+ (end (progn (org-with-limited-levels (outline-next-heading))
+ (point)))
+ (pos-before-blank (progn (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))))
+ (list 'section
+ (list :begin begin
+ :end end
+ :contents-begin begin
+ :contents-end pos-before-blank
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated begin)))))
+
+(defun org-element-section-interpreter (_ contents)
+ "Interpret section element as Org syntax.
+CONTENTS is the contents of the element."
+ contents)
+
+
+;;;; Special Block
+
+(defun org-element-special-block-parser (limit affiliated)
+ "Parse a special block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `special-block' and CDR is a plist
+containing `:type', `:begin', `:end', `:contents-begin',
+`:contents-end', `:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the block."
+ (let* ((case-fold-search t)
+ (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
+ (match-string-no-properties 1))))
+ (if (not (save-excursion
+ (re-search-forward
+ (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
+ limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((block-end-line (match-beginning 0)))
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ ;; Empty blocks have no contents.
+ (contents-begin (progn (forward-line)
+ (and (< (point) block-end-line)
+ (point))))
+ (contents-end (and contents-begin block-end-line))
+ (pos-before-blank (progn (goto-char block-end-line)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'special-block
+ (nconc
+ (list :type type
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-special-block-interpreter (special-block contents)
+ "Interpret SPECIAL-BLOCK element as Org syntax.
+CONTENTS is the contents of the element."
+ (let ((block-type (org-element-property :type special-block)))
+ (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type)))
+
+
+
+;;; Elements
+;;
+;; For each element, a parser and an interpreter are also defined.
+;; Both follow the same naming convention used for greater elements.
+;;
+;; Also, as for greater elements, adding a new element type is done
+;; through the following steps: implement a parser and an interpreter,
+;; tweak `org-element--current-element' so that it recognizes the new
+;; type and add that new type to `org-element-all-elements'.
+
+
+;;;; Babel Call
+
+(defun org-element-babel-call-parser (limit affiliated)
+ "Parse a babel call.
+
+LIMIT bounds the search. AFFILIATED is a list of which car is
+the buffer position at the beginning of the first affiliated
+keyword and cdr is a plist of affiliated keywords along with
+their value.
+
+Return a list whose car is `babel-call' and cdr is a plist
+containing `:call', `:inside-header', `:arguments',
+`:end-header', `:begin', `:end', `:value', `:post-blank' and
+`:post-affiliated' as keywords."
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ (before-blank (line-beginning-position 2))
+ (value (progn (search-forward ":" before-blank t)
+ (skip-chars-forward " \t")
+ (org-trim
+ (buffer-substring-no-properties
+ (point) (line-end-position)))))
+ (call
+ (or (org-string-nw-p
+ (buffer-substring-no-properties
+ (point) (progn (skip-chars-forward "^[]()" before-blank)
+ (point))))))
+ (inside-header (org-element--parse-paired-brackets ?\[))
+ (arguments (org-string-nw-p
+ (org-element--parse-paired-brackets ?\()))
+ (end-header
+ (org-string-nw-p
+ (org-trim
+ (buffer-substring-no-properties (point) (line-end-position)))))
+ (end (progn (forward-line)
+ (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'babel-call
+ (nconc
+ (list :call call
+ :inside-header inside-header
+ :arguments arguments
+ :end-header end-header
+ :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-babel-call-interpreter (babel-call _)
+ "Interpret BABEL-CALL element as Org syntax."
+ (concat "#+CALL: "
+ (org-element-property :call babel-call)
+ (let ((h (org-element-property :inside-header babel-call)))
+ (and h (format "[%s]" h)))
+ (concat "(" (org-element-property :arguments babel-call) ")")
+ (let ((h (org-element-property :end-header babel-call)))
+ (and h (concat " " h)))))
+
+
+;;;; Clock
+
+(defun org-element-clock-parser (limit)
+ "Parse a clock.
+
+LIMIT bounds the search.
+
+Return a list whose CAR is `clock' and CDR is a plist containing
+`:status', `:value', `:time', `:begin', `:end', `:post-blank' and
+`:post-affiliated' as keywords."
+ (save-excursion
+ (let* ((case-fold-search nil)
+ (begin (point))
+ (value (progn (search-forward org-clock-string (line-end-position) t)
+ (skip-chars-forward " \t")
+ (org-element-timestamp-parser)))
+ (duration (and (search-forward " => " (line-end-position) t)
+ (progn (skip-chars-forward " \t")
+ (looking-at "\\(\\S-+\\)[ \t]*$"))
+ (match-string-no-properties 1)))
+ (status (if duration 'closed 'running))
+ (post-blank (let ((before-blank (progn (forward-line) (point))))
+ (skip-chars-forward " \r\t\n" limit)
+ (skip-chars-backward " \t")
+ (unless (bolp) (end-of-line))
+ (count-lines before-blank (point))))
+ (end (point)))
+ (list 'clock
+ (list :status status
+ :value value
+ :duration duration
+ :begin begin
+ :end end
+ :post-blank post-blank
+ :post-affiliated begin)))))
+
+(defun org-element-clock-interpreter (clock _)
+ "Interpret CLOCK element as Org syntax."
+ (concat org-clock-string " "
+ (org-element-timestamp-interpreter
+ (org-element-property :value clock) nil)
+ (let ((duration (org-element-property :duration clock)))
+ (and duration
+ (concat " => "
+ (apply 'format
+ "%2s:%02s"
+ (org-split-string duration ":")))))))
+
+
+;;;; Comment
+
+(defun org-element-comment-parser (limit affiliated)
+ "Parse a comment.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `comment' and CDR is a plist
+containing `:begin', `:end', `:value', `:post-blank',
+`:post-affiliated' keywords.
+
+Assume point is at comment beginning."
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ (value (prog2 (looking-at "[ \t]*# ?")
+ (buffer-substring-no-properties
+ (match-end 0) (line-end-position))
+ (forward-line)))
+ (com-end
+ ;; Get comments ending.
+ (progn
+ (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
+ ;; Accumulate lines without leading hash and first
+ ;; whitespace.
+ (setq value
+ (concat value
+ "\n"
+ (buffer-substring-no-properties
+ (match-end 0) (line-end-position))))
+ (forward-line))
+ (point)))
+ (end (progn (goto-char com-end)
+ (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'comment
+ (nconc
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines com-end end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-comment-interpreter (comment _)
+ "Interpret COMMENT element as Org syntax.
+CONTENTS is nil."
+ (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
+
+
+;;;; Comment Block
+
+(defun org-element-comment-block-parser (limit affiliated)
+ "Parse an export block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `comment-block' and CDR is a plist
+containing `:begin', `:end', `:value', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at comment block beginning."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((contents-end (match-beginning 0)))
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ (contents-begin (progn (forward-line) (point)))
+ (pos-before-blank (progn (goto-char contents-end)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position))))
+ (value (buffer-substring-no-properties
+ contents-begin contents-end)))
+ (list 'comment-block
+ (nconc
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-comment-block-interpreter (comment-block _)
+ "Interpret COMMENT-BLOCK element as Org syntax."
+ (format "#+BEGIN_COMMENT\n%s#+END_COMMENT"
+ (org-element-normalize-string
+ (org-remove-indentation
+ (org-element-property :value comment-block)))))
+
+
+;;;; Diary Sexp
+
+(defun org-element-diary-sexp-parser (limit affiliated)
+ "Parse a diary sexp.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `diary-sexp' and CDR is a plist
+containing `:begin', `:end', `:value', `:post-blank' and
+`:post-affiliated' keywords."
+ (save-excursion
+ (let ((begin (car affiliated))
+ (post-affiliated (point))
+ (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
+ (match-string-no-properties 1)))
+ (pos-before-blank (progn (forward-line) (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'diary-sexp
+ (nconc
+ (list :value value
+ :begin begin
+ :end end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-diary-sexp-interpreter (diary-sexp _)
+ "Interpret DIARY-SEXP as Org syntax."
+ (org-element-property :value diary-sexp))
+
+
+;;;; Example Block
+
+(defun org-element-example-block-parser (limit affiliated)
+ "Parse an example block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `example-block' and CDR is a plist
+containing `:begin', `:end', `:number-lines', `:preserve-indent',
+`:retain-labels', `:use-labels', `:label-fmt', `:switches',
+`:value', `:post-blank' and `:post-affiliated' keywords."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((contents-end (match-beginning 0)))
+ (save-excursion
+ (let* ((switches
+ (progn
+ (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
+ (match-string-no-properties 1)))
+ ;; Switches analysis.
+ (number-lines
+ (and switches
+ (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
+ switches)
+ (cons
+ (if (equal (match-string 1 switches) "-")
+ 'new
+ 'continued)
+ (if (not (match-end 2)) 0
+ ;; Subtract 1 to give number of lines before
+ ;; first line.
+ (1- (string-to-number (match-string 2 switches)))))))
+ (preserve-indent
+ (and switches (string-match "-i\\>" switches)))
+ ;; Should labels be retained in (or stripped from) example
+ ;; blocks?
+ (retain-labels
+ (or (not switches)
+ (not (string-match "-r\\>" switches))
+ (and number-lines (string-match "-k\\>" switches))))
+ ;; What should code-references use - labels or
+ ;; line-numbers?
+ (use-labels
+ (or (not switches)
+ (and retain-labels
+ (not (string-match "-k\\>" switches)))))
+ (label-fmt
+ (and switches
+ (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
+ (match-string 1 switches)))
+ ;; Standard block parsing.
+ (begin (car affiliated))
+ (post-affiliated (point))
+ (contents-begin (line-beginning-position 2))
+ (value (org-unescape-code-in-string
+ (buffer-substring-no-properties
+ contents-begin contents-end)))
+ (pos-before-blank (progn (goto-char contents-end)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'example-block
+ (nconc
+ (list :begin begin
+ :end end
+ :value value
+ :switches switches
+ :number-lines number-lines
+ :preserve-indent preserve-indent
+ :retain-labels retain-labels
+ :use-labels use-labels
+ :label-fmt label-fmt
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-example-block-interpreter (example-block _)
+ "Interpret EXAMPLE-BLOCK element as Org syntax."
+ (let ((switches (org-element-property :switches example-block))
+ (value (org-element-property :value example-block)))
+ (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n"
+ (org-element-normalize-string
+ (org-escape-code-in-string
+ (if (or org-src-preserve-indentation
+ (org-element-property :preserve-indent example-block))
+ value
+ (org-remove-indentation value))))
+ "#+END_EXAMPLE")))
+
+
+;;;; Export Block
+
+(defun org-element-export-block-parser (limit affiliated)
+ "Parse an export block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `export-block' and CDR is a plist
+containing `:begin', `:end', `:type', `:value', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at export-block beginning."
+ (let* ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (save-excursion
+ (let* ((contents-end (match-beginning 0))
+ (backend
+ (progn
+ (looking-at
+ "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
+ (match-string-no-properties 1)))
+ (begin (car affiliated))
+ (post-affiliated (point))
+ (contents-begin (progn (forward-line) (point)))
+ (pos-before-blank (progn (goto-char contents-end)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position))))
+ (value (org-unescape-code-in-string
+ (buffer-substring-no-properties contents-begin
+ contents-end))))
+ (list 'export-block
+ (nconc
+ (list :type (and backend (upcase backend))
+ :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))))
+
+(defun org-element-export-block-interpreter (export-block _)
+ "Interpret EXPORT-BLOCK element as Org syntax."
+ (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT"
+ (org-element-property :type export-block)
+ (org-element-property :value export-block)))
+
+
+;;;; Fixed-width
+
+(defun org-element-fixed-width-parser (limit affiliated)
+ "Parse a fixed-width section.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `fixed-width' and CDR is a plist
+containing `:begin', `:end', `:value', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at the beginning of the fixed-width area."
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ value
+ (end-area
+ (progn
+ (while (and (< (point) limit)
+ (looking-at "[ \t]*:\\( \\|$\\)"))
+ ;; Accumulate text without starting colons.
+ (setq value
+ (concat value
+ (buffer-substring-no-properties
+ (match-end 0) (point-at-eol))
+ "\n"))
+ (forward-line))
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'fixed-width
+ (nconc
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines end-area end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-fixed-width-interpreter (fixed-width _)
+ "Interpret FIXED-WIDTH element as Org syntax."
+ (let ((value (org-element-property :value fixed-width)))
+ (and value
+ (replace-regexp-in-string
+ "^" ": "
+ (if (string-match "\n\\'" value) (substring value 0 -1) value)))))
+
+
+;;;; Horizontal Rule
+
+(defun org-element-horizontal-rule-parser (limit affiliated)
+ "Parse an horizontal rule.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `horizontal-rule' and CDR is a plist
+containing `:begin', `:end', `:post-blank' and `:post-affiliated'
+keywords."
+ (save-excursion
+ (let ((begin (car affiliated))
+ (post-affiliated (point))
+ (post-hr (progn (forward-line) (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'horizontal-rule
+ (nconc
+ (list :begin begin
+ :end end
+ :post-blank (count-lines post-hr end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-horizontal-rule-interpreter (&rest _)
+ "Interpret HORIZONTAL-RULE element as Org syntax."
+ "-----")
+
+
+;;;; Keyword
+
+(defun org-element-keyword-parser (limit affiliated)
+ "Parse a keyword at point.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `keyword' and CDR is a plist
+containing `:key', `:value', `:begin', `:end', `:post-blank' and
+`:post-affiliated' keywords."
+ (save-excursion
+ ;; An orphaned affiliated keyword is considered as a regular
+ ;; keyword. In this case AFFILIATED is nil, so we take care of
+ ;; this corner case.
+ (let ((begin (or (car affiliated) (point)))
+ (post-affiliated (point))
+ (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):")
+ (upcase (match-string-no-properties 1))))
+ (value (org-trim (buffer-substring-no-properties
+ (match-end 0) (point-at-eol))))
+ (pos-before-blank (progn (forward-line) (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'keyword
+ (nconc
+ (list :key key
+ :value value
+ :begin begin
+ :end end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated))))))
+
+(defun org-element-keyword-interpreter (keyword _)
+ "Interpret KEYWORD element as Org syntax."
+ (format "#+%s: %s"
+ (org-element-property :key keyword)
+ (org-element-property :value keyword)))
+
+
+;;;; Latex Environment
+
+(defconst org-element--latex-begin-environment
+ "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
+ "Regexp matching the beginning of a LaTeX environment.
+The environment is captured by the first group.
+
+See also `org-element--latex-end-environment'.")
+
+(defconst org-element--latex-end-environment
+ "\\\\end{%s}[ \t]*$"
+ "Format string matching the ending of a LaTeX environment.
+See also `org-element--latex-begin-environment'.")
+
+(defun org-element-latex-environment-parser (limit affiliated)
+ "Parse a LaTeX environment.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `latex-environment' and CDR is a plist
+containing `:begin', `:end', `:value', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at the beginning of the latex environment."
+ (save-excursion
+ (let ((case-fold-search t)
+ (code-begin (point)))
+ (looking-at org-element--latex-begin-environment)
+ (if (not (re-search-forward (format org-element--latex-end-environment
+ (regexp-quote (match-string 1)))
+ limit t))
+ ;; Incomplete latex environment: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let* ((code-end (progn (forward-line) (point)))
+ (begin (car affiliated))
+ (value (buffer-substring-no-properties code-begin code-end))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'latex-environment
+ (nconc
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank (count-lines code-end end)
+ :post-affiliated code-begin)
+ (cdr affiliated))))))))
+
+(defun org-element-latex-environment-interpreter (latex-environment _)
+ "Interpret LATEX-ENVIRONMENT element as Org syntax."
+ (org-element-property :value latex-environment))
+
+
+;;;; Node Property
+
+(defun org-element-node-property-parser (limit)
+ "Parse a node-property at point.
+
+LIMIT bounds the search.
+
+Return a list whose CAR is `node-property' and CDR is a plist
+containing `:key', `:value', `:begin', `:end', `:post-blank' and
+`:post-affiliated' keywords."
+ (looking-at org-property-re)
+ (let ((case-fold-search t)
+ (begin (point))
+ (key (match-string-no-properties 2))
+ (value (match-string-no-properties 3))
+ (end (save-excursion
+ (end-of-line)
+ (if (re-search-forward org-property-re limit t)
+ (line-beginning-position)
+ limit))))
+ (list 'node-property
+ (list :key key
+ :value value
+ :begin begin
+ :end end
+ :post-blank 0
+ :post-affiliated begin))))
+
+(defun org-element-node-property-interpreter (node-property _)
+ "Interpret NODE-PROPERTY element as Org syntax."
+ (format org-property-format
+ (format ":%s:" (org-element-property :key node-property))
+ (or (org-element-property :value node-property) "")))
+
+
+;;;; Paragraph
+
+(defun org-element-paragraph-parser (limit affiliated)
+ "Parse a paragraph.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `paragraph' and CDR is a plist
+containing `:begin', `:end', `:contents-begin' and
+`:contents-end', `:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at the beginning of the paragraph."
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (contents-begin (point))
+ (before-blank
+ (let ((case-fold-search t))
+ (end-of-line)
+ ;; A matching `org-element-paragraph-separate' is not
+ ;; necessarily the end of the paragraph. In particular,
+ ;; drawers, blocks or LaTeX environments opening lines
+ ;; must be closed. Moreover keywords with a secondary
+ ;; value must belong to "dual keywords".
+ (while (not
+ (cond
+ ((not (and (re-search-forward
+ org-element-paragraph-separate limit 'move)
+ (progn (beginning-of-line) t))))
+ ((looking-at org-drawer-regexp)
+ (save-excursion
+ (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
+ ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
+ (save-excursion
+ (re-search-forward
+ (format "^[ \t]*#\\+END_%s[ \t]*$"
+ (regexp-quote (match-string 1)))
+ limit t)))
+ ((looking-at org-element--latex-begin-environment)
+ (save-excursion
+ (re-search-forward
+ (format org-element--latex-end-environment
+ (regexp-quote (match-string 1)))
+ limit t)))
+ ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
+ (member-ignore-case (match-string 1)
+ org-element-dual-keywords))
+ ;; Everything else is unambiguous.
+ (t)))
+ (end-of-line))
+ (if (= (point) limit) limit
+ (goto-char (line-beginning-position)))))
+ (contents-end (save-excursion
+ (skip-chars-backward " \r\t\n" contents-begin)
+ (line-beginning-position 2)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'paragraph
+ (nconc
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines before-blank end)
+ :post-affiliated contents-begin)
+ (cdr affiliated))))))
+
+(defun org-element-paragraph-interpreter (_ contents)
+ "Interpret paragraph element as Org syntax.
+CONTENTS is the contents of the element."
+ contents)
+
+
+;;;; Planning
+
+(defun org-element-planning-parser (limit)
+ "Parse a planning.
+
+LIMIT bounds the search.
+
+Return a list whose CAR is `planning' and CDR is a plist
+containing `:closed', `:deadline', `:scheduled', `:begin',
+`:end', `:post-blank' and `:post-affiliated' keywords."
+ (save-excursion
+ (let* ((case-fold-search nil)
+ (begin (point))
+ (post-blank (let ((before-blank (progn (forward-line) (point))))
+ (skip-chars-forward " \r\t\n" limit)
+ (skip-chars-backward " \t")
+ (unless (bolp) (end-of-line))
+ (count-lines before-blank (point))))
+ (end (point))
+ closed deadline scheduled)
+ (goto-char begin)
+ (while (re-search-forward org-keyword-time-not-clock-regexp end t)
+ (goto-char (match-end 1))
+ (skip-chars-forward " \t" end)
+ (let ((keyword (match-string 1))
+ (time (org-element-timestamp-parser)))
+ (cond ((equal keyword org-closed-string) (setq closed time))
+ ((equal keyword org-deadline-string) (setq deadline time))
+ (t (setq scheduled time)))))
+ (list 'planning
+ (list :closed closed
+ :deadline deadline
+ :scheduled scheduled
+ :begin begin
+ :end end
+ :post-blank post-blank
+ :post-affiliated begin)))))
+
+(defun org-element-planning-interpreter (planning _)
+ "Interpret PLANNING element as Org syntax."
+ (mapconcat
+ #'identity
+ (delq nil
+ (list (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat org-deadline-string " "
+ (org-element-timestamp-interpreter deadline nil))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat org-scheduled-string " "
+ (org-element-timestamp-interpreter scheduled nil))))
+ (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat org-closed-string " "
+ (org-element-timestamp-interpreter closed nil))))))
+ " "))
+
+
+;;;; Src Block
+
+(defun org-element-src-block-parser (limit affiliated)
+ "Parse a src block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `src-block' and CDR is a plist
+containing `:language', `:switches', `:parameters', `:begin',
+`:end', `:number-lines', `:retain-labels', `:use-labels',
+`:label-fmt', `:preserve-indent', `:value', `:post-blank' and
+`:post-affiliated' keywords.
+
+Assume point is at the beginning of the block."
+ (let ((case-fold-search t))
+ (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
+ limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((contents-end (match-beginning 0)))
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ ;; Get language as a string.
+ (language
+ (progn
+ (looking-at
+ "^[ \t]*#\\+BEGIN_SRC\
+\\(?: +\\(\\S-+\\)\\)?\
+\\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
+\\(.*\\)[ \t]*$")
+ (match-string-no-properties 1)))
+ ;; Get switches.
+ (switches (match-string-no-properties 2))
+ ;; Get parameters.
+ (parameters (match-string-no-properties 3))
+ ;; Switches analysis.
+ (number-lines
+ (and switches
+ (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
+ switches)
+ (cons
+ (if (equal (match-string 1 switches) "-")
+ 'new
+ 'continued)
+ (if (not (match-end 2)) 0
+ ;; Subtract 1 to give number of lines before
+ ;; first line.
+ (1- (string-to-number (match-string 2 switches)))))))
+ (preserve-indent (and switches
+ (string-match "-i\\>" switches)))
+ (label-fmt
+ (and switches
+ (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
+ (match-string 1 switches)))
+ ;; Should labels be retained in (or stripped from)
+ ;; src blocks?
+ (retain-labels
+ (or (not switches)
+ (not (string-match "-r\\>" switches))
+ (and number-lines (string-match "-k\\>" switches))))
+ ;; What should code-references use - labels or
+ ;; line-numbers?
+ (use-labels
+ (or (not switches)
+ (and retain-labels
+ (not (string-match "-k\\>" switches)))))
+ ;; Retrieve code.
+ (value (org-unescape-code-in-string
+ (buffer-substring-no-properties
+ (line-beginning-position 2) contents-end)))
+ (pos-before-blank (progn (goto-char contents-end)
+ (forward-line)
+ (point)))
+ ;; Get position after ending blank lines.
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'src-block
+ (nconc
+ (list :language language
+ :switches (and (org-string-nw-p switches)
+ (org-trim switches))
+ :parameters (and (org-string-nw-p parameters)
+ (org-trim parameters))
+ :begin begin
+ :end end
+ :number-lines number-lines
+ :preserve-indent preserve-indent
+ :retain-labels retain-labels
+ :use-labels use-labels
+ :label-fmt label-fmt
+ :value value
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-src-block-interpreter (src-block _)
+ "Interpret SRC-BLOCK element as Org syntax."
+ (let ((lang (org-element-property :language src-block))
+ (switches (org-element-property :switches src-block))
+ (params (org-element-property :parameters src-block))
+ (value
+ (let ((val (org-element-property :value src-block)))
+ (cond
+ ((or org-src-preserve-indentation
+ (org-element-property :preserve-indent src-block))
+ val)
+ ((zerop org-edit-src-content-indentation)
+ (org-remove-indentation val))
+ (t
+ (let ((ind (make-string org-edit-src-content-indentation ?\s)))
+ (replace-regexp-in-string
+ "^" ind (org-remove-indentation val))))))))
+ (concat (format "#+BEGIN_SRC%s\n"
+ (concat (and lang (concat " " lang))
+ (and switches (concat " " switches))
+ (and params (concat " " params))))
+ (org-element-normalize-string (org-escape-code-in-string value))
+ "#+END_SRC")))
+
+
+;;;; Table
+
+(defun org-element-table-parser (limit affiliated)
+ "Parse a table at point.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `table' and CDR is a plist containing
+`:begin', `:end', `:tblfm', `:type', `:contents-begin',
+`:contents-end', `:value', `:post-blank' and `:post-affiliated'
+keywords.
+
+Assume point is at the beginning of the table."
+ (save-excursion
+ (let* ((case-fold-search t)
+ (table-begin (point))
+ (type (if (looking-at "[ \t]*|") 'org 'table.el))
+ (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
+ (if (eq type 'org) "" "+")))
+ (begin (car affiliated))
+ (table-end
+ (if (re-search-forward end-re limit 'move)
+ (goto-char (match-beginning 0))
+ (point)))
+ (tblfm (let (acc)
+ (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
+ (push (match-string-no-properties 1) acc)
+ (forward-line))
+ acc))
+ (pos-before-blank (point))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'table
+ (nconc
+ (list :begin begin
+ :end end
+ :type type
+ :tblfm tblfm
+ ;; Only `org' tables have contents. `table.el' tables
+ ;; use a `:value' property to store raw table as
+ ;; a string.
+ :contents-begin (and (eq type 'org) table-begin)
+ :contents-end (and (eq type 'org) table-end)
+ :value (and (eq type 'table.el)
+ (buffer-substring-no-properties
+ table-begin table-end))
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated table-begin)
+ (cdr affiliated))))))
+
+(defun org-element-table-interpreter (table contents)
+ "Interpret TABLE element as Org syntax.
+CONTENTS is a string, if table's type is `org', or nil."
+ (if (eq (org-element-property :type table) 'table.el)
+ (org-remove-indentation (org-element-property :value table))
+ (concat (with-temp-buffer (insert contents)
+ (org-table-align)
+ (buffer-string))
+ (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
+ (reverse (org-element-property :tblfm table))
+ "\n"))))
+
+
+;;;; Table Row
+
+(defun org-element-table-row-parser (_)
+ "Parse table row at point.
+
+Return a list whose CAR is `table-row' and CDR is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end',
+`:type', `:post-blank' and `:post-affiliated' keywords."
+ (save-excursion
+ (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
+ (begin (point))
+ ;; A table rule has no contents. In that case, ensure
+ ;; CONTENTS-BEGIN matches CONTENTS-END.
+ (contents-begin (and (eq type 'standard) (search-forward "|")))
+ (contents-end (and (eq type 'standard)
+ (progn
+ (end-of-line)
+ (skip-chars-backward " \t")
+ (point))))
+ (end (line-beginning-position 2)))
+ (list 'table-row
+ (list :type type
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank 0
+ :post-affiliated begin)))))
+
+(defun org-element-table-row-interpreter (table-row contents)
+ "Interpret TABLE-ROW element as Org syntax.
+CONTENTS is the contents of the table row."
+ (if (eq (org-element-property :type table-row) 'rule) "|-"
+ (concat "|" contents)))
+
+
+;;;; Verse Block
+
+(defun org-element-verse-block-parser (limit affiliated)
+ "Parse a verse block.
+
+LIMIT bounds the search. AFFILIATED is a list of which CAR is
+the buffer position at the beginning of the first affiliated
+keyword and CDR is a plist of affiliated keywords along with
+their value.
+
+Return a list whose CAR is `verse-block' and CDR is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end',
+`:post-blank' and `:post-affiliated' keywords.
+
+Assume point is at beginning of the block."
+ (let ((case-fold-search t))
+ (if (not (save-excursion
+ (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
+ ;; Incomplete block: parse it as a paragraph.
+ (org-element-paragraph-parser limit affiliated)
+ (let ((contents-end (match-beginning 0)))
+ (save-excursion
+ (let* ((begin (car affiliated))
+ (post-affiliated (point))
+ (contents-begin (progn (forward-line) (point)))
+ (pos-before-blank (progn (goto-char contents-end)
+ (forward-line)
+ (point)))
+ (end (progn (skip-chars-forward " \r\t\n" limit)
+ (if (eobp) (point) (line-beginning-position)))))
+ (list 'verse-block
+ (nconc
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank (count-lines pos-before-blank end)
+ :post-affiliated post-affiliated)
+ (cdr affiliated)))))))))
+
+(defun org-element-verse-block-interpreter (_ contents)
+ "Interpret verse-block element as Org syntax.
+CONTENTS is verse block contents."
+ (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents))
+
+
+
+;;; Objects
+;;
+;; Unlike to elements, raw text can be found between objects. Hence,
+;; `org-element--object-lex' is provided to find the next object in
+;; buffer.
+;;
+;; Some object types (e.g., `italic') are recursive. Restrictions on
+;; object types they can contain will be specified in
+;; `org-element-object-restrictions'.
+;;
+;; Creating a new type of object requires to alter
+;; `org-element--object-regexp' and `org-element--object-lex', add the
+;; new type in `org-element-all-objects', and possibly add
+;; restrictions in `org-element-object-restrictions'.
+
+;;;; Bold
+
+(defun org-element-bold-parser ()
+ "Parse bold object at point, if any.
+
+When at a bold object, return a list whose car is `bold' and cdr
+is a plist with `:begin', `:end', `:contents-begin' and
+`:contents-end' and `:post-blank' keywords. Otherwise, return
+nil.
+
+Assume point is at the first star marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (contents-begin (match-beginning 4))
+ (contents-end (match-end 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'bold
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-bold-interpreter (_ contents)
+ "Interpret bold object as Org syntax.
+CONTENTS is the contents of the object."
+ (format "*%s*" contents))
+
+
+;;;; Code
+
+(defun org-element-code-parser ()
+ "Parse code object at point, if any.
+
+When at a code object, return a list whose car is `code' and cdr
+is a plist with `:value', `:begin', `:end' and `:post-blank'
+keywords. Otherwise, return nil.
+
+Assume point is at the first tilde marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (value (match-string-no-properties 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'code
+ (list :value value
+ :begin begin
+ :end end
+ :post-blank post-blank))))))
+
+(defun org-element-code-interpreter (code _)
+ "Interpret CODE object as Org syntax."
+ (format "~%s~" (org-element-property :value code)))
+
+
+;;;; Entity
+
+(defun org-element-entity-parser ()
+ "Parse entity at point, if any.
+
+When at an entity, return a list whose car is `entity' and cdr
+a plist with `:begin', `:end', `:latex', `:latex-math-p',
+`:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
+`:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the beginning of the entity."
+ (catch 'no-object
+ (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
+ (save-excursion
+ (let* ((value (or (org-entity-get (match-string 1))
+ (throw 'no-object nil)))
+ (begin (match-beginning 0))
+ (bracketsp (string= (match-string 2) "{}"))
+ (post-blank (progn (goto-char (match-end 1))
+ (when bracketsp (forward-char 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'entity
+ (list :name (car value)
+ :latex (nth 1 value)
+ :latex-math-p (nth 2 value)
+ :html (nth 3 value)
+ :ascii (nth 4 value)
+ :latin1 (nth 5 value)
+ :utf-8 (nth 6 value)
+ :begin begin
+ :end end
+ :use-brackets-p bracketsp
+ :post-blank post-blank)))))))
+
+(defun org-element-entity-interpreter (entity _)
+ "Interpret ENTITY object as Org syntax."
+ (concat "\\"
+ (org-element-property :name entity)
+ (when (org-element-property :use-brackets-p entity) "{}")))
+
+
+;;;; Export Snippet
+
+(defun org-element-export-snippet-parser ()
+ "Parse export snippet at point.
+
+When at an export snippet, return a list whose car is
+`export-snippet' and cdr a plist with `:begin', `:end',
+`:back-end', `:value' and `:post-blank' as keywords. Otherwise,
+return nil.
+
+Assume point is at the beginning of the snippet."
+ (save-excursion
+ (let (contents-end)
+ (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
+ (setq contents-end
+ (save-match-data (goto-char (match-end 0))
+ (re-search-forward "@@" nil t)
+ (match-beginning 0))))
+ (let* ((begin (match-beginning 0))
+ (back-end (match-string-no-properties 1))
+ (value (buffer-substring-no-properties
+ (match-end 0) contents-end))
+ (post-blank (skip-chars-forward " \t"))
+ (end (point)))
+ (list 'export-snippet
+ (list :back-end back-end
+ :value value
+ :begin begin
+ :end end
+ :post-blank post-blank)))))))
+
+(defun org-element-export-snippet-interpreter (export-snippet _)
+ "Interpret EXPORT-SNIPPET object as Org syntax."
+ (format "@@%s:%s@@"
+ (org-element-property :back-end export-snippet)
+ (org-element-property :value export-snippet)))
+
+
+;;;; Footnote Reference
+
+(defun org-element-footnote-reference-parser ()
+ "Parse footnote reference at point, if any.
+
+When at a footnote reference, return a list whose car is
+`footnote-reference' and cdr a plist with `:label', `:type',
+`:begin', `:end', `:content-begin', `:contents-end' and
+`:post-blank' as keywords. Otherwise, return nil."
+ (when (looking-at org-footnote-re)
+ (let ((closing (with-syntax-table org-element--pair-square-table
+ (ignore-errors (scan-lists (point) 1 0)))))
+ (when closing
+ (save-excursion
+ (let* ((begin (point))
+ (label (match-string-no-properties 1))
+ (inner-begin (match-end 0))
+ (inner-end (1- closing))
+ (type (if (match-end 2) 'inline 'standard))
+ (post-blank (progn (goto-char closing)
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'footnote-reference
+ (list :label label
+ :type type
+ :begin begin
+ :end end
+ :contents-begin (and (eq type 'inline) inner-begin)
+ :contents-end (and (eq type 'inline) inner-end)
+ :post-blank post-blank))))))))
+
+(defun org-element-footnote-reference-interpreter (footnote-reference contents)
+ "Interpret FOOTNOTE-REFERENCE object as Org syntax.
+CONTENTS is its definition, when inline, or nil."
+ (format "[fn:%s%s]"
+ (or (org-element-property :label footnote-reference) "")
+ (if contents (concat ":" contents) "")))
+
+
+;;;; Inline Babel Call
+
+(defun org-element-inline-babel-call-parser ()
+ "Parse inline babel call at point, if any.
+
+When at an inline babel call, return a list whose car is
+`inline-babel-call' and cdr a plist with `:call',
+`:inside-header', `:arguments', `:end-header', `:begin', `:end',
+`:value' and `:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the beginning of the babel call."
+ (save-excursion
+ (catch :no-object
+ (when (let ((case-fold-search nil))
+ (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
+ (goto-char (match-end 1))
+ (let* ((begin (match-beginning 0))
+ (call (match-string-no-properties 1))
+ (inside-header
+ (let ((p (org-element--parse-paired-brackets ?\[)))
+ (and (org-string-nw-p p)
+ (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
+ (arguments (org-string-nw-p
+ (or (org-element--parse-paired-brackets ?\()
+ ;; Parenthesis are mandatory.
+ (throw :no-object nil))))
+ (end-header
+ (let ((p (org-element--parse-paired-brackets ?\[)))
+ (and (org-string-nw-p p)
+ (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
+ (value (buffer-substring-no-properties begin (point)))
+ (post-blank (skip-chars-forward " \t"))
+ (end (point)))
+ (list 'inline-babel-call
+ (list :call call
+ :inside-header inside-header
+ :arguments arguments
+ :end-header end-header
+ :begin begin
+ :end end
+ :value value
+ :post-blank post-blank)))))))
+
+(defun org-element-inline-babel-call-interpreter (inline-babel-call _)
+ "Interpret INLINE-BABEL-CALL object as Org syntax."
+ (concat "call_"
+ (org-element-property :call inline-babel-call)
+ (let ((h (org-element-property :inside-header inline-babel-call)))
+ (and h (format "[%s]" h)))
+ "(" (org-element-property :arguments inline-babel-call) ")"
+ (let ((h (org-element-property :end-header inline-babel-call)))
+ (and h (format "[%s]" h)))))
+
+
+;;;; Inline Src Block
+
+(defun org-element-inline-src-block-parser ()
+ "Parse inline source block at point, if any.
+
+When at an inline source block, return a list whose car is
+`inline-src-block' and cdr a plist with `:begin', `:end',
+`:language', `:value', `:parameters' and `:post-blank' as
+keywords. Otherwise, return nil.
+
+Assume point is at the beginning of the inline src block."
+ (save-excursion
+ (catch :no-object
+ (when (let ((case-fold-search nil))
+ (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
+ (goto-char (match-end 1))
+ (let ((begin (match-beginning 0))
+ (language (match-string-no-properties 1))
+ (parameters
+ (let ((p (org-element--parse-paired-brackets ?\[)))
+ (and (org-string-nw-p p)
+ (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
+ (value (or (org-element--parse-paired-brackets ?\{)
+ (throw :no-object nil)))
+ (post-blank (skip-chars-forward " \t")))
+ (list 'inline-src-block
+ (list :language language
+ :value value
+ :parameters parameters
+ :begin begin
+ :end (point)
+ :post-blank post-blank)))))))
+
+(defun org-element-inline-src-block-interpreter (inline-src-block _)
+ "Interpret INLINE-SRC-BLOCK object as Org syntax."
+ (let ((language (org-element-property :language inline-src-block))
+ (arguments (org-element-property :parameters inline-src-block))
+ (body (org-element-property :value inline-src-block)))
+ (format "src_%s%s{%s}"
+ language
+ (if arguments (format "[%s]" arguments) "")
+ body)))
+
+;;;; Italic
+
+(defun org-element-italic-parser ()
+ "Parse italic object at point, if any.
+
+When at an italic object, return a list whose car is `italic' and
+cdr is a plist with `:begin', `:end', `:contents-begin' and
+`:contents-end' and `:post-blank' keywords. Otherwise, return
+nil.
+
+Assume point is at the first slash marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (contents-begin (match-beginning 4))
+ (contents-end (match-end 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'italic
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-italic-interpreter (_ contents)
+ "Interpret italic object as Org syntax.
+CONTENTS is the contents of the object."
+ (format "/%s/" contents))
+
+
+;;;; Latex Fragment
+
+(defun org-element-latex-fragment-parser ()
+ "Parse LaTeX fragment at point, if any.
+
+When at a LaTeX fragment, return a list whose car is
+`latex-fragment' and cdr a plist with `:value', `:begin', `:end',
+and `:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the beginning of the LaTeX fragment."
+ (catch 'no-object
+ (save-excursion
+ (let* ((begin (point))
+ (after-fragment
+ (if (eq (char-after) ?$)
+ (if (eq (char-after (1+ (point))) ?$)
+ (search-forward "$$" nil t 2)
+ (and (not (eq (char-before) ?$))
+ (search-forward "$" nil t 2)
+ (not (memq (char-before (match-beginning 0))
+ '(?\s ?\t ?\n ?, ?.)))
+ (looking-at-p
+ "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
+ (point)))
+ (pcase (char-after (1+ (point)))
+ (?\( (search-forward "\\)" nil t))
+ (?\[ (search-forward "\\]" nil t))
+ (_
+ ;; Macro.
+ (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
+\\|\\({[^{}\n]*}\\)\\)*")
+ (match-end 0))))))
+ (post-blank (if (not after-fragment) (throw 'no-object nil)
+ (goto-char after-fragment)
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'latex-fragment
+ (list :value (buffer-substring-no-properties begin after-fragment)
+ :begin begin
+ :end end
+ :post-blank post-blank))))))
+
+(defun org-element-latex-fragment-interpreter (latex-fragment _)
+ "Interpret LATEX-FRAGMENT object as Org syntax."
+ (org-element-property :value latex-fragment))
+
+;;;; Line Break
+
+(defun org-element-line-break-parser ()
+ "Parse line break at point, if any.
+
+When at a line break, return a list whose car is `line-break',
+and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
+Otherwise, return nil.
+
+Assume point is at the beginning of the line break."
+ (when (and (looking-at-p "\\\\\\\\[ \t]*$")
+ (not (eq (char-before) ?\\)))
+ (list 'line-break
+ (list :begin (point)
+ :end (line-beginning-position 2)
+ :post-blank 0))))
+
+(defun org-element-line-break-interpreter (&rest _)
+ "Interpret LINE-BREAK object as Org syntax."
+ "\\\\\n")
+
+
+;;;; Link
+
+(defun org-element-link-parser ()
+ "Parse link at point, if any.
+
+When at a link, return a list whose car is `link' and cdr a plist
+with `:type', `:path', `:format', `:raw-link', `:application',
+`:search-option', `:begin', `:end', `:contents-begin',
+`:contents-end' and `:post-blank' as keywords. Otherwise, return
+nil.
+
+Assume point is at the beginning of the link."
+ (catch 'no-object
+ (let ((begin (point))
+ end contents-begin contents-end link-end post-blank path type format
+ raw-link search-option application)
+ (cond
+ ;; Type 1: Text targeted from a radio target.
+ ((and org-target-link-regexp
+ (save-excursion (or (bolp) (backward-char))
+ (looking-at org-target-link-regexp)))
+ (setq type "radio")
+ (setq format 'plain)
+ (setq link-end (match-end 1))
+ (setq path (match-string-no-properties 1))
+ (setq contents-begin (match-beginning 1))
+ (setq contents-end (match-end 1)))
+ ;; Type 2: Standard link, i.e. [[http://orgmode.org][homepage]]
+ ((looking-at org-bracket-link-regexp)
+ (setq format 'bracket)
+ (setq contents-begin (match-beginning 3))
+ (setq contents-end (match-end 3))
+ (setq link-end (match-end 0))
+ ;; RAW-LINK is the original link. Expand any
+ ;; abbreviation in it.
+ ;;
+ ;; Also treat any newline character and associated
+ ;; indentation as a single space character. This is not
+ ;; compatible with RFC 3986, which requires to ignore
+ ;; them altogether. However, doing so would require
+ ;; users to encode spaces on the fly when writing links
+ ;; (e.g., insert [[shell:ls%20*.org]] instead of
+ ;; [[shell:ls *.org]], which defeats Org's focus on
+ ;; simplicity.
+ (setq raw-link (org-link-expand-abbrev
+ (replace-regexp-in-string
+ "[ \t]*\n[ \t]*" " "
+ (match-string-no-properties 1))))
+ ;; Determine TYPE of link and set PATH accordingly. According
+ ;; to RFC 3986, remove whitespaces from URI in external links.
+ ;; In internal ones, treat indentation as a single space.
+ (cond
+ ;; File type.
+ ((or (file-name-absolute-p raw-link)
+ (string-match "\\`\\.\\.?/" raw-link))
+ (setq type "file")
+ (setq path raw-link))
+ ;; Explicit type (http, irc, bbdb...).
+ ((string-match org-link-types-re raw-link)
+ (setq type (match-string 1 raw-link))
+ (setq path (substring raw-link (match-end 0))))
+ ;; Code-ref type: PATH is the name of the reference.
+ ((and (string-match-p "\\`(" raw-link)
+ (string-match-p ")\\'" raw-link))
+ (setq type "coderef")
+ (setq path (substring raw-link 1 -1)))
+ ;; Custom-id type: PATH is the name of the custom id.
+ ((= (string-to-char raw-link) ?#)
+ (setq type "custom-id")
+ (setq path (substring raw-link 1)))
+ ;; Fuzzy type: Internal link either matches a target, an
+ ;; headline name or nothing. PATH is the target or
+ ;; headline's name.
+ (t
+ (setq type "fuzzy")
+ (setq path raw-link))))
+ ;; Type 3: Plain link, e.g., http://orgmode.org
+ ((looking-at org-plain-link-re)
+ (setq format 'plain)
+ (setq raw-link (match-string-no-properties 0))
+ (setq type (match-string-no-properties 1))
+ (setq link-end (match-end 0))
+ (setq path (match-string-no-properties 2)))
+ ;; Type 4: Angular link, e.g., <http://orgmode.org>. Unlike to
+ ;; bracket links, follow RFC 3986 and remove any extra
+ ;; whitespace in URI.
+ ((looking-at org-angle-link-re)
+ (setq format 'angle)
+ (setq type (match-string-no-properties 1))
+ (setq link-end (match-end 0))
+ (setq raw-link
+ (buffer-substring-no-properties
+ (match-beginning 1) (match-end 2)))
+ (setq path (replace-regexp-in-string
+ "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
+ (t (throw 'no-object nil)))
+ ;; In any case, deduce end point after trailing white space from
+ ;; LINK-END variable.
+ (save-excursion
+ (setq post-blank
+ (progn (goto-char link-end) (skip-chars-forward " \t")))
+ (setq end (point)))
+ ;; Special "file" type link processing. Extract opening
+ ;; application and search option, if any. Also normalize URI.
+ (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
+ (setq application (match-string 1 type) type "file")
+ (when (string-match "::\\(.*\\)\\'" path)
+ (setq search-option (match-string 1 path))
+ (setq path (replace-match "" nil nil path)))
+ (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
+ ;; Translate link, if `org-link-translation-function' is set.
+ (let ((trans (and (functionp org-link-translation-function)
+ (funcall org-link-translation-function type path))))
+ (when trans
+ (setq type (car trans))
+ (setq path (cdr trans))))
+ (list 'link
+ (list :type type
+ :path path
+ :format format
+ :raw-link (or raw-link path)
+ :application application
+ :search-option search-option
+ :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank)))))
+
+(defun org-element-link-interpreter (link contents)
+ "Interpret LINK object as Org syntax.
+CONTENTS is the contents of the object, or nil."
+ (let ((type (org-element-property :type link))
+ (path (org-element-property :path link)))
+ (if (string= type "radio") path
+ (let ((fmt (pcase (org-element-property :format link)
+ ;; Links with contents and internal links have to
+ ;; use bracket syntax. Ignore `:format' in these
+ ;; cases. This is also the default syntax when the
+ ;; property is not defined, e.g., when the object
+ ;; was crafted by the user.
+ ((guard contents)
+ (format "[[%%s][%s]]"
+ ;; Since this is going to be used as
+ ;; a format string, escape percent signs
+ ;; in description.
+ (replace-regexp-in-string "%" "%%" contents)))
+ ((or `bracket
+ `nil
+ (guard (member type '("coderef" "custom-id" "fuzzy"))))
+ "[[%s]]")
+ ;; Otherwise, just obey to `:format'.
+ (`angle "<%s>")
+ (`plain "%s")
+ (f (error "Wrong `:format' value: %s" f)))))
+ (format fmt
+ (pcase type
+ ("coderef" (format "(%s)" path))
+ ("custom-id" (concat "#" path))
+ ("file"
+ (let ((app (org-element-property :application link))
+ (opt (org-element-property :search-option link)))
+ (concat type (and app (concat "+" app)) ":"
+ path
+ (and opt (concat "::" opt)))))
+ ("fuzzy" path)
+ (_ (concat type ":" path))))))))
+
+
+;;;; Macro
+
+(defun org-element-macro-parser ()
+ "Parse macro at point, if any.
+
+When at a macro, return a list whose car is `macro' and cdr
+a plist with `:key', `:args', `:begin', `:end', `:value' and
+`:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the macro."
+ (save-excursion
+ (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}")
+ (let ((begin (point))
+ (key (downcase (match-string-no-properties 1)))
+ (value (match-string-no-properties 0))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point))
+ (args (let ((args (match-string-no-properties 3)))
+ (and args (org-macro-extract-arguments args)))))
+ (list 'macro
+ (list :key key
+ :value value
+ :args args
+ :begin begin
+ :end end
+ :post-blank post-blank))))))
+
+(defun org-element-macro-interpreter (macro _)
+ "Interpret MACRO object as Org syntax."
+ (org-element-property :value macro))
+
+
+;;;; Radio-target
+
+(defun org-element-radio-target-parser ()
+ "Parse radio target at point, if any.
+
+When at a radio target, return a list whose car is `radio-target'
+and cdr a plist with `:begin', `:end', `:contents-begin',
+`:contents-end', `:value' and `:post-blank' as keywords.
+Otherwise, return nil.
+
+Assume point is at the radio target."
+ (save-excursion
+ (when (looking-at org-radio-target-regexp)
+ (let ((begin (point))
+ (contents-begin (match-beginning 1))
+ (contents-end (match-end 1))
+ (value (match-string-no-properties 1))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'radio-target
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank
+ :value value))))))
+
+(defun org-element-radio-target-interpreter (_ contents)
+ "Interpret target object as Org syntax.
+CONTENTS is the contents of the object."
+ (concat "<<<" contents ">>>"))
+
+
+;;;; Statistics Cookie
+
+(defun org-element-statistics-cookie-parser ()
+ "Parse statistics cookie at point, if any.
+
+When at a statistics cookie, return a list whose car is
+`statistics-cookie', and cdr a plist with `:begin', `:end',
+`:value' and `:post-blank' keywords. Otherwise, return nil.
+
+Assume point is at the beginning of the statistics-cookie."
+ (save-excursion
+ (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
+ (let* ((begin (point))
+ (value (buffer-substring-no-properties
+ (match-beginning 0) (match-end 0)))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'statistics-cookie
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank post-blank))))))
+
+(defun org-element-statistics-cookie-interpreter (statistics-cookie _)
+ "Interpret STATISTICS-COOKIE object as Org syntax."
+ (org-element-property :value statistics-cookie))
+
+
+;;;; Strike-Through
+
+(defun org-element-strike-through-parser ()
+ "Parse strike-through object at point, if any.
+
+When at a strike-through object, return a list whose car is
+`strike-through' and cdr is a plist with `:begin', `:end',
+`:contents-begin' and `:contents-end' and `:post-blank' keywords.
+Otherwise, return nil.
+
+Assume point is at the first plus sign marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (contents-begin (match-beginning 4))
+ (contents-end (match-end 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'strike-through
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-strike-through-interpreter (_ contents)
+ "Interpret strike-through object as Org syntax.
+CONTENTS is the contents of the object."
+ (format "+%s+" contents))
+
+
+;;;; Subscript
+
+(defun org-element-subscript-parser ()
+ "Parse subscript at point, if any.
+
+When at a subscript object, return a list whose car is
+`subscript' and cdr a plist with `:begin', `:end',
+`:contents-begin', `:contents-end', `:use-brackets-p' and
+`:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the underscore."
+ (save-excursion
+ (unless (bolp) (backward-char))
+ (when (looking-at org-match-substring-regexp)
+ (let ((bracketsp (match-beginning 4))
+ (begin (match-beginning 2))
+ (contents-begin (or (match-beginning 4)
+ (match-beginning 3)))
+ (contents-end (or (match-end 4) (match-end 3)))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'subscript
+ (list :begin begin
+ :end end
+ :use-brackets-p bracketsp
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-subscript-interpreter (subscript contents)
+ "Interpret SUBSCRIPT object as Org syntax.
+CONTENTS is the contents of the object."
+ (format
+ (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
+ contents))
+
+
+;;;; Superscript
+
+(defun org-element-superscript-parser ()
+ "Parse superscript at point, if any.
+
+When at a superscript object, return a list whose car is
+`superscript' and cdr a plist with `:begin', `:end',
+`:contents-begin', `:contents-end', `:use-brackets-p' and
+`:post-blank' as keywords. Otherwise, return nil.
+
+Assume point is at the caret."
+ (save-excursion
+ (unless (bolp) (backward-char))
+ (when (looking-at org-match-substring-regexp)
+ (let ((bracketsp (match-beginning 4))
+ (begin (match-beginning 2))
+ (contents-begin (or (match-beginning 4)
+ (match-beginning 3)))
+ (contents-end (or (match-end 4) (match-end 3)))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'superscript
+ (list :begin begin
+ :end end
+ :use-brackets-p bracketsp
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-superscript-interpreter (superscript contents)
+ "Interpret SUPERSCRIPT object as Org syntax.
+CONTENTS is the contents of the object."
+ (format
+ (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
+ contents))
+
+
+;;;; Table Cell
+
+(defun org-element-table-cell-parser ()
+ "Parse table cell at point.
+Return a list whose car is `table-cell' and cdr is a plist
+containing `:begin', `:end', `:contents-begin', `:contents-end'
+and `:post-blank' keywords."
+ (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
+ (let* ((begin (match-beginning 0))
+ (end (match-end 0))
+ (contents-begin (match-beginning 1))
+ (contents-end (match-end 1)))
+ (list 'table-cell
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank 0))))
+
+(defun org-element-table-cell-interpreter (_ contents)
+ "Interpret table-cell element as Org syntax.
+CONTENTS is the contents of the cell, or nil."
+ (concat " " contents " |"))
+
+
+;;;; Target
+
+(defun org-element-target-parser ()
+ "Parse target at point, if any.
+
+When at a target, return a list whose car is `target' and cdr
+a plist with `:begin', `:end', `:value' and `:post-blank' as
+keywords. Otherwise, return nil.
+
+Assume point is at the target."
+ (save-excursion
+ (when (looking-at org-target-regexp)
+ (let ((begin (point))
+ (value (match-string-no-properties 1))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'target
+ (list :begin begin
+ :end end
+ :value value
+ :post-blank post-blank))))))
+
+(defun org-element-target-interpreter (target _)
+ "Interpret TARGET object as Org syntax."
+ (format "<<%s>>" (org-element-property :value target)))
+
+
+;;;; Timestamp
+
+(defconst org-element--timestamp-regexp
+ (concat org-ts-regexp-both
+ "\\|"
+ "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
+ "\\|"
+ "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
+ "Regexp matching any timestamp type object.")
+
+(defun org-element-timestamp-parser ()
+ "Parse time stamp at point, if any.
+
+When at a time stamp, return a list whose car is `timestamp', and
+cdr a plist with `:type', `:raw-value', `:year-start',
+`:month-start', `:day-start', `:hour-start', `:minute-start',
+`:year-end', `:month-end', `:day-end', `:hour-end',
+`:minute-end', `:repeater-type', `:repeater-value',
+`:repeater-unit', `:warning-type', `:warning-value',
+`:warning-unit', `:begin', `:end' and `:post-blank' keywords.
+Otherwise, return nil.
+
+Assume point is at the beginning of the timestamp."
+ (when (looking-at-p org-element--timestamp-regexp)
+ (save-excursion
+ (let* ((begin (point))
+ (activep (eq (char-after) ?<))
+ (raw-value
+ (progn
+ (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
+ (match-string-no-properties 0)))
+ (date-start (match-string-no-properties 1))
+ (date-end (match-string 3))
+ (diaryp (match-beginning 2))
+ (post-blank (progn (goto-char (match-end 0))
+ (skip-chars-forward " \t")))
+ (end (point))
+ (time-range
+ (and (not diaryp)
+ (string-match
+ "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
+ date-start)
+ (cons (string-to-number (match-string 2 date-start))
+ (string-to-number (match-string 3 date-start)))))
+ (type (cond (diaryp 'diary)
+ ((and activep (or date-end time-range)) 'active-range)
+ (activep 'active)
+ ((or date-end time-range) 'inactive-range)
+ (t 'inactive)))
+ (repeater-props
+ (and (not diaryp)
+ (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
+ raw-value)
+ (list
+ :repeater-type
+ (let ((type (match-string 1 raw-value)))
+ (cond ((equal "++" type) 'catch-up)
+ ((equal ".+" type) 'restart)
+ (t 'cumulate)))
+ :repeater-value (string-to-number (match-string 2 raw-value))
+ :repeater-unit
+ (pcase (string-to-char (match-string 3 raw-value))
+ (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
+ (warning-props
+ (and (not diaryp)
+ (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
+ (list
+ :warning-type (if (match-string 1 raw-value) 'first 'all)
+ :warning-value (string-to-number (match-string 2 raw-value))
+ :warning-unit
+ (pcase (string-to-char (match-string 3 raw-value))
+ (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
+ year-start month-start day-start hour-start minute-start year-end
+ month-end day-end hour-end minute-end)
+ ;; Parse date-start.
+ (unless diaryp
+ (let ((date (org-parse-time-string date-start t)))
+ (setq year-start (nth 5 date)
+ month-start (nth 4 date)
+ day-start (nth 3 date)
+ hour-start (nth 2 date)
+ minute-start (nth 1 date))))
+ ;; Compute date-end. It can be provided directly in time-stamp,
+ ;; or extracted from time range. Otherwise, it defaults to the
+ ;; same values as date-start.
+ (unless diaryp
+ (let ((date (and date-end (org-parse-time-string date-end t))))
+ (setq year-end (or (nth 5 date) year-start)
+ month-end (or (nth 4 date) month-start)
+ day-end (or (nth 3 date) day-start)
+ hour-end (or (nth 2 date) (car time-range) hour-start)
+ minute-end (or (nth 1 date) (cdr time-range) minute-start))))
+ (list 'timestamp
+ (nconc (list :type type
+ :raw-value raw-value
+ :year-start year-start
+ :month-start month-start
+ :day-start day-start
+ :hour-start hour-start
+ :minute-start minute-start
+ :year-end year-end
+ :month-end month-end
+ :day-end day-end
+ :hour-end hour-end
+ :minute-end minute-end
+ :begin begin
+ :end end
+ :post-blank post-blank)
+ repeater-props
+ warning-props))))))
+
+(defun org-element-timestamp-interpreter (timestamp _)
+ "Interpret TIMESTAMP object as Org syntax."
+ (let* ((repeat-string
+ (concat
+ (pcase (org-element-property :repeater-type timestamp)
+ (`cumulate "+") (`catch-up "++") (`restart ".+"))
+ (let ((val (org-element-property :repeater-value timestamp)))
+ (and val (number-to-string val)))
+ (pcase (org-element-property :repeater-unit timestamp)
+ (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
+ (warning-string
+ (concat
+ (pcase (org-element-property :warning-type timestamp)
+ (`first "--") (`all "-"))
+ (let ((val (org-element-property :warning-value timestamp)))
+ (and val (number-to-string val)))
+ (pcase (org-element-property :warning-unit timestamp)
+ (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
+ (build-ts-string
+ ;; Build an Org timestamp string from TIME. ACTIVEP is
+ ;; non-nil when time stamp is active. If WITH-TIME-P is
+ ;; non-nil, add a time part. HOUR-END and MINUTE-END
+ ;; specify a time range in the timestamp. REPEAT-STRING is
+ ;; the repeater string, if any.
+ (lambda (time activep &optional with-time-p hour-end minute-end)
+ (let ((ts (format-time-string
+ (funcall (if with-time-p #'cdr #'car)
+ org-time-stamp-formats)
+ time)))
+ (when (and hour-end minute-end)
+ (string-match "[012]?[0-9]:[0-5][0-9]" ts)
+ (setq ts
+ (replace-match
+ (format "\\&-%02d:%02d" hour-end minute-end)
+ nil nil ts)))
+ (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
+ (dolist (s (list repeat-string warning-string))
+ (when (org-string-nw-p s)
+ (setq ts (concat (substring ts 0 -1)
+ " "
+ s
+ (substring ts -1)))))
+ ;; Return value.
+ ts)))
+ (type (org-element-property :type timestamp)))
+ (pcase type
+ ((or `active `inactive)
+ (let* ((minute-start (org-element-property :minute-start timestamp))
+ (minute-end (org-element-property :minute-end timestamp))
+ (hour-start (org-element-property :hour-start timestamp))
+ (hour-end (org-element-property :hour-end timestamp))
+ (time-range-p (and hour-start hour-end minute-start minute-end
+ (or (/= hour-start hour-end)
+ (/= minute-start minute-end)))))
+ (funcall
+ build-ts-string
+ (encode-time 0
+ (or minute-start 0)
+ (or hour-start 0)
+ (org-element-property :day-start timestamp)
+ (org-element-property :month-start timestamp)
+ (org-element-property :year-start timestamp))
+ (eq type 'active)
+ (and hour-start minute-start)
+ (and time-range-p hour-end)
+ (and time-range-p minute-end))))
+ ((or `active-range `inactive-range)
+ (let ((minute-start (org-element-property :minute-start timestamp))
+ (minute-end (org-element-property :minute-end timestamp))
+ (hour-start (org-element-property :hour-start timestamp))
+ (hour-end (org-element-property :hour-end timestamp)))
+ (concat
+ (funcall
+ build-ts-string (encode-time
+ 0
+ (or minute-start 0)
+ (or hour-start 0)
+ (org-element-property :day-start timestamp)
+ (org-element-property :month-start timestamp)
+ (org-element-property :year-start timestamp))
+ (eq type 'active-range)
+ (and hour-start minute-start))
+ "--"
+ (funcall build-ts-string
+ (encode-time 0
+ (or minute-end 0)
+ (or hour-end 0)
+ (org-element-property :day-end timestamp)
+ (org-element-property :month-end timestamp)
+ (org-element-property :year-end timestamp))
+ (eq type 'active-range)
+ (and hour-end minute-end)))))
+ (_ (org-element-property :raw-value timestamp)))))
+
+
+;;;; Underline
+
+(defun org-element-underline-parser ()
+ "Parse underline object at point, if any.
+
+When at an underline object, return a list whose car is
+`underline' and cdr is a plist with `:begin', `:end',
+`:contents-begin' and `:contents-end' and `:post-blank' keywords.
+Otherwise, return nil.
+
+Assume point is at the first underscore marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (contents-begin (match-beginning 4))
+ (contents-end (match-end 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'underline
+ (list :begin begin
+ :end end
+ :contents-begin contents-begin
+ :contents-end contents-end
+ :post-blank post-blank))))))
+
+(defun org-element-underline-interpreter (_ contents)
+ "Interpret underline object as Org syntax.
+CONTENTS is the contents of the object."
+ (format "_%s_" contents))
+
+
+;;;; Verbatim
+
+(defun org-element-verbatim-parser ()
+ "Parse verbatim object at point, if any.
+
+When at a verbatim object, return a list whose car is `verbatim'
+and cdr is a plist with `:value', `:begin', `:end' and
+`:post-blank' keywords. Otherwise, return nil.
+
+Assume point is at the first equal sign marker."
+ (save-excursion
+ (unless (bolp) (backward-char 1))
+ (when (looking-at org-emph-re)
+ (let ((begin (match-beginning 2))
+ (value (match-string-no-properties 4))
+ (post-blank (progn (goto-char (match-end 2))
+ (skip-chars-forward " \t")))
+ (end (point)))
+ (list 'verbatim
+ (list :value value
+ :begin begin
+ :end end
+ :post-blank post-blank))))))
+
+(defun org-element-verbatim-interpreter (verbatim _)
+ "Interpret VERBATIM object as Org syntax."
+ (format "=%s=" (org-element-property :value verbatim)))
+
+
+
+;;; Parsing Element Starting At Point
+;;
+;; `org-element--current-element' is the core function of this section.
+;; It returns the Lisp representation of the element starting at
+;; point.
+;;
+;; `org-element--current-element' makes use of special modes. They
+;; are activated for fixed element chaining (e.g., `plain-list' >
+;; `item') or fixed conditional element chaining (e.g., `headline' >
+;; `section'). Special modes are: `first-section', `item',
+;; `node-property', `section' and `table-row'.
+
+(defun org-element--current-element (limit &optional granularity mode structure)
+ "Parse the element starting at point.
+
+Return value is a list like (TYPE PROPS) where TYPE is the type
+of the element and PROPS a plist of properties associated to the
+element.
+
+Possible types are defined in `org-element-all-elements'.
+
+LIMIT bounds the search.
+
+Optional argument GRANULARITY determines the depth of the
+recursion. Allowed values are `headline', `greater-element',
+`element', `object' or nil. When it is broader than `object' (or
+nil), secondary values will not be parsed, since they only
+contain objects.
+
+Optional argument MODE, when non-nil, can be either
+`first-section', `section', `planning', `item', `node-property'
+and `table-row'.
+
+If STRUCTURE isn't provided but MODE is set to `item', it will be
+computed.
+
+This function assumes point is always at the beginning of the
+element it has to parse."
+ (save-excursion
+ (let ((case-fold-search t)
+ ;; Determine if parsing depth allows for secondary strings
+ ;; parsing. It only applies to elements referenced in
+ ;; `org-element-secondary-value-alist'.
+ (raw-secondary-p (and granularity (not (eq granularity 'object)))))
+ (cond
+ ;; Item.
+ ((eq mode 'item)
+ (org-element-item-parser limit structure raw-secondary-p))
+ ;; Table Row.
+ ((eq mode 'table-row) (org-element-table-row-parser limit))
+ ;; Node Property.
+ ((eq mode 'node-property) (org-element-node-property-parser limit))
+ ;; Headline.
+ ((org-with-limited-levels (org-at-heading-p))
+ (org-element-headline-parser limit raw-secondary-p))
+ ;; Sections (must be checked after headline).
+ ((eq mode 'section) (org-element-section-parser limit))
+ ((eq mode 'first-section)
+ (org-element-section-parser
+ (or (save-excursion (org-with-limited-levels (outline-next-heading)))
+ limit)))
+ ;; Planning.
+ ((and (eq mode 'planning)
+ (eq ?* (char-after (line-beginning-position 0)))
+ (looking-at org-planning-line-re))
+ (org-element-planning-parser limit))
+ ;; Property drawer.
+ ((and (memq mode '(planning property-drawer))
+ (eq ?* (char-after (line-beginning-position
+ (if (eq mode 'planning) 0 -1))))
+ (looking-at org-property-drawer-re))
+ (org-element-property-drawer-parser limit))
+ ;; When not at bol, point is at the beginning of an item or
+ ;; a footnote definition: next item is always a paragraph.
+ ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
+ ;; Clock.
+ ((looking-at org-clock-line-re) (org-element-clock-parser limit))
+ ;; Inlinetask.
+ ((org-at-heading-p)
+ (org-element-inlinetask-parser limit raw-secondary-p))
+ ;; From there, elements can have affiliated keywords.
+ (t (let ((affiliated (org-element--collect-affiliated-keywords limit)))
+ (cond
+ ;; Jumping over affiliated keywords put point off-limits.
+ ;; Parse them as regular keywords.
+ ((and (cdr affiliated) (>= (point) limit))
+ (goto-char (car affiliated))
+ (org-element-keyword-parser limit nil))
+ ;; LaTeX Environment.
+ ((looking-at org-element--latex-begin-environment)
+ (org-element-latex-environment-parser limit affiliated))
+ ;; Drawer and Property Drawer.
+ ((looking-at org-drawer-regexp)
+ (org-element-drawer-parser limit affiliated))
+ ;; Fixed Width
+ ((looking-at "[ \t]*:\\( \\|$\\)")
+ (org-element-fixed-width-parser limit affiliated))
+ ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
+ ;; Keywords.
+ ((looking-at "[ \t]*#")
+ (goto-char (match-end 0))
+ (cond
+ ((looking-at "\\(?: \\|$\\)")
+ (beginning-of-line)
+ (org-element-comment-parser limit affiliated))
+ ((looking-at "\\+BEGIN_\\(\\S-+\\)")
+ (beginning-of-line)
+ (funcall (pcase (upcase (match-string 1))
+ ("CENTER" #'org-element-center-block-parser)
+ ("COMMENT" #'org-element-comment-block-parser)
+ ("EXAMPLE" #'org-element-example-block-parser)
+ ("EXPORT" #'org-element-export-block-parser)
+ ("QUOTE" #'org-element-quote-block-parser)
+ ("SRC" #'org-element-src-block-parser)
+ ("VERSE" #'org-element-verse-block-parser)
+ (_ #'org-element-special-block-parser))
+ limit
+ affiliated))
+ ((looking-at "\\+CALL:")
+ (beginning-of-line)
+ (org-element-babel-call-parser limit affiliated))
+ ((looking-at "\\+BEGIN:? ")
+ (beginning-of-line)
+ (org-element-dynamic-block-parser limit affiliated))
+ ((looking-at "\\+\\S-+:")
+ (beginning-of-line)
+ (org-element-keyword-parser limit affiliated))
+ (t
+ (beginning-of-line)
+ (org-element-paragraph-parser limit affiliated))))
+ ;; Footnote Definition.
+ ((looking-at org-footnote-definition-re)
+ (org-element-footnote-definition-parser limit affiliated))
+ ;; Horizontal Rule.
+ ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
+ (org-element-horizontal-rule-parser limit affiliated))
+ ;; Diary Sexp.
+ ((looking-at "%%(")
+ (org-element-diary-sexp-parser limit affiliated))
+ ;; Table.
+ ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)")
+ (org-element-table-parser limit affiliated))
+ ;; List.
+ ((looking-at (org-item-re))
+ (org-element-plain-list-parser
+ limit affiliated
+ (or structure (org-element--list-struct limit))))
+ ;; Default element: Paragraph.
+ (t (org-element-paragraph-parser limit affiliated)))))))))
+
+
+;; Most elements can have affiliated keywords. When looking for an
+;; element beginning, we want to move before them, as they belong to
+;; that element, and, in the meantime, collect information they give
+;; into appropriate properties. Hence the following function.
+
+(defun org-element--collect-affiliated-keywords (limit)
+ "Collect affiliated keywords from point down to LIMIT.
+
+Return a list whose CAR is the position at the first of them and
+CDR a plist of keywords and values and move point to the
+beginning of the first line after them.
+
+As a special case, if element doesn't start at the beginning of
+the line (e.g., a paragraph starting an item), CAR is current
+position of point and CDR is nil."
+ (if (not (bolp)) (list (point))
+ (let ((case-fold-search t)
+ (origin (point))
+ ;; RESTRICT is the list of objects allowed in parsed
+ ;; keywords value.
+ (restrict (org-element-restriction 'keyword))
+ output)
+ (while (and (< (point) limit) (looking-at org-element--affiliated-re))
+ (let* ((raw-kwd (upcase (match-string 1)))
+ ;; Apply translation to RAW-KWD. From there, KWD is
+ ;; the official keyword.
+ (kwd (or (cdr (assoc raw-kwd
+ org-element-keyword-translation-alist))
+ raw-kwd))
+ ;; Find main value for any keyword.
+ (value
+ (save-match-data
+ (org-trim
+ (buffer-substring-no-properties
+ (match-end 0) (line-end-position)))))
+ ;; PARSEDP is non-nil when keyword should have its
+ ;; value parsed.
+ (parsedp (member kwd org-element-parsed-keywords))
+ ;; If KWD is a dual keyword, find its secondary
+ ;; value. Maybe parse it.
+ (dualp (member kwd org-element-dual-keywords))
+ (dual-value
+ (and dualp
+ (let ((sec (match-string-no-properties 2)))
+ (if (or (not sec) (not parsedp)) sec
+ (save-match-data
+ (org-element--parse-objects
+ (match-beginning 2) (match-end 2) nil restrict))))))
+ ;; Attribute a property name to KWD.
+ (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
+ ;; Now set final shape for VALUE.
+ (when parsedp
+ (setq value
+ (org-element--parse-objects
+ (match-end 0)
+ (progn (end-of-line) (skip-chars-backward " \t") (point))
+ nil restrict)))
+ (when dualp
+ (setq value (and (or value dual-value) (cons value dual-value))))
+ (when (or (member kwd org-element-multiple-keywords)
+ ;; Attributes can always appear on multiple lines.
+ (string-match "^ATTR_" kwd))
+ (setq value (cons value (plist-get output kwd-sym))))
+ ;; Eventually store the new value in OUTPUT.
+ (setq output (plist-put output kwd-sym value))
+ ;; Move to next keyword.
+ (forward-line)))
+ ;; If affiliated keywords are orphaned: move back to first one.
+ ;; They will be parsed as a paragraph.
+ (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
+ ;; Return value.
+ (cons origin output))))
+
+
+
+;;; The Org Parser
+;;
+;; The two major functions here are `org-element-parse-buffer', which
+;; parses Org syntax inside the current buffer, taking into account
+;; region, narrowing, or even visibility if specified, and
+;; `org-element-parse-secondary-string', which parses objects within
+;; a given string.
+;;
+;; The (almost) almighty `org-element-map' allows applying a function
+;; on elements or objects matching some type, and accumulating the
+;; resulting values. In an export situation, it also skips unneeded
+;; parts of the parse tree.
+
+(defun org-element-parse-buffer (&optional granularity visible-only)
+ "Recursively parse the buffer and return structure.
+If narrowing is in effect, only parse the visible part of the
+buffer.
+
+Optional argument GRANULARITY determines the depth of the
+recursion. It can be set to the following symbols:
+
+`headline' Only parse headlines.
+`greater-element' Don't recurse into greater elements except
+ headlines and sections. Thus, elements
+ parsed are the top-level ones.
+`element' Parse everything but objects and plain text.
+`object' Parse the complete buffer (default).
+
+When VISIBLE-ONLY is non-nil, don't parse contents of hidden
+elements.
+
+An element or object is represented as a list with the
+pattern (TYPE PROPERTIES CONTENTS), where :
+
+ TYPE is a symbol describing the element or object. See
+ `org-element-all-elements' and `org-element-all-objects' for an
+ exhaustive list of such symbols. One can retrieve it with
+ `org-element-type' function.
+
+ PROPERTIES is the list of attributes attached to the element or
+ object, as a plist. Although most of them are specific to the
+ element or object type, all types share `:begin', `:end',
+ `:post-blank' and `:parent' properties, which respectively
+ refer to buffer position where the element or object starts,
+ ends, the number of white spaces or blank lines after it, and
+ the element or object containing it. Properties values can be
+ obtained by using `org-element-property' function.
+
+ CONTENTS is a list of elements, objects or raw strings
+ contained in the current element or object, when applicable.
+ One can access them with `org-element-contents' function.
+
+The Org buffer has `org-data' as type and nil as properties.
+`org-element-map' function can be used to find specific elements
+or objects within the parse tree.
+
+This function assumes that current major mode is `org-mode'."
+ (save-excursion
+ (goto-char (point-min))
+ (org-skip-whitespace)
+ (org-element--parse-elements
+ (point-at-bol) (point-max)
+ ;; Start in `first-section' mode so text before the first
+ ;; headline belongs to a section.
+ 'first-section nil granularity visible-only (list 'org-data nil))))
+
+(defun org-element-parse-secondary-string (string restriction &optional parent)
+ "Recursively parse objects in STRING and return structure.
+
+RESTRICTION is a symbol limiting the object types that will be
+looked after.
+
+Optional argument PARENT, when non-nil, is the element or object
+containing the secondary string. It is used to set correctly
+`:parent' property within the string.
+
+If STRING is the empty string or nil, return nil."
+ (cond
+ ((not string) nil)
+ ((equal string "") nil)
+ (t (let ((local-variables (buffer-local-variables)))
+ (with-temp-buffer
+ (dolist (v local-variables)
+ (ignore-errors
+ (if (symbolp v) (makunbound v)
+ (set (make-local-variable (car v)) (cdr v)))))
+ (insert string)
+ (restore-buffer-modified-p nil)
+ (org-element--parse-objects
+ (point-min) (point-max) nil restriction parent))))))
+
+(defun org-element-map
+ (data types fun &optional info first-match no-recursion with-affiliated)
+ "Map a function on selected elements or objects.
+
+DATA is a parse tree, an element, an object, a string, or a list
+of such constructs. TYPES is a symbol or list of symbols of
+elements or objects types (see `org-element-all-elements' and
+`org-element-all-objects' for a complete list of types). FUN is
+the function called on the matching element or object. It has to
+accept one argument: the element or object itself.
+
+When optional argument INFO is non-nil, it should be a plist
+holding export options. In that case, parts of the parse tree
+not exportable according to that property list will be skipped.
+
+When optional argument FIRST-MATCH is non-nil, stop at the first
+match for which FUN doesn't return nil, and return that value.
+
+Optional argument NO-RECURSION is a symbol or a list of symbols
+representing elements or objects types. `org-element-map' won't
+enter any recursive element or object whose type belongs to that
+list. Though, FUN can still be applied on them.
+
+When optional argument WITH-AFFILIATED is non-nil, FUN will also
+apply to matching objects within parsed affiliated keywords (see
+`org-element-parsed-keywords').
+
+Nil values returned from FUN do not appear in the results.
+
+
+Examples:
+---------
+
+Assuming TREE is a variable containing an Org buffer parse tree,
+the following example will return a flat list of all `src-block'
+and `example-block' elements in it:
+
+ (org-element-map tree \\='(example-block src-block) #\\='identity)
+
+The following snippet will find the first headline with a level
+of 1 and a \"phone\" tag, and will return its beginning position:
+
+ (org-element-map tree \\='headline
+ (lambda (hl)
+ (and (= (org-element-property :level hl) 1)
+ (member \"phone\" (org-element-property :tags hl))
+ (org-element-property :begin hl)))
+ nil t)
+
+The next example will return a flat list of all `plain-list' type
+elements in TREE that are not a sub-list themselves:
+
+ (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
+
+Eventually, this example will return a flat list of all `bold'
+type objects containing a `latex-snippet' type object, even
+looking into captions:
+
+ (org-element-map tree \\='bold
+ (lambda (b)
+ (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
+ nil nil nil t)"
+ ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
+ (let* ((types (if (listp types) types (list types)))
+ (no-recursion (if (listp no-recursion) no-recursion
+ (list no-recursion)))
+ ;; Recursion depth is determined by --CATEGORY.
+ (--category
+ (catch :--found
+ (let ((category 'greater-elements)
+ (all-objects (cons 'plain-text org-element-all-objects)))
+ (dolist (type types category)
+ (cond ((memq type all-objects)
+ ;; If one object is found, the function has
+ ;; to recurse into every object.
+ (throw :--found 'objects))
+ ((not (memq type org-element-greater-elements))
+ ;; If one regular element is found, the
+ ;; function has to recurse, at least, into
+ ;; every element it encounters.
+ (and (not (eq category 'elements))
+ (setq category 'elements))))))))
+ --acc)
+ (letrec ((--walk-tree
+ (lambda (--data)
+ ;; Recursively walk DATA. INFO, if non-nil, is a plist
+ ;; holding contextual information.
+ (let ((--type (org-element-type --data)))
+ (cond
+ ((not --data))
+ ;; Ignored element in an export context.
+ ((and info (memq --data (plist-get info :ignore-list))))
+ ;; List of elements or objects.
+ ((not --type) (mapc --walk-tree --data))
+ ;; Unconditionally enter parse trees.
+ ((eq --type 'org-data)
+ (mapc --walk-tree (org-element-contents --data)))
+ (t
+ ;; Check if TYPE is matching among TYPES. If so,
+ ;; apply FUN to --DATA and accumulate return value
+ ;; into --ACC (or exit if FIRST-MATCH is non-nil).
+ (when (memq --type types)
+ (let ((result (funcall fun --data)))
+ (cond ((not result))
+ (first-match (throw :--map-first-match result))
+ (t (push result --acc)))))
+ ;; If --DATA has a secondary string that can contain
+ ;; objects with their type among TYPES, look inside.
+ (when (and (eq --category 'objects) (not (stringp --data)))
+ (dolist (p (cdr (assq --type
+ org-element-secondary-value-alist)))
+ (funcall --walk-tree (org-element-property p --data))))
+ ;; If --DATA has any parsed affiliated keywords and
+ ;; WITH-AFFILIATED is non-nil, look for objects in
+ ;; them.
+ (when (and with-affiliated
+ (eq --category 'objects)
+ (eq (org-element-class --data) 'element))
+ (dolist (kwd-pair org-element--parsed-properties-alist)
+ (let ((kwd (car kwd-pair))
+ (value (org-element-property (cdr kwd-pair) --data)))
+ ;; Pay attention to the type of parsed
+ ;; keyword. In particular, preserve order for
+ ;; multiple keywords.
+ (cond
+ ((not value))
+ ((member kwd org-element-dual-keywords)
+ (if (member kwd org-element-multiple-keywords)
+ (dolist (line (reverse value))
+ (funcall --walk-tree (cdr line))
+ (funcall --walk-tree (car line)))
+ (funcall --walk-tree (cdr value))
+ (funcall --walk-tree (car value))))
+ ((member kwd org-element-multiple-keywords)
+ (mapc --walk-tree (reverse value)))
+ (t (funcall --walk-tree value))))))
+ ;; Determine if a recursion into --DATA is possible.
+ (cond
+ ;; --TYPE is explicitly removed from recursion.
+ ((memq --type no-recursion))
+ ;; --DATA has no contents.
+ ((not (org-element-contents --data)))
+ ;; Looking for greater elements but --DATA is
+ ;; simply an element or an object.
+ ((and (eq --category 'greater-elements)
+ (not (memq --type org-element-greater-elements))))
+ ;; Looking for elements but --DATA is an object.
+ ((and (eq --category 'elements)
+ (eq (org-element-class --data) 'object)))
+ ;; In any other case, map contents.
+ (t (mapc --walk-tree (org-element-contents --data))))))))))
+ (catch :--map-first-match
+ (funcall --walk-tree data)
+ ;; Return value in a proper order.
+ (nreverse --acc)))))
+(put 'org-element-map 'lisp-indent-function 2)
+
+;; The following functions are internal parts of the parser.
+;;
+;; The first one, `org-element--parse-elements' acts at the element's
+;; level.
+;;
+;; The second one, `org-element--parse-objects' applies on all objects
+;; of a paragraph or a secondary string. It calls
+;; `org-element--object-lex' to find the next object in the current
+;; container.
+
+(defsubst org-element--next-mode (type parentp)
+ "Return next special mode according to TYPE, or nil.
+TYPE is a symbol representing the type of an element or object
+containing next element if PARENTP is non-nil, or before it
+otherwise. Modes can be either `first-section', `item',
+`node-property', `planning', `property-drawer', `section',
+`table-row' or nil."
+ (if parentp
+ (pcase type
+ (`headline 'section)
+ (`inlinetask 'planning)
+ (`plain-list 'item)
+ (`property-drawer 'node-property)
+ (`section 'planning)
+ (`table 'table-row))
+ (pcase type
+ (`item 'item)
+ (`node-property 'node-property)
+ (`planning 'property-drawer)
+ (`table-row 'table-row))))
+
+(defun org-element--parse-elements
+ (beg end mode structure granularity visible-only acc)
+ "Parse elements between BEG and END positions.
+
+MODE prioritizes some elements over the others. It can be set to
+`first-section', `section', `planning', `item', `node-property'
+or `table-row'.
+
+When value is `item', STRUCTURE will be used as the current list
+structure.
+
+GRANULARITY determines the depth of the recursion. See
+`org-element-parse-buffer' for more information.
+
+When VISIBLE-ONLY is non-nil, don't parse contents of hidden
+elements.
+
+Elements are accumulated into ACC."
+ (save-excursion
+ (goto-char beg)
+ ;; Visible only: skip invisible parts at the beginning of the
+ ;; element.
+ (when (and visible-only (org-invisible-p2))
+ (goto-char (min (1+ (org-find-visible)) end)))
+ ;; When parsing only headlines, skip any text before first one.
+ (when (and (eq granularity 'headline) (not (org-at-heading-p)))
+ (org-with-limited-levels (outline-next-heading)))
+ (let (elements)
+ (while (< (point) end)
+ ;; Find current element's type and parse it accordingly to
+ ;; its category.
+ (let* ((element (org-element--current-element
+ end granularity mode structure))
+ (type (org-element-type element))
+ (cbeg (org-element-property :contents-begin element)))
+ (goto-char (org-element-property :end element))
+ ;; Visible only: skip invisible parts between siblings.
+ (when (and visible-only (org-invisible-p2))
+ (goto-char (min (1+ (org-find-visible)) end)))
+ ;; Fill ELEMENT contents by side-effect.
+ (cond
+ ;; If element has no contents, don't modify it.
+ ((not cbeg))
+ ;; Greater element: parse it between `contents-begin' and
+ ;; `contents-end'. Make sure GRANULARITY allows the
+ ;; recursion, or ELEMENT is a headline, in which case going
+ ;; inside is mandatory, in order to get sub-level headings.
+ ((and (memq type org-element-greater-elements)
+ (or (memq granularity '(element object nil))
+ (and (eq granularity 'greater-element)
+ (eq type 'section))
+ (eq type 'headline)))
+ (org-element--parse-elements
+ cbeg (org-element-property :contents-end element)
+ ;; Possibly switch to a special mode.
+ (org-element--next-mode type t)
+ (and (memq type '(item plain-list))
+ (org-element-property :structure element))
+ granularity visible-only element))
+ ;; ELEMENT has contents. Parse objects inside, if
+ ;; GRANULARITY allows it.
+ ((memq granularity '(object nil))
+ (org-element--parse-objects
+ cbeg (org-element-property :contents-end element) element
+ (org-element-restriction type))))
+ (push (org-element-put-property element :parent acc) elements)
+ ;; Update mode.
+ (setq mode (org-element--next-mode type nil))))
+ ;; Return result.
+ (apply #'org-element-set-contents acc (nreverse elements)))))
+
+(defun org-element--object-lex (restriction)
+ "Return next object in current buffer or nil.
+RESTRICTION is a list of object types, as symbols, that should be
+looked after. This function assumes that the buffer is narrowed
+to an appropriate container (e.g., a paragraph)."
+ (if (memq 'table-cell restriction) (org-element-table-cell-parser)
+ (let* ((start (point))
+ (limit
+ ;; Object regexp sometimes needs to have a peek at
+ ;; a character ahead. Therefore, when there is a hard
+ ;; limit, make it one more than the true beginning of the
+ ;; radio target.
+ (save-excursion
+ (cond ((not org-target-link-regexp) nil)
+ ((not (memq 'link restriction)) nil)
+ ((progn
+ (unless (bolp) (forward-char -1))
+ (not (re-search-forward org-target-link-regexp nil t)))
+ nil)
+ ;; Since we moved backward, we do not want to
+ ;; match again an hypothetical 1-character long
+ ;; radio link before us. Realizing that this can
+ ;; only happen if such a radio link starts at
+ ;; beginning of line, we prevent this here.
+ ((and (= start (1+ (line-beginning-position)))
+ (= start (match-end 1)))
+ (and (re-search-forward org-target-link-regexp nil t)
+ (1+ (match-beginning 1))))
+ (t (1+ (match-beginning 1))))))
+ found)
+ (save-excursion
+ (while (and (not found)
+ (re-search-forward org-element--object-regexp limit 'move))
+ (goto-char (match-beginning 0))
+ (let ((result (match-string 0)))
+ (setq found
+ (cond
+ ((string-prefix-p "call_" result t)
+ (and (memq 'inline-babel-call restriction)
+ (org-element-inline-babel-call-parser)))
+ ((string-prefix-p "src_" result t)
+ (and (memq 'inline-src-block restriction)
+ (org-element-inline-src-block-parser)))
+ (t
+ (pcase (char-after)
+ (?^ (and (memq 'superscript restriction)
+ (org-element-superscript-parser)))
+ (?_ (or (and (memq 'subscript restriction)
+ (org-element-subscript-parser))
+ (and (memq 'underline restriction)
+ (org-element-underline-parser))))
+ (?* (and (memq 'bold restriction)
+ (org-element-bold-parser)))
+ (?/ (and (memq 'italic restriction)
+ (org-element-italic-parser)))
+ (?~ (and (memq 'code restriction)
+ (org-element-code-parser)))
+ (?= (and (memq 'verbatim restriction)
+ (org-element-verbatim-parser)))
+ (?+ (and (memq 'strike-through restriction)
+ (org-element-strike-through-parser)))
+ (?@ (and (memq 'export-snippet restriction)
+ (org-element-export-snippet-parser)))
+ (?{ (and (memq 'macro restriction)
+ (org-element-macro-parser)))
+ (?$ (and (memq 'latex-fragment restriction)
+ (org-element-latex-fragment-parser)))
+ (?<
+ (if (eq (aref result 1) ?<)
+ (or (and (memq 'radio-target restriction)
+ (org-element-radio-target-parser))
+ (and (memq 'target restriction)
+ (org-element-target-parser)))
+ (or (and (memq 'timestamp restriction)
+ (org-element-timestamp-parser))
+ (and (or (memq 'link restriction)
+ (memq 'simple-link restriction))
+ (org-element-link-parser)))))
+ (?\\
+ (if (eq (aref result 1) ?\\)
+ (and (memq 'line-break restriction)
+ (org-element-line-break-parser))
+ (or (and (memq 'entity restriction)
+ (org-element-entity-parser))
+ (and (memq 'latex-fragment restriction)
+ (org-element-latex-fragment-parser)))))
+ (?\[
+ (if (eq (aref result 1) ?\[)
+ (and (memq 'link restriction)
+ (org-element-link-parser))
+ (or (and (memq 'footnote-reference restriction)
+ (org-element-footnote-reference-parser))
+ (and (memq 'timestamp restriction)
+ (org-element-timestamp-parser))
+ (and (memq 'statistics-cookie restriction)
+ (org-element-statistics-cookie-parser)))))
+ ;; This is probably a plain link.
+ (_ (and (or (memq 'link restriction)
+ (memq 'simple-link restriction))
+ (org-element-link-parser)))))))
+ (or (eobp) (forward-char))))
+ (cond (found)
+ (limit (forward-char -1)
+ (org-element-link-parser)) ;radio link
+ (t nil))))))
+
+(defun org-element--parse-objects (beg end acc restriction &optional parent)
+ "Parse objects between BEG and END and return recursive structure.
+
+Objects are accumulated in ACC. RESTRICTION is a list of object
+successors which are allowed in the current object.
+
+ACC becomes the parent for all parsed objects. However, if ACC
+is nil (i.e., a secondary string is being parsed) and optional
+argument PARENT is non-nil, use it as the parent for all objects.
+Eventually, if both ACC and PARENT are nil, the common parent is
+the list of objects itself."
+ (save-excursion
+ (save-restriction
+ (narrow-to-region beg end)
+ (goto-char (point-min))
+ (let (next-object contents)
+ (while (and (not (eobp))
+ (setq next-object (org-element--object-lex restriction)))
+ ;; Text before any object.
+ (let ((obj-beg (org-element-property :begin next-object)))
+ (unless (= (point) obj-beg)
+ (let ((text (buffer-substring-no-properties (point) obj-beg)))
+ (push (if acc (org-element-put-property text :parent acc) text)
+ contents))))
+ ;; Object...
+ (let ((obj-end (org-element-property :end next-object))
+ (cont-beg (org-element-property :contents-begin next-object)))
+ (when acc (org-element-put-property next-object :parent acc))
+ (push (if cont-beg
+ ;; Fill contents of NEXT-OBJECT if possible.
+ (org-element--parse-objects
+ cont-beg
+ (org-element-property :contents-end next-object)
+ next-object
+ (org-element-restriction next-object))
+ next-object)
+ contents)
+ (goto-char obj-end)))
+ ;; Text after last object.
+ (unless (eobp)
+ (let ((text (buffer-substring-no-properties (point) end)))
+ (push (if acc (org-element-put-property text :parent acc) text)
+ contents)))
+ ;; Result. Set appropriate parent.
+ (if acc (apply #'org-element-set-contents acc (nreverse contents))
+ (let* ((contents (nreverse contents))
+ (parent (or parent contents)))
+ (dolist (datum contents contents)
+ (org-element-put-property datum :parent parent))))))))
+
+
+
+;;; Towards A Bijective Process
+;;
+;; The parse tree obtained with `org-element-parse-buffer' is really
+;; a snapshot of the corresponding Org buffer. Therefore, it can be
+;; interpreted and expanded into a string with canonical Org syntax.
+;; Hence `org-element-interpret-data'.
+;;
+;; The function relies internally on
+;; `org-element--interpret-affiliated-keywords'.
+
+;;;###autoload
+(defun org-element-interpret-data (data)
+ "Interpret DATA as Org syntax.
+DATA is a parse tree, an element, an object or a secondary string
+to interpret. Return Org syntax as a string."
+ (letrec ((fun
+ (lambda (data parent)
+ (let* ((type (org-element-type data))
+ ;; Find interpreter for current object or
+ ;; element. If it doesn't exist (e.g. this is
+ ;; a pseudo object or element), return contents,
+ ;; if any.
+ (interpret
+ (let ((fun (intern
+ (format "org-element-%s-interpreter" type))))
+ (if (fboundp fun) fun (lambda (_ contents) contents))))
+ (results
+ (cond
+ ;; Secondary string.
+ ((not type)
+ (mapconcat (lambda (obj) (funcall fun obj parent))
+ data
+ ""))
+ ;; Full Org document.
+ ((eq type 'org-data)
+ (mapconcat (lambda (obj) (funcall fun obj parent))
+ (org-element-contents data)
+ ""))
+ ;; Plain text: return it.
+ ((stringp data) data)
+ ;; Element or object without contents.
+ ((not (org-element-contents data))
+ (funcall interpret data nil))
+ ;; Element or object with contents.
+ (t
+ (funcall
+ interpret
+ data
+ ;; Recursively interpret contents.
+ (mapconcat
+ (lambda (datum) (funcall fun datum data))
+ (org-element-contents
+ (if (not (memq type '(paragraph verse-block)))
+ data
+ ;; Fix indentation of elements containing
+ ;; objects. We ignore `table-row'
+ ;; elements as they are one line long
+ ;; anyway.
+ (org-element-normalize-contents
+ data
+ ;; When normalizing first paragraph of
+ ;; an item or a footnote-definition,
+ ;; ignore first line's indentation.
+ (and (eq type 'paragraph)
+ (memq (org-element-type parent)
+ '(footnote-definition item))
+ (eq data
+ (car (org-element-contents parent)))))))
+ ""))))))
+ (if (memq type '(org-data plain-text nil)) results
+ ;; Build white spaces. If no `:post-blank' property
+ ;; is specified, assume its value is 0.
+ (let ((blank (or (org-element-property :post-blank data) 0)))
+ (if (eq (org-element-class data parent) 'object)
+ (concat results (make-string blank ?\s))
+ (concat (org-element--interpret-affiliated-keywords data)
+ (org-element-normalize-string results)
+ (make-string blank ?\n)))))))))
+ (funcall fun data nil)))
+
+(defun org-element--interpret-affiliated-keywords (element)
+ "Return ELEMENT's affiliated keywords as Org syntax.
+If there is no affiliated keyword, return the empty string."
+ (let ((keyword-to-org
+ (function
+ (lambda (key value)
+ (let (dual)
+ (when (member key org-element-dual-keywords)
+ (setq dual (cdr value) value (car value)))
+ (concat "#+" key
+ (and dual
+ (format "[%s]" (org-element-interpret-data dual)))
+ ": "
+ (if (member key org-element-parsed-keywords)
+ (org-element-interpret-data value)
+ value)
+ "\n"))))))
+ (mapconcat
+ (lambda (prop)
+ (let ((value (org-element-property prop element))
+ (keyword (upcase (substring (symbol-name prop) 1))))
+ (when value
+ (if (or (member keyword org-element-multiple-keywords)
+ ;; All attribute keywords can have multiple lines.
+ (string-match "^ATTR_" keyword))
+ (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
+ (reverse value)
+ "")
+ (funcall keyword-to-org keyword value)))))
+ ;; List all ELEMENT's properties matching an attribute line or an
+ ;; affiliated keyword, but ignore translated keywords since they
+ ;; cannot belong to the property list.
+ (cl-loop for prop in (nth 1 element) by 'cddr
+ when (let ((keyword (upcase (substring (symbol-name prop) 1))))
+ (or (string-match "^ATTR_" keyword)
+ (and
+ (member keyword org-element-affiliated-keywords)
+ (not (assoc keyword
+ org-element-keyword-translation-alist)))))
+ collect prop)
+ "")))
+
+;; Because interpretation of the parse tree must return the same
+;; number of blank lines between elements and the same number of white
+;; space after objects, some special care must be given to white
+;; spaces.
+;;
+;; The first function, `org-element-normalize-string', ensures any
+;; string different from the empty string will end with a single
+;; newline character.
+;;
+;; The second function, `org-element-normalize-contents', removes
+;; global indentation from the contents of the current element.
+
+(defun org-element-normalize-string (s)
+ "Ensure string S ends with a single newline character.
+
+If S isn't a string return it unchanged. If S is the empty
+string, return it. Otherwise, return a new string with a single
+newline character at its end."
+ (cond
+ ((not (stringp s)) s)
+ ((string= "" s) "")
+ (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
+ (replace-match "\n" nil nil s)))))
+
+(defun org-element-normalize-contents (element &optional ignore-first)
+ "Normalize plain text in ELEMENT's contents.
+
+ELEMENT must only contain plain text and objects.
+
+If optional argument IGNORE-FIRST is non-nil, ignore first line's
+indentation to compute maximal common indentation.
+
+Return the normalized element that is element with global
+indentation removed from its contents."
+ (letrec ((find-min-ind
+ ;; Return minimal common indentation within BLOB. This is
+ ;; done by walking recursively BLOB and updating MIN-IND
+ ;; along the way. FIRST-FLAG is non-nil when the next
+ ;; object is expected to be a string that doesn't start
+ ;; with a newline character. It happens for strings at
+ ;; the beginnings of the contents or right after a line
+ ;; break.
+ (lambda (blob first-flag min-ind)
+ (dolist (datum (org-element-contents blob) min-ind)
+ (when first-flag
+ (setq first-flag nil)
+ (cond
+ ;; Objects cannot start with spaces: in this
+ ;; case, indentation is 0.
+ ((not (stringp datum)) (throw :zero 0))
+ ((not (string-match
+ "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
+ (throw :zero 0))
+ ((equal (match-string 2 datum) "\n")
+ (put-text-property
+ (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
+ (t
+ (let ((i (string-width (match-string 1 datum))))
+ (put-text-property
+ (match-beginning 1) (match-end 1) 'org-ind i datum)
+ (setq min-ind (min i min-ind))))))
+ (cond
+ ((stringp datum)
+ (let ((s 0))
+ (while (string-match
+ "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
+ (setq s (match-end 1))
+ (cond
+ ((equal (match-string 1 datum) "")
+ (unless (member (match-string 2 datum) '("" "\n"))
+ (throw :zero 0)))
+ ((equal (match-string 2 datum) "\n")
+ (put-text-property (match-beginning 1) (match-end 1)
+ 'org-ind 'empty datum))
+ (t
+ (let ((i (string-width (match-string 1 datum))))
+ (put-text-property (match-beginning 1) (match-end 1)
+ 'org-ind i datum)
+ (setq min-ind (min i min-ind))))))))
+ ((eq (org-element-type datum) 'line-break)
+ (setq first-flag t))
+ ((memq (org-element-type datum) org-element-recursive-objects)
+ (setq min-ind
+ (funcall find-min-ind datum first-flag min-ind)))))))
+ (min-ind
+ (catch :zero
+ (funcall find-min-ind
+ element (not ignore-first) most-positive-fixnum))))
+ (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
+ ;; Build ELEMENT back, replacing each string with the same
+ ;; string minus common indentation.
+ (letrec ((build
+ (lambda (datum)
+ ;; Return DATUM with all its strings indentation
+ ;; shortened from MIN-IND white spaces.
+ (setcdr
+ (cdr datum)
+ (mapcar
+ (lambda (object)
+ (cond
+ ((stringp object)
+ (with-temp-buffer
+ (insert object)
+ (let ((s (point-min)))
+ (while (setq s (text-property-not-all
+ s (point-max) 'org-ind nil))
+ (goto-char s)
+ (let ((i (get-text-property s 'org-ind)))
+ (delete-region s (progn
+ (skip-chars-forward " \t")
+ (point)))
+ (when (integerp i) (indent-to (- i min-ind))))))
+ (buffer-string)))
+ ((memq (org-element-type object)
+ org-element-recursive-objects)
+ (funcall build object))
+ (t object)))
+ (org-element-contents datum)))
+ datum)))
+ (funcall build element)))))
+
+
+
+;;; Cache
+;;
+;; Implement a caching mechanism for `org-element-at-point' and
+;; `org-element-context', which see.
+;;
+;; A single public function is provided: `org-element-cache-reset'.
+;;
+;; Cache is enabled by default, but can be disabled globally with
+;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
+;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
+;; can be tweaked to control caching behaviour.
+;;
+;; Internally, parsed elements are stored in an AVL tree,
+;; `org-element--cache'. This tree is updated lazily: whenever
+;; a change happens to the buffer, a synchronization request is
+;; registered in `org-element--cache-sync-requests' (see
+;; `org-element--cache-submit-request'). During idle time, requests
+;; are processed by `org-element--cache-sync'. Synchronization also
+;; happens when an element is required from the cache. In this case,
+;; the process stops as soon as the needed element is up-to-date.
+;;
+;; A synchronization request can only apply on a synchronized part of
+;; the cache. Therefore, the cache is updated at least to the
+;; location where the new request applies. Thus, requests are ordered
+;; from left to right and all elements starting before the first
+;; request are correct. This property is used by functions like
+;; `org-element--cache-find' to retrieve elements in the part of the
+;; cache that can be trusted.
+;;
+;; A request applies to every element, starting from its original
+;; location (or key, see below). When a request is processed, it
+;; moves forward and may collide the next one. In this case, both
+;; requests are merged into a new one that starts from that element.
+;; As a consequence, the whole synchronization complexity does not
+;; depend on the number of pending requests, but on the number of
+;; elements the very first request will be applied on.
+;;
+;; Elements cannot be accessed through their beginning position, which
+;; may or may not be up-to-date. Instead, each element in the tree is
+;; associated to a key, obtained with `org-element--cache-key'. This
+;; mechanism is robust enough to preserve total order among elements
+;; even when the tree is only partially synchronized.
+;;
+;; Objects contained in an element are stored in a hash table,
+;; `org-element--cache-objects'.
+
+
+(defvar org-element-use-cache nil
+ "Non-nil when Org parser should cache its results.
+
+WARNING: for the time being, using cache sometimes triggers
+freezes. Therefore, it is disabled by default. Activate it if
+you want to help debugging the issue.")
+
+(defvar org-element-cache-sync-idle-time 0.6
+ "Length, in seconds, of idle time before syncing cache.")
+
+(defvar org-element-cache-sync-duration (seconds-to-time 0.04)
+ "Maximum duration, as a time value, for a cache synchronization.
+If the synchronization is not over after this delay, the process
+pauses and resumes after `org-element-cache-sync-break'
+seconds.")
+
+(defvar org-element-cache-sync-break (seconds-to-time 0.3)
+ "Duration, as a time value, of the pause between synchronizations.
+See `org-element-cache-sync-duration' for more information.")
+
+
+;;;; Data Structure
+
+(defvar org-element--cache nil
+ "AVL tree used to cache elements.
+Each node of the tree contains an element. Comparison is done
+with `org-element--cache-compare'. This cache is used in
+`org-element-at-point'.")
+
+(defvar org-element--cache-objects nil
+ "Hash table used as to cache objects.
+Key is an element, as returned by `org-element-at-point', and
+value is an alist where each association is:
+
+ (PARENT COMPLETEP . OBJECTS)
+
+where PARENT is an element or object, COMPLETEP is a boolean,
+non-nil when all direct children of parent are already cached and
+OBJECTS is a list of such children, as objects, from farthest to
+closest.
+
+In the following example, \\alpha, bold object and \\beta are
+contained within a paragraph
+
+ \\alpha *\\beta*
+
+If the paragraph is completely parsed, OBJECTS-DATA will be
+
+ ((PARAGRAPH t BOLD-OBJECT ENTITY-OBJECT)
+ (BOLD-OBJECT t ENTITY-OBJECT))
+
+whereas in a partially parsed paragraph, it could be
+
+ ((PARAGRAPH nil ENTITY-OBJECT))
+
+This cache is used in `org-element-context'.")
+
+(defvar org-element--cache-sync-requests nil
+ "List of pending synchronization requests.
+
+A request is a vector with the following pattern:
+
+ \[NEXT BEG END OFFSET PARENT PHASE]
+
+Processing a synchronization request consists of three phases:
+
+ 0. Delete modified elements,
+ 1. Fill missing area in cache,
+ 2. Shift positions and re-parent elements after the changes.
+
+During phase 0, NEXT is the key of the first element to be
+removed, BEG and END is buffer position delimiting the
+modifications. Elements starting between them (inclusive) are
+removed. So are elements whose parent is removed. PARENT, when
+non-nil, is the parent of the first element to be removed.
+
+During phase 1, NEXT is the key of the next known element in
+cache and BEG its beginning position. Parse buffer between that
+element and the one before it in order to determine the parent of
+the next element. Set PARENT to the element containing NEXT.
+
+During phase 2, NEXT is the key of the next element to shift in
+the parse tree. All elements starting from this one have their
+properties relatives to buffer positions shifted by integer
+OFFSET and, if they belong to element PARENT, are adopted by it.
+
+PHASE specifies the phase number, as an integer.")
+
+(defvar org-element--cache-sync-timer nil
+ "Timer used for cache synchronization.")
+
+(defvar org-element--cache-sync-keys nil
+ "Hash table used to store keys during synchronization.
+See `org-element--cache-key' for more information.")
+
+(defsubst org-element--cache-key (element)
+ "Return a unique key for ELEMENT in cache tree.
+
+Keys are used to keep a total order among elements in the cache.
+Comparison is done with `org-element--cache-key-less-p'.
+
+When no synchronization is taking place, a key is simply the
+beginning position of the element, or that position plus one in
+the case of an first item (respectively row) in
+a list (respectively a table).
+
+During a synchronization, the key is the one the element had when
+the cache was synchronized for the last time. Elements added to
+cache during the synchronization get a new key generated with
+`org-element--cache-generate-key'.
+
+Such keys are stored in `org-element--cache-sync-keys'. The hash
+table is cleared once the synchronization is complete."
+ (or (gethash element org-element--cache-sync-keys)
+ (let* ((begin (org-element-property :begin element))
+ ;; Increase beginning position of items (respectively
+ ;; table rows) by one, so the first item can get
+ ;; a different key from its parent list (respectively
+ ;; table).
+ (key (if (memq (org-element-type element) '(item table-row))
+ (1+ begin)
+ begin)))
+ (if org-element--cache-sync-requests
+ (puthash element key org-element--cache-sync-keys)
+ key))))
+
+(defun org-element--cache-generate-key (lower upper)
+ "Generate a key between LOWER and UPPER.
+
+LOWER and UPPER are integers or lists, possibly empty.
+
+If LOWER and UPPER are equals, return LOWER. Otherwise, return
+a unique key, as an integer or a list of integers, according to
+the following rules:
+
+ - LOWER and UPPER are compared level-wise until values differ.
+
+ - If, at a given level, LOWER and UPPER differ from more than
+ 2, the new key shares all the levels above with LOWER and
+ gets a new level. Its value is the mean between LOWER and
+ UPPER:
+
+ (1 2) + (1 4) --> (1 3)
+
+ - If LOWER has no value to compare with, it is assumed that its
+ value is `most-negative-fixnum'. E.g.,
+
+ (1 1) + (1 1 2)
+
+ is equivalent to
+
+ (1 1 m) + (1 1 2)
+
+ where m is `most-negative-fixnum'. Likewise, if UPPER is
+ short of levels, the current value is `most-positive-fixnum'.
+
+ - If they differ from only one, the new key inherits from
+ current LOWER level and fork it at the next level. E.g.,
+
+ (2 1) + (3 3)
+
+ is equivalent to
+
+ (2 1) + (2 M)
+
+ where M is `most-positive-fixnum'.
+
+ - If the key is only one level long, it is returned as an
+ integer:
+
+ (1 2) + (3 2) --> 2
+
+When they are not equals, the function assumes that LOWER is
+lesser than UPPER, per `org-element--cache-key-less-p'."
+ (if (equal lower upper) lower
+ (let ((lower (if (integerp lower) (list lower) lower))
+ (upper (if (integerp upper) (list upper) upper))
+ skip-upper key)
+ (catch 'exit
+ (while t
+ (let ((min (or (car lower) most-negative-fixnum))
+ (max (cond (skip-upper most-positive-fixnum)
+ ((car upper))
+ (t most-positive-fixnum))))
+ (if (< (1+ min) max)
+ (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
+ (throw 'exit (if key (nreverse (cons mean key)) mean)))
+ (when (and (< min max) (not skip-upper))
+ ;; When at a given level, LOWER and UPPER differ from
+ ;; 1, ignore UPPER altogether. Instead create a key
+ ;; between LOWER and the greatest key with the same
+ ;; prefix as LOWER so far.
+ (setq skip-upper t))
+ (push min key)
+ (setq lower (cdr lower) upper (cdr upper)))))))))
+
+(defsubst org-element--cache-key-less-p (a b)
+ "Non-nil if key A is less than key B.
+A and B are either integers or lists of integers, as returned by
+`org-element--cache-key'."
+ (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
+ (if (integerp b) (< (car a) b)
+ (catch 'exit
+ (while (and a b)
+ (cond ((car-less-than-car a b) (throw 'exit t))
+ ((car-less-than-car b a) (throw 'exit nil))
+ (t (setq a (cdr a) b (cdr b)))))
+ ;; If A is empty, either keys are equal (B is also empty) and
+ ;; we return nil, or A is lesser than B (B is longer) and we
+ ;; return a non-nil value.
+ ;;
+ ;; If A is not empty, B is necessarily empty and A is greater
+ ;; than B (A is longer). Therefore, return nil.
+ (and (null a) b)))))
+
+(defun org-element--cache-compare (a b)
+ "Non-nil when element A is located before element B."
+ (org-element--cache-key-less-p (org-element--cache-key a)
+ (org-element--cache-key b)))
+
+(defsubst org-element--cache-root ()
+ "Return root value in cache.
+This function assumes `org-element--cache' is a valid AVL tree."
+ (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
+
+
+;;;; Tools
+
+(defsubst org-element--cache-active-p ()
+ "Non-nil when cache is active in current buffer."
+ (and org-element-use-cache
+ org-element--cache
+ (derived-mode-p 'org-mode)))
+
+(defun org-element--cache-find (pos &optional side)
+ "Find element in cache starting at POS or before.
+
+POS refers to a buffer position.
+
+When optional argument SIDE is non-nil, the function checks for
+elements starting at or past POS instead. If SIDE is `both', the
+function returns a cons cell where car is the first element
+starting at or before POS and cdr the first element starting
+after POS.
+
+The function can only find elements in the synchronized part of
+the cache."
+ (let ((limit (and org-element--cache-sync-requests
+ (aref (car org-element--cache-sync-requests) 0)))
+ (node (org-element--cache-root))
+ lower upper)
+ (while node
+ (let* ((element (avl-tree--node-data node))
+ (begin (org-element-property :begin element)))
+ (cond
+ ((and limit
+ (not (org-element--cache-key-less-p
+ (org-element--cache-key element) limit)))
+ (setq node (avl-tree--node-left node)))
+ ((> begin pos)
+ (setq upper element
+ node (avl-tree--node-left node)))
+ ((< begin pos)
+ (setq lower element
+ node (avl-tree--node-right node)))
+ ;; We found an element in cache starting at POS. If `side'
+ ;; is `both' we also want the next one in order to generate
+ ;; a key in-between.
+ ;;
+ ;; If the element is the first row or item in a table or
+ ;; a plain list, we always return the table or the plain
+ ;; list.
+ ;;
+ ;; In any other case, we return the element found.
+ ((eq side 'both)
+ (setq lower element)
+ (setq node (avl-tree--node-right node)))
+ ((and (memq (org-element-type element) '(item table-row))
+ (let ((parent (org-element-property :parent element)))
+ (and (= (org-element-property :begin element)
+ (org-element-property :contents-begin parent))
+ (setq node nil
+ lower parent
+ upper parent)))))
+ (t
+ (setq node nil
+ lower element
+ upper element)))))
+ (pcase side
+ (`both (cons lower upper))
+ (`nil lower)
+ (_ upper))))
+
+(defun org-element--cache-put (element &optional data)
+ "Store ELEMENT in current buffer's cache, if allowed.
+When optional argument DATA is non-nil, assume is it object data
+relative to ELEMENT and store it in the objects cache."
+ (cond ((not (org-element--cache-active-p)) nil)
+ ((not data)
+ (when org-element--cache-sync-requests
+ ;; During synchronization, first build an appropriate key
+ ;; for the new element so `avl-tree-enter' can insert it at
+ ;; the right spot in the cache.
+ (let ((keys (org-element--cache-find
+ (org-element-property :begin element) 'both)))
+ (puthash element
+ (org-element--cache-generate-key
+ (and (car keys) (org-element--cache-key (car keys)))
+ (cond ((cdr keys) (org-element--cache-key (cdr keys)))
+ (org-element--cache-sync-requests
+ (aref (car org-element--cache-sync-requests) 0))))
+ org-element--cache-sync-keys)))
+ (avl-tree-enter org-element--cache element))
+ ;; Headlines are not stored in cache, so objects in titles are
+ ;; not stored either.
+ ((eq (org-element-type element) 'headline) nil)
+ (t (puthash element data org-element--cache-objects))))
+
+(defsubst org-element--cache-remove (element)
+ "Remove ELEMENT from cache.
+Assume ELEMENT belongs to cache and that a cache is active."
+ (avl-tree-delete org-element--cache element)
+ (remhash element org-element--cache-objects))
+
+
+;;;; Synchronization
+
+(defsubst org-element--cache-set-timer (buffer)
+ "Set idle timer for cache synchronization in BUFFER."
+ (when org-element--cache-sync-timer
+ (cancel-timer org-element--cache-sync-timer))
+ (setq org-element--cache-sync-timer
+ (run-with-idle-timer
+ (let ((idle (current-idle-time)))
+ (if idle (time-add idle org-element-cache-sync-break)
+ org-element-cache-sync-idle-time))
+ nil
+ #'org-element--cache-sync
+ buffer)))
+
+(defsubst org-element--cache-interrupt-p (time-limit)
+ "Non-nil when synchronization process should be interrupted.
+TIME-LIMIT is a time value or nil."
+ (and time-limit
+ (or (input-pending-p)
+ (time-less-p time-limit (current-time)))))
+
+(defsubst org-element--cache-shift-positions (element offset &optional props)
+ "Shift ELEMENT properties relative to buffer positions by OFFSET.
+
+Properties containing buffer positions are `:begin', `:end',
+`:contents-begin', `:contents-end' and `:structure'. When
+optional argument PROPS is a list of keywords, only shift
+properties provided in that list.
+
+Properties are modified by side-effect."
+ (let ((properties (nth 1 element)))
+ ;; Shift `:structure' property for the first plain list only: it
+ ;; is the only one that really matters and it prevents from
+ ;; shifting it more than once.
+ (when (and (or (not props) (memq :structure props))
+ (eq (org-element-type element) 'plain-list)
+ (not (eq (org-element-type (plist-get properties :parent))
+ 'item)))
+ (dolist (item (plist-get properties :structure))
+ (cl-incf (car item) offset)
+ (cl-incf (nth 6 item) offset)))
+ (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
+ (let ((value (and (or (not props) (memq key props))
+ (plist-get properties key))))
+ (and value (plist-put properties key (+ offset value)))))))
+
+(defun org-element--cache-sync (buffer &optional threshold future-change)
+ "Synchronize cache with recent modification in BUFFER.
+
+When optional argument THRESHOLD is non-nil, do the
+synchronization for all elements starting before or at threshold,
+then exit. Otherwise, synchronize cache for as long as
+`org-element-cache-sync-duration' or until Emacs leaves idle
+state.
+
+FUTURE-CHANGE, when non-nil, is a buffer position where changes
+not registered yet in the cache are going to happen. It is used
+in `org-element--cache-submit-request', where cache is partially
+updated before current modification are actually submitted."
+ (when (buffer-live-p buffer)
+ (with-current-buffer buffer
+ (let ((inhibit-quit t) request next)
+ (when org-element--cache-sync-timer
+ (cancel-timer org-element--cache-sync-timer))
+ (catch 'interrupt
+ (while org-element--cache-sync-requests
+ (setq request (car org-element--cache-sync-requests)
+ next (nth 1 org-element--cache-sync-requests))
+ (org-element--cache-process-request
+ request
+ (and next (aref next 0))
+ threshold
+ (and (not threshold)
+ (time-add (current-time)
+ org-element-cache-sync-duration))
+ future-change)
+ ;; Request processed. Merge current and next offsets and
+ ;; transfer ending position.
+ (when next
+ (cl-incf (aref next 3) (aref request 3))
+ (aset next 2 (aref request 2)))
+ (setq org-element--cache-sync-requests
+ (cdr org-element--cache-sync-requests))))
+ ;; If more requests are awaiting, set idle timer accordingly.
+ ;; Otherwise, reset keys.
+ (if org-element--cache-sync-requests
+ (org-element--cache-set-timer buffer)
+ (clrhash org-element--cache-sync-keys))))))
+
+(defun org-element--cache-process-request
+ (request next threshold time-limit future-change)
+ "Process synchronization REQUEST for all entries before NEXT.
+
+REQUEST is a vector, built by `org-element--cache-submit-request'.
+
+NEXT is a cache key, as returned by `org-element--cache-key'.
+
+When non-nil, THRESHOLD is a buffer position. Synchronization
+stops as soon as a shifted element begins after it.
+
+When non-nil, TIME-LIMIT is a time value. Synchronization stops
+after this time or when Emacs exits idle state.
+
+When non-nil, FUTURE-CHANGE is a buffer position where changes
+not registered yet in the cache are going to happen. See
+`org-element--cache-submit-request' for more information.
+
+Throw `interrupt' if the process stops before completing the
+request."
+ (catch 'quit
+ (when (= (aref request 5) 0)
+ ;; Phase 0.
+ ;;
+ ;; Delete all elements starting after BEG, but not after buffer
+ ;; position END or past element with key NEXT. Also delete
+ ;; elements contained within a previously removed element
+ ;; (stored in `last-container').
+ ;;
+ ;; At each iteration, we start again at tree root since
+ ;; a deletion modifies structure of the balanced tree.
+ (catch 'end-phase
+ (while t
+ (when (org-element--cache-interrupt-p time-limit)
+ (throw 'interrupt nil))
+ ;; Find first element in cache with key BEG or after it.
+ (let ((beg (aref request 0))
+ (end (aref request 2))
+ (node (org-element--cache-root))
+ data data-key last-container)
+ (while node
+ (let* ((element (avl-tree--node-data node))
+ (key (org-element--cache-key element)))
+ (cond
+ ((org-element--cache-key-less-p key beg)
+ (setq node (avl-tree--node-right node)))
+ ((org-element--cache-key-less-p beg key)
+ (setq data element
+ data-key key
+ node (avl-tree--node-left node)))
+ (t (setq data element
+ data-key key
+ node nil)))))
+ (if data
+ (let ((pos (org-element-property :begin data)))
+ (if (if (or (not next)
+ (org-element--cache-key-less-p data-key next))
+ (<= pos end)
+ (and last-container
+ (let ((up data))
+ (while (and up (not (eq up last-container)))
+ (setq up (org-element-property :parent up)))
+ up)))
+ (progn (when (and (not last-container)
+ (> (org-element-property :end data)
+ end))
+ (setq last-container data))
+ (org-element--cache-remove data))
+ (aset request 0 data-key)
+ (aset request 1 pos)
+ (aset request 5 1)
+ (throw 'end-phase nil)))
+ ;; No element starting after modifications left in
+ ;; cache: further processing is futile.
+ (throw 'quit t))))))
+ (when (= (aref request 5) 1)
+ ;; Phase 1.
+ ;;
+ ;; Phase 0 left a hole in the cache. Some elements after it
+ ;; could have parents within. For example, in the following
+ ;; buffer:
+ ;;
+ ;; - item
+ ;;
+ ;;
+ ;; Paragraph1
+ ;;
+ ;; Paragraph2
+ ;;
+ ;; if we remove a blank line between "item" and "Paragraph1",
+ ;; everything down to "Paragraph2" is removed from cache. But
+ ;; the paragraph now belongs to the list, and its `:parent'
+ ;; property no longer is accurate.
+ ;;
+ ;; Therefore we need to parse again elements in the hole, or at
+ ;; least in its last section, so that we can re-parent
+ ;; subsequent elements, during phase 2.
+ ;;
+ ;; Note that we only need to get the parent from the first
+ ;; element in cache after the hole.
+ ;;
+ ;; When next key is lesser or equal to the current one, delegate
+ ;; phase 1 processing to next request in order to preserve key
+ ;; order among requests.
+ (let ((key (aref request 0)))
+ (when (and next (not (org-element--cache-key-less-p key next)))
+ (let ((next-request (nth 1 org-element--cache-sync-requests)))
+ (aset next-request 0 key)
+ (aset next-request 1 (aref request 1))
+ (aset next-request 5 1))
+ (throw 'quit t)))
+ ;; Next element will start at its beginning position plus
+ ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
+ ;; contains the real beginning position of the first element to
+ ;; shift and re-parent.
+ (let ((limit (+ (aref request 1) (aref request 3))))
+ (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
+ ((and future-change (>= limit future-change))
+ ;; Changes are going to happen around this element and
+ ;; they will trigger another phase 1 request. Skip the
+ ;; current one.
+ (aset request 5 2))
+ (t
+ (let ((parent (org-element--parse-to limit t time-limit)))
+ (aset request 4 parent)
+ (aset request 5 2))))))
+ ;; Phase 2.
+ ;;
+ ;; Shift all elements starting from key START, but before NEXT, by
+ ;; OFFSET, and re-parent them when appropriate.
+ ;;
+ ;; Elements are modified by side-effect so the tree structure
+ ;; remains intact.
+ ;;
+ ;; Once THRESHOLD, if any, is reached, or once there is an input
+ ;; pending, exit. Before leaving, the current synchronization
+ ;; request is updated.
+ (let ((start (aref request 0))
+ (offset (aref request 3))
+ (parent (aref request 4))
+ (node (org-element--cache-root))
+ (stack (list nil))
+ (leftp t)
+ exit-flag)
+ ;; No re-parenting nor shifting planned: request is over.
+ (when (and (not parent) (zerop offset)) (throw 'quit t))
+ (while node
+ (let* ((data (avl-tree--node-data node))
+ (key (org-element--cache-key data)))
+ (if (and leftp (avl-tree--node-left node)
+ (not (org-element--cache-key-less-p key start)))
+ (progn (push node stack)
+ (setq node (avl-tree--node-left node)))
+ (unless (org-element--cache-key-less-p key start)
+ ;; We reached NEXT. Request is complete.
+ (when (equal key next) (throw 'quit t))
+ ;; Handle interruption request. Update current request.
+ (when (or exit-flag (org-element--cache-interrupt-p time-limit))
+ (aset request 0 key)
+ (aset request 4 parent)
+ (throw 'interrupt nil))
+ ;; Shift element.
+ (unless (zerop offset)
+ (org-element--cache-shift-positions data offset)
+ ;; Shift associated objects data, if any.
+ (dolist (object-data (gethash data org-element--cache-objects))
+ (dolist (object (cddr object-data))
+ (org-element--cache-shift-positions object offset))))
+ (let ((begin (org-element-property :begin data)))
+ ;; Update PARENT and re-parent DATA, only when
+ ;; necessary. Propagate new structures for lists.
+ (while (and parent
+ (<= (org-element-property :end parent) begin))
+ (setq parent (org-element-property :parent parent)))
+ (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
+ ((and parent
+ (let ((p (org-element-property :parent data)))
+ (or (not p)
+ (< (org-element-property :begin p)
+ (org-element-property :begin parent)))))
+ (org-element-put-property data :parent parent)
+ (let ((s (org-element-property :structure parent)))
+ (when (and s (org-element-property :structure data))
+ (org-element-put-property data :structure s)))))
+ ;; Cache is up-to-date past THRESHOLD. Request
+ ;; interruption.
+ (when (and threshold (> begin threshold)) (setq exit-flag t))))
+ (setq node (if (setq leftp (avl-tree--node-right node))
+ (avl-tree--node-right node)
+ (pop stack))))))
+ ;; We reached end of tree: synchronization complete.
+ t)))
+
+(defun org-element--parse-to (pos &optional syncp time-limit)
+ "Parse elements in current section, down to POS.
+
+Start parsing from the closest between the last known element in
+cache or headline above. Return the smallest element containing
+POS.
+
+When optional argument SYNCP is non-nil, return the parent of the
+element containing POS instead. In that case, it is also
+possible to provide TIME-LIMIT, which is a time value specifying
+when the parsing should stop. The function throws `interrupt' if
+the process stopped before finding the expected result."
+ (catch 'exit
+ (org-with-wide-buffer
+ (goto-char pos)
+ (let* ((cached (and (org-element--cache-active-p)
+ (org-element--cache-find pos nil)))
+ (begin (org-element-property :begin cached))
+ element next mode)
+ (cond
+ ;; Nothing in cache before point: start parsing from first
+ ;; element following headline above, or first element in
+ ;; buffer.
+ ((not cached)
+ (when (org-with-limited-levels (outline-previous-heading))
+ (setq mode 'planning)
+ (forward-line))
+ (skip-chars-forward " \r\t\n")
+ (beginning-of-line))
+ ;; Cache returned exact match: return it.
+ ((= pos begin)
+ (throw 'exit (if syncp (org-element-property :parent cached) cached)))
+ ;; There's a headline between cached value and POS: cached
+ ;; value is invalid. Start parsing from first element
+ ;; following the headline.
+ ((re-search-backward
+ (org-with-limited-levels org-outline-regexp-bol) begin t)
+ (forward-line)
+ (skip-chars-forward " \r\t\n")
+ (beginning-of-line)
+ (setq mode 'planning))
+ ;; Check if CACHED or any of its ancestors contain point.
+ ;;
+ ;; If there is such an element, we inspect it in order to know
+ ;; if we return it or if we need to parse its contents.
+ ;; Otherwise, we just start parsing from current location,
+ ;; which is right after the top-most element containing
+ ;; CACHED.
+ ;;
+ ;; As a special case, if POS is at the end of the buffer, we
+ ;; want to return the innermost element ending there.
+ ;;
+ ;; Also, if we find an ancestor and discover that we need to
+ ;; parse its contents, make sure we don't start from
+ ;; `:contents-begin', as we would otherwise go past CACHED
+ ;; again. Instead, in that situation, we will resume parsing
+ ;; from NEXT, which is located after CACHED or its higher
+ ;; ancestor not containing point.
+ (t
+ (let ((up cached)
+ (pos (if (= (point-max) pos) (1- pos) pos)))
+ (goto-char (or (org-element-property :contents-begin cached) begin))
+ (while (let ((end (org-element-property :end up)))
+ (and (<= end pos)
+ (goto-char end)
+ (setq up (org-element-property :parent up)))))
+ (cond ((not up))
+ ((eobp) (setq element up))
+ (t (setq element up next (point)))))))
+ ;; Parse successively each element until we reach POS.
+ (let ((end (or (org-element-property :end element)
+ (save-excursion
+ (org-with-limited-levels (outline-next-heading))
+ (point))))
+ (parent element))
+ (while t
+ (when syncp
+ (cond ((= (point) pos) (throw 'exit parent))
+ ((org-element--cache-interrupt-p time-limit)
+ (throw 'interrupt nil))))
+ (unless element
+ (setq element (org-element--current-element
+ end 'element mode
+ (org-element-property :structure parent)))
+ (org-element-put-property element :parent parent)
+ (org-element--cache-put element))
+ (let ((elem-end (org-element-property :end element))
+ (type (org-element-type element)))
+ (cond
+ ;; Skip any element ending before point. Also skip
+ ;; element ending at point (unless it is also the end of
+ ;; buffer) since we're sure that another element begins
+ ;; after it.
+ ((and (<= elem-end pos) (/= (point-max) elem-end))
+ (goto-char elem-end)
+ (setq mode (org-element--next-mode type nil)))
+ ;; A non-greater element contains point: return it.
+ ((not (memq type org-element-greater-elements))
+ (throw 'exit element))
+ ;; Otherwise, we have to decide if ELEMENT really
+ ;; contains POS. In that case we start parsing from
+ ;; contents' beginning.
+ ;;
+ ;; If POS is at contents' beginning but it is also at
+ ;; the beginning of the first item in a list or a table.
+ ;; In that case, we need to create an anchor for that
+ ;; list or table, so return it.
+ ;;
+ ;; Also, if POS is at the end of the buffer, no element
+ ;; can start after it, but more than one may end there.
+ ;; Arbitrarily, we choose to return the innermost of
+ ;; such elements.
+ ((let ((cbeg (org-element-property :contents-begin element))
+ (cend (org-element-property :contents-end element)))
+ (when (or syncp
+ (and cbeg cend
+ (or (< cbeg pos)
+ (and (= cbeg pos)
+ (not (memq type '(plain-list table)))))
+ (or (> cend pos)
+ (and (= cend pos) (= (point-max) pos)))))
+ (goto-char (or next cbeg))
+ (setq next nil
+ mode (org-element--next-mode type t)
+ parent element
+ end cend))))
+ ;; Otherwise, return ELEMENT as it is the smallest
+ ;; element containing POS.
+ (t (throw 'exit element))))
+ (setq element nil)))))))
+
+
+;;;; Staging Buffer Changes
+
+(defconst org-element--cache-sensitive-re
+ (concat
+ org-outline-regexp-bol "\\|"
+ "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
+ "^[ \t]*\\(?:"
+ "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
+ "\\\\begin{[A-Za-z0-9*]+}" "\\|"
+ ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
+ "\\)")
+ "Regexp matching a sensitive line, structure wise.
+A sensitive line is a headline, inlinetask, block, drawer, or
+latex-environment boundary. When such a line is modified,
+structure changes in the document may propagate in the whole
+section, possibly making cache invalid.")
+
+(defvar org-element--cache-change-warning nil
+ "Non-nil when a sensitive line is about to be changed.
+It is a symbol among nil, t and `headline'.")
+
+(defun org-element--cache-before-change (beg end)
+ "Request extension of area going to be modified if needed.
+BEG and END are the beginning and end of the range of changed
+text. See `before-change-functions' for more information."
+ (when (org-element--cache-active-p)
+ (org-with-wide-buffer
+ (goto-char beg)
+ (beginning-of-line)
+ (let ((bottom (save-excursion (goto-char end) (line-end-position))))
+ (setq org-element--cache-change-warning
+ (save-match-data
+ (if (and (org-with-limited-levels (org-at-heading-p))
+ (= (line-end-position) bottom))
+ 'headline
+ (let ((case-fold-search t))
+ (re-search-forward
+ org-element--cache-sensitive-re bottom t)))))))))
+
+(defun org-element--cache-after-change (beg end pre)
+ "Update buffer modifications for current buffer.
+BEG and END are the beginning and end of the range of changed
+text, and the length in bytes of the pre-change text replaced by
+that range. See `after-change-functions' for more information."
+ (when (org-element--cache-active-p)
+ (org-with-wide-buffer
+ (goto-char beg)
+ (beginning-of-line)
+ (save-match-data
+ (let ((top (point))
+ (bottom (save-excursion (goto-char end) (line-end-position))))
+ ;; Determine if modified area needs to be extended, according
+ ;; to both previous and current state. We make a special
+ ;; case for headline editing: if a headline is modified but
+ ;; not removed, do not extend.
+ (when (pcase org-element--cache-change-warning
+ (`t t)
+ (`headline
+ (not (and (org-with-limited-levels (org-at-heading-p))
+ (= (line-end-position) bottom))))
+ (_
+ (let ((case-fold-search t))
+ (re-search-forward
+ org-element--cache-sensitive-re bottom t))))
+ ;; Effectively extend modified area.
+ (org-with-limited-levels
+ (setq top (progn (goto-char top)
+ (when (outline-previous-heading) (forward-line))
+ (point)))
+ (setq bottom (progn (goto-char bottom)
+ (if (outline-next-heading) (1- (point))
+ (point))))))
+ ;; Store synchronization request.
+ (let ((offset (- end beg pre)))
+ (org-element--cache-submit-request top (- bottom offset) offset)))))
+ ;; Activate a timer to process the request during idle time.
+ (org-element--cache-set-timer (current-buffer))))
+
+(defun org-element--cache-for-removal (beg end offset)
+ "Return first element to remove from cache.
+
+BEG and END are buffer positions delimiting buffer modifications.
+OFFSET is the size of the changes.
+
+Returned element is usually the first element in cache containing
+any position between BEG and END. As an exception, greater
+elements around the changes that are robust to contents
+modifications are preserved and updated according to the
+changes."
+ (let* ((elements (org-element--cache-find (1- beg) 'both))
+ (before (car elements))
+ (after (cdr elements)))
+ (if (not before) after
+ (let ((up before)
+ (robust-flag t))
+ (while up
+ (if (let ((type (org-element-type up)))
+ (and (or (memq type '(center-block dynamic-block quote-block
+ special-block))
+ ;; Drawers named "PROPERTIES" are probably
+ ;; a properties drawer being edited. Force
+ ;; parsing to check if editing is over.
+ (and (eq type 'drawer)
+ (not (string=
+ (org-element-property :drawer-name up)
+ "PROPERTIES"))))
+ (let ((cbeg (org-element-property :contents-begin up)))
+ (and cbeg
+ (<= cbeg beg)
+ (> (org-element-property :contents-end up) end)))))
+ ;; UP is a robust greater element containing changes.
+ ;; We only need to extend its ending boundaries.
+ (org-element--cache-shift-positions
+ up offset '(:contents-end :end))
+ (setq before up)
+ (when robust-flag (setq robust-flag nil)))
+ (setq up (org-element-property :parent up)))
+ ;; We're at top level element containing ELEMENT: if it's
+ ;; altered by buffer modifications, it is first element in
+ ;; cache to be removed. Otherwise, that first element is the
+ ;; following one.
+ ;;
+ ;; As a special case, do not remove BEFORE if it is a robust
+ ;; container for current changes.
+ (if (or (< (org-element-property :end before) beg) robust-flag) after
+ before)))))
+
+(defun org-element--cache-submit-request (beg end offset)
+ "Submit a new cache synchronization request for current buffer.
+BEG and END are buffer positions delimiting the minimal area
+where cache data should be removed. OFFSET is the size of the
+change, as an integer."
+ (let ((next (car org-element--cache-sync-requests))
+ delete-to delete-from)
+ (if (and next
+ (zerop (aref next 5))
+ (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
+ (<= (setq delete-from (aref next 1)) end))
+ ;; Current changes can be merged with first sync request: we
+ ;; can save a partial cache synchronization.
+ (progn
+ (cl-incf (aref next 3) offset)
+ ;; If last change happened within area to be removed, extend
+ ;; boundaries of robust parents, if any. Otherwise, find
+ ;; first element to remove and update request accordingly.
+ (if (> beg delete-from)
+ (let ((up (aref next 4)))
+ (while up
+ (org-element--cache-shift-positions
+ up offset '(:contents-end :end))
+ (setq up (org-element-property :parent up))))
+ (let ((first (org-element--cache-for-removal beg delete-to offset)))
+ (when first
+ (aset next 0 (org-element--cache-key first))
+ (aset next 1 (org-element-property :begin first))
+ (aset next 4 (org-element-property :parent first))))))
+ ;; Ensure cache is correct up to END. Also make sure that NEXT,
+ ;; if any, is no longer a 0-phase request, thus ensuring that
+ ;; phases are properly ordered. We need to provide OFFSET as
+ ;; optional parameter since current modifications are not known
+ ;; yet to the otherwise correct part of the cache (i.e, before
+ ;; the first request).
+ (when next (org-element--cache-sync (current-buffer) end beg))
+ (let ((first (org-element--cache-for-removal beg end offset)))
+ (if first
+ (push (let ((beg (org-element-property :begin first))
+ (key (org-element--cache-key first)))
+ (cond
+ ;; When changes happen before the first known
+ ;; element, re-parent and shift the rest of the
+ ;; cache.
+ ((> beg end) (vector key beg nil offset nil 1))
+ ;; Otherwise, we find the first non robust
+ ;; element containing END. All elements between
+ ;; FIRST and this one are to be removed.
+ ((let ((first-end (org-element-property :end first)))
+ (and (> first-end end)
+ (vector key beg first-end offset first 0))))
+ (t
+ (let* ((element (org-element--cache-find end))
+ (end (org-element-property :end element))
+ (up element))
+ (while (and (setq up (org-element-property :parent up))
+ (>= (org-element-property :begin up) beg))
+ (setq end (org-element-property :end up)
+ element up))
+ (vector key beg end offset element 0)))))
+ org-element--cache-sync-requests)
+ ;; No element to remove. No need to re-parent either.
+ ;; Simply shift additional elements, if any, by OFFSET.
+ (when org-element--cache-sync-requests
+ (cl-incf (aref (car org-element--cache-sync-requests) 3)
+ offset)))))))
+
+
+;;;; Public Functions
+
+;;;###autoload
+(defun org-element-cache-reset (&optional all)
+ "Reset cache in current buffer.
+When optional argument ALL is non-nil, reset cache in all Org
+buffers."
+ (interactive "P")
+ (dolist (buffer (if all (buffer-list) (list (current-buffer))))
+ (with-current-buffer buffer
+ (when (and org-element-use-cache (derived-mode-p 'org-mode))
+ (setq-local org-element--cache
+ (avl-tree-create #'org-element--cache-compare))
+ (setq-local org-element--cache-objects (make-hash-table :test #'eq))
+ (setq-local org-element--cache-sync-keys
+ (make-hash-table :weakness 'key :test #'eq))
+ (setq-local org-element--cache-change-warning nil)
+ (setq-local org-element--cache-sync-requests nil)
+ (setq-local org-element--cache-sync-timer nil)
+ (add-hook 'before-change-functions
+ #'org-element--cache-before-change nil t)
+ (add-hook 'after-change-functions
+ #'org-element--cache-after-change nil t)))))
+
+;;;###autoload
+(defun org-element-cache-refresh (pos)
+ "Refresh cache at position POS."
+ (when (org-element--cache-active-p)
+ (org-element--cache-sync (current-buffer) pos)
+ (org-element--cache-submit-request pos pos 0)
+ (org-element--cache-set-timer (current-buffer))))
+
+
+
+;;; The Toolbox
+;;
+;; The first move is to implement a way to obtain the smallest element
+;; containing point. This is the job of `org-element-at-point'. It
+;; basically jumps back to the beginning of section containing point
+;; and proceed, one element after the other, with
+;; `org-element--current-element' until the container is found. Note:
+;; When using `org-element-at-point', secondary values are never
+;; parsed since the function focuses on elements, not on objects.
+;;
+;; At a deeper level, `org-element-context' lists all elements and
+;; objects containing point.
+;;
+;; `org-element-nested-p' and `org-element-swap-A-B' may be used
+;; internally by navigation and manipulation tools.
+
+
+;;;###autoload
+(defun org-element-at-point ()
+ "Determine closest element around point.
+
+Return value is a list like (TYPE PROPS) where TYPE is the type
+of the element and PROPS a plist of properties associated to the
+element.
+
+Possible types are defined in `org-element-all-elements'.
+Properties depend on element or object type, but always include
+`:begin', `:end', `:parent' and `:post-blank' properties.
+
+As a special case, if point is at the very beginning of the first
+item in a list or sub-list, returned element will be that list
+instead of the item. Likewise, if point is at the beginning of
+the first row of a table, returned element will be the table
+instead of the first row.
+
+When point is at the end of the buffer, return the innermost
+element ending there."
+ (org-with-wide-buffer
+ (let ((origin (point)))
+ (end-of-line)
+ (skip-chars-backward " \r\t\n")
+ (cond
+ ;; Within blank lines at the beginning of buffer, return nil.
+ ((bobp) nil)
+ ;; Within blank lines right after a headline, return that
+ ;; headline.
+ ((org-with-limited-levels (org-at-heading-p))
+ (beginning-of-line)
+ (org-element-headline-parser (point-max) t))
+ ;; Otherwise parse until we find element containing ORIGIN.
+ (t
+ (when (org-element--cache-active-p)
+ (if (not org-element--cache) (org-element-cache-reset)
+ (org-element--cache-sync (current-buffer) origin)))
+ (org-element--parse-to origin))))))
+
+;;;###autoload
+(defun org-element-context (&optional element)
+ "Return smallest element or object around point.
+
+Return value is a list like (TYPE PROPS) where TYPE is the type
+of the element or object and PROPS a plist of properties
+associated to it.
+
+Possible types are defined in `org-element-all-elements' and
+`org-element-all-objects'. Properties depend on element or
+object type, but always include `:begin', `:end', `:parent' and
+`:post-blank'.
+
+As a special case, if point is right after an object and not at
+the beginning of any other object, return that object.
+
+Optional argument ELEMENT, when non-nil, is the closest element
+containing point, as returned by `org-element-at-point'.
+Providing it allows for quicker computation."
+ (catch 'objects-forbidden
+ (org-with-wide-buffer
+ (let* ((pos (point))
+ (element (or element (org-element-at-point)))
+ (type (org-element-type element))
+ (post (org-element-property :post-affiliated element)))
+ ;; If point is inside an element containing objects or
+ ;; a secondary string, narrow buffer to the container and
+ ;; proceed with parsing. Otherwise, return ELEMENT.
+ (cond
+ ;; At a parsed affiliated keyword, check if we're inside main
+ ;; or dual value.
+ ((and post (< pos post))
+ (beginning-of-line)
+ (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
+ (cond
+ ((not (member-ignore-case (match-string 1)
+ org-element-parsed-keywords))
+ (throw 'objects-forbidden element))
+ ((< (match-end 0) pos)
+ (narrow-to-region (match-end 0) (line-end-position)))
+ ((and (match-beginning 2)
+ (>= pos (match-beginning 2))
+ (< pos (match-end 2)))
+ (narrow-to-region (match-beginning 2) (match-end 2)))
+ (t (throw 'objects-forbidden element)))
+ ;; Also change type to retrieve correct restrictions.
+ (setq type 'keyword))
+ ;; At an item, objects can only be located within tag, if any.
+ ((eq type 'item)
+ (let ((tag (org-element-property :tag element)))
+ (if (or (not tag) (/= (line-beginning-position) post))
+ (throw 'objects-forbidden element)
+ (beginning-of-line)
+ (search-forward tag (line-end-position))
+ (goto-char (match-beginning 0))
+ (if (and (>= pos (point)) (< pos (match-end 0)))
+ (narrow-to-region (point) (match-end 0))
+ (throw 'objects-forbidden element)))))
+ ;; At an headline or inlinetask, objects are in title.
+ ((memq type '(headline inlinetask))
+ (let ((case-fold-search nil))
+ (goto-char (org-element-property :begin element))
+ (looking-at org-complex-heading-regexp)
+ (let ((end (match-end 4)))
+ (if (not end) (throw 'objects-forbidden element)
+ (goto-char (match-beginning 4))
+ (when (looking-at org-comment-string)
+ (goto-char (match-end 0)))
+ (if (>= (point) end) (throw 'objects-forbidden element)
+ (narrow-to-region (point) end))))))
+ ;; At a paragraph, a table-row or a verse block, objects are
+ ;; located within their contents.
+ ((memq type '(paragraph table-row verse-block))
+ (let ((cbeg (org-element-property :contents-begin element))
+ (cend (org-element-property :contents-end element)))
+ ;; CBEG is nil for table rules.
+ (if (and cbeg cend (>= pos cbeg)
+ (or (< pos cend) (and (= pos cend) (eobp))))
+ (narrow-to-region cbeg cend)
+ (throw 'objects-forbidden element))))
+ ;; At a planning line, if point is at a timestamp, return it,
+ ;; otherwise, return element.
+ ((eq type 'planning)
+ (dolist (p '(:closed :deadline :scheduled))
+ (let ((timestamp (org-element-property p element)))
+ (when (and timestamp
+ (<= (org-element-property :begin timestamp) pos)
+ (> (org-element-property :end timestamp) pos))
+ (throw 'objects-forbidden timestamp))))
+ ;; All other locations cannot contain objects: bail out.
+ (throw 'objects-forbidden element))
+ (t (throw 'objects-forbidden element)))
+ (goto-char (point-min))
+ (let ((restriction (org-element-restriction type))
+ (parent element)
+ (cache (cond ((not (org-element--cache-active-p)) nil)
+ (org-element--cache-objects
+ (gethash element org-element--cache-objects))
+ (t (org-element-cache-reset) nil)))
+ next object-data last)
+ (prog1
+ (catch 'exit
+ (while t
+ ;; When entering PARENT for the first time, get list
+ ;; of objects within known so far. Store it in
+ ;; OBJECT-DATA.
+ (unless next
+ (let ((data (assq parent cache)))
+ (if data (setq object-data data)
+ (push (setq object-data (list parent nil)) cache))))
+ ;; Find NEXT object for analysis.
+ (catch 'found
+ ;; If NEXT is non-nil, we already exhausted the
+ ;; cache so we can parse buffer to find the object
+ ;; after it.
+ (if next (setq next (org-element--object-lex restriction))
+ ;; Otherwise, check if cache can help us.
+ (let ((objects (cddr object-data))
+ (completep (nth 1 object-data)))
+ (cond
+ ((and (not objects) completep) (throw 'exit parent))
+ ((not objects)
+ (setq next (org-element--object-lex restriction)))
+ (t
+ (let ((cache-limit
+ (org-element-property :end (car objects))))
+ (if (>= cache-limit pos)
+ ;; Cache contains the information needed.
+ (dolist (object objects (throw 'exit parent))
+ (when (<= (org-element-property :begin object)
+ pos)
+ (if (>= (org-element-property :end object)
+ pos)
+ (throw 'found (setq next object))
+ (throw 'exit parent))))
+ (goto-char cache-limit)
+ (setq next
+ (org-element--object-lex restriction))))))))
+ ;; If we have a new object to analyze, store it in
+ ;; cache. Otherwise record that there is nothing
+ ;; more to parse in this element at this depth.
+ (if next
+ (progn (org-element-put-property next :parent parent)
+ (push next (cddr object-data)))
+ (setcar (cdr object-data) t)))
+ ;; Process NEXT, if any, in order to know if we need
+ ;; to skip it, return it or move into it.
+ (if (or (not next) (> (org-element-property :begin next) pos))
+ (throw 'exit (or last parent))
+ (let ((end (org-element-property :end next))
+ (cbeg (org-element-property :contents-begin next))
+ (cend (org-element-property :contents-end next)))
+ (cond
+ ;; Skip objects ending before point. Also skip
+ ;; objects ending at point unless it is also the
+ ;; end of buffer, since we want to return the
+ ;; innermost object.
+ ((and (<= end pos) (/= (point-max) end))
+ (goto-char end)
+ ;; For convenience, when object ends at POS,
+ ;; without any space, store it in LAST, as we
+ ;; will return it if no object starts here.
+ (when (and (= end pos)
+ (not (memq (char-before) '(?\s ?\t))))
+ (setq last next)))
+ ;; If POS is within a container object, move
+ ;; into that object.
+ ((and cbeg cend
+ (>= pos cbeg)
+ (or (< pos cend)
+ ;; At contents' end, if there is no
+ ;; space before point, also move into
+ ;; object, for consistency with
+ ;; convenience feature above.
+ (and (= pos cend)
+ (or (= (point-max) pos)
+ (not (memq (char-before pos)
+ '(?\s ?\t)))))))
+ (goto-char cbeg)
+ (narrow-to-region (point) cend)
+ (setq parent next
+ restriction (org-element-restriction next)
+ next nil
+ object-data nil))
+ ;; Otherwise, return NEXT.
+ (t (throw 'exit next)))))))
+ ;; Store results in cache, if applicable.
+ (org-element--cache-put element cache)))))))
+
+(defun org-element-lineage (blob &optional types with-self)
+ "List all ancestors of a given element or object.
+
+BLOB is an object or element.
+
+When optional argument TYPES is a list of symbols, return the
+first element or object in the lineage whose type belongs to that
+list.
+
+When optional argument WITH-SELF is non-nil, lineage includes
+BLOB itself as the first element, and TYPES, if provided, also
+apply to it.
+
+When BLOB is obtained through `org-element-context' or
+`org-element-at-point', only ancestors from its section can be
+found. There is no such limitation when BLOB belongs to a full
+parse tree."
+ (let ((up (if with-self blob (org-element-property :parent blob)))
+ ancestors)
+ (while (and up (not (memq (org-element-type up) types)))
+ (unless types (push up ancestors))
+ (setq up (org-element-property :parent up)))
+ (if types up (nreverse ancestors))))
+
+(defun org-element-nested-p (elem-A elem-B)
+ "Non-nil when elements ELEM-A and ELEM-B are nested."
+ (let ((beg-A (org-element-property :begin elem-A))
+ (beg-B (org-element-property :begin elem-B))
+ (end-A (org-element-property :end elem-A))
+ (end-B (org-element-property :end elem-B)))
+ (or (and (>= beg-A beg-B) (<= end-A end-B))
+ (and (>= beg-B beg-A) (<= end-B end-A)))))
+
+(defun org-element-swap-A-B (elem-A elem-B)
+ "Swap elements ELEM-A and ELEM-B.
+Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
+end of ELEM-A."
+ (goto-char (org-element-property :begin elem-A))
+ ;; There are two special cases when an element doesn't start at bol:
+ ;; the first paragraph in an item or in a footnote definition.
+ (let ((specialp (not (bolp))))
+ ;; Only a paragraph without any affiliated keyword can be moved at
+ ;; ELEM-A position in such a situation. Note that the case of
+ ;; a footnote definition is impossible: it cannot contain two
+ ;; paragraphs in a row because it cannot contain a blank line.
+ (if (and specialp
+ (or (not (eq (org-element-type elem-B) 'paragraph))
+ (/= (org-element-property :begin elem-B)
+ (org-element-property :contents-begin elem-B))))
+ (error "Cannot swap elements"))
+ ;; In a special situation, ELEM-A will have no indentation. We'll
+ ;; give it ELEM-B's (which will in, in turn, have no indentation).
+ (let* ((ind-B (when specialp
+ (goto-char (org-element-property :begin elem-B))
+ (org-get-indentation)))
+ (beg-A (org-element-property :begin elem-A))
+ (end-A (save-excursion
+ (goto-char (org-element-property :end elem-A))
+ (skip-chars-backward " \r\t\n")
+ (point-at-eol)))
+ (beg-B (org-element-property :begin elem-B))
+ (end-B (save-excursion
+ (goto-char (org-element-property :end elem-B))
+ (skip-chars-backward " \r\t\n")
+ (point-at-eol)))
+ ;; Store inner overlays responsible for visibility status.
+ ;; We also need to store their boundaries as they will be
+ ;; removed from buffer.
+ (overlays
+ (cons
+ (delq nil
+ (mapcar (lambda (o)
+ (and (>= (overlay-start o) beg-A)
+ (<= (overlay-end o) end-A)
+ (list o (overlay-start o) (overlay-end o))))
+ (overlays-in beg-A end-A)))
+ (delq nil
+ (mapcar (lambda (o)
+ (and (>= (overlay-start o) beg-B)
+ (<= (overlay-end o) end-B)
+ (list o (overlay-start o) (overlay-end o))))
+ (overlays-in beg-B end-B)))))
+ ;; Get contents.
+ (body-A (buffer-substring beg-A end-A))
+ (body-B (delete-and-extract-region beg-B end-B)))
+ (goto-char beg-B)
+ (when specialp
+ (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
+ (indent-to-column ind-B))
+ (insert body-A)
+ ;; Restore ex ELEM-A overlays.
+ (let ((offset (- beg-B beg-A)))
+ (dolist (o (car overlays))
+ (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
+ (goto-char beg-A)
+ (delete-region beg-A end-A)
+ (insert body-B)
+ ;; Restore ex ELEM-B overlays.
+ (dolist (o (cdr overlays))
+ (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
+ (goto-char (org-element-property :end elem-B)))))
+
+
+(provide 'org-element)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-element.el ends here
diff --git a/lisp/org-entities.el b/lisp/org-entities.el
new file mode 100644
index 0000000..05ccf0c
--- /dev/null
+++ b/lisp/org-entities.el
@@ -0,0 +1,597 @@
+;;; org-entities.el --- Support for Special Entities -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>,
+;; Ulf Stegemann <ulf at zeitform dot de>
+;; Keywords: outlines, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;;; Code:
+
+(declare-function org-toggle-pretty-entities "org" ())
+(declare-function org-table-align "org-table" ())
+
+(defgroup org-entities nil
+ "Options concerning entities in Org mode."
+ :tag "Org Entities"
+ :group 'org)
+
+(defun org-entities--user-safe-p (v)
+ "Non-nil if V is a safe value for `org-entities-user'."
+ (pcase v
+ (`nil t)
+ (`(,(and (pred stringp)
+ (pred (string-match-p "\\`[a-zA-Z][a-zA-Z0-9]*\\'")))
+ ,(pred stringp) ,(pred booleanp) ,(pred stringp)
+ ,(pred stringp) ,(pred stringp) ,(pred stringp))
+ t)
+ (_ nil)))
+
+(defcustom org-entities-user nil
+ "User-defined entities used in Org to produce special characters.
+Each entry in this list is a list of strings. It associates the name
+of the entity that can be inserted into an Org file as \\name with the
+appropriate replacements for the different export backends. The order
+of the fields is the following
+
+name As a string, without the leading backslash.
+LaTeX replacement In ready LaTeX, no further processing will take place.
+LaTeX mathp Either t or nil. When t this entity needs to be in
+ math mode.
+HTML replacement In ready HTML, no further processing will take place.
+ Usually this will be an &...; entity.
+ASCII replacement Plain ASCII, no extensions.
+Latin1 replacement Use the special characters available in latin1.
+utf-8 replacement Use the special characters available in utf-8.
+
+If you define new entities here that require specific LaTeX
+packages to be loaded, add these packages to `org-latex-packages-alist'."
+ :group 'org-entities
+ :version "24.1"
+ :type '(repeat
+ (list
+ (string :tag "name ")
+ (string :tag "LaTeX ")
+ (boolean :tag "Require LaTeX math?")
+ (string :tag "HTML ")
+ (string :tag "ASCII ")
+ (string :tag "Latin1")
+ (string :tag "utf-8 ")))
+ :safe #'org-entities--user-safe-p)
+
+(defconst org-entities
+ (append
+ '("* Letters"
+ "** Latin"
+ ("Agrave" "\\`{A}" nil "&Agrave;" "A" "À" "À")
+ ("agrave" "\\`{a}" nil "&agrave;" "a" "à" "à")
+ ("Aacute" "\\'{A}" nil "&Aacute;" "A" "Á" "Á")
+ ("aacute" "\\'{a}" nil "&aacute;" "a" "á" "á")
+ ("Acirc" "\\^{A}" nil "&Acirc;" "A" "Â" "Â")
+ ("acirc" "\\^{a}" nil "&acirc;" "a" "â" "â")
+ ("Amacr" "\\bar{A}" nil "&Amacr;" "A" "Ã" "Ã")
+ ("amacr" "\\bar{a}" nil "&amacr;" "a" "ã" "ã")
+ ("Atilde" "\\~{A}" nil "&Atilde;" "A" "Ã" "Ã")
+ ("atilde" "\\~{a}" nil "&atilde;" "a" "ã" "ã")
+ ("Auml" "\\\"{A}" nil "&Auml;" "Ae" "Ä" "Ä")
+ ("auml" "\\\"{a}" nil "&auml;" "ae" "ä" "ä")
+ ("Aring" "\\AA{}" nil "&Aring;" "A" "Å" "Å")
+ ("AA" "\\AA{}" nil "&Aring;" "A" "Å" "Å")
+ ("aring" "\\aa{}" nil "&aring;" "a" "å" "å")
+ ("AElig" "\\AE{}" nil "&AElig;" "AE" "Æ" "Æ")
+ ("aelig" "\\ae{}" nil "&aelig;" "ae" "æ" "æ")
+ ("Ccedil" "\\c{C}" nil "&Ccedil;" "C" "Ç" "Ç")
+ ("ccedil" "\\c{c}" nil "&ccedil;" "c" "ç" "ç")
+ ("Egrave" "\\`{E}" nil "&Egrave;" "E" "È" "È")
+ ("egrave" "\\`{e}" nil "&egrave;" "e" "è" "è")
+ ("Eacute" "\\'{E}" nil "&Eacute;" "E" "É" "É")
+ ("eacute" "\\'{e}" nil "&eacute;" "e" "é" "é")
+ ("Ecirc" "\\^{E}" nil "&Ecirc;" "E" "Ê" "Ê")
+ ("ecirc" "\\^{e}" nil "&ecirc;" "e" "ê" "ê")
+ ("Euml" "\\\"{E}" nil "&Euml;" "E" "Ë" "Ë")
+ ("euml" "\\\"{e}" nil "&euml;" "e" "ë" "ë")
+ ("Igrave" "\\`{I}" nil "&Igrave;" "I" "Ì" "Ì")
+ ("igrave" "\\`{i}" nil "&igrave;" "i" "ì" "ì")
+ ("Iacute" "\\'{I}" nil "&Iacute;" "I" "Í" "Í")
+ ("iacute" "\\'{i}" nil "&iacute;" "i" "í" "í")
+ ("Icirc" "\\^{I}" nil "&Icirc;" "I" "Î" "Î")
+ ("icirc" "\\^{i}" nil "&icirc;" "i" "î" "î")
+ ("Iuml" "\\\"{I}" nil "&Iuml;" "I" "Ï" "Ï")
+ ("iuml" "\\\"{i}" nil "&iuml;" "i" "ï" "ï")
+ ("Ntilde" "\\~{N}" nil "&Ntilde;" "N" "Ñ" "Ñ")
+ ("ntilde" "\\~{n}" nil "&ntilde;" "n" "ñ" "ñ")
+ ("Ograve" "\\`{O}" nil "&Ograve;" "O" "Ò" "Ò")
+ ("ograve" "\\`{o}" nil "&ograve;" "o" "ò" "ò")
+ ("Oacute" "\\'{O}" nil "&Oacute;" "O" "Ó" "Ó")
+ ("oacute" "\\'{o}" nil "&oacute;" "o" "ó" "ó")
+ ("Ocirc" "\\^{O}" nil "&Ocirc;" "O" "Ô" "Ô")
+ ("ocirc" "\\^{o}" nil "&ocirc;" "o" "ô" "ô")
+ ("Otilde" "\\~{O}" nil "&Otilde;" "O" "Õ" "Õ")
+ ("otilde" "\\~{o}" nil "&otilde;" "o" "õ" "õ")
+ ("Ouml" "\\\"{O}" nil "&Ouml;" "Oe" "Ö" "Ö")
+ ("ouml" "\\\"{o}" nil "&ouml;" "oe" "ö" "ö")
+ ("Oslash" "\\O" nil "&Oslash;" "O" "Ø" "Ø")
+ ("oslash" "\\o{}" nil "&oslash;" "o" "ø" "ø")
+ ("OElig" "\\OE{}" nil "&OElig;" "OE" "OE" "Œ")
+ ("oelig" "\\oe{}" nil "&oelig;" "oe" "oe" "œ")
+ ("Scaron" "\\v{S}" nil "&Scaron;" "S" "S" "Š")
+ ("scaron" "\\v{s}" nil "&scaron;" "s" "s" "š")
+ ("szlig" "\\ss{}" nil "&szlig;" "ss" "ß" "ß")
+ ("Ugrave" "\\`{U}" nil "&Ugrave;" "U" "Ù" "Ù")
+ ("ugrave" "\\`{u}" nil "&ugrave;" "u" "ù" "ù")
+ ("Uacute" "\\'{U}" nil "&Uacute;" "U" "Ú" "Ú")
+ ("uacute" "\\'{u}" nil "&uacute;" "u" "ú" "ú")
+ ("Ucirc" "\\^{U}" nil "&Ucirc;" "U" "Û" "Û")
+ ("ucirc" "\\^{u}" nil "&ucirc;" "u" "û" "û")
+ ("Uuml" "\\\"{U}" nil "&Uuml;" "Ue" "Ü" "Ü")
+ ("uuml" "\\\"{u}" nil "&uuml;" "ue" "ü" "ü")
+ ("Yacute" "\\'{Y}" nil "&Yacute;" "Y" "Ý" "Ý")
+ ("yacute" "\\'{y}" nil "&yacute;" "y" "ý" "ý")
+ ("Yuml" "\\\"{Y}" nil "&Yuml;" "Y" "Y" "Ÿ")
+ ("yuml" "\\\"{y}" nil "&yuml;" "y" "ÿ" "ÿ")
+
+ "** Latin (special face)"
+ ("fnof" "\\textit{f}" nil "&fnof;" "f" "f" "ƒ")
+ ("real" "\\Re" t "&real;" "R" "R" "ℜ")
+ ("image" "\\Im" t "&image;" "I" "I" "ℑ")
+ ("weierp" "\\wp" t "&weierp;" "P" "P" "℘")
+ ("ell" "\\ell" t "&ell;" "ell" "ell" "ℓ")
+ ("imath" "\\imath" t "&imath;" "[dotless i]" "dotless i" "ı")
+ ("jmath" "\\jmath" t "&jmath;" "[dotless j]" "dotless j" "ȷ")
+
+ "** Greek"
+ ("Alpha" "A" nil "&Alpha;" "Alpha" "Alpha" "Α")
+ ("alpha" "\\alpha" t "&alpha;" "alpha" "alpha" "α")
+ ("Beta" "B" nil "&Beta;" "Beta" "Beta" "Β")
+ ("beta" "\\beta" t "&beta;" "beta" "beta" "β")
+ ("Gamma" "\\Gamma" t "&Gamma;" "Gamma" "Gamma" "Γ")
+ ("gamma" "\\gamma" t "&gamma;" "gamma" "gamma" "γ")
+ ("Delta" "\\Delta" t "&Delta;" "Delta" "Delta" "Δ")
+ ("delta" "\\delta" t "&delta;" "delta" "delta" "δ")
+ ("Epsilon" "E" nil "&Epsilon;" "Epsilon" "Epsilon" "Ε")
+ ("epsilon" "\\epsilon" t "&epsilon;" "epsilon" "epsilon" "ε")
+ ("varepsilon" "\\varepsilon" t "&epsilon;" "varepsilon" "varepsilon" "ε")
+ ("Zeta" "Z" nil "&Zeta;" "Zeta" "Zeta" "Ζ")
+ ("zeta" "\\zeta" t "&zeta;" "zeta" "zeta" "ζ")
+ ("Eta" "H" nil "&Eta;" "Eta" "Eta" "Η")
+ ("eta" "\\eta" t "&eta;" "eta" "eta" "η")
+ ("Theta" "\\Theta" t "&Theta;" "Theta" "Theta" "Θ")
+ ("theta" "\\theta" t "&theta;" "theta" "theta" "θ")
+ ("thetasym" "\\vartheta" t "&thetasym;" "theta" "theta" "ϑ")
+ ("vartheta" "\\vartheta" t "&thetasym;" "theta" "theta" "ϑ")
+ ("Iota" "I" nil "&Iota;" "Iota" "Iota" "Ι")
+ ("iota" "\\iota" t "&iota;" "iota" "iota" "ι")
+ ("Kappa" "K" nil "&Kappa;" "Kappa" "Kappa" "Κ")
+ ("kappa" "\\kappa" t "&kappa;" "kappa" "kappa" "κ")
+ ("Lambda" "\\Lambda" t "&Lambda;" "Lambda" "Lambda" "Λ")
+ ("lambda" "\\lambda" t "&lambda;" "lambda" "lambda" "λ")
+ ("Mu" "M" nil "&Mu;" "Mu" "Mu" "Μ")
+ ("mu" "\\mu" t "&mu;" "mu" "mu" "μ")
+ ("nu" "\\nu" t "&nu;" "nu" "nu" "ν")
+ ("Nu" "N" nil "&Nu;" "Nu" "Nu" "Ν")
+ ("Xi" "\\Xi" t "&Xi;" "Xi" "Xi" "Ξ")
+ ("xi" "\\xi" t "&xi;" "xi" "xi" "ξ")
+ ("Omicron" "O" nil "&Omicron;" "Omicron" "Omicron" "Ο")
+ ("omicron" "\\textit{o}" nil "&omicron;" "omicron" "omicron" "ο")
+ ("Pi" "\\Pi" t "&Pi;" "Pi" "Pi" "Π")
+ ("pi" "\\pi" t "&pi;" "pi" "pi" "π")
+ ("Rho" "P" nil "&Rho;" "Rho" "Rho" "Ρ")
+ ("rho" "\\rho" t "&rho;" "rho" "rho" "ρ")
+ ("Sigma" "\\Sigma" t "&Sigma;" "Sigma" "Sigma" "Σ")
+ ("sigma" "\\sigma" t "&sigma;" "sigma" "sigma" "σ")
+ ("sigmaf" "\\varsigma" t "&sigmaf;" "sigmaf" "sigmaf" "ς")
+ ("varsigma" "\\varsigma" t "&sigmaf;" "varsigma" "varsigma" "ς")
+ ("Tau" "T" nil "&Tau;" "Tau" "Tau" "Τ")
+ ("Upsilon" "\\Upsilon" t "&Upsilon;" "Upsilon" "Upsilon" "Υ")
+ ("upsih" "\\Upsilon" t "&upsih;" "upsilon" "upsilon" "ϒ")
+ ("upsilon" "\\upsilon" t "&upsilon;" "upsilon" "upsilon" "υ")
+ ("Phi" "\\Phi" t "&Phi;" "Phi" "Phi" "Φ")
+ ("phi" "\\phi" t "&phi;" "phi" "phi" "ɸ")
+ ("varphi" "\\varphi" t "&varphi;" "varphi" "varphi" "φ")
+ ("Chi" "X" nil "&Chi;" "Chi" "Chi" "Χ")
+ ("chi" "\\chi" t "&chi;" "chi" "chi" "χ")
+ ("acutex" "\\acute x" t "&acute;x" "'x" "'x" "𝑥́")
+ ("Psi" "\\Psi" t "&Psi;" "Psi" "Psi" "Ψ")
+ ("psi" "\\psi" t "&psi;" "psi" "psi" "ψ")
+ ("tau" "\\tau" t "&tau;" "tau" "tau" "τ")
+ ("Omega" "\\Omega" t "&Omega;" "Omega" "Omega" "Ω")
+ ("omega" "\\omega" t "&omega;" "omega" "omega" "ω")
+ ("piv" "\\varpi" t "&piv;" "omega-pi" "omega-pi" "ϖ")
+ ("varpi" "\\varpi" t "&piv;" "omega-pi" "omega-pi" "ϖ")
+ ("partial" "\\partial" t "&part;" "[partial differential]" "[partial differential]" "∂")
+
+ "** Hebrew"
+ ("alefsym" "\\aleph" t "&alefsym;" "aleph" "aleph" "ℵ")
+ ("aleph" "\\aleph" t "&aleph;" "aleph" "aleph" "ℵ")
+ ("gimel" "\\gimel" t "&gimel;" "gimel" "gimel" "ℷ")
+ ("beth" "\\beth" t "&beth;" "beth" "beth" "ב")
+ ("dalet" "\\daleth" t "&daleth;" "dalet" "dalet" "ד")
+
+ "** Dead languages"
+ ("ETH" "\\DH{}" nil "&ETH;" "D" "Ð" "Ð")
+ ("eth" "\\dh{}" nil "&eth;" "dh" "ð" "ð")
+ ("THORN" "\\TH{}" nil "&THORN;" "TH" "Þ" "Þ")
+ ("thorn" "\\th{}" nil "&thorn;" "th" "þ" "þ")
+
+ "* Punctuation"
+ "** Dots and Marks"
+ ("dots" "\\dots{}" nil "&hellip;" "..." "..." "…")
+ ("cdots" "\\cdots{}" t "&ctdot;" "..." "..." "⋯")
+ ("hellip" "\\dots{}" nil "&hellip;" "..." "..." "…")
+ ("middot" "\\textperiodcentered{}" nil "&middot;" "." "·" "·")
+ ("iexcl" "!`" nil "&iexcl;" "!" "¡" "¡")
+ ("iquest" "?`" nil "&iquest;" "?" "¿" "¿")
+
+ "** Dash-like"
+ ("shy" "\\-" nil "&shy;" "" "" "")
+ ("ndash" "--" nil "&ndash;" "-" "-" "–")
+ ("mdash" "---" nil "&mdash;" "--" "--" "—")
+
+ "** Quotations"
+ ("quot" "\\textquotedbl{}" nil "&quot;" "\"" "\"" "\"")
+ ("acute" "\\textasciiacute{}" nil "&acute;" "'" "´" "´")
+ ("ldquo" "\\textquotedblleft{}" nil "&ldquo;" "\"" "\"" "“")
+ ("rdquo" "\\textquotedblright{}" nil "&rdquo;" "\"" "\"" "”")
+ ("bdquo" "\\quotedblbase{}" nil "&bdquo;" "\"" "\"" "„")
+ ("lsquo" "\\textquoteleft{}" nil "&lsquo;" "`" "`" "‘")
+ ("rsquo" "\\textquoteright{}" nil "&rsquo;" "'" "'" "’")
+ ("sbquo" "\\quotesinglbase{}" nil "&sbquo;" "," "," "‚")
+ ("laquo" "\\guillemotleft{}" nil "&laquo;" "<<" "«" "«")
+ ("raquo" "\\guillemotright{}" nil "&raquo;" ">>" "»" "»")
+ ("lsaquo" "\\guilsinglleft{}" nil "&lsaquo;" "<" "<" "‹")
+ ("rsaquo" "\\guilsinglright{}" nil "&rsaquo;" ">" ">" "›")
+
+ "* Other"
+ "** Misc. (often used)"
+ ("circ" "\\^{}" nil "&circ;" "^" "^" "∘")
+ ("vert" "\\vert{}" t "&vert;" "|" "|" "|")
+ ("vbar" "|" nil "|" "|" "|" "|")
+ ("brvbar" "\\textbrokenbar{}" nil "&brvbar;" "|" "¦" "¦")
+ ("S" "\\S" nil "&sect;" "paragraph" "§" "§")
+ ("sect" "\\S" nil "&sect;" "paragraph" "§" "§")
+ ("amp" "\\&" nil "&amp;" "&" "&" "&")
+ ("lt" "\\textless{}" nil "&lt;" "<" "<" "<")
+ ("gt" "\\textgreater{}" nil "&gt;" ">" ">" ">")
+ ("tilde" "\\textasciitilde{}" nil "~" "~" "~" "~")
+ ("slash" "/" nil "/" "/" "/" "/")
+ ("plus" "+" nil "+" "+" "+" "+")
+ ("under" "\\_" nil "_" "_" "_" "_")
+ ("equal" "=" nil "=" "=" "=" "=")
+ ("asciicirc" "\\textasciicircum{}" nil "^" "^" "^" "^")
+ ("dagger" "\\textdagger{}" nil "&dagger;" "[dagger]" "[dagger]" "†")
+ ("dag" "\\dag{}" nil "&dagger;" "[dagger]" "[dagger]" "†")
+ ("Dagger" "\\textdaggerdbl{}" nil "&Dagger;" "[doubledagger]" "[doubledagger]" "‡")
+ ("ddag" "\\ddag{}" nil "&Dagger;" "[doubledagger]" "[doubledagger]" "‡")
+
+ "** Whitespace"
+ ("nbsp" "~" nil "&nbsp;" " " "\x00A0" "\x00A0")
+ ("ensp" "\\hspace*{.5em}" nil "&ensp;" " " " " " ")
+ ("emsp" "\\hspace*{1em}" nil "&emsp;" " " " " " ")
+ ("thinsp" "\\hspace*{.2em}" nil "&thinsp;" " " " " " ")
+
+ "** Currency"
+ ("curren" "\\textcurrency{}" nil "&curren;" "curr." "¤" "¤")
+ ("cent" "\\textcent{}" nil "&cent;" "cent" "¢" "¢")
+ ("pound" "\\pounds{}" nil "&pound;" "pound" "£" "£")
+ ("yen" "\\textyen{}" nil "&yen;" "yen" "¥" "¥")
+ ("euro" "\\texteuro{}" nil "&euro;" "EUR" "EUR" "€")
+ ("EUR" "\\texteuro{}" nil "&euro;" "EUR" "EUR" "€")
+
+ "** Property Marks"
+ ("copy" "\\textcopyright{}" nil "&copy;" "(c)" "©" "©")
+ ("reg" "\\textregistered{}" nil "&reg;" "(r)" "®" "®")
+ ("trade" "\\texttrademark{}" nil "&trade;" "TM" "TM" "™")
+
+ "** Science et al."
+ ("minus" "\\minus" t "&minus;" "-" "-" "−")
+ ("pm" "\\textpm{}" nil "&plusmn;" "+-" "±" "±")
+ ("plusmn" "\\textpm{}" nil "&plusmn;" "+-" "±" "±")
+ ("times" "\\texttimes{}" nil "&times;" "*" "×" "×")
+ ("frasl" "/" nil "&frasl;" "/" "/" "⁄")
+ ("colon" "\\colon" t ":" ":" ":" ":")
+ ("div" "\\textdiv{}" nil "&divide;" "/" "÷" "÷")
+ ("frac12" "\\textonehalf{}" nil "&frac12;" "1/2" "½" "½")
+ ("frac14" "\\textonequarter{}" nil "&frac14;" "1/4" "¼" "¼")
+ ("frac34" "\\textthreequarters{}" nil "&frac34;" "3/4" "¾" "¾")
+ ("permil" "\\textperthousand{}" nil "&permil;" "per thousand" "per thousand" "‰")
+ ("sup1" "\\textonesuperior{}" nil "&sup1;" "^1" "¹" "¹")
+ ("sup2" "\\texttwosuperior{}" nil "&sup2;" "^2" "²" "²")
+ ("sup3" "\\textthreesuperior{}" nil "&sup3;" "^3" "³" "³")
+ ("radic" "\\sqrt{\\,}" t "&radic;" "[square root]" "[square root]" "√")
+ ("sum" "\\sum" t "&sum;" "[sum]" "[sum]" "∑")
+ ("prod" "\\prod" t "&prod;" "[product]" "[n-ary product]" "∏")
+ ("micro" "\\textmu{}" nil "&micro;" "micro" "µ" "µ")
+ ("macr" "\\textasciimacron{}" nil "&macr;" "[macron]" "¯" "¯")
+ ("deg" "\\textdegree{}" nil "&deg;" "degree" "°" "°")
+ ("prime" "\\prime" t "&prime;" "'" "'" "′")
+ ("Prime" "\\prime{}\\prime" t "&Prime;" "''" "''" "″")
+ ("infin" "\\infty" t "&infin;" "[infinity]" "[infinity]" "∞")
+ ("infty" "\\infty" t "&infin;" "[infinity]" "[infinity]" "∞")
+ ("prop" "\\propto" t "&prop;" "[proportional to]" "[proportional to]" "∝")
+ ("propto" "\\propto" t "&prop;" "[proportional to]" "[proportional to]" "∝")
+ ("not" "\\textlnot{}" nil "&not;" "[angled dash]" "¬" "¬")
+ ("neg" "\\neg{}" t "&not;" "[angled dash]" "¬" "¬")
+ ("land" "\\land" t "&and;" "[logical and]" "[logical and]" "∧")
+ ("wedge" "\\wedge" t "&and;" "[logical and]" "[logical and]" "∧")
+ ("lor" "\\lor" t "&or;" "[logical or]" "[logical or]" "∨")
+ ("vee" "\\vee" t "&or;" "[logical or]" "[logical or]" "∨")
+ ("cap" "\\cap" t "&cap;" "[intersection]" "[intersection]" "∩")
+ ("cup" "\\cup" t "&cup;" "[union]" "[union]" "∪")
+ ("smile" "\\smile" t "&smile;" "[cup product]" "[cup product]" "⌣")
+ ("frown" "\\frown" t "&frown;" "[Cap product]" "[cap product]" "⌢")
+ ("int" "\\int" t "&int;" "[integral]" "[integral]" "∫")
+ ("therefore" "\\therefore" t "&there4;" "[therefore]" "[therefore]" "∴")
+ ("there4" "\\therefore" t "&there4;" "[therefore]" "[therefore]" "∴")
+ ("because" "\\because" t "&because;" "[because]" "[because]" "∵")
+ ("sim" "\\sim" t "&sim;" "~" "~" "∼")
+ ("cong" "\\cong" t "&cong;" "[approx. equal to]" "[approx. equal to]" "≅")
+ ("simeq" "\\simeq" t "&cong;" "[approx. equal to]" "[approx. equal to]" "≅")
+ ("asymp" "\\asymp" t "&asymp;" "[almost equal to]" "[almost equal to]" "≈")
+ ("approx" "\\approx" t "&asymp;" "[almost equal to]" "[almost equal to]" "≈")
+ ("ne" "\\ne" t "&ne;" "[not equal to]" "[not equal to]" "≠")
+ ("neq" "\\neq" t "&ne;" "[not equal to]" "[not equal to]" "≠")
+ ("equiv" "\\equiv" t "&equiv;" "[identical to]" "[identical to]" "≡")
+
+ ("triangleq" "\\triangleq" t "&triangleq;" "[defined to]" "[defined to]" "≜")
+ ("le" "\\le" t "&le;" "<=" "<=" "≤")
+ ("leq" "\\le" t "&le;" "<=" "<=" "≤")
+ ("ge" "\\ge" t "&ge;" ">=" ">=" "≥")
+ ("geq" "\\ge" t "&ge;" ">=" ">=" "≥")
+ ("lessgtr" "\\lessgtr" t "&lessgtr;" "[less than or greater than]" "[less than or greater than]" "≶")
+ ("lesseqgtr" "\\lesseqgtr" t "&lesseqgtr;" "[less than or equal or greater than or equal]" "[less than or equal or greater than or equal]" "⋚")
+ ("ll" "\\ll" t "&Lt;" "<<" "<<" "≪")
+ ("Ll" "\\lll" t "&Ll;" "<<<" "<<<" "⋘")
+ ("lll" "\\lll" t "&Ll;" "<<<" "<<<" "⋘")
+ ("gg" "\\gg" t "&Gt;" ">>" ">>" "≫")
+ ("Gg" "\\ggg" t "&Gg;" ">>>" ">>>" "⋙")
+ ("ggg" "\\ggg" t "&Gg;" ">>>" ">>>" "⋙")
+ ("prec" "\\prec" t "&pr;" "[precedes]" "[precedes]" "≺")
+ ("preceq" "\\preceq" t "&prcue;" "[precedes or equal]" "[precedes or equal]" "≼")
+ ("preccurlyeq" "\\preccurlyeq" t "&prcue;" "[precedes or equal]" "[precedes or equal]" "≼")
+ ("succ" "\\succ" t "&sc;" "[succeeds]" "[succeeds]" "≻")
+ ("succeq" "\\succeq" t "&sccue;" "[succeeds or equal]" "[succeeds or equal]" "≽")
+ ("succcurlyeq" "\\succcurlyeq" t "&sccue;" "[succeeds or equal]" "[succeeds or equal]" "≽")
+ ("sub" "\\subset" t "&sub;" "[subset of]" "[subset of]" "⊂")
+ ("subset" "\\subset" t "&sub;" "[subset of]" "[subset of]" "⊂")
+ ("sup" "\\supset" t "&sup;" "[superset of]" "[superset of]" "⊃")
+ ("supset" "\\supset" t "&sup;" "[superset of]" "[superset of]" "⊃")
+ ("nsub" "\\not\\subset" t "&nsub;" "[not a subset of]" "[not a subset of" "⊄")
+ ("sube" "\\subseteq" t "&sube;" "[subset of or equal to]" "[subset of or equal to]" "⊆")
+ ("nsup" "\\not\\supset" t "&nsup;" "[not a superset of]" "[not a superset of]" "⊅")
+ ("supe" "\\supseteq" t "&supe;" "[superset of or equal to]" "[superset of or equal to]" "⊇")
+ ("setminus" "\\setminus" t "&setminus;" "\" "\" "⧵")
+ ("forall" "\\forall" t "&forall;" "[for all]" "[for all]" "∀")
+ ("exist" "\\exists" t "&exist;" "[there exists]" "[there exists]" "∃")
+ ("exists" "\\exists" t "&exist;" "[there exists]" "[there exists]" "∃")
+ ("nexist" "\\nexists" t "&exist;" "[there does not exists]" "[there does not exists]" "∄")
+ ("nexists" "\\nexists" t "&exist;" "[there does not exists]" "[there does not exists]" "∄")
+ ("empty" "\\empty" t "&empty;" "[empty set]" "[empty set]" "∅")
+ ("emptyset" "\\emptyset" t "&empty;" "[empty set]" "[empty set]" "∅")
+ ("isin" "\\in" t "&isin;" "[element of]" "[element of]" "∈")
+ ("in" "\\in" t "&isin;" "[element of]" "[element of]" "∈")
+ ("notin" "\\notin" t "&notin;" "[not an element of]" "[not an element of]" "∉")
+ ("ni" "\\ni" t "&ni;" "[contains as member]" "[contains as member]" "∋")
+ ("nabla" "\\nabla" t "&nabla;" "[nabla]" "[nabla]" "∇")
+ ("ang" "\\angle" t "&ang;" "[angle]" "[angle]" "∠")
+ ("angle" "\\angle" t "&ang;" "[angle]" "[angle]" "∠")
+ ("perp" "\\perp" t "&perp;" "[up tack]" "[up tack]" "⊥")
+ ("parallel" "\\parallel" t "&parallel;" "||" "||" "∥")
+ ("sdot" "\\cdot" t "&sdot;" "[dot]" "[dot]" "⋅")
+ ("cdot" "\\cdot" t "&sdot;" "[dot]" "[dot]" "⋅")
+ ("lceil" "\\lceil" t "&lceil;" "[left ceiling]" "[left ceiling]" "⌈")
+ ("rceil" "\\rceil" t "&rceil;" "[right ceiling]" "[right ceiling]" "⌉")
+ ("lfloor" "\\lfloor" t "&lfloor;" "[left floor]" "[left floor]" "⌊")
+ ("rfloor" "\\rfloor" t "&rfloor;" "[right floor]" "[right floor]" "⌋")
+ ("lang" "\\langle" t "&lang;" "<" "<" "⟨")
+ ("rang" "\\rangle" t "&rang;" ">" ">" "⟩")
+ ("langle" "\\langle" t "&lang;" "<" "<" "⟨")
+ ("rangle" "\\rangle" t "&rang;" ">" ">" "⟩")
+ ("hbar" "\\hbar" t "&hbar;" "hbar" "hbar" "ℏ")
+ ("mho" "\\mho" t "&mho;" "mho" "mho" "℧")
+
+ "** Arrows"
+ ("larr" "\\leftarrow" t "&larr;" "<-" "<-" "←")
+ ("leftarrow" "\\leftarrow" t "&larr;" "<-" "<-" "←")
+ ("gets" "\\gets" t "&larr;" "<-" "<-" "←")
+ ("lArr" "\\Leftarrow" t "&lArr;" "<=" "<=" "⇐")
+ ("Leftarrow" "\\Leftarrow" t "&lArr;" "<=" "<=" "⇐")
+ ("uarr" "\\uparrow" t "&uarr;" "[uparrow]" "[uparrow]" "↑")
+ ("uparrow" "\\uparrow" t "&uarr;" "[uparrow]" "[uparrow]" "↑")
+ ("uArr" "\\Uparrow" t "&uArr;" "[dbluparrow]" "[dbluparrow]" "⇑")
+ ("Uparrow" "\\Uparrow" t "&uArr;" "[dbluparrow]" "[dbluparrow]" "⇑")
+ ("rarr" "\\rightarrow" t "&rarr;" "->" "->" "→")
+ ("to" "\\to" t "&rarr;" "->" "->" "→")
+ ("rightarrow" "\\rightarrow" t "&rarr;" "->" "->" "→")
+ ("rArr" "\\Rightarrow" t "&rArr;" "=>" "=>" "⇒")
+ ("Rightarrow" "\\Rightarrow" t "&rArr;" "=>" "=>" "⇒")
+ ("darr" "\\downarrow" t "&darr;" "[downarrow]" "[downarrow]" "↓")
+ ("downarrow" "\\downarrow" t "&darr;" "[downarrow]" "[downarrow]" "↓")
+ ("dArr" "\\Downarrow" t "&dArr;" "[dbldownarrow]" "[dbldownarrow]" "⇓")
+ ("Downarrow" "\\Downarrow" t "&dArr;" "[dbldownarrow]" "[dbldownarrow]" "⇓")
+ ("harr" "\\leftrightarrow" t "&harr;" "<->" "<->" "↔")
+ ("leftrightarrow" "\\leftrightarrow" t "&harr;" "<->" "<->" "↔")
+ ("hArr" "\\Leftrightarrow" t "&hArr;" "<=>" "<=>" "⇔")
+ ("Leftrightarrow" "\\Leftrightarrow" t "&hArr;" "<=>" "<=>" "⇔")
+ ("crarr" "\\hookleftarrow" t "&crarr;" "<-'" "<-'" "↵")
+ ("hookleftarrow" "\\hookleftarrow" t "&crarr;" "<-'" "<-'" "↵")
+
+ "** Function names"
+ ("arccos" "\\arccos" t "arccos" "arccos" "arccos" "arccos")
+ ("arcsin" "\\arcsin" t "arcsin" "arcsin" "arcsin" "arcsin")
+ ("arctan" "\\arctan" t "arctan" "arctan" "arctan" "arctan")
+ ("arg" "\\arg" t "arg" "arg" "arg" "arg")
+ ("cos" "\\cos" t "cos" "cos" "cos" "cos")
+ ("cosh" "\\cosh" t "cosh" "cosh" "cosh" "cosh")
+ ("cot" "\\cot" t "cot" "cot" "cot" "cot")
+ ("coth" "\\coth" t "coth" "coth" "coth" "coth")
+ ("csc" "\\csc" t "csc" "csc" "csc" "csc")
+ ("deg" "\\deg" t "&deg;" "deg" "deg" "deg")
+ ("det" "\\det" t "det" "det" "det" "det")
+ ("dim" "\\dim" t "dim" "dim" "dim" "dim")
+ ("exp" "\\exp" t "exp" "exp" "exp" "exp")
+ ("gcd" "\\gcd" t "gcd" "gcd" "gcd" "gcd")
+ ("hom" "\\hom" t "hom" "hom" "hom" "hom")
+ ("inf" "\\inf" t "inf" "inf" "inf" "inf")
+ ("ker" "\\ker" t "ker" "ker" "ker" "ker")
+ ("lg" "\\lg" t "lg" "lg" "lg" "lg")
+ ("lim" "\\lim" t "lim" "lim" "lim" "lim")
+ ("liminf" "\\liminf" t "liminf" "liminf" "liminf" "liminf")
+ ("limsup" "\\limsup" t "limsup" "limsup" "limsup" "limsup")
+ ("ln" "\\ln" t "ln" "ln" "ln" "ln")
+ ("log" "\\log" t "log" "log" "log" "log")
+ ("max" "\\max" t "max" "max" "max" "max")
+ ("min" "\\min" t "min" "min" "min" "min")
+ ("Pr" "\\Pr" t "Pr" "Pr" "Pr" "Pr")
+ ("sec" "\\sec" t "sec" "sec" "sec" "sec")
+ ("sin" "\\sin" t "sin" "sin" "sin" "sin")
+ ("sinh" "\\sinh" t "sinh" "sinh" "sinh" "sinh")
+ ("sup" "\\sup" t "&sup;" "sup" "sup" "sup")
+ ("tan" "\\tan" t "tan" "tan" "tan" "tan")
+ ("tanh" "\\tanh" t "tanh" "tanh" "tanh" "tanh")
+
+ "** Signs & Symbols"
+ ("bull" "\\textbullet{}" nil "&bull;" "*" "*" "•")
+ ("bullet" "\\textbullet{}" nil "&bull;" "*" "*" "•")
+ ("star" "\\star" t "*" "*" "*" "⋆")
+ ("lowast" "\\ast" t "&lowast;" "*" "*" "∗")
+ ("ast" "\\ast" t "&lowast;" "*" "*" "*")
+ ("odot" "\\odot" t "o" "[circled dot]" "[circled dot]" "ʘ")
+ ("oplus" "\\oplus" t "&oplus;" "[circled plus]" "[circled plus]" "⊕")
+ ("otimes" "\\otimes" t "&otimes;" "[circled times]" "[circled times]" "⊗")
+ ("check" "\\checkmark" t "&checkmark;" "[checkmark]" "[checkmark]" "✓")
+ ("checkmark" "\\checkmark" t "&check;" "[checkmark]" "[checkmark]" "✓")
+
+ "** Miscellaneous (seldom used)"
+ ("para" "\\P{}" nil "&para;" "[pilcrow]" "¶" "¶")
+ ("ordf" "\\textordfeminine{}" nil "&ordf;" "_a_" "ª" "ª")
+ ("ordm" "\\textordmasculine{}" nil "&ordm;" "_o_" "º" "º")
+ ("cedil" "\\c{}" nil "&cedil;" "[cedilla]" "¸" "¸")
+ ("oline" "\\overline{~}" t "&oline;" "[overline]" "¯" "‾")
+ ("uml" "\\textasciidieresis{}" nil "&uml;" "[diaeresis]" "¨" "¨")
+ ("zwnj" "\\/{}" nil "&zwnj;" "" "" "‌")
+ ("zwj" "" nil "&zwj;" "" "" "‍")
+ ("lrm" "" nil "&lrm;" "" "" "‎")
+ ("rlm" "" nil "&rlm;" "" "" "‏")
+
+ "** Smilies"
+ ("smiley" "\\ddot\\smile" t "&#9786;" ":-)" ":-)" "☺")
+ ("blacksmile" "\\ddot\\smile" t "&#9787;" ":-)" ":-)" "☻")
+ ("sad" "\\ddot\\frown" t "&#9785;" ":-(" ":-(" "☹")
+ ("frowny" "\\ddot\\frown" t "&#9785;" ":-(" ":-(" "☹")
+
+ "** Suits"
+ ("clubs" "\\clubsuit" t "&clubs;" "[clubs]" "[clubs]" "♣")
+ ("clubsuit" "\\clubsuit" t "&clubs;" "[clubs]" "[clubs]" "♣")
+ ("spades" "\\spadesuit" t "&spades;" "[spades]" "[spades]" "♠")
+ ("spadesuit" "\\spadesuit" t "&spades;" "[spades]" "[spades]" "♠")
+ ("hearts" "\\heartsuit" t "&hearts;" "[hearts]" "[hearts]" "♥")
+ ("heartsuit" "\\heartsuit" t "&heartsuit;" "[hearts]" "[hearts]" "♥")
+ ("diams" "\\diamondsuit" t "&diams;" "[diamonds]" "[diamonds]" "◆")
+ ("diamondsuit" "\\diamondsuit" t "&diams;" "[diamonds]" "[diamonds]" "◆")
+ ("diamond" "\\diamondsuit" t "&diamond;" "[diamond]" "[diamond]" "◆")
+ ("Diamond" "\\diamondsuit" t "&diamond;" "[diamond]" "[diamond]" "◆")
+ ("loz" "\\lozenge" t "&loz;" "[lozenge]" "[lozenge]" "⧫"))
+ ;; Add "\_ "-entity family for spaces.
+ (let (space-entities html-spaces (entity "_"))
+ (dolist (n (number-sequence 1 20) (nreverse space-entities))
+ (let ((spaces (make-string n ?\s)))
+ (push (list (setq entity (concat entity " "))
+ (format "\\hspace*{%sem}" (* n .5))
+ nil
+ (setq html-spaces (concat "&ensp;" html-spaces))
+ spaces
+ spaces
+ (make-string n ?\x2002))
+ space-entities)))))
+ "Default entities used in Org mode to produce special characters.
+For details see `org-entities-user'.")
+
+(defsubst org-entity-get (name)
+ "Get the proper association for NAME from the entity lists.
+This first checks the user list, then the built-in list."
+ (or (assoc name org-entities-user)
+ (assoc name org-entities)))
+
+;; Helpfunctions to create a table for orgmode.org/worg/org-symbols.org
+
+(defun org-entities-create-table ()
+ "Create an Org mode table with all entities."
+ (interactive)
+ (let ((pos (point)))
+ (insert "|Name|LaTeX code|LaTeX|HTML code |HTML|ASCII|Latin1|UTF-8\n|-\n")
+ (dolist (e org-entities)
+ (pcase e
+ (`(,name ,latex ,mathp ,html ,ascii ,latin ,utf8)
+ (if (equal ascii "|") (setq ascii "\\vert"))
+ (if (equal latin "|") (setq latin "\\vert"))
+ (if (equal utf8 "|") (setq utf8 "\\vert"))
+ (if (equal ascii "=>") (setq ascii "= >"))
+ (if (equal latin "=>") (setq latin "= >"))
+ (insert "|" name
+ "|" (format "=%s=" latex)
+ "|" (format (if mathp "$%s$" "$\\mbox{%s}$") latex)
+ "|" (format "=%s=" html) "|" html
+ "|" ascii "|" latin "|" utf8
+ "|\n"))))
+ (goto-char pos)
+ (org-table-align)))
+
+(defvar org-pretty-entities) ;; declare defcustom from org
+(defun org-entities-help ()
+ "Create a Help buffer with all available entities."
+ (interactive)
+ (with-output-to-temp-buffer "*Org Entity Help*"
+ (princ "Org mode entities\n=================\n\n")
+ (let ((ll (append '("* User-defined additions (variable org-entities-user)")
+ org-entities-user
+ org-entities))
+ (lastwasstring t)
+ (head (concat
+ "\n"
+ " Symbol Org entity LaTeX code HTML code\n"
+ " -----------------------------------------------------------\n")))
+ (dolist (e ll)
+ (pcase e
+ (`(,name ,latex ,_ ,html ,_ ,_ ,utf8)
+ (when lastwasstring
+ (princ head)
+ (setq lastwasstring nil))
+ (princ (format " %-8s \\%-16s %-22s %-13s\n"
+ utf8 name latex html)))
+ ((pred stringp)
+ (princ e)
+ (princ "\n")
+ (setq lastwasstring t))))))
+ (with-current-buffer "*Org Entity Help*"
+ (org-mode)
+ (when org-pretty-entities
+ (org-toggle-pretty-entities)))
+ (select-window (get-buffer-window "*Org Entity Help*")))
+
+
+(provide 'org-entities)
+
+;; Local variables:
+;; coding: utf-8
+;; End:
+
+;;; org-entities.el ends here
diff --git a/lisp/org-eshell.el b/lisp/org-eshell.el
new file mode 100644
index 0000000..34cc4ff
--- /dev/null
+++ b/lisp/org-eshell.el
@@ -0,0 +1,66 @@
+;;; org-eshell.el - Support for Links to Working Directories in Eshell -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Konrad Hinsen <konrad.hinsen AT fastmail.net>
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Code:
+
+(require 'org)
+(require 'eshell)
+(require 'esh-mode)
+
+(org-link-set-parameters "eshell"
+ :follow #'org-eshell-open
+ :store #'org-eshell-store-link)
+
+(defun org-eshell-open (link)
+ "Switch to am eshell buffer and execute a command line.
+ The link can be just a command line (executed in the default
+ eshell buffer) or a command line prefixed by a buffer name
+ followed by a colon."
+ (let* ((buffer-and-command
+ (if (string-match "\\([A-Za-z0-9-+*]+\\):\\(.*\\)" link)
+ (list (match-string 1 link)
+ (match-string 2 link))
+ (list eshell-buffer-name link)))
+ (eshell-buffer-name (car buffer-and-command))
+ (command (cadr buffer-and-command)))
+ (if (get-buffer eshell-buffer-name)
+ (pop-to-buffer-same-window eshell-buffer-name)
+ (eshell))
+ (goto-char (point-max))
+ (eshell-kill-input)
+ (insert command)
+ (eshell-send-input)))
+
+(defun org-eshell-store-link ()
+ "Store a link that, when opened, switches back to the current eshell buffer
+ and the current working directory."
+ (when (eq major-mode 'eshell-mode)
+ (let* ((command (concat "cd " dired-directory))
+ (link (concat (buffer-name) ":" command)))
+ (org-store-link-props
+ :link (concat "eshell:" link)
+ :description command))))
+
+(provide 'org-eshell)
+
+;;; org-eshell.el ends here
diff --git a/lisp/org-eww.el b/lisp/org-eww.el
new file mode 100644
index 0000000..7bc248d
--- /dev/null
+++ b/lisp/org-eww.el
@@ -0,0 +1,175 @@
+;;; org-eww.el --- Store url and kill from Eww mode for Org -*- lexical-binding: t -*-
+
+;; Copyright (C) 2014-2017 Free Software Foundation, Inc.
+
+;; Author: Marco Wahl <marcowahlsoft>a<gmailcom>
+;; Keywords: link, eww
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+
+;;; Commentary:
+
+;; When this module is active `org-store-link' (often on key C-c l) in
+;; a eww buffer stores a link to the current url of the eww buffer.
+
+;; In an eww buffer function `org-eww-copy-for-org-mode' kills either
+;; a region or the whole buffer if no region is set and transforms the
+;; text on the fly so that it can be pasted into an Org buffer with
+;; hot links.
+
+;; C-c C-x C-w (and also C-c C-x M-w) trigger
+;; `org-eww-copy-for-org-mode'.
+
+;; Hint: A lot of code of this module comes from module org-w3m which
+;; has been written by Andy Steward based on the idea of Richard
+;; Riley. Thanks!
+
+;; Potential: Since the code for w3m and eww is so similar one could
+;; try to refactor.
+
+
+;;; Code:
+(require 'org)
+(require 'cl-lib)
+
+(defvar eww-current-title)
+(defvar eww-current-url)
+(defvar eww-data)
+(defvar eww-mode-map)
+
+(declare-function eww-current-url "eww")
+
+
+;; Store Org-link in eww-mode buffer
+(org-link-set-parameters "eww" :follow #'eww :store #'org-eww-store-link)
+(defun org-eww-store-link ()
+ "Store a link to the url of a Eww buffer."
+ (when (eq major-mode 'eww-mode)
+ (org-store-link-props
+ :type "eww"
+ :link (if (< emacs-major-version 25)
+ eww-current-url
+ (eww-current-url))
+ :url (url-view-url t)
+ :description (if (< emacs-major-version 25)
+ (or eww-current-title eww-current-url)
+ (or (plist-get eww-data :title)
+ (eww-current-url))))))
+
+
+;; Some auxiliary functions concerning links in eww buffers
+(defun org-eww-goto-next-url-property-change ()
+ "Move to the start of next link if exists.
+Otherwise point is not moved. Return point."
+ (goto-char
+ (or (next-single-property-change (point) 'shr-url)
+ (point))))
+
+(defun org-eww-has-further-url-property-change-p ()
+ "Non-nil if there is a next url property change."
+ (save-excursion
+ (not (eq (point) (org-eww-goto-next-url-property-change)))))
+
+(defun org-eww-url-below-point ()
+ "Return the url below point if there is an url; otherwise, return nil."
+ (get-text-property (point) 'shr-url))
+
+
+(defun org-eww-copy-for-org-mode ()
+ "Copy current buffer content or active region with `org-mode' style links.
+This will encode `link-title' and `link-location' with
+`org-make-link-string', and insert the transformed test into the kill ring,
+so that it can be yanked into an Org mode buffer with links working correctly.
+
+Further lines starting with a star get quoted with a comma to keep
+the structure of the Org file."
+ (interactive)
+ (let* ((regionp (org-region-active-p))
+ (transform-start (point-min))
+ (transform-end (point-max))
+ return-content
+ link-location link-title
+ temp-position out-bound)
+ (when regionp
+ (setq transform-start (region-beginning))
+ (setq transform-end (region-end))
+ ;; Deactivate mark if current mark is activate.
+ (when (fboundp 'deactivate-mark) (deactivate-mark)))
+ (message "Transforming links...")
+ (save-excursion
+ (goto-char transform-start)
+ (while (and (not out-bound) ; still inside region to copy
+ (org-eww-has-further-url-property-change-p)) ; there is a next link
+ ;; Store current point before jump next anchor.
+ (setq temp-position (point))
+ ;; Move to next anchor when current point is not at anchor.
+ (or (org-eww-url-below-point)
+ (org-eww-goto-next-url-property-change))
+ (cl-assert
+ (org-eww-url-below-point) t
+ "program logic error: point must have an url below but it hasn't")
+ (if (<= (point) transform-end) ; if point is inside transform bound
+ (progn
+ ;; Get content between two links.
+ (when (< temp-position (point))
+ (setq return-content (concat return-content
+ (buffer-substring
+ temp-position (point)))))
+ ;; Get link location at current point.
+ (setq link-location (org-eww-url-below-point))
+ ;; Get link title at current point.
+ (setq link-title
+ (buffer-substring
+ (point)
+ (org-eww-goto-next-url-property-change)))
+ ;; concat `org-mode' style url to `return-content'.
+ (setq return-content
+ (concat return-content
+ (if (stringp link-location)
+ ;; hint: link-location is different for form-elements.
+ (org-make-link-string link-location link-title)
+ link-title))))
+ (goto-char temp-position) ; reset point before jump next anchor
+ (setq out-bound t) ; for break out `while' loop
+ ))
+ ;; Add the rest until end of the region to be copied.
+ (when (< (point) transform-end)
+ (setq return-content
+ (concat return-content
+ (buffer-substring (point) transform-end))))
+ ;; Quote lines starting with *.
+ (org-kill-new (replace-regexp-in-string "^\\*" ",*" return-content))
+ (message "Transforming links...done, use C-y to insert text into Org mode file"))))
+
+
+;; Additional keys for eww-mode
+
+(defun org-eww-extend-eww-keymap ()
+ (define-key eww-mode-map "\C-c\C-x\M-w" 'org-eww-copy-for-org-mode)
+ (define-key eww-mode-map "\C-c\C-x\C-w" 'org-eww-copy-for-org-mode))
+
+(when (and (boundp 'eww-mode-map)
+ (keymapp eww-mode-map)) ; eww is already up.
+ (org-eww-extend-eww-keymap))
+
+(add-hook 'eww-mode-hook #'org-eww-extend-eww-keymap)
+
+
+(provide 'org-eww)
+
+;;; org-eww.el ends here
diff --git a/lisp/org-faces.el b/lisp/org-faces.el
new file mode 100644
index 0000000..cd43d37
--- /dev/null
+++ b/lisp/org-faces.el
@@ -0,0 +1,653 @@
+;;; org-faces.el --- Face definitions -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the face definitions for Org.
+
+;;; Code:
+
+(defgroup org-faces nil
+ "Faces in Org mode."
+ :tag "Org Faces"
+ :group 'org-appearance)
+
+(defface org-default '((t :inherit default))
+ "Face used for default text."
+ :group 'org-faces)
+
+(defface org-hide
+ '((((background light)) (:foreground "white"))
+ (((background dark)) (:foreground "black")))
+ "Face used to hide leading stars in headlines.
+The foreground color of this face should be equal to the background
+color of the frame."
+ :group 'org-faces)
+
+(defface org-level-1 '((t :inherit outline-1))
+ "Face used for level 1 headlines."
+ :group 'org-faces)
+
+(defface org-level-2 '((t :inherit outline-2))
+ "Face used for level 2 headlines."
+ :group 'org-faces)
+
+(defface org-level-3 '((t :inherit outline-3))
+ "Face used for level 3 headlines."
+ :group 'org-faces)
+
+(defface org-level-4 '((t :inherit outline-4))
+ "Face used for level 4 headlines."
+ :group 'org-faces)
+
+(defface org-level-5 '((t :inherit outline-5))
+ "Face used for level 5 headlines."
+ :group 'org-faces)
+
+(defface org-level-6 '((t :inherit outline-6))
+ "Face used for level 6 headlines."
+ :group 'org-faces)
+
+(defface org-level-7 '((t :inherit outline-7))
+ "Face used for level 7 headlines."
+ :group 'org-faces)
+
+(defface org-level-8 '((t :inherit outline-8))
+ "Face used for level 8 headlines."
+ :group 'org-faces)
+
+(defface org-special-keyword '((t :inherit font-lock-keyword-face))
+ "Face used for special keywords."
+ :group 'org-faces)
+
+(defface org-drawer ;Copied from `font-lock-function-name-face'
+ '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 8)) (:foreground "blue" :bold t))
+ (t (:bold t)))
+ "Face used for drawers."
+ :group 'org-faces)
+
+(defface org-property-value nil
+ "Face used for the value of a property."
+ :group 'org-faces)
+
+(defface org-column
+ '((((class color) (min-colors 16) (background light))
+ (:background "grey90" :weight normal :slant normal :strike-through nil
+ :underline nil))
+ (((class color) (min-colors 16) (background dark))
+ (:background "grey30" :weight normal :slant normal :strike-through nil
+ :underline nil))
+ (((class color) (min-colors 8))
+ (:background "cyan" :foreground "black"
+ :weight normal :slant normal :strike-through nil
+ :underline nil))
+ (t (:inverse-video t)))
+ "Face for column display of entry properties.
+This is actually only part of the face definition for the text in column view.
+The following faces apply, with this priority.
+
+1. The color of the reference face. This is normally the level fact that
+ is used in the outline. In agenda-mode, it will be the face of the
+ first character in the line. The color is explicitly retained to
+ make sure that the column line still looks a bit like the structure
+ line it is masking.
+
+2. The `org-column' face.
+
+3. The remaining properties of the reference face.
+
+Since column view works by putting overlays with a display property
+over individual characters in the buffer, the face of the underlining
+character (this might for example be the a TODO keyword) might still
+shine through in some properties. So when your column view looks
+funny, with \"random\" colors, weight, strike-through, try to explicitly
+set the properties in the `org-column' face. For example, set
+:underline to nil, or the :slant to `normal'."
+ :group 'org-faces)
+
+(defface org-column-title
+ '((((class color) (min-colors 16) (background light))
+ (:background "grey90" :underline t :weight bold))
+ (((class color) (min-colors 16) (background dark))
+ (:background "grey30" :underline t :weight bold))
+ (((class color) (min-colors 8))
+ (:background "cyan" :foreground "black" :underline t :weight bold))
+ (t (:inverse-video t)))
+ "Face for column display of entry properties."
+ :group 'org-faces)
+
+(defface org-agenda-column-dateline '((t :inherit org-column))
+ "Face used in agenda column view for datelines with summaries."
+ :group 'org-faces)
+
+(defface org-warning '((t :inherit font-lock-warning-face))
+ "Face for deadlines and TODO keywords."
+ :group 'org-faces)
+
+(defface org-archived '((t :inherit shadow))
+ "Face for headline with the ARCHIVE tag."
+ :group 'org-faces)
+
+(defface org-link '((t :inherit link))
+ "Face for links."
+ :group 'org-faces)
+
+(defface org-footnote
+ '((((class color) (background light)) (:foreground "Purple" :underline t))
+ (((class color) (background dark)) (:foreground "Cyan" :underline t))
+ (t (:underline t)))
+ "Face for footnotes."
+ :group 'org-faces)
+
+(defface org-ellipsis
+ '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
+ (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
+ (t (:strike-through t)))
+ "Face for the ellipsis in folded text."
+ :group 'org-faces)
+
+(defface org-target
+ '((((class color) (background light)) (:underline t))
+ (((class color) (background dark)) (:underline t))
+ (t (:underline t)))
+ "Face for link targets."
+ :group 'org-faces)
+
+(defface org-date
+ '((((class color) (background light)) (:foreground "Purple" :underline t))
+ (((class color) (background dark)) (:foreground "Cyan" :underline t))
+ (t (:underline t)))
+ "Face for date/time stamps."
+ :group 'org-faces)
+
+(defface org-date-selected
+ '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :inverse-video t))
+ (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :inverse-video t))
+ (((class color) (min-colors 8) (background light)) (:foreground "red" :inverse-video t))
+ (((class color) (min-colors 8) (background dark)) (:foreground "red" :inverse-video t))
+ (t (:inverse-video t)))
+ "Face for highlighting the calendar day when using `org-read-date'.
+Using a bold face here might cause discrepancies while displaying the
+calendar."
+ :group 'org-faces)
+
+(defface org-sexp-date
+ '((((class color) (background light)) (:foreground "Purple"))
+ (((class color) (background dark)) (:foreground "Cyan"))
+ (t (:underline t)))
+ "Face for diary-like sexp date specifications."
+ :group 'org-faces)
+
+(defface org-tag '((t (:bold t)))
+ "Default face for tags.
+Note that the variable `org-tag-faces' can be used to overrule this face for
+specific tags."
+ :group 'org-faces)
+
+(defface org-list-dt '((t (:bold t)))
+ "Default face for definition terms in lists."
+ :group 'org-faces)
+
+(defface org-todo ;Copied from `font-lock-warning-face'
+ '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
+ (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
+ (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
+ (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
+ (t (:inverse-video t :bold t)))
+ "Face for TODO keywords."
+ :group 'org-faces)
+
+(defface org-done ;Copied from `font-lock-type-face'
+ '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
+ (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
+ (((class color) (min-colors 8)) (:foreground "green"))
+ (t (:bold t)))
+ "Face used for todo keywords that indicate DONE items."
+ :group 'org-faces)
+
+(defface org-agenda-done ;Copied from `font-lock-type-face'
+ '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
+ (((class color) (min-colors 8)) (:foreground "green"))
+ (t (:bold nil)))
+ "Face used in agenda, to indicate lines switched to DONE.
+This face is used to de-emphasize items that where brightly colored in the
+agenda because they were things to do, or overdue. The DONE state itself
+is of course immediately visible, but for example a passed deadline is
+\(by default) very bright read. This face could be simply the default face
+of the frame, for example."
+ :group 'org-faces)
+
+(defface org-headline-done ;Copied from `font-lock-string-face'
+ '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
+ (((class color) (min-colors 8) (background light)) (:bold nil)))
+ "Face used to indicate that a headline is DONE.
+This face is only used if `org-fontify-done-headline' is set. If applies
+to the part of the headline after the DONE keyword."
+ :group 'org-faces)
+
+(defcustom org-faces-easy-properties
+ '((todo . :foreground) (tag . :foreground) (priority . :foreground))
+ "The property changes by easy faces.
+This is an alist, the keys show the area of application, the values
+can be `:foreground' or `:background'. A color string for special
+keywords will then be interpreted as either foreground or background
+color."
+ :group 'org-faces
+ :group 'org-todo
+ :version "24.1"
+ :type '(repeat
+ (cons (choice (const todo) (const tag) (const priority))
+ (choice (const :foreground) (const :background)))))
+
+(defcustom org-todo-keyword-faces nil
+ "Faces for specific TODO keywords.
+This is a list of cons cells, with TODO keywords in the car
+and faces in the cdr. The face can be a symbol, a color
+as a string (in which case the rest is inherited from the `org-todo' face),
+or a property list of attributes, like
+ (:foreground \"blue\" :weight bold :underline t).
+If it is a color string, the variable `org-faces-easy-properties'
+determines if it is a foreground or a background color."
+ :group 'org-faces
+ :group 'org-todo
+ :type '(repeat
+ (cons
+ (string :tag "Keyword")
+ (choice :tag "Face "
+ (string :tag "Color")
+ (sexp :tag "Face")))))
+
+(defface org-priority '((t :inherit font-lock-keyword-face))
+ "Face used for priority cookies."
+ :group 'org-faces)
+
+(defcustom org-priority-faces nil
+ "Faces for specific Priorities.
+This is a list of cons cells, with priority character in the car
+and faces in the cdr. The face can be a symbol, a color as
+as a string, or a property list of attributes, like
+ (:foreground \"blue\" :weight bold :underline t).
+If it is a color string, the variable `org-faces-easy-properties'
+determines if it is a foreground or a background color."
+ :group 'org-faces
+ :group 'org-todo
+ :type '(repeat
+ (cons
+ (character :tag "Priority")
+ (choice :tag "Face "
+ (string :tag "Color")
+ (sexp :tag "Face")))))
+
+(defvar org-tags-special-faces-re nil)
+(defun org-set-tag-faces (var value)
+ (set var value)
+ (if (not value)
+ (setq org-tags-special-faces-re nil)
+ (setq org-tags-special-faces-re
+ (concat ":\\(" (mapconcat 'car value "\\|") "\\):"))))
+
+(defface org-checkbox '((t :inherit bold))
+ "Face for checkboxes."
+ :group 'org-faces)
+
+(defface org-checkbox-statistics-todo '((t (:inherit org-todo)))
+ "Face used for unfinished checkbox statistics."
+ :group 'org-faces)
+
+(defface org-checkbox-statistics-done '((t (:inherit org-done)))
+ "Face used for finished checkbox statistics."
+ :group 'org-faces)
+
+(defcustom org-tag-faces nil
+ "Faces for specific tags.
+This is a list of cons cells, with tags in the car and faces in the cdr.
+The face can be a symbol, a foreground color (in which case the rest is
+inherited from the `org-tag' face) or a property list of attributes,
+like (:foreground \"blue\" :weight bold :underline t).
+If you set this variable through customize, it will immediately be effective
+in new buffers and in modified lines.
+If you set it with Lisp, a restart of Emacs is required to activate the
+changes."
+ :group 'org-faces
+ :group 'org-tags
+ :set 'org-set-tag-faces
+ :type '(repeat
+ (cons
+ (string :tag "Tag ")
+ (choice :tag "Face"
+ (string :tag "Foreground color")
+ (sexp :tag "Face")))))
+
+(defface org-table ;Copied from `font-lock-function-name-face'
+ '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 8) (background light)) (:foreground "blue"))
+ (((class color) (min-colors 8) (background dark))))
+ "Face used for tables."
+ :group 'org-faces)
+
+(defface org-formula
+ '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
+ (((class color) (min-colors 8) (background light)) (:foreground "red"))
+ (((class color) (min-colors 8) (background dark)) (:foreground "red"))
+ (t (:bold t :italic t)))
+ "Face for formulas."
+ :group 'org-faces)
+
+(defface org-code '((t :inherit shadow))
+ "Face for fixed-width text like code snippets."
+ :group 'org-faces
+ :version "22.1")
+
+(defface org-meta-line '((t :inherit font-lock-comment-face))
+ "Face for meta lines starting with \"#+\"."
+ :group 'org-faces
+ :version "22.1")
+
+(defface org-document-title
+ '((((class color) (background light)) (:foreground "midnight blue" :weight bold))
+ (((class color) (background dark)) (:foreground "pale turquoise" :weight bold))
+ (t (:weight bold)))
+ "Face for document title, i.e. that which follows the #+TITLE: keyword."
+ :group 'org-faces)
+
+(defface org-document-info
+ '((((class color) (background light)) (:foreground "midnight blue"))
+ (((class color) (background dark)) (:foreground "pale turquoise"))
+ (t nil))
+ "Face for document date, author and email; i.e. that which
+follows a #+DATE:, #+AUTHOR: or #+EMAIL: keyword."
+ :group 'org-faces)
+
+(defface org-document-info-keyword '((t :inherit shadow))
+ "Face for #+TITLE:, #+AUTHOR:, #+EMAIL: and #+DATE: keywords."
+ :group 'org-faces)
+
+(defface org-block '((t :inherit shadow))
+ "Face text in #+begin ... #+end blocks.
+For source-blocks `org-src-block-faces' takes precedence.
+See also `org-fontify-quote-and-verse-blocks'."
+ :group 'org-faces
+ :version "26.1")
+
+(defface org-block-begin-line '((t (:inherit org-meta-line)))
+ "Face used for the line delimiting the begin of source blocks."
+ :group 'org-faces)
+
+(defface org-block-end-line '((t (:inherit org-block-begin-line)))
+ "Face used for the line delimiting the end of source blocks."
+ :group 'org-faces)
+
+(defface org-verbatim '((t (:inherit shadow)))
+ "Face for fixed-with text like code snippets"
+ :group 'org-faces
+ :version "22.1")
+
+(defface org-quote '((t (:inherit org-block)))
+ "Face for #+BEGIN_QUOTE ... #+END_QUOTE blocks."
+ :group 'org-faces)
+
+(defface org-verse '((t (:inherit org-block)))
+ "Face for #+BEGIN_VERSE ... #+END_VERSE blocks."
+ :group 'org-faces)
+
+(defcustom org-fontify-quote-and-verse-blocks nil
+ "Non-nil means, add a special face to #+begin_quote and #+begin_verse block.
+When nil, format these as normal Org. This is the default, because the
+content of these blocks will still be treated as Org syntax."
+ :group 'org-faces
+ :version "24.1"
+ :type 'boolean)
+
+(defface org-clock-overlay ;Copied from `secondary-selection'
+ '((((class color) (min-colors 88) (background light))
+ (:background "LightGray" :foreground "black"))
+ (((class color) (min-colors 88) (background dark))
+ (:background "SkyBlue4" :foreground "white"))
+ (((class color) (min-colors 16) (background light))
+ (:background "gray" :foreground "black"))
+ (((class color) (min-colors 16) (background dark))
+ (:background "SkyBlue4" :foreground "white"))
+ (((class color) (min-colors 8))
+ (:background "cyan" :foreground "black"))
+ (t (:inverse-video t)))
+ "Basic face for displaying the secondary selection."
+ :group 'org-faces)
+
+(defface org-agenda-structure ;Copied from `font-lock-function-name-face'
+ '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
+ (((class color) (min-colors 8)) (:foreground "blue" :bold t))
+ (t (:bold t)))
+ "Face used in agenda for captions and dates."
+ :group 'org-faces)
+
+(defface org-agenda-date '((t (:inherit org-agenda-structure)))
+ "Face used in agenda for normal days."
+ :group 'org-faces)
+
+(defface org-agenda-date-today
+ '((t (:inherit org-agenda-date :weight bold :italic t)))
+ "Face used in agenda for today."
+ :group 'org-faces)
+
+(defface org-agenda-clocking '((t (:inherit secondary-selection)))
+ "Face marking the current clock item in the agenda."
+ :group 'org-faces)
+
+(defface org-agenda-date-weekend '((t (:inherit org-agenda-date :weight bold)))
+ "Face used in agenda for weekend days.
+
+See the variable `org-agenda-weekend-days' for a definition of
+which days belong to the weekend."
+ :group 'org-faces)
+
+(defface org-scheduled
+ '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
+ (((class color) (min-colors 8)) (:foreground "green"))
+ (t (:bold t :italic t)))
+ "Face for items scheduled for a certain day."
+ :group 'org-faces)
+
+(defface org-scheduled-today
+ '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
+ (((class color) (min-colors 8)) (:foreground "green"))
+ (t (:bold t :italic t)))
+ "Face for items scheduled for a certain day."
+ :group 'org-faces)
+
+(defface org-agenda-dimmed-todo-face
+ '((((background light)) (:foreground "grey50"))
+ (((background dark)) (:foreground "grey50")))
+ "Face used to dim blocked tasks in the agenda."
+ :group 'org-faces)
+
+(defface org-scheduled-previously
+ '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
+ (((class color) (min-colors 8) (background light)) (:foreground "red"))
+ (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
+ (t (:bold t)))
+ "Face for items scheduled previously, and not yet done."
+ :group 'org-faces)
+
+(defface org-upcoming-deadline
+ '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
+ (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
+ (((class color) (min-colors 8) (background light)) (:foreground "red"))
+ (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
+ (t (:bold t)))
+ "Face for items scheduled previously, and not yet done."
+ :group 'org-faces)
+
+(defcustom org-agenda-deadline-faces
+ '((1.0 . org-warning)
+ (0.5 . org-upcoming-deadline)
+ (0.0 . default))
+ "Faces for showing deadlines in the agenda.
+This is a list of cons cells. The cdr of each cell is a face to be used,
+and it can also just be like \\='(:foreground \"yellow\").
+Each car is a fraction of the head-warning time that must have passed for
+this the face in the cdr to be used for display. The numbers must be
+given in descending order. The head-warning time is normally taken
+from `org-deadline-warning-days', but can also be specified in the deadline
+timestamp itself, like this:
+
+ DEADLINE: <2007-08-13 Mon -8d>
+
+You may use d for days, w for weeks, m for months and y for years. Months
+and years will only be treated in an approximate fashion (30.4 days for a
+month and 365.24 days for a year)."
+ :group 'org-faces
+ :group 'org-agenda-daily/weekly
+ :type '(repeat
+ (cons
+ (number :tag "Fraction of head-warning time passed")
+ (sexp :tag "Face"))))
+
+(defface org-agenda-restriction-lock
+ '((((class color) (min-colors 88) (background light)) (:background "#eeeeee"))
+ (((class color) (min-colors 88) (background dark)) (:background "#1C1C1C"))
+ (((class color) (min-colors 16) (background light)) (:background "#eeeeee"))
+ (((class color) (min-colors 16) (background dark)) (:background "#1C1C1C"))
+ (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
+ (t (:inverse-video t)))
+ "Face for showing the agenda restriction lock."
+ :group 'org-faces)
+
+(defface org-agenda-filter-tags '((t :inherit mode-line))
+ "Face for tag(s) in the mode-line when filtering the agenda."
+ :group 'org-faces)
+
+(defface org-agenda-filter-regexp '((t :inherit mode-line))
+ "Face for regexp(s) in the mode-line when filtering the agenda."
+ :group 'org-faces)
+
+(defface org-agenda-filter-category '((t :inherit mode-line))
+ "Face for categories in the mode-line when filtering the agenda."
+ :group 'org-faces)
+
+(defface org-agenda-filter-effort '((t :inherit mode-line))
+ "Face for effort in the mode-line when filtering the agenda."
+ :group 'org-faces)
+
+(defface org-time-grid ;Copied from `font-lock-variable-name-face'
+ '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
+ (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
+ (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))
+ "Face used for time grids."
+ :group 'org-faces)
+
+(defface org-agenda-current-time '((t (:inherit org-time-grid)))
+ "Face used to show the current time in the time grid."
+ :group 'org-faces)
+
+(defface org-agenda-diary '((t :inherit default))
+ "Face used for agenda entries that come from the Emacs diary."
+ :group 'org-faces)
+
+(defface org-agenda-calendar-event '((t :inherit default))
+ "Face used to show events and appointments in the agenda."
+ :group 'org-faces)
+
+(defface org-agenda-calendar-sexp '((t :inherit default))
+ "Face used to show events computed from a S-expression."
+ :group 'org-faces)
+
+(defconst org-level-faces
+ '(org-level-1 org-level-2 org-level-3 org-level-4
+ org-level-5 org-level-6 org-level-7 org-level-8))
+
+(defcustom org-n-level-faces (length org-level-faces)
+ "The number of different faces to be used for headlines.
+Org mode defines 8 different headline faces, so this can be at most 8.
+If it is less than 8, the level-1 face gets re-used for level N+1 etc."
+ :type 'integer
+ :group 'org-faces)
+
+(defcustom org-cycle-level-faces t
+ "Non-nil means level styles cycle after level `org-n-level-faces'.
+Then so level org-n-level-faces+1 is styled like level 1.
+If nil, then all levels >=org-n-level-faces are styled like
+level org-n-level-faces"
+ :group 'org-appearance
+ :group 'org-faces
+ :version "24.1"
+ :type 'boolean)
+
+(defface org-latex-and-related
+ (let ((font (cond ((assq :inherit custom-face-attributes)
+ '(:inherit underline))
+ (t '(:underline t)))))
+ `((((class grayscale) (background light))
+ (:foreground "DimGray" ,@font))
+ (((class grayscale) (background dark))
+ (:foreground "LightGray" ,@font))
+ (((class color) (background light))
+ (:foreground "SaddleBrown"))
+ (((class color) (background dark))
+ (:foreground "burlywood"))
+ (t (,@font))))
+ "Face used to highlight LaTeX data, entities and sub/superscript."
+ :group 'org-faces
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defface org-macro '((t :inherit org-latex-and-related))
+ "Face for macros."
+ :group 'org-faces
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defface org-tag-group '((t :inherit org-tag))
+ "Face for group tags."
+ :group 'org-faces
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defface org-mode-line-clock '((t (:inherit mode-line)))
+ "Face used for clock display in mode line."
+ :group 'org-faces)
+
+(defface org-mode-line-clock-overrun
+ '((t (:inherit mode-line :background "red")))
+ "Face used for clock display for overrun tasks in mode line."
+ :group 'org-faces)
+
+(provide 'org-faces)
+
+;;; org-faces.el ends here
diff --git a/lisp/org-feed.el b/lisp/org-feed.el
new file mode 100644
index 0000000..6ebe5ec
--- /dev/null
+++ b/lisp/org-feed.el
@@ -0,0 +1,713 @@
+;;; org-feed.el --- Add RSS feed items to Org files -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This module allows entries to be created and changed in an Org mode
+;; file triggered by items in an RSS feed. The basic functionality
+;; is geared toward simply adding new items found in a feed as
+;; outline nodes to an Org file. Using hooks, arbitrary actions can
+;; be triggered for new or changed items.
+;;
+;; Selecting feeds and target locations
+;; ------------------------------------
+;;
+;; This module is configured through a single variable, `org-feed-alist'.
+;; Here is an example, using a notes/tasks feed from reQall.com.
+;;
+;; (setq org-feed-alist
+;; '(("ReQall"
+;; "http://www.reqall.com/user/feeds/rss/a1b2c3....."
+;; "~/org/feeds.org" "ReQall Entries")
+;;
+;; With this setup, the command `M-x org-feed-update-all' will
+;; collect new entries in the feed at the given URL and create
+;; entries as subheadings under the "ReQall Entries" heading in the
+;; file "~/org/feeds.org". Each feed should normally have its own
+;; heading - however see the `:drawer' parameter.
+;;
+;; Besides these standard elements that need to be specified for each
+;; feed, keyword-value pairs can set additional options. For example,
+;; to de-select transitional entries with a title containing
+;;
+;; "reQall is typing what you said",
+;;
+;; you could use the `:filter' argument:
+;;
+;; (setq org-feed-alist
+;; '(("ReQall"
+;; "http://www.reqall.com/user/feeds/rss/a1b2c3....."
+;; "~/org/feeds.org" "ReQall Entries"
+;; :filter my-reqall-filter)))
+;;
+;; (defun my-reqall-filter (e)
+;; (if (string-match "reQall is typing what you said"
+;; (plist-get e :title))
+;; nil
+;; e))
+;;
+;; See the docstring for `org-feed-alist' for more details.
+;;
+;;
+;; Keeping track of previously added entries
+;; -----------------------------------------
+;;
+;; Since Org allows you to delete, archive, or move outline nodes,
+;; org-feed.el needs to keep track of which feed items have been handled
+;; before, so that they will not be handled again. For this, org-feed.el
+;; stores information in a special drawer, FEEDSTATUS, under the heading
+;; that received the input of the feed.
+;;
+;;
+;; Acknowledgments
+;; ---------------
+;;
+;; org-feed.el is based on ideas by Brad Bozarth who implemented a
+;; similar mechanism using shell and awk scripts.
+
+;;; Code:
+
+(require 'org)
+(require 'sha1)
+
+(declare-function url-retrieve-synchronously "url"
+ (url &optional silent inhibit-cookies timeout))
+(declare-function xml-node-children "xml" (node))
+(declare-function xml-get-children "xml" (node child-name))
+(declare-function xml-get-attribute "xml" (node attribute))
+(declare-function xml-get-attribute-or-nil "xml" (node attribute))
+(declare-function xml-substitute-special "xml" (string))
+
+(declare-function org-capture-escaped-% "org-capture" ())
+(declare-function org-capture-expand-embedded-elisp "org-capture" (&optional mark))
+(declare-function org-capture-inside-embedded-elisp-p "org-capture" ())
+
+(defgroup org-feed nil
+ "Options concerning RSS feeds as inputs for Org files."
+ :tag "Org Feed"
+ :group 'org)
+
+(defcustom org-feed-alist nil
+ "Alist specifying RSS feeds that should create inputs for Org.
+Each entry in this list specified an RSS feed tat should be queried
+to create inbox items in Org. Each entry is a list with the following items:
+
+name a custom name for this feed
+URL the Feed URL
+file the target Org file where entries should be listed, when
+ nil the target becomes the current buffer (may be an
+ indirect buffer) each time the feed update is invoked
+headline the headline under which entries should be listed
+
+Additional arguments can be given using keyword-value pairs. Many of these
+specify functions that receive one or a list of \"entries\" as their single
+argument. An entry is a property list that describes a feed item. The
+property list has properties for each field in the item, for example `:title'
+for the `<title>' field and `:pubDate' for the publication date. In addition,
+it contains the following properties:
+
+`:item-full-text' the full text in the <item> tag
+`:guid-permalink' t when the guid property is a permalink
+
+Here are the keyword-value pair allows in `org-feed-alist'.
+
+:drawer drawer-name
+ The name of the drawer for storing feed information. The default is
+ \"FEEDSTATUS\". Using different drawers for different feeds allows
+ several feeds to target the same inbox heading.
+
+:filter filter-function
+ A function to select interesting entries in the feed. It gets a single
+ entry as parameter. It should return the entry if it is relevant, or
+ nil if it is not.
+
+:template template-string
+ The default action on new items in the feed is to add them as children
+ under the headline for the feed. The template describes how the entry
+ should be formatted. If not given, it defaults to
+ `org-feed-default-template'.
+
+:formatter formatter-function
+ Instead of relying on a template, you may specify a function to format
+ the outline node to be inserted as a child. This function gets passed
+ a property list describing a single feed item, and it should return a
+ string that is a properly formatted Org outline node of level 1.
+
+:new-handler function
+ If adding new items as children to the outline is not what you want
+ to do with new items, define a handler function that is called with
+ a list of all new items in the feed, each one represented as a property
+ list. The handler should do what needs to be done, and org-feed will
+ mark all items given to this handler as \"handled\", i.e. they will not
+ be passed to this handler again in future readings of the feed.
+ When the handler is called, point will be at the feed headline.
+
+:changed-handler function
+ This function gets passed a list of all entries that have been
+ handled before, but are now still in the feed and have *changed*
+ since last handled (as evidenced by a different sha1 hash).
+ When the handler is called, point will be at the feed headline.
+
+:parse-feed function
+ This function gets passed a buffer, and should return a list
+ of entries, each being a property list containing the
+ `:guid' and `:item-full-text' keys. The default is
+ `org-feed-parse-rss-feed'; `org-feed-parse-atom-feed' is an
+ alternative.
+
+:parse-entry function
+ This function gets passed an entry as returned by the parse-feed
+ function, and should return the entry with interesting properties added.
+ The default is `org-feed-parse-rss-entry'; `org-feed-parse-atom-entry'
+ is an alternative."
+ :group 'org-feed
+ :type '(repeat
+ (list :value ("" "http://" "" "")
+ (string :tag "Name")
+ (string :tag "Feed URL")
+ (file :tag "File for inbox")
+ (string :tag "Headline for inbox")
+ (repeat :inline t
+ (choice
+ (list :inline t :tag "Filter"
+ (const :filter)
+ (symbol :tag "Filter Function"))
+ (list :inline t :tag "Template"
+ (const :template)
+ (string :tag "Template"))
+ (list :inline t :tag "Formatter"
+ (const :formatter)
+ (symbol :tag "Formatter Function"))
+ (list :inline t :tag "New items handler"
+ (const :new-handler)
+ (symbol :tag "Handler Function"))
+ (list :inline t :tag "Changed items"
+ (const :changed-handler)
+ (symbol :tag "Handler Function"))
+ (list :inline t :tag "Parse Feed"
+ (const :parse-feed)
+ (symbol :tag "Parse Feed Function"))
+ (list :inline t :tag "Parse Entry"
+ (const :parse-entry)
+ (symbol :tag "Parse Entry Function"))
+ )))))
+
+(defcustom org-feed-drawer "FEEDSTATUS"
+ "The name of the drawer for feed status information.
+Each feed may also specify its own drawer name using the `:drawer'
+parameter in `org-feed-alist'."
+ :group 'org-feed
+ :type '(string :tag "Drawer Name"))
+
+(defcustom org-feed-default-template "\n* %h\n %U\n %description\n %a\n"
+ "Template for the Org node created from RSS feed items.
+This is just the default, each feed can specify its own.
+Any fields from the feed item can be interpolated into the template with
+%name, for example %title, %description, %pubDate etc. In addition, the
+following special escapes are valid as well:
+
+%h The title, or the first line of the description
+%t The date as a stamp, either from <pubDate> (if present), or
+ the current date
+%T Date and time
+%u,%U Like %t,%T, but inactive time stamps
+%a A link, from <guid> if that is a permalink, else from <link>
+%(sexp) Evaluate elisp `(sexp)' and replace with the result, the simple
+ %-escapes above can be used as arguments, e.g. %(capitalize \\\"%h\\\")"
+ :group 'org-feed
+ :type '(string :tag "Template"))
+
+(defcustom org-feed-save-after-adding t
+ "Non-nil means save buffer after adding new feed items."
+ :group 'org-feed
+ :type 'boolean)
+
+(defcustom org-feed-retrieve-method 'url-retrieve-synchronously
+ "The method to be used to retrieve a feed URL.
+This can be `curl' or `wget' to call these external programs, or it can be
+an Emacs Lisp function that will return a buffer containing the content
+of the file pointed to by the URL."
+ :group 'org-feed
+ :type '(choice
+ (const :tag "Internally with url.el" url-retrieve-synchronously)
+ (const :tag "Externally with curl" curl)
+ (const :tag "Externally with wget" wget)
+ (function :tag "Function")))
+
+(defcustom org-feed-before-adding-hook nil
+ "Hook that is run before adding new feed items to a file.
+You might want to commit the file in its current state to version control,
+for example."
+ :group 'org-feed
+ :type 'hook)
+
+(defcustom org-feed-after-adding-hook nil
+ "Hook that is run after new items have been added to a file.
+Depending on `org-feed-save-after-adding', the buffer will already
+have been saved."
+ :group 'org-feed
+ :type 'hook)
+
+(defvar org-feed-buffer "*Org feed*"
+ "The buffer used to retrieve a feed.")
+
+;;;###autoload
+(defun org-feed-update-all ()
+ "Get inbox items from all feeds in `org-feed-alist'."
+ (interactive)
+ (let ((nfeeds (length org-feed-alist))
+ (nnew (apply '+ (mapcar 'org-feed-update org-feed-alist))))
+ (message "%s from %d %s"
+ (cond ((= nnew 0) "No new entries")
+ ((= nnew 1) "1 new entry")
+ (t (format "%d new entries" nnew)))
+ nfeeds
+ (if (= nfeeds 1) "feed" "feeds"))))
+
+;;;###autoload
+(defun org-feed-update (feed &optional retrieve-only)
+ "Get inbox items from FEED.
+FEED can be a string with an association in `org-feed-alist', or
+it can be a list structured like an entry in `org-feed-alist'."
+ (interactive (list (org-completing-read "Feed name: " org-feed-alist)))
+ (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
+ (unless feed
+ (error "No such feed in `org-feed-alist"))
+ (catch 'exit
+ (let ((name (car feed))
+ (url (nth 1 feed))
+ (file (or (nth 2 feed) (buffer-file-name (or (buffer-base-buffer)
+ (current-buffer)))))
+ (headline (nth 3 feed))
+ (filter (nth 1 (memq :filter feed)))
+ (formatter (nth 1 (memq :formatter feed)))
+ (new-handler (nth 1 (memq :new-handler feed)))
+ (changed-handler (nth 1 (memq :changed-handler feed)))
+ (template (or (nth 1 (memq :template feed))
+ org-feed-default-template))
+ (drawer (or (nth 1 (memq :drawer feed))
+ org-feed-drawer))
+ (parse-feed (or (nth 1 (memq :parse-feed feed))
+ 'org-feed-parse-rss-feed))
+ (parse-entry (or (nth 1 (memq :parse-entry feed))
+ 'org-feed-parse-rss-entry))
+ feed-buffer inbox-pos new-formatted
+ entries old-status status new changed guid-alist guid olds)
+ (setq feed-buffer (org-feed-get-feed url))
+ (unless (and feed-buffer (bufferp (get-buffer feed-buffer)))
+ (error "Cannot get feed %s" name))
+ (when retrieve-only
+ (throw 'exit feed-buffer))
+ (setq entries (funcall parse-feed feed-buffer))
+ (ignore-errors (kill-buffer feed-buffer))
+ (save-excursion
+ (save-window-excursion
+ (setq inbox-pos (org-feed-goto-inbox-internal file headline))
+ (setq old-status (org-feed-read-previous-status inbox-pos drawer))
+ ;; Add the "handled" status to the appropriate entries
+ (setq entries (mapcar (lambda (e)
+ (setq e
+ (plist-put e :handled
+ (nth 1 (assoc
+ (plist-get e :guid)
+ old-status)))))
+ entries))
+ ;; Find out which entries are new and which are changed
+ (dolist (e entries)
+ (if (not (plist-get e :handled))
+ (push e new)
+ (setq olds (nth 2 (assoc (plist-get e :guid) old-status)))
+ (if (and olds
+ (not (string= (sha1
+ (plist-get e :item-full-text))
+ olds)))
+ (push e changed))))
+
+ ;; Parse the relevant entries fully
+ (setq new (mapcar parse-entry new)
+ changed (mapcar parse-entry changed))
+
+ ;; Run the filter
+ (when filter
+ (setq new (delq nil (mapcar filter new))
+ changed (delq nil (mapcar filter new))))
+
+ (when (not (or new changed))
+ (message "No new items in feed %s" name)
+ (throw 'exit 0))
+
+ ;; Get alist based on guid, to look up entries
+ (setq guid-alist
+ (append
+ (mapcar (lambda (e) (list (plist-get e :guid) e)) new)
+ (mapcar (lambda (e) (list (plist-get e :guid) e)) changed)))
+
+ ;; Construct the new status
+ (setq status
+ (mapcar
+ (lambda (e)
+ (setq guid (plist-get e :guid))
+ (list guid
+ ;; things count as handled if we handle them now,
+ ;; or if they were handled previously
+ (if (assoc guid guid-alist) t (plist-get e :handled))
+ ;; A hash, to detect changes
+ (sha1 (plist-get e :item-full-text))))
+ entries))
+
+ ;; Handle new items in the feed
+ (when new
+ (if new-handler
+ (progn
+ (goto-char inbox-pos)
+ (funcall new-handler new))
+ ;; No custom handler, do the default adding
+ ;; Format the new entries into an alist with GUIDs in the car
+ (setq new-formatted
+ (mapcar
+ (lambda (e) (org-feed-format-entry e template formatter))
+ new)))
+
+ ;; Insert the new items
+ (org-feed-add-items inbox-pos new-formatted))
+
+ ;; Handle changed items in the feed
+ (when (and changed-handler changed)
+ (goto-char inbox-pos)
+ (funcall changed-handler changed))
+
+ ;; Write the new status
+ ;; We do this only now, in case something goes wrong above, so
+ ;; that would would end up with a status that does not reflect
+ ;; which items truely have been handled
+ (org-feed-write-status inbox-pos drawer status)
+
+ ;; Normalize the visibility of the inbox tree
+ (goto-char inbox-pos)
+ (outline-hide-subtree)
+ (org-show-children)
+ (org-cycle-hide-drawers 'children)
+
+ ;; Hooks and messages
+ (when org-feed-save-after-adding (save-buffer))
+ (message "Added %d new item%s from feed %s to file %s, heading %s"
+ (length new) (if (> (length new) 1) "s" "")
+ name
+ (file-name-nondirectory file) headline)
+ (run-hooks 'org-feed-after-adding-hook)
+ (length new))))))
+
+;;;###autoload
+(defun org-feed-goto-inbox (feed)
+ "Go to the inbox that captures the feed named FEED."
+ (interactive
+ (list (if (= (length org-feed-alist) 1)
+ (car org-feed-alist)
+ (org-completing-read "Feed name: " org-feed-alist))))
+ (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
+ (unless feed
+ (error "No such feed in `org-feed-alist"))
+ (org-feed-goto-inbox-internal (nth 2 feed) (nth 3 feed)))
+
+;;;###autoload
+(defun org-feed-show-raw-feed (feed)
+ "Show the raw feed buffer of a feed."
+ (interactive
+ (list (if (= (length org-feed-alist) 1)
+ (car org-feed-alist)
+ (org-completing-read "Feed name: " org-feed-alist))))
+ (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
+ (unless feed
+ (error "No such feed in `org-feed-alist"))
+ (pop-to-buffer-same-window
+ (org-feed-update feed 'retrieve-only))
+ (goto-char (point-min)))
+
+(defun org-feed-goto-inbox-internal (file heading)
+ "Find or create HEADING in FILE.
+Switch to that buffer, and return the position of that headline."
+ (find-file file)
+ (widen)
+ (goto-char (point-min))
+ (if (re-search-forward
+ (concat "^\\*+[ \t]+" heading "[ \t]*\\(:.*?:[ \t]*\\)?$")
+ nil t)
+ (goto-char (match-beginning 0))
+ (goto-char (point-max))
+ (insert "\n\n* " heading "\n\n")
+ (org-back-to-heading t))
+ (point))
+
+(defun org-feed-read-previous-status (pos drawer)
+ "Get the alist of old GUIDs from the entry at POS.
+This will find DRAWER and extract the alist."
+ (save-excursion
+ (goto-char pos)
+ (let ((end (save-excursion (org-end-of-subtree t t))))
+ (if (re-search-forward
+ (concat "^[ \t]*:" drawer ":[ \t]*\n\\([^\000]*?\\)\n[ \t]*:END:")
+ end t)
+ (read (match-string 1))
+ nil))))
+
+(defun org-feed-write-status (pos drawer status)
+ "Write the feed STATUS to DRAWER in entry at POS."
+ (save-excursion
+ (goto-char pos)
+ (let ((end (save-excursion (org-end-of-subtree t t))))
+ (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*\n")
+ end t)
+ (progn
+ (goto-char (match-end 0))
+ (delete-region (point)
+ (save-excursion
+ (and (re-search-forward "^[ \t]*:END:" nil t)
+ (match-beginning 0)))))
+ (outline-next-heading)
+ (insert " :" drawer ":\n :END:\n")
+ (beginning-of-line 0))
+ (insert (pp-to-string status)))))
+
+(defun org-feed-add-items (pos entries)
+ "Add the formatted items to the headline as POS."
+ (let (entry level)
+ (save-excursion
+ (goto-char pos)
+ (unless (looking-at org-complex-heading-regexp)
+ (error "Wrong position"))
+ (setq level (org-get-valid-level (length (match-string 1)) 1))
+ (org-end-of-subtree t t)
+ (skip-chars-backward " \t\n")
+ (beginning-of-line 2)
+ (setq pos (point))
+ (while (setq entry (pop entries))
+ (org-paste-subtree level entry 'yank))
+ (org-mark-ring-push pos))))
+
+(defun org-feed-format-entry (entry template formatter)
+ "Format ENTRY so that it can be inserted into an Org file.
+ENTRY is a property list. This function adds a `:formatted-for-org' property
+and returns the full property list.
+If that property is already present, nothing changes."
+ (require 'org-capture)
+ (if formatter (funcall formatter entry)
+ (let* ((dlines
+ (org-split-string (or (plist-get entry :description) "???")
+ "\n"))
+ (time (or (if (plist-get entry :pubDate)
+ (org-read-date t t (plist-get entry :pubDate)))
+ (current-time)))
+ (v-h (or (plist-get entry :title) (car dlines) "???"))
+ (v-t (format-time-string (org-time-stamp-format nil nil) time))
+ (v-T (format-time-string (org-time-stamp-format t nil) time))
+ (v-u (format-time-string (org-time-stamp-format nil t) time))
+ (v-U (format-time-string (org-time-stamp-format t t) time))
+ (v-a (let ((tmp (or (and (plist-get entry :guid-permalink)
+ (plist-get entry :guid))
+ (plist-get entry :link))))
+ (if tmp (format "[[%s]]\n" tmp ) ""))))
+ (with-temp-buffer
+ (insert template)
+ (goto-char (point-min))
+
+ ;; Mark %() embedded elisp for later evaluation.
+ (org-capture-expand-embedded-elisp 'mark)
+
+ ;; Simple %-escapes. `org-capture-escaped-%' may modify
+ ;; buffer and cripple match-data. Use markers instead.
+ (while (re-search-forward "%\\([a-zA-Z]+\\)" nil t)
+ (let ((key (match-string 1))
+ (beg (copy-marker (match-beginning 0)))
+ (end (copy-marker (match-end 0))))
+ (unless (org-capture-escaped-%)
+ (delete-region beg end)
+ (set-marker beg nil)
+ (set-marker end nil)
+ (let ((replacement
+ (pcase key
+ ("h" v-h)
+ ("t" v-t)
+ ("T" v-T)
+ ("u" v-u)
+ ("U" v-U)
+ ("a" v-a)
+ (name
+ (let ((v (plist-get entry (intern (concat ":" name)))))
+ (save-excursion
+ (save-match-data
+ (beginning-of-line)
+ (if (looking-at
+ (concat "^\\([ \t]*\\)%" name "[ \t]*$"))
+ (org-feed-make-indented-block
+ v (org-get-indentation))
+ v))))))))
+ (when replacement
+ (insert
+ ;; Escape string delimiters within embedded lisp.
+ (if (org-capture-inside-embedded-elisp-p)
+ (replace-regexp-in-string "\"" "\\\\\"" replacement)
+ replacement)))))))
+
+ ;; %() embedded elisp
+ (org-capture-expand-embedded-elisp)
+
+ (decode-coding-string
+ (buffer-string) (detect-coding-region (point-min) (point-max) t))))))
+
+(defun org-feed-make-indented-block (s n)
+ "Add indentation of N spaces to a multiline string S."
+ (if (not (string-match "\n" s))
+ s
+ (mapconcat 'identity
+ (org-split-string s "\n")
+ (concat "\n" (make-string n ?\ )))))
+
+(defun org-feed-skip-http-headers (buffer)
+ "Remove HTTP headers from BUFFER, and return it.
+Assumes headers are indeed present!"
+ (with-current-buffer buffer
+ (widen)
+ (goto-char (point-min))
+ (search-forward "\n\n")
+ (delete-region (point-min) (point))
+ buffer))
+
+(defun org-feed-get-feed (url)
+ "Get the RSS feed file at URL and return the buffer."
+ (cond
+ ((eq org-feed-retrieve-method 'url-retrieve-synchronously)
+ (org-feed-skip-http-headers (url-retrieve-synchronously url)))
+ ((eq org-feed-retrieve-method 'curl)
+ (ignore-errors (kill-buffer org-feed-buffer))
+ (call-process "curl" nil org-feed-buffer nil "--silent" url)
+ org-feed-buffer)
+ ((eq org-feed-retrieve-method 'wget)
+ (ignore-errors (kill-buffer org-feed-buffer))
+ (call-process "wget" nil org-feed-buffer nil "-q" "-O" "-" url)
+ org-feed-buffer)
+ ((functionp org-feed-retrieve-method)
+ (funcall org-feed-retrieve-method url))))
+
+(defun org-feed-parse-rss-feed (buffer)
+ "Parse BUFFER for RSS feed entries.
+Returns a list of entries, with each entry a property list,
+containing the properties `:guid' and `:item-full-text'."
+ (require 'xml)
+ (let ((case-fold-search t)
+ entries beg end item guid entry)
+ (with-current-buffer buffer
+ (widen)
+ (goto-char (point-min))
+ (while (re-search-forward "<item\\>.*?>" nil t)
+ (setq beg (point)
+ end (and (re-search-forward "</item>" nil t)
+ (match-beginning 0)))
+ (setq item (buffer-substring beg end)
+ guid (if (string-match "<guid\\>.*?>\\(.*?\\)</guid>" item)
+ (xml-substitute-special (match-string-no-properties 1 item))))
+ (setq entry (list :guid guid :item-full-text item))
+ (push entry entries)
+ (widen)
+ (goto-char end))
+ (nreverse entries))))
+
+(defun org-feed-parse-rss-entry (entry)
+ "Parse the `:item-full-text' field for xml tags and create new properties."
+ (require 'xml)
+ (with-temp-buffer
+ (insert (plist-get entry :item-full-text))
+ (goto-char (point-min))
+ (while (re-search-forward "<\\([a-zA-Z]+\\>\\).*?>\\([^\000]*?\\)</\\1>"
+ nil t)
+ (setq entry (plist-put entry
+ (intern (concat ":" (match-string 1)))
+ (xml-substitute-special (match-string 2)))))
+ (goto-char (point-min))
+ (unless (re-search-forward "isPermaLink[ \t]*=[ \t]*\"false\"" nil t)
+ (setq entry (plist-put entry :guid-permalink t))))
+ entry)
+
+(defun org-feed-parse-atom-feed (buffer)
+ "Parse BUFFER for Atom feed entries.
+Returns a list of entries, with each entry a property list,
+containing the properties `:guid' and `:item-full-text'.
+
+The `:item-full-text' property actually contains the sexp
+formatted as a string, not the original XML data."
+ (require 'xml)
+ (with-current-buffer buffer
+ (widen)
+ (let ((feed (car (xml-parse-region (point-min) (point-max)))))
+ (mapcar
+ (lambda (entry)
+ (list
+ :guid (car (xml-node-children (car (xml-get-children entry 'id))))
+ :item-full-text (prin1-to-string entry)))
+ (xml-get-children feed 'entry)))))
+
+(defun org-feed-parse-atom-entry (entry)
+ "Parse the `:item-full-text' as a sexp and create new properties."
+ (let ((xml (car (read-from-string (plist-get entry :item-full-text)))))
+ ;; Get first <link href='foo'/>.
+ (setq entry (plist-put entry :link
+ (xml-get-attribute
+ (car (xml-get-children xml 'link))
+ 'href)))
+ ;; Add <title/> as :title.
+ (setq entry (plist-put entry :title
+ (xml-substitute-special
+ (car (xml-node-children
+ (car (xml-get-children xml 'title)))))))
+ (let* ((content (car (xml-get-children xml 'content)))
+ (type (xml-get-attribute-or-nil content 'type)))
+ (when content
+ (cond
+ ((string= type "text")
+ ;; We like plain text.
+ (setq entry (plist-put entry :description
+ (xml-substitute-special
+ (car (xml-node-children content))))))
+ ((string= type "html")
+ ;; TODO: convert HTML to Org markup.
+ (setq entry (plist-put entry :description
+ (xml-substitute-special
+ (car (xml-node-children content))))))
+ ((string= type "xhtml")
+ ;; TODO: convert XHTML to Org markup.
+ (setq entry (plist-put entry :description
+ (prin1-to-string
+ (xml-node-children content)))))
+ (t
+ (setq entry (plist-put entry :description
+ (format-message
+ "Unknown `%s' content." type)))))))
+ entry))
+
+(provide 'org-feed)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-feed.el ends here
diff --git a/lisp/org-footnote.el b/lisp/org-footnote.el
new file mode 100644
index 0000000..af03fbf
--- /dev/null
+++ b/lisp/org-footnote.el
@@ -0,0 +1,1005 @@
+;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code dealing with footnotes in Org mode.
+
+;;; Code:
+
+;;;; Declarations
+
+(require 'cl-lib)
+(require 'org-macs)
+(require 'org-compat)
+
+(declare-function org-at-comment-p "org" ())
+(declare-function org-at-heading-p "org" (&optional ignored))
+(declare-function org-back-over-empty-lines "org" ())
+(declare-function org-edit-footnote-reference "org-src" ())
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-class "org-element" (datum &optional parent))
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-lineage "org-element" (blob &optional types with-self))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
+(declare-function org-fill-paragraph "org" (&optional justify))
+(declare-function org-in-block-p "org" (names))
+(declare-function org-in-regexp "org" (re &optional nlines visually))
+(declare-function org-in-verbatim-emphasis "org" ())
+(declare-function org-inside-LaTeX-fragment-p "org" ())
+(declare-function org-inside-latex-macro-p "org" ())
+(declare-function org-mark-ring-push "org" (&optional pos buffer))
+(declare-function org-show-context "org" (&optional key))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function outline-next-heading "outline")
+
+(defvar electric-indent-mode)
+(defvar org-blank-before-new-entry) ; defined in org.el
+(defvar org-bracket-link-regexp) ; defined in org.el
+(defvar org-complex-heading-regexp) ; defined in org.el
+(defvar org-odd-levels-only) ; defined in org.el
+(defvar org-outline-regexp) ; defined in org.el
+(defvar org-outline-regexp-bol) ; defined in org.el
+
+
+;;;; Constants
+
+(defconst org-footnote-re
+ "\\[fn:\\(?:\\(?1:[-_[:word:]]+\\)?\\(:\\)\\|\\(?1:[-_[:word:]]+\\)\\]\\)"
+ "Regular expression for matching footnotes.
+Match group 1 contains footnote's label. It is nil for anonymous
+footnotes. Match group 2 is non-nil only when footnote is
+inline, i.e., it contains its own definition.")
+
+(defconst org-footnote-definition-re "^\\[fn:\\([-_[:word:]]+\\)\\]"
+ "Regular expression matching the definition of a footnote.
+Match group 1 contains definition's label.")
+
+(defconst org-footnote-forbidden-blocks '("comment" "example" "export" "src")
+ "Names of blocks where footnotes are not allowed.")
+
+
+;;;; Customization
+
+(defgroup org-footnote nil
+ "Footnotes in Org mode."
+ :tag "Org Footnote"
+ :group 'org)
+
+(defcustom org-footnote-section "Footnotes"
+ "Outline heading containing footnote definitions.
+
+This can be nil, to place footnotes locally at the end of the
+current outline node. If can also be the name of a special
+outline heading under which footnotes should be put.
+
+This variable defines the place where Org puts the definition
+automatically, i.e. when creating the footnote, and when sorting
+the notes. However, by hand you may place definitions
+*anywhere*.
+
+If this is a string, during export, all subtrees starting with
+this heading will be ignored.
+
+If you don't use the customize interface to change this variable,
+you will need to run the following command after the change:
+
+ `\\[universal-argument] \\[org-element-cache-reset]'"
+ :group 'org-footnote
+ :initialize 'custom-initialize-default
+ :set (lambda (var val)
+ (set var val)
+ (when (fboundp 'org-element-cache-reset)
+ (org-element-cache-reset 'all)))
+ :type '(choice
+ (string :tag "Collect footnotes under heading")
+ (const :tag "Define footnotes locally" nil)))
+
+(defcustom org-footnote-define-inline nil
+ "Non-nil means define footnotes inline, at reference location.
+When nil, footnotes will be defined in a special section near
+the end of the document. When t, the [fn:label:definition] notation
+will be used to define the footnote at the reference position."
+ :group 'org-footnote
+ :type 'boolean)
+
+(defcustom org-footnote-auto-label t
+ "Non-nil means define automatically new labels for footnotes.
+Possible values are:
+
+nil Prompt the user for each label.
+t Create unique labels of the form [fn:1], [fn:2], etc.
+confirm Like t, but let the user edit the created value.
+ The label can be removed from the minibuffer to create
+ an anonymous footnote.
+random Automatically generate a unique, random label."
+ :group 'org-footnote
+ :type '(choice
+ (const :tag "Prompt for label" nil)
+ (const :tag "Create automatic [fn:N]" t)
+ (const :tag "Offer automatic [fn:N] for editing" confirm)
+ (const :tag "Create a random label" random)))
+
+(defcustom org-footnote-auto-adjust nil
+ "Non-nil means automatically adjust footnotes after insert/delete.
+When this is t, after each insertion or deletion of a footnote,
+simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
+If you want to have just sorting or just renumbering, set this variable
+to `sort' or `renumber'.
+
+The main values of this variable can be set with in-buffer options:
+
+#+STARTUP: fnadjust
+#+STARTUP: nofnadjust"
+ :group 'org-footnote
+ :type '(choice
+ (const :tag "No adjustment" nil)
+ (const :tag "Renumber" renumber)
+ (const :tag "Sort" sort)
+ (const :tag "Renumber and Sort" t)))
+
+(defcustom org-footnote-fill-after-inline-note-extraction nil
+ "Non-nil means fill paragraphs after extracting footnotes.
+When extracting inline footnotes, the lengths of lines can change a lot.
+When this option is set, paragraphs from which an inline footnote has been
+extracted will be filled again."
+ :group 'org-footnote
+ :type 'boolean)
+
+
+;;;; Predicates
+
+(defun org-footnote-in-valid-context-p ()
+ "Is point in a context where footnotes are allowed?"
+ (save-match-data
+ (not (or (org-at-comment-p)
+ (org-inside-LaTeX-fragment-p)
+ ;; Avoid literal example.
+ (org-in-verbatim-emphasis)
+ (save-excursion
+ (beginning-of-line)
+ (looking-at "[ \t]*:[ \t]+"))
+ ;; Avoid forbidden blocks.
+ (org-in-block-p org-footnote-forbidden-blocks)))))
+
+(defun org-footnote-at-reference-p ()
+ "Is the cursor at a footnote reference?
+
+If so, return a list containing its label, beginning and ending
+positions, and the definition, when inlined."
+ (when (and (org-footnote-in-valid-context-p)
+ (or (looking-at org-footnote-re)
+ (org-in-regexp org-footnote-re)
+ (save-excursion (re-search-backward org-footnote-re nil t)))
+ (/= (match-beginning 0) (line-beginning-position)))
+ (let* ((beg (match-beginning 0))
+ (label (match-string-no-properties 1))
+ ;; Inline footnotes don't end at (match-end 0) as
+ ;; `org-footnote-re' stops just after the second colon.
+ ;; Find the real ending with `scan-sexps', so Org doesn't
+ ;; get fooled by unrelated closing square brackets.
+ (end (ignore-errors (scan-sexps beg 1))))
+ ;; Point is really at a reference if it's located before true
+ ;; ending of the footnote.
+ (when (and end
+ (< (point) end)
+ ;; Verify match isn't a part of a link.
+ (not (save-excursion
+ (goto-char beg)
+ (let ((linkp
+ (save-match-data
+ (org-in-regexp org-bracket-link-regexp))))
+ (and linkp (< (point) (cdr linkp))))))
+ ;; Verify point doesn't belong to a LaTeX macro.
+ (not (org-inside-latex-macro-p)))
+ (list label beg end
+ ;; Definition: ensure this is an inline footnote first.
+ (and (match-end 2)
+ (org-trim
+ (buffer-substring-no-properties
+ (match-end 0) (1- end)))))))))
+
+(defun org-footnote-at-definition-p ()
+ "Is point within a footnote definition?
+
+This matches only pure definitions like [1] or [fn:name] at the
+beginning of a line. It does not match references like
+\[fn:name:definition], where the footnote text is included and
+defined locally.
+
+The return value will be nil if not at a footnote definition, and
+a list with label, start, end and definition of the footnote
+otherwise."
+ (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
+ (save-excursion
+ (end-of-line)
+ ;; Footnotes definitions are separated by new headlines, another
+ ;; footnote definition or 2 blank lines.
+ (let ((lim (save-excursion
+ (re-search-backward
+ (concat org-outline-regexp-bol
+ "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t))))
+ (when (re-search-backward org-footnote-definition-re lim t)
+ (let ((label (match-string-no-properties 1))
+ (beg (match-beginning 0))
+ (beg-def (match-end 0))
+ (end (if (progn
+ (end-of-line)
+ (re-search-forward
+ (concat org-outline-regexp-bol "\\|"
+ org-footnote-definition-re "\\|"
+ "^\\([ \t]*\n\\)\\{2,\\}") nil 'move))
+ (match-beginning 0)
+ (point))))
+ (list label beg end
+ (org-trim (buffer-substring-no-properties beg-def end)))))))))
+
+
+;;;; Internal functions
+
+(defun org-footnote--allow-reference-p ()
+ "Non-nil when a footnote reference can be inserted at point."
+ ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
+ ;; more accurate and usually faster, except in some corner cases.
+ ;; It may replace it after doing proper benchmarks as it would be
+ ;; used in fontification.
+ (unless (bolp)
+ (let* ((context (org-element-context))
+ (type (org-element-type context)))
+ (cond
+ ;; No footnote reference in attributes.
+ ((let ((post (org-element-property :post-affiliated context)))
+ (and post (< (point) post)))
+ nil)
+ ;; Paragraphs and blank lines at top of document are fine.
+ ((memq type '(nil paragraph)))
+ ;; So are contents of verse blocks.
+ ((eq type 'verse-block)
+ (and (>= (point) (org-element-property :contents-begin context))
+ (< (point) (org-element-property :contents-end context))))
+ ;; In an headline or inlinetask, point must be either on the
+ ;; heading itself or on the blank lines below.
+ ((memq type '(headline inlinetask))
+ (or (not (org-at-heading-p))
+ (and (save-excursion
+ (beginning-of-line)
+ (and (let ((case-fold-search t))
+ (not (looking-at-p "\\*+ END[ \t]*$")))
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))))
+ (match-beginning 4)
+ (>= (point) (match-beginning 4))
+ (or (not (match-beginning 5))
+ (< (point) (match-beginning 5))))))
+ ;; White spaces after an object or blank lines after an element
+ ;; are OK.
+ ((>= (point)
+ (save-excursion (goto-char (org-element-property :end context))
+ (skip-chars-backward " \r\t\n")
+ (if (eq (org-element-class context) 'object) (point)
+ (1+ (line-beginning-position 2))))))
+ ;; Other elements are invalid.
+ ((eq (org-element-class context) 'element) nil)
+ ;; Just before object is fine.
+ ((= (point) (org-element-property :begin context)))
+ ;; Within recursive object too, but not in a link.
+ ((eq type 'link) nil)
+ ((let ((cbeg (org-element-property :contents-begin context))
+ (cend (org-element-property :contents-end context)))
+ (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
+
+(defun org-footnote--clear-footnote-section ()
+ "Remove all footnote sections in buffer and create a new one.
+New section is created at the end of the buffer, before any file
+local variable definition. Leave point within the new section."
+ (when org-footnote-section
+ (goto-char (point-min))
+ (let ((regexp
+ (format "^\\*+ +%s[ \t]*$"
+ (regexp-quote org-footnote-section))))
+ (while (re-search-forward regexp nil t)
+ (delete-region
+ (match-beginning 0)
+ (progn (org-end-of-subtree t t)
+ (if (not (eobp)) (point)
+ (org-footnote--goto-local-insertion-point)
+ (skip-chars-forward " \t\n")
+ (if (eobp) (point) (line-beginning-position)))))))
+ (goto-char (point-max))
+ (org-footnote--goto-local-insertion-point)
+ (when (and (cdr (assq 'heading org-blank-before-new-entry))
+ (zerop (save-excursion (org-back-over-empty-lines))))
+ (insert "\n"))
+ (insert "* " org-footnote-section "\n")))
+
+(defun org-footnote--set-label (label)
+ "Set label of footnote at point to string LABEL.
+Assume point is at the beginning of the reference or definition
+to rename."
+ (forward-char 4)
+ (cond ((eq (char-after) ?:) (insert label))
+ ((looking-at "\\([-_[:word:]]+\\)") (replace-match label nil nil nil 1))
+ (t nil)))
+
+(defun org-footnote--collect-references (&optional anonymous)
+ "Collect all labelled footnote references in current buffer.
+
+Return an alist where associations follow the pattern
+
+ (LABEL MARKER TOP-LEVEL SIZE)
+
+with
+
+ LABEL the label of the of the definition,
+ MARKER a marker pointing to its beginning,
+ TOP-LEVEL a boolean, nil when the footnote is contained within
+ another one,
+ SIZE the length of the inline definition, in characters,
+ or nil for non-inline references.
+
+When optional ANONYMOUS is non-nil, also collect anonymous
+references. In such cases, LABEL is nil.
+
+References are sorted according to a deep-reading order."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((regexp (if anonymous org-footnote-re "\\[fn:[-_[:word:]]+[]:]"))
+ references nested)
+ (save-excursion
+ (while (re-search-forward regexp nil t)
+ ;; Ignore definitions.
+ (unless (and (eq (char-before) ?\])
+ (= (line-beginning-position) (match-beginning 0)))
+ ;; Ensure point is within the reference before parsing it.
+ (backward-char)
+ (let ((object (org-element-context)))
+ (when (eq (org-element-type object) 'footnote-reference)
+ (let* ((label (org-element-property :label object))
+ (begin (org-element-property :begin object))
+ (size
+ (and (eq (org-element-property :type object) 'inline)
+ (- (org-element-property :contents-end object)
+ (org-element-property :contents-begin object)))))
+ (let ((d (org-element-lineage object '(footnote-definition))))
+ (push (list label (copy-marker begin) (not d) size)
+ references)
+ (when d
+ ;; Nested references are stored in alist NESTED.
+ ;; Associations there follow the pattern
+ ;;
+ ;; (DEFINITION-LABEL . REFERENCES)
+ (let* ((def-label (org-element-property :label d))
+ (labels (assoc def-label nested)))
+ (if labels (push label (cdr labels))
+ (push (list def-label label) nested)))))))))))
+ ;; Sort the list of references. Nested footnotes have priority
+ ;; over top-level ones.
+ (letrec ((ordered nil)
+ (add-reference
+ (lambda (ref allow-nested)
+ (when (or allow-nested (nth 2 ref))
+ (push ref ordered)
+ (dolist (r (mapcar (lambda (l) (assoc l references))
+ (reverse
+ (cdr (assoc (nth 0 ref) nested)))))
+ (funcall add-reference r t))))))
+ (dolist (r (reverse references) (nreverse ordered))
+ (funcall add-reference r nil))))))
+
+(defun org-footnote--collect-definitions (&optional delete)
+ "Collect all footnote definitions in current buffer.
+
+Return an alist where associations follow the pattern
+
+ (LABEL . DEFINITION)
+
+with LABEL and DEFINITION being, respectively, the label and the
+definition of the footnote, as strings.
+
+When optional argument DELETE is non-nil, delete the definition
+while collecting them."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let (definitions seen)
+ (while (re-search-forward org-footnote-definition-re nil t)
+ (backward-char)
+ (let ((element (org-element-at-point)))
+ (let ((label (org-element-property :label element)))
+ (when (and (eq (org-element-type element) 'footnote-definition)
+ (not (member label seen)))
+ (push label seen)
+ (let* ((beg (progn
+ (goto-char (org-element-property :begin element))
+ (skip-chars-backward " \r\t\n")
+ (if (bobp) (point) (line-beginning-position 2))))
+ (end (progn
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2)))
+ (def (org-trim (buffer-substring-no-properties beg end))))
+ (push (cons label def) definitions)
+ (when delete (delete-region beg end)))))))
+ definitions)))
+
+(defun org-footnote--goto-local-insertion-point ()
+ "Find insertion point for footnote, just before next outline heading.
+Assume insertion point is within currently accessible part of the buffer."
+ (org-with-limited-levels (outline-next-heading))
+ ;; Skip file local variables. See `modify-file-local-variable'.
+ (when (eobp)
+ (let ((case-fold-search t))
+ (re-search-backward "^[ \t]*# +Local Variables:"
+ (max (- (point-max) 3000) (point-min))
+ t)))
+ (skip-chars-backward " \t\n")
+ (forward-line)
+ (unless (bolp) (insert "\n")))
+
+
+;;;; Navigation
+
+(defun org-footnote-get-next-reference (&optional label backward limit)
+ "Return complete reference of the next footnote.
+
+If LABEL is provided, get the next reference of that footnote. If
+BACKWARD is non-nil, find previous reference instead. LIMIT is
+the buffer position bounding the search.
+
+Return value is a list like those provided by `org-footnote-at-reference-p'.
+If no footnote is found, return nil."
+ (save-excursion
+ (let* ((label-fmt (if label (format "\\[fn:%s[]:]" label) org-footnote-re)))
+ (catch 'exit
+ (while t
+ (unless (funcall (if backward #'re-search-backward #'re-search-forward)
+ label-fmt limit t)
+ (throw 'exit nil))
+ (unless backward (backward-char))
+ (let ((ref (org-footnote-at-reference-p)))
+ (when ref (throw 'exit ref))))))))
+
+(defun org-footnote-next-reference-or-definition (limit)
+ "Move point to next footnote reference or definition.
+
+LIMIT is the buffer position bounding the search.
+
+Return value is a list like those provided by
+`org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
+If no footnote is found, return nil."
+ (let* (ref (origin (point)))
+ (catch 'exit
+ (while t
+ (unless (re-search-forward org-footnote-re limit t)
+ (goto-char origin)
+ (throw 'exit nil))
+ ;; Beware: with non-inline footnotes point will be just after
+ ;; the closing square bracket.
+ (backward-char)
+ (cond
+ ((setq ref (org-footnote-at-reference-p))
+ (throw 'exit ref))
+ ;; Definition: also grab the last square bracket, matched in
+ ;; `org-footnote-re' for non-inline footnotes.
+ ((save-match-data (org-footnote-at-definition-p))
+ (let ((end (match-end 0)))
+ (throw 'exit
+ (list nil (match-beginning 0)
+ (if (eq (char-before end) ?\]) end (1+ end)))))))))))
+
+(defun org-footnote-goto-definition (label &optional location)
+ "Move point to the definition of the footnote LABEL.
+
+LOCATION, when non-nil specifies the buffer position of the
+definition.
+
+Throw an error if there is no definition or if it cannot be
+reached from current narrowed part of buffer. Return a non-nil
+value if point was successfully moved."
+ (interactive "sLabel: ")
+ (let* ((label (org-footnote-normalize-label label))
+ (def-start (or location (nth 1 (org-footnote-get-definition label)))))
+ (cond
+ ((not def-start)
+ (user-error "Cannot find definition of footnote %s" label))
+ ((or (> def-start (point-max)) (< def-start (point-min)))
+ (user-error "Definition is outside narrowed part of buffer")))
+ (org-mark-ring-push)
+ (goto-char def-start)
+ (looking-at (format "\\[fn:%s[]:] ?" (regexp-quote label)))
+ (goto-char (match-end 0))
+ (org-show-context 'link-search)
+ (when (derived-mode-p 'org-mode)
+ (message "%s" (substitute-command-keys
+ "Edit definition and go back with \
+`\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
+ t))
+
+(defun org-footnote-goto-previous-reference (label)
+ "Find the first closest (to point) reference of footnote with label LABEL."
+ (interactive "sLabel: ")
+ (org-mark-ring-push)
+ (let ((label (org-footnote-normalize-label label))
+ ref)
+ (save-excursion
+ (setq ref (or (org-footnote-get-next-reference label t)
+ (org-footnote-get-next-reference label)
+ (save-restriction
+ (widen)
+ (or
+ (org-footnote-get-next-reference label t)
+ (org-footnote-get-next-reference label))))))
+ (if (not ref)
+ (error "Cannot find reference of footnote %s" label)
+ (goto-char (nth 1 ref))
+ (org-show-context 'link-search))))
+
+
+;;;; Getters
+
+(defun org-footnote-normalize-label (label)
+ "Return LABEL without \"fn:\" prefix.
+If LABEL is the empty string or constituted of white spaces only,
+return nil instead."
+ (pcase (org-trim label)
+ ("" nil)
+ ((pred (string-prefix-p "fn:")) (substring label 3))
+ (_ label)))
+
+(defun org-footnote-get-definition (label)
+ "Return label, boundaries and definition of the footnote LABEL."
+ (let* ((label (regexp-quote (org-footnote-normalize-label label)))
+ (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label)))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (catch 'found
+ (while (re-search-forward re nil t)
+ (let* ((datum (progn (backward-char) (org-element-context)))
+ (type (org-element-type datum)))
+ (when (memq type '(footnote-definition footnote-reference))
+ (throw 'found
+ (list
+ label
+ (org-element-property :begin datum)
+ (org-element-property :end datum)
+ (let ((cbeg (org-element-property :contents-begin datum)))
+ (if (not cbeg) ""
+ (replace-regexp-in-string
+ "[ \t\n]*\\'"
+ ""
+ (buffer-substring-no-properties
+ cbeg
+ (org-element-property :contents-end datum))))))))))
+ nil))))
+
+(defun org-footnote-all-labels ()
+ "List all defined footnote labels used throughout the buffer.
+This function ignores narrowing, if any."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let (all)
+ (while (re-search-forward org-footnote-re nil t)
+ (backward-char)
+ (let ((context (org-element-context)))
+ (when (memq (org-element-type context)
+ '(footnote-definition footnote-reference))
+ (let ((label (org-element-property :label context)))
+ (when label (cl-pushnew label all :test #'equal))))))
+ all)))
+
+(defun org-footnote-unique-label (&optional current)
+ "Return a new unique footnote label.
+
+The function returns the first numeric label currently unused.
+
+Optional argument CURRENT is the list of labels active in the
+buffer."
+ (let ((current (or current (org-footnote-all-labels))))
+ (let ((count 1))
+ (while (member (number-to-string count) current)
+ (cl-incf count))
+ (number-to-string count))))
+
+
+;;;; Adding, Deleting Footnotes
+
+(defun org-footnote-new ()
+ "Insert a new footnote.
+This command prompts for a label. If this is a label referencing an
+existing label, only insert the label. If the footnote label is empty
+or new, let the user edit the definition of the footnote."
+ (interactive)
+ (unless (org-footnote--allow-reference-p)
+ (user-error "Cannot insert a footnote here"))
+ (let* ((all (org-footnote-all-labels))
+ (label
+ (if (eq org-footnote-auto-label 'random)
+ (format "%x" (random most-positive-fixnum))
+ (org-footnote-normalize-label
+ (let ((propose (org-footnote-unique-label all)))
+ (if (eq org-footnote-auto-label t) propose
+ (completing-read
+ "Label (leave empty for anonymous): "
+ (mapcar #'list all) nil nil
+ (and (eq org-footnote-auto-label 'confirm) propose))))))))
+ (cond ((not label)
+ (insert "[fn::]")
+ (backward-char 1))
+ ((member label all)
+ (insert "[fn:" label "]")
+ (message "New reference to existing note"))
+ (org-footnote-define-inline
+ (insert "[fn:" label ":]")
+ (backward-char 1)
+ (org-footnote-auto-adjust-maybe))
+ (t
+ (insert "[fn:" label "]")
+ (let ((p (org-footnote-create-definition label)))
+ ;; `org-footnote-goto-definition' needs to be called
+ ;; after `org-footnote-auto-adjust-maybe'. Otherwise
+ ;; both label and location of the definition are lost.
+ ;; On the contrary, it needs to be called before
+ ;; `org-edit-footnote-reference' so that the remote
+ ;; editing buffer can display the correct label.
+ (if (ignore-errors (org-footnote-goto-definition label p))
+ (org-footnote-auto-adjust-maybe)
+ ;; Definition was created outside current scope: edit
+ ;; it remotely.
+ (org-footnote-auto-adjust-maybe)
+ (org-edit-footnote-reference)))))))
+
+(defun org-footnote-create-definition (label)
+ "Start the definition of a footnote with label LABEL.
+Return buffer position at the beginning of the definition. This
+function doesn't move point."
+ (let ((label (org-footnote-normalize-label label))
+ electric-indent-mode) ; Prevent wrong indentation.
+ (org-with-wide-buffer
+ (cond
+ ((not org-footnote-section) (org-footnote--goto-local-insertion-point))
+ ((save-excursion
+ (goto-char (point-min))
+ (re-search-forward
+ (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
+ nil t))
+ (goto-char (match-end 0))
+ (forward-line)
+ (unless (bolp) (insert "\n")))
+ (t (org-footnote--clear-footnote-section)))
+ (when (zerop (org-back-over-empty-lines)) (insert "\n"))
+ (insert "[fn:" label "] \n")
+ (line-beginning-position 0))))
+
+(defun org-footnote-delete-references (label)
+ "Delete every reference to footnote LABEL.
+Return the number of footnotes removed."
+ (save-excursion
+ (goto-char (point-min))
+ (let (ref (nref 0))
+ (while (setq ref (org-footnote-get-next-reference label))
+ (goto-char (nth 1 ref))
+ (delete-region (nth 1 ref) (nth 2 ref))
+ (cl-incf nref))
+ nref)))
+
+(defun org-footnote-delete-definitions (label)
+ "Delete every definition of the footnote LABEL.
+Return the number of footnotes removed."
+ (save-excursion
+ (goto-char (point-min))
+ (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label)))
+ (ndef 0))
+ (while (re-search-forward def-re nil t)
+ (pcase (org-footnote-at-definition-p)
+ (`(,_ ,start ,end ,_)
+ ;; Remove the footnote, and all blank lines before it.
+ (delete-region (progn
+ (goto-char start)
+ (skip-chars-backward " \r\t\n")
+ (if (bobp) (point) (line-beginning-position 2)))
+ (progn
+ (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (if (bobp) (point) (line-beginning-position 2))))
+ (cl-incf ndef))))
+ ndef)))
+
+(defun org-footnote-delete (&optional label)
+ "Delete the footnote at point.
+This will remove the definition (even multiple definitions if they exist)
+and all references of a footnote label.
+
+If LABEL is non-nil, delete that footnote instead."
+ (catch 'done
+ (let* ((nref 0) (ndef 0) x
+ ;; 1. Determine LABEL of footnote at point.
+ (label (cond
+ ;; LABEL is provided as argument.
+ (label)
+ ;; Footnote reference at point. If the footnote is
+ ;; anonymous, delete it and exit instead.
+ ((setq x (org-footnote-at-reference-p))
+ (or (car x)
+ (progn
+ (delete-region (nth 1 x) (nth 2 x))
+ (message "Anonymous footnote removed")
+ (throw 'done t))))
+ ;; Footnote definition at point.
+ ((setq x (org-footnote-at-definition-p))
+ (car x))
+ (t (error "Don't know which footnote to remove")))))
+ ;; 2. Now that LABEL is non-nil, find every reference and every
+ ;; definition, and delete them.
+ (setq nref (org-footnote-delete-references label)
+ ndef (org-footnote-delete-definitions label))
+ ;; 3. Verify consistency of footnotes and notify user.
+ (org-footnote-auto-adjust-maybe)
+ (message "%d definition(s) of and %d reference(s) of footnote %s removed"
+ ndef nref label))))
+
+
+;;;; Sorting, Renumbering, Normalizing
+
+(defun org-footnote-renumber-fn:N ()
+ "Order numbered footnotes into a sequence in the document."
+ (interactive)
+ (let ((references (org-footnote--collect-references)))
+ (unwind-protect
+ (let* ((c 0)
+ (references (cl-remove-if-not
+ (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r)))
+ references))
+ (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c))))
+ (delete-dups (mapcar #'car references)))))
+ (org-with-wide-buffer
+ ;; Re-number references.
+ (dolist (ref references)
+ (goto-char (nth 1 ref))
+ (org-footnote--set-label (cdr (assoc (nth 0 ref) alist))))
+ ;; Re-number definitions.
+ (goto-char (point-min))
+ (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t)
+ (replace-match (or (cdr (assoc (match-string 1) alist))
+ ;; Un-referenced definitions get
+ ;; higher numbers.
+ (number-to-string (cl-incf c)))
+ nil nil nil 1))))
+ (dolist (r references) (set-marker (nth 1 r) nil)))))
+
+(defun org-footnote-sort ()
+ "Rearrange footnote definitions in the current buffer.
+Sort footnote definitions so they match order of footnote
+references. Also relocate definitions at the end of their
+relative section or within a single footnote section, according
+to `org-footnote-section'. Inline definitions are ignored."
+ (let ((references (org-footnote--collect-references)))
+ (unwind-protect
+ (let ((definitions (org-footnote--collect-definitions 'delete)))
+ (org-with-wide-buffer
+ (org-footnote--clear-footnote-section)
+ ;; Insert footnote definitions at the appropriate location,
+ ;; separated by a blank line. Each definition is inserted
+ ;; only once throughout the buffer.
+ (let (inserted)
+ (dolist (cell references)
+ (let ((label (car cell))
+ (nested (not (nth 2 cell)))
+ (inline (nth 3 cell)))
+ (unless (or (member label inserted) inline)
+ (push label inserted)
+ (unless (or org-footnote-section nested)
+ ;; If `org-footnote-section' is non-nil, or
+ ;; reference is nested, point is already at the
+ ;; correct position. Otherwise, move at the
+ ;; appropriate location within the section
+ ;; containing the reference.
+ (goto-char (nth 1 cell))
+ (org-footnote--goto-local-insertion-point))
+ (insert "\n"
+ (or (cdr (assoc label definitions))
+ (format "[fn:%s] DEFINITION NOT FOUND." label))
+ "\n"))))
+ ;; Insert un-referenced footnote definitions at the end.
+ (let ((unreferenced
+ (cl-remove-if (lambda (d) (member (car d) inserted))
+ definitions)))
+ (dolist (d unreferenced) (insert "\n" (cdr d) "\n"))))))
+ ;; Clear dangling markers in the buffer.
+ (dolist (r references) (set-marker (nth 1 r) nil)))))
+
+(defun org-footnote-normalize ()
+ "Turn every footnote in buffer into a numbered one."
+ (interactive)
+ (let ((references (org-footnote--collect-references 'anonymous)))
+ (unwind-protect
+ (let ((n 0)
+ (translations nil)
+ (definitions nil))
+ (org-with-wide-buffer
+ ;; Update label for reference. We need to do this before
+ ;; clearing definitions in order to rename nested footnotes
+ ;; before they are deleted.
+ (dolist (cell references)
+ (let* ((label (car cell))
+ (anonymous (not label))
+ (new
+ (cond
+ ;; In order to differentiate anonymous
+ ;; references from regular ones, set their
+ ;; labels to integers, not strings.
+ (anonymous (setcar cell (cl-incf n)))
+ ((cdr (assoc label translations)))
+ (t (let ((l (number-to-string (cl-incf n))))
+ (push (cons label l) translations)
+ l)))))
+ (goto-char (nth 1 cell)) ; Move to reference's start.
+ (org-footnote--set-label
+ (if anonymous (number-to-string new) new))
+ (let ((size (nth 3 cell)))
+ ;; Transform inline footnotes into regular references
+ ;; and retain their definition for later insertion as
+ ;; a regular footnote definition.
+ (when size
+ (let ((def (concat
+ (format "[fn:%s] " new)
+ (org-trim
+ (substring
+ (delete-and-extract-region
+ (point) (+ (point) size 1))
+ 1)))))
+ (push (cons (if anonymous new label) def) definitions)
+ (when org-footnote-fill-after-inline-note-extraction
+ (org-fill-paragraph)))))))
+ ;; Collect definitions. Update labels according to ALIST.
+ (let ((definitions
+ (nconc definitions
+ (org-footnote--collect-definitions 'delete)))
+ (inserted))
+ (org-footnote--clear-footnote-section)
+ (dolist (cell references)
+ (let* ((label (car cell))
+ (anonymous (integerp label))
+ (pos (nth 1 cell)))
+ ;; Move to appropriate location, if required. When
+ ;; there is a footnote section or reference is
+ ;; nested, point is already at the expected location.
+ (unless (or org-footnote-section (not (nth 2 cell)))
+ (goto-char pos)
+ (org-footnote--goto-local-insertion-point))
+ ;; Insert new definition once label is updated.
+ (unless (member label inserted)
+ (push label inserted)
+ (let ((stored (cdr (assoc label definitions)))
+ ;; Anonymous footnotes' label is already
+ ;; up-to-date.
+ (new (if anonymous label
+ (cdr (assoc label translations)))))
+ (insert "\n"
+ (cond
+ ((not stored)
+ (format "[fn:%s] DEFINITION NOT FOUND." new))
+ (anonymous stored)
+ (t
+ (replace-regexp-in-string
+ "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1)))
+ "\n")))))
+ ;; Insert un-referenced footnote definitions at the end.
+ (let ((unreferenced
+ (cl-remove-if (lambda (d) (member (car d) inserted))
+ definitions)))
+ (dolist (d unreferenced)
+ (insert "\n"
+ (replace-regexp-in-string
+ org-footnote-definition-re
+ (format "[fn:%d]" (cl-incf n))
+ (cdr d))
+ "\n"))))))
+ ;; Clear dangling markers.
+ (dolist (r references) (set-marker (nth 1 r) nil)))))
+
+(defun org-footnote-auto-adjust-maybe ()
+ "Renumber and/or sort footnotes according to user settings."
+ (when (memq org-footnote-auto-adjust '(t renumber))
+ (org-footnote-renumber-fn:N))
+ (when (memq org-footnote-auto-adjust '(t sort))
+ (let ((label (car (org-footnote-at-definition-p))))
+ (org-footnote-sort)
+ (when label
+ (goto-char (point-min))
+ (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label))
+ nil t)
+ (progn (insert " ")
+ (just-one-space)))))))
+
+
+;;;; End-user interface
+
+;;;###autoload
+(defun org-footnote-action (&optional special)
+ "Do the right thing for footnotes.
+
+When at a footnote reference, jump to the definition.
+
+When at a definition, jump to the references if they exist, offer
+to create them otherwise.
+
+When neither at definition or reference, create a new footnote,
+interactively if possible.
+
+With prefix arg SPECIAL, or when no footnote can be created,
+offer additional commands in a menu."
+ (interactive "P")
+ (let* ((context (and (not special) (org-element-context)))
+ (type (org-element-type context)))
+ (cond
+ ;; On white space after element, insert a new footnote.
+ ((and context
+ (> (point)
+ (save-excursion
+ (goto-char (org-element-property :end context))
+ (skip-chars-backward " \t")
+ (point))))
+ (org-footnote-new))
+ ((eq type 'footnote-reference)
+ (let ((label (org-element-property :label context)))
+ (cond
+ ;; Anonymous footnote: move point at the beginning of its
+ ;; definition.
+ ((not label)
+ (goto-char (org-element-property :contents-begin context)))
+ ;; Check if a definition exists: then move to it.
+ ((let ((p (nth 1 (org-footnote-get-definition label))))
+ (when p (org-footnote-goto-definition label p))))
+ ;; No definition exists: offer to create it.
+ ((yes-or-no-p (format "No definition for %s. Create one? " label))
+ (let ((p (org-footnote-create-definition label)))
+ (or (ignore-errors (org-footnote-goto-definition label p))
+ ;; Since definition was created outside current scope,
+ ;; edit it remotely.
+ (org-edit-footnote-reference)))))))
+ ((eq type 'footnote-definition)
+ (org-footnote-goto-previous-reference
+ (org-element-property :label context)))
+ ((or special (not (org-footnote--allow-reference-p)))
+ (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \
+\[d]elete")
+ (pcase (read-char-exclusive)
+ (?s (org-footnote-sort))
+ (?r (org-footnote-renumber-fn:N))
+ (?S (org-footnote-renumber-fn:N)
+ (org-footnote-sort))
+ (?n (org-footnote-normalize))
+ (?d (org-footnote-delete))
+ (char (error "No such footnote command %c" char))))
+ (t (org-footnote-new)))))
+
+
+(provide 'org-footnote)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-footnote.el ends here
diff --git a/lisp/org-gnus.el b/lisp/org-gnus.el
new file mode 100644
index 0000000..b9d0989
--- /dev/null
+++ b/lisp/org-gnus.el
@@ -0,0 +1,295 @@
+;;; org-gnus.el --- Support for Links to Gnus Groups and Messages -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Tassilo Horn <tassilo at member dot fsf dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to Gnus groups and messages from within Org.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+(require 'gnus-util)
+(eval-when-compile (require 'gnus-sum))
+
+;; Declare external functions and variables
+
+(declare-function message-fetch-field "message" (header &optional not-all))
+(declare-function message-narrow-to-head-1 "message" nil)
+(declare-function gnus-summary-last-subject "gnus-sum" nil)
+(declare-function nnvirtual-map-article "nnvirtual" (article))
+
+;; Customization variables
+
+(defvaralias 'org-usenet-links-prefer-google 'org-gnus-prefer-web-links)
+
+(defcustom org-gnus-prefer-web-links nil
+ "If non-nil, `org-store-link' creates web links to Google groups or Gmane.
+\\<org-mode-map>When nil, Gnus will be used for such links.
+Using a prefix argument to the command `\\[org-store-link]' (`org-store-link')
+negates this setting for the duration of the command."
+ :group 'org-link-store
+ :type 'boolean)
+
+(defcustom org-gnus-nnimap-query-article-no-from-file nil
+ "If non-nil, `org-gnus-follow-link' will try to translate
+Message-Ids to article numbers by querying the .overview file.
+Normally, this translation is done by querying the IMAP server,
+which is usually very fast. Unfortunately, some (maybe badly
+configured) IMAP servers don't support this operation quickly.
+So if following a link to a Gnus article takes ages, try setting
+this variable to t."
+ :group 'org-link-store
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-gnus-no-server nil
+ "Should Gnus be started using `gnus-no-server'?"
+ :group 'org-gnus
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+;; Install the link type
+(org-link-set-parameters "gnus" :follow #'org-gnus-open :store #'org-gnus-store-link)
+
+;; Implementation
+
+(defun org-gnus-nnimap-cached-article-number (group server message-id)
+ "Return cached article number (uid) of message in GROUP on SERVER.
+MESSAGE-ID is the message-id header field that identifies the
+message. If the uid is not cached, return nil."
+ (with-temp-buffer
+ (let ((nov (and (fboundp 'nnimap-group-overview-filename)
+ ;; nnimap-group-overview-filename was removed from
+ ;; Gnus in September 2010, and therefore should
+ ;; only be present in Emacs 23.1.
+ (nnimap-group-overview-filename group server))))
+ (when (and nov (file-exists-p nov))
+ (mm-insert-file-contents nov)
+ (set-buffer-modified-p nil)
+ (goto-char (point-min))
+ (catch 'found
+ (while (search-forward message-id nil t)
+ (let ((hdr (split-string (thing-at-point 'line) "\t")))
+ (if (string= (nth 4 hdr) message-id)
+ (throw 'found (nth 0 hdr))))))))))
+
+(defun org-gnus-group-link (group)
+ "Create a link to the Gnus group GROUP.
+If GROUP is a newsgroup and `org-gnus-prefer-web-links' is
+non-nil, create a link to groups.google.com or gmane.org.
+Otherwise create a link to the group inside Gnus.
+
+If `org-store-link' was called with a prefix arg the meaning of
+`org-gnus-prefer-web-links' is reversed."
+ (let ((unprefixed-group (replace-regexp-in-string "^[^:]+:" "" group)))
+ (if (and (string-prefix-p "nntp" group) ;; Only for nntp groups
+ (org-xor current-prefix-arg
+ org-gnus-prefer-web-links))
+ (concat (if (string-match "gmane" unprefixed-group)
+ "http://news.gmane.org/"
+ "http://groups.google.com/group/")
+ unprefixed-group)
+ (concat "gnus:" group))))
+
+(defun org-gnus-article-link (group newsgroups message-id x-no-archive)
+ "Create a link to a Gnus article.
+The article is specified by its MESSAGE-ID. Additional
+parameters are the Gnus GROUP, the NEWSGROUPS the article was
+posted to and the X-NO-ARCHIVE header value of that article.
+
+If GROUP is a newsgroup and `org-gnus-prefer-web-links' is
+non-nil, create a link to groups.google.com or gmane.org.
+Otherwise create a link to the article inside Gnus.
+
+If `org-store-link' was called with a prefix arg the meaning of
+`org-gnus-prefer-web-links' is reversed."
+ (if (and (org-xor current-prefix-arg org-gnus-prefer-web-links)
+ newsgroups ;; Make web links only for nntp groups
+ (not x-no-archive)) ;; and if X-No-Archive isn't set.
+ (format (if (string-match "gmane\\." newsgroups)
+ "http://mid.gmane.org/%s"
+ "http://groups.google.com/groups/search?as_umsgid=%s")
+ (org-fixup-message-id-for-http message-id))
+ (concat "gnus:" group "#" message-id)))
+
+(defun org-gnus-store-link ()
+ "Store a link to a Gnus folder or message."
+ (cond
+ ((eq major-mode 'gnus-group-mode)
+ (let* ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
+ (gnus-group-group-name)) ; version
+ ((fboundp 'gnus-group-name)
+ (gnus-group-name))
+ (t "???")))
+ desc link)
+ (when group
+ (org-store-link-props :type "gnus" :group group)
+ (setq desc (org-gnus-group-link group)
+ link desc)
+ (org-add-link-props :link link :description desc)
+ link)))
+
+ ((memq major-mode '(gnus-summary-mode gnus-article-mode))
+ (let* ((group gnus-newsgroup-name)
+ (header (with-current-buffer gnus-summary-buffer
+ (gnus-summary-article-header)))
+ (from (mail-header-from header))
+ (message-id (org-unbracket-string "<" ">" (mail-header-id header)))
+ (date (org-trim (mail-header-date header)))
+ (subject (copy-sequence (mail-header-subject header)))
+ (to (cdr (assq 'To (mail-header-extra header))))
+ newsgroups x-no-archive desc link)
+ (cl-case (car (gnus-find-method-for-group gnus-newsgroup-name))
+ (nnvirtual
+ (setq group (car (nnvirtual-map-article
+ (gnus-summary-article-number)))))
+ (nnir
+ (setq group (nnir-article-group (gnus-summary-article-number)))))
+ ;; Remove text properties of subject string to avoid Emacs bug
+ ;; #3506
+ (set-text-properties 0 (length subject) nil subject)
+
+ ;; Fetching an article is an expensive operation; newsgroup and
+ ;; x-no-archive are only needed for web links.
+ (when (org-xor current-prefix-arg org-gnus-prefer-web-links)
+ ;; Make sure the original article buffer is up-to-date
+ (save-window-excursion (gnus-summary-select-article))
+ (setq to (or to (gnus-fetch-original-field "To"))
+ newsgroups (gnus-fetch-original-field "Newsgroups")
+ x-no-archive (gnus-fetch-original-field "x-no-archive")))
+ (org-store-link-props :type "gnus" :from from :date date :subject subject
+ :message-id message-id :group group :to to)
+ (setq desc (org-email-link-description)
+ link (org-gnus-article-link
+ group newsgroups message-id x-no-archive))
+ (org-add-link-props :link link :description desc)
+ link))
+ ((eq major-mode 'message-mode)
+ (setq org-store-link-plist nil) ; reset
+ (save-excursion
+ (save-restriction
+ (message-narrow-to-headers)
+ (and (not (message-fetch-field "Message-ID"))
+ (message-generate-headers '(Message-ID)))
+ (goto-char (point-min))
+ (re-search-forward "^Message-ID: *.*$" nil t)
+ (put-text-property (match-beginning 0) (match-end 0) 'message-deletable nil)
+ (let ((gcc (car (last
+ (message-unquote-tokens
+ (message-tokenize-header (mail-fetch-field "gcc" nil t) " ,")))))
+ (id (org-unbracket-string "<" ">" (mail-fetch-field "Message-ID")))
+ (to (mail-fetch-field "To"))
+ (from (mail-fetch-field "From"))
+ (subject (mail-fetch-field "Subject"))
+ desc link
+ newsgroup xarchive) ; those are always nil for gcc
+ (and (not gcc)
+ (error "Can not create link: No Gcc header found"))
+ (org-store-link-props :type "gnus" :from from :subject subject
+ :message-id id :group gcc :to to)
+ (setq desc (org-email-link-description)
+ link (org-gnus-article-link
+ gcc newsgroup id xarchive))
+ (org-add-link-props :link link :description desc)
+ link))))))
+
+(defun org-gnus-open-nntp (path)
+ "Follow the nntp: link specified by PATH."
+ (let* ((spec (split-string path "/"))
+ (server (split-string (nth 2 spec) "@"))
+ (group (nth 3 spec))
+ (article (nth 4 spec)))
+ (org-gnus-follow-link
+ (format "nntp+%s:%s" (or (cdr server) (car server)) group)
+ article)))
+
+(defun org-gnus-open (path)
+ "Follow the Gnus message or folder link specified by PATH."
+ (let (group article)
+ (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
+ (error "Error in Gnus link"))
+ (setq group (match-string 1 path)
+ article (match-string 3 path))
+ (when group
+ (setq group (org-no-properties group)))
+ (when article
+ (setq article (org-no-properties article)))
+ (org-gnus-follow-link group article)))
+
+(defun org-gnus-follow-link (&optional group article)
+ "Follow a Gnus link to GROUP and ARTICLE."
+ (require 'gnus)
+ (funcall (cdr (assq 'gnus org-link-frame-setup)))
+ (if gnus-other-frame-object (select-frame gnus-other-frame-object))
+ (setq group (org-no-properties group))
+ (setq article (org-no-properties article))
+ (cond ((and group article)
+ (gnus-activate-group group)
+ (condition-case nil
+ (let* ((method (gnus-find-method-for-group group))
+ (backend (car method))
+ (server (cadr method)))
+ (cond
+ ((eq backend 'nndoc)
+ (if (gnus-group-read-group t nil group)
+ (gnus-summary-goto-article article nil t)
+ (message "Couldn't follow gnus link. %s"
+ "The summary couldn't be opened.")))
+ (t
+ (let ((articles 1)
+ group-opened)
+ (when (and (eq backend 'nnimap)
+ org-gnus-nnimap-query-article-no-from-file)
+ (setq article
+ (or (org-gnus-nnimap-cached-article-number
+ (nth 1 (split-string group ":"))
+ server (concat "<" article ">")) article)))
+ (while (and (not group-opened)
+ ;; stop on integer overflows
+ (> articles 0))
+ (setq group-opened (gnus-group-read-group
+ articles t group)
+ articles (if (< articles 16)
+ (1+ articles)
+ (* articles 2))))
+ (if group-opened
+ (gnus-summary-goto-article article nil t)
+ (message "Couldn't follow gnus link. %s"
+ "The summary couldn't be opened."))))))
+ (quit (message "Couldn't follow gnus link. %s"
+ "The linked group is empty."))))
+ (group (gnus-group-jump-to-group group))))
+
+(defun org-gnus-no-new-news ()
+ "Like `\\[gnus]' but doesn't check for new news."
+ (if (not (gnus-alive-p)) (if org-gnus-no-server (gnus-no-server) (gnus))))
+
+(provide 'org-gnus)
+
+
+;;; org-gnus.el ends here
diff --git a/lisp/org-habit.el b/lisp/org-habit.el
new file mode 100644
index 0000000..1f61565
--- /dev/null
+++ b/lisp/org-habit.el
@@ -0,0 +1,442 @@
+;;; org-habit.el --- The habit tracking code for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+
+;; Author: John Wiegley <johnw at gnu dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the habit tracking code for Org mode
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+(require 'org-agenda)
+
+(defgroup org-habit nil
+ "Options concerning habit tracking in Org mode."
+ :tag "Org Habit"
+ :group 'org-progress)
+
+(defcustom org-habit-graph-column 40
+ "The absolute column at which to insert habit consistency graphs.
+Note that consistency graphs will overwrite anything else in the buffer."
+ :group 'org-habit
+ :type 'integer)
+
+(defcustom org-habit-preceding-days 21
+ "Number of days before today to appear in consistency graphs."
+ :group 'org-habit
+ :type 'integer)
+
+(defcustom org-habit-following-days 7
+ "Number of days after today to appear in consistency graphs."
+ :group 'org-habit
+ :type 'integer)
+
+(defcustom org-habit-show-habits t
+ "If non-nil, show habits in agenda buffers."
+ :group 'org-habit
+ :type 'boolean)
+
+(defcustom org-habit-show-habits-only-for-today t
+ "If non-nil, only show habits on today's agenda, and not for future days.
+Note that even when shown for future days, the graph is always
+relative to the current effective date."
+ :group 'org-habit
+ :type 'boolean)
+
+(defcustom org-habit-show-all-today nil
+ "If non-nil, will show the consistency graph of all habits on
+today's agenda, even if they are not scheduled."
+ :group 'org-habit
+ :type 'boolean)
+
+(defcustom org-habit-today-glyph ?!
+ "Glyph character used to identify today."
+ :group 'org-habit
+ :version "24.1"
+ :type 'character)
+
+(defcustom org-habit-completed-glyph ?*
+ "Glyph character used to show completed days on which a task was done."
+ :group 'org-habit
+ :version "24.1"
+ :type 'character)
+
+(defcustom org-habit-show-done-always-green nil
+ "Non-nil means DONE days will always be green in the consistency graph.
+It will be green even if it was done after the deadline."
+ :group 'org-habit
+ :type 'boolean)
+
+(defface org-habit-clear-face
+ '((((background light)) (:background "#8270f9"))
+ (((background dark)) (:background "blue")))
+ "Face for days on which a task shouldn't be done yet."
+ :group 'org-habit
+ :group 'org-faces)
+(defface org-habit-clear-future-face
+ '((((background light)) (:background "#d6e4fc"))
+ (((background dark)) (:background "midnightblue")))
+ "Face for future days on which a task shouldn't be done yet."
+ :group 'org-habit
+ :group 'org-faces)
+
+(defface org-habit-ready-face
+ '((((background light)) (:background "#4df946"))
+ (((background dark)) (:background "forestgreen")))
+ "Face for days on which a task should start to be done."
+ :group 'org-habit
+ :group 'org-faces)
+(defface org-habit-ready-future-face
+ '((((background light)) (:background "#acfca9"))
+ (((background dark)) (:background "darkgreen")))
+ "Face for days on which a task should start to be done."
+ :group 'org-habit
+ :group 'org-faces)
+
+(defface org-habit-alert-face
+ '((((background light)) (:background "#f5f946"))
+ (((background dark)) (:background "gold")))
+ "Face for days on which a task is due."
+ :group 'org-habit
+ :group 'org-faces)
+(defface org-habit-alert-future-face
+ '((((background light)) (:background "#fafca9"))
+ (((background dark)) (:background "darkgoldenrod")))
+ "Face for days on which a task is due."
+ :group 'org-habit
+ :group 'org-faces)
+
+(defface org-habit-overdue-face
+ '((((background light)) (:background "#f9372d"))
+ (((background dark)) (:background "firebrick")))
+ "Face for days on which a task is overdue."
+ :group 'org-habit
+ :group 'org-faces)
+(defface org-habit-overdue-future-face
+ '((((background light)) (:background "#fc9590"))
+ (((background dark)) (:background "darkred")))
+ "Face for days on which a task is overdue."
+ :group 'org-habit
+ :group 'org-faces)
+
+(defun org-habit-duration-to-days (ts)
+ (if (string-match "\\([0-9]+\\)\\([dwmy]\\)" ts)
+ ;; lead time is specified.
+ (floor (* (string-to-number (match-string 1 ts))
+ (cdr (assoc (match-string 2 ts)
+ '(("d" . 1) ("w" . 7)
+ ("m" . 30.4) ("y" . 365.25))))))
+ (error "Invalid duration string: %s" ts)))
+
+(defun org-is-habit-p (&optional pom)
+ "Is the task at POM or point a habit?"
+ (string= "habit" (org-entry-get (or pom (point)) "STYLE")))
+
+(defun org-habit-parse-todo (&optional pom)
+ "Parse the TODO surrounding point for its habit-related data.
+Returns a list with the following elements:
+
+ 0: Scheduled date for the habit (may be in the past)
+ 1: \".+\"-style repeater for the schedule, in days
+ 2: Optional deadline (nil if not present)
+ 3: If deadline, the repeater for the deadline, otherwise nil
+ 4: A list of all the past dates this todo was mark closed
+ 5: Repeater type as a string
+
+This list represents a \"habit\" for the rest of this module."
+ (save-excursion
+ (if pom (goto-char pom))
+ (cl-assert (org-is-habit-p (point)))
+ (let* ((scheduled (org-get-scheduled-time (point)))
+ (scheduled-repeat (org-get-repeat org-scheduled-string))
+ (end (org-entry-end-position))
+ (habit-entry (org-no-properties (nth 4 (org-heading-components))))
+ closed-dates deadline dr-days sr-days sr-type)
+ (if scheduled
+ (setq scheduled (time-to-days scheduled))
+ (error "Habit %s has no scheduled date" habit-entry))
+ (unless scheduled-repeat
+ (error
+ "Habit `%s' has no scheduled repeat period or has an incorrect one"
+ habit-entry))
+ (setq sr-days (org-habit-duration-to-days scheduled-repeat)
+ sr-type (progn (string-match "[\\.+]?\\+" scheduled-repeat)
+ (match-string-no-properties 0 scheduled-repeat)))
+ (unless (> sr-days 0)
+ (error "Habit %s scheduled repeat period is less than 1d" habit-entry))
+ (when (string-match "/\\([0-9]+[dwmy]\\)" scheduled-repeat)
+ (setq dr-days (org-habit-duration-to-days
+ (match-string-no-properties 1 scheduled-repeat)))
+ (if (<= dr-days sr-days)
+ (error "Habit %s deadline repeat period is less than or equal to scheduled (%s)"
+ habit-entry scheduled-repeat))
+ (setq deadline (+ scheduled (- dr-days sr-days))))
+ (org-back-to-heading t)
+ (let* ((maxdays (+ org-habit-preceding-days org-habit-following-days))
+ (reversed org-log-states-order-reversed)
+ (search (if reversed 're-search-forward 're-search-backward))
+ (limit (if reversed end (point)))
+ (count 0)
+ (re (format
+ "^[ \t]*-[ \t]+\\(?:State \"%s\".*%s%s\\)"
+ (regexp-opt org-done-keywords)
+ org-ts-regexp-inactive
+ (let ((value (cdr (assq 'done org-log-note-headings))))
+ (if (not value) ""
+ (concat "\\|"
+ (org-replace-escapes
+ (regexp-quote value)
+ `(("%d" . ,org-ts-regexp-inactive)
+ ("%D" . ,org-ts-regexp)
+ ("%s" . "\"\\S-+\"")
+ ("%S" . "\"\\S-+\"")
+ ("%t" . ,org-ts-regexp-inactive)
+ ("%T" . ,org-ts-regexp)
+ ("%u" . ".*?")
+ ("%U" . ".*?")))))))))
+ (unless reversed (goto-char end))
+ (while (and (< count maxdays) (funcall search re limit t))
+ (push (time-to-days
+ (org-time-string-to-time
+ (or (match-string-no-properties 1)
+ (match-string-no-properties 2))))
+ closed-dates)
+ (setq count (1+ count))))
+ (list scheduled sr-days deadline dr-days closed-dates sr-type))))
+
+(defsubst org-habit-scheduled (habit)
+ (nth 0 habit))
+(defsubst org-habit-scheduled-repeat (habit)
+ (nth 1 habit))
+(defsubst org-habit-deadline (habit)
+ (let ((deadline (nth 2 habit)))
+ (or deadline
+ (if (nth 3 habit)
+ (+ (org-habit-scheduled habit)
+ (1- (org-habit-scheduled-repeat habit)))
+ (org-habit-scheduled habit)))))
+(defsubst org-habit-deadline-repeat (habit)
+ (or (nth 3 habit)
+ (org-habit-scheduled-repeat habit)))
+(defsubst org-habit-done-dates (habit)
+ (nth 4 habit))
+(defsubst org-habit-repeat-type (habit)
+ (nth 5 habit))
+
+(defsubst org-habit-get-priority (habit &optional moment)
+ "Determine the relative priority of a habit.
+This must take into account not just urgency, but consistency as well."
+ (let ((pri 1000)
+ (now (if moment (time-to-days moment) (org-today)))
+ (scheduled (org-habit-scheduled habit))
+ (deadline (org-habit-deadline habit)))
+ ;; add 10 for every day past the scheduled date, and subtract for every
+ ;; day before it
+ (setq pri (+ pri (* (- now scheduled) 10)))
+ ;; add 50 if the deadline is today
+ (if (and (/= scheduled deadline)
+ (= now deadline))
+ (setq pri (+ pri 50)))
+ ;; add 100 for every day beyond the deadline date, and subtract 10 for
+ ;; every day before it
+ (let ((slip (- now (1- deadline))))
+ (if (> slip 0)
+ (setq pri (+ pri (* slip 100)))
+ (setq pri (+ pri (* slip 10)))))
+ pri))
+
+(defun org-habit-get-faces (habit &optional now-days scheduled-days donep)
+ "Return faces for HABIT relative to NOW-DAYS and SCHEDULED-DAYS.
+NOW-DAYS defaults to the current time's days-past-the-epoch if nil.
+SCHEDULED-DAYS defaults to the habit's actual scheduled days if nil.
+
+Habits are assigned colors on the following basis:
+ Blue Task is before the scheduled date.
+ Green Task is on or after scheduled date, but before the
+ end of the schedule's repeat period.
+ Yellow If the task has a deadline, then it is after schedule's
+ repeat period, but before the deadline.
+ Orange The task has reached the deadline day, or if there is
+ no deadline, the end of the schedule's repeat period.
+ Red The task has gone beyond the deadline day or the
+ schedule's repeat period."
+ (let* ((scheduled (or scheduled-days (org-habit-scheduled habit)))
+ (s-repeat (org-habit-scheduled-repeat habit))
+ (d-repeat (org-habit-deadline-repeat habit))
+ (deadline (if scheduled-days
+ (+ scheduled-days (- d-repeat s-repeat))
+ (org-habit-deadline habit)))
+ (m-days (or now-days (time-to-days (current-time)))))
+ (cond
+ ((< m-days scheduled)
+ '(org-habit-clear-face . org-habit-clear-future-face))
+ ((< m-days deadline)
+ '(org-habit-ready-face . org-habit-ready-future-face))
+ ((= m-days deadline)
+ (if donep
+ '(org-habit-ready-face . org-habit-ready-future-face)
+ '(org-habit-alert-face . org-habit-alert-future-face)))
+ ((and org-habit-show-done-always-green donep)
+ '(org-habit-ready-face . org-habit-ready-future-face))
+ (t '(org-habit-overdue-face . org-habit-overdue-future-face)))))
+
+(defun org-habit-build-graph (habit starting current ending)
+ "Build a graph for the given HABIT, from STARTING to ENDING.
+CURRENT gives the current time between STARTING and ENDING, for
+the purpose of drawing the graph. It need not be the actual
+current time."
+ (let* ((all-done-dates (sort (org-habit-done-dates habit) #'<))
+ (done-dates all-done-dates)
+ (scheduled (org-habit-scheduled habit))
+ (s-repeat (org-habit-scheduled-repeat habit))
+ (start (time-to-days starting))
+ (now (time-to-days current))
+ (end (time-to-days ending))
+ (graph (make-string (1+ (- end start)) ?\s))
+ (index 0)
+ last-done-date)
+ (while (and done-dates (< (car done-dates) start))
+ (setq last-done-date (car done-dates)
+ done-dates (cdr done-dates)))
+ (while (< start end)
+ (let* ((in-the-past-p (< start now))
+ (todayp (= start now))
+ (donep (and done-dates (= start (car done-dates))))
+ (faces
+ (if (and in-the-past-p
+ (not last-done-date)
+ (not (< scheduled now)))
+ '(org-habit-clear-face . org-habit-clear-future-face)
+ (org-habit-get-faces
+ habit start
+ (and in-the-past-p
+ last-done-date
+ ;; Compute scheduled time for habit at the time
+ ;; START was current.
+ (let ((type (org-habit-repeat-type habit)))
+ (cond
+ ;; At the last done date, use current
+ ;; scheduling in all cases.
+ ((null done-dates) scheduled)
+ ((equal type ".+") (+ last-done-date s-repeat))
+ ((equal type "+")
+ ;; Since LAST-DONE-DATE, each done mark
+ ;; shifted scheduled date by S-REPEAT.
+ (- scheduled (* (length done-dates) s-repeat)))
+ (t
+ ;; Compute the scheduled time after the
+ ;; first repeat. This is the closest time
+ ;; past FIRST-DONE which can reach SCHEDULED
+ ;; by a number of S-REPEAT hops.
+ ;;
+ ;; Then, play TODO state change history from
+ ;; the beginning in order to find current
+ ;; scheduled time.
+ (let* ((first-done (car all-done-dates))
+ (s (let ((shift (mod (- scheduled first-done)
+ s-repeat)))
+ (+ (if (= shift 0) s-repeat shift)
+ first-done))))
+ (if (= first-done last-done-date) s
+ (catch :exit
+ (dolist (done (cdr all-done-dates) s)
+ ;; Each repeat shifts S by any
+ ;; number of S-REPEAT hops it takes
+ ;; to get past DONE, with a minimum
+ ;; of one hop.
+ (cl-incf s (* (1+ (/ (max (- done s) 0)
+ s-repeat))
+ s-repeat))
+ (when (= done last-done-date)
+ (throw :exit s))))))))))
+ donep)))
+ markedp face)
+ (if donep
+ (let ((done-time (time-add
+ starting
+ (days-to-time
+ (- start (time-to-days starting))))))
+
+ (aset graph index org-habit-completed-glyph)
+ (setq markedp t)
+ (put-text-property
+ index (1+ index) 'help-echo
+ (format-time-string (org-time-stamp-format) done-time) graph)
+ (while (and done-dates
+ (= start (car done-dates)))
+ (setq last-done-date (car done-dates)
+ done-dates (cdr done-dates))))
+ (if todayp
+ (aset graph index org-habit-today-glyph)))
+ (setq face (if (or in-the-past-p todayp)
+ (car faces)
+ (cdr faces)))
+ (if (and in-the-past-p
+ (not (eq face 'org-habit-overdue-face))
+ (not markedp))
+ (setq face (cdr faces)))
+ (put-text-property index (1+ index) 'face face graph))
+ (setq start (1+ start)
+ index (1+ index)))
+ graph))
+
+(defun org-habit-insert-consistency-graphs (&optional line)
+ "Insert consistency graph for any habitual tasks."
+ (let ((inhibit-read-only t)
+ (buffer-invisibility-spec '(org-link))
+ (moment (time-subtract (current-time)
+ (list 0 (* 3600 org-extend-today-until) 0))))
+ (save-excursion
+ (goto-char (if line (point-at-bol) (point-min)))
+ (while (not (eobp))
+ (let ((habit (get-text-property (point) 'org-habit-p)))
+ (when habit
+ (move-to-column org-habit-graph-column t)
+ (delete-char (min (+ 1 org-habit-preceding-days
+ org-habit-following-days)
+ (- (line-end-position) (point))))
+ (insert-before-markers
+ (org-habit-build-graph
+ habit
+ (time-subtract moment (days-to-time org-habit-preceding-days))
+ moment
+ (time-add moment (days-to-time org-habit-following-days))))))
+ (forward-line)))))
+
+(defun org-habit-toggle-habits ()
+ "Toggle display of habits in an agenda buffer."
+ (interactive)
+ (org-agenda-check-type t 'agenda)
+ (setq org-habit-show-habits (not org-habit-show-habits))
+ (org-agenda-redo)
+ (org-agenda-set-mode-name)
+ (message "Habits turned %s"
+ (if org-habit-show-habits "on" "off")))
+
+(org-defkey org-agenda-mode-map "K" 'org-habit-toggle-habits)
+
+(provide 'org-habit)
+
+;;; org-habit.el ends here
diff --git a/lisp/org-id.el b/lisp/org-id.el
new file mode 100644
index 0000000..f07d243
--- /dev/null
+++ b/lisp/org-id.el
@@ -0,0 +1,685 @@
+;;; org-id.el --- Global identifiers for Org entries -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements globally unique identifiers for Org entries.
+;; Identifiers are stored in the entry as an :ID: property. Functions
+;; are provided that create and retrieve such identifiers, and that find
+;; entries based on the identifier.
+
+;; Identifiers consist of a prefix (default "Org" given by the variable
+;; `org-id-prefix') and a unique part that can be created by a number
+;; of different methods, see the variable `org-id-method'.
+;; Org has a builtin method that uses a compact encoding of the creation
+;; time of the ID, with microsecond accuracy. This virtually
+;; guarantees globally unique identifiers, even if several people are
+;; creating IDs at the same time in files that will eventually be used
+;; together.
+;;
+;; By default Org uses UUIDs as global unique identifiers.
+;;
+;; This file defines the following API:
+;;
+;; org-id-get-create
+;; Create an ID for the entry at point if it does not yet have one.
+;; Returns the ID (old or new). This function can be used
+;; interactively, with prefix argument the creation of a new ID is
+;; forced, even if there was an old one.
+;;
+;; org-id-get
+;; Get the ID property of an entry. Using appropriate arguments
+;; to the function, it can also create the ID for this entry.
+;;
+;; org-id-goto
+;; Command to go to a specific ID, this command can be used
+;; interactively.
+;;
+;; org-id-get-with-outline-path-completion
+;; Retrieve the ID of an entry, using outline path completion.
+;; This function can work for multiple files.
+;;
+;; org-id-get-with-outline-drilling
+;; Retrieve the ID of an entry, using outline path completion.
+;; This function only works for the current file.
+;;
+;; org-id-find
+;; Find the location of an entry with specific id.
+;;
+
+;;; Code:
+
+(require 'org)
+
+(declare-function message-make-fqdn "message" ())
+
+;;; Customization
+
+(defgroup org-id nil
+ "Options concerning global entry identifiers in Org mode."
+ :tag "Org ID"
+ :group 'org)
+
+(defcustom org-id-link-to-org-use-id nil
+ "Non-nil means storing a link to an Org file will use entry IDs.
+\\<org-mode-map>\
+
+The variable can have the following values:
+
+t Create an ID if needed to make a link to the current entry.
+
+create-if-interactive
+ If `org-store-link' is called directly (interactively, as a user
+ command), do create an ID to support the link. But when doing the
+ job for capture, only use the ID if it already exists. The
+ purpose of this setting is to avoid proliferation of unwanted
+ IDs, just because you happen to be in an Org file when you
+ call `org-capture' that automatically and preemptively creates a
+ link. If you do want to get an ID link in a capture template to
+ an entry not having an ID, create it first by explicitly creating
+ a link to it, using `\\[org-store-link]' first.
+
+create-if-interactive-and-no-custom-id
+ Like create-if-interactive, but do not create an ID if there is
+ a CUSTOM_ID property defined in the entry.
+
+use-existing
+ Use existing ID, do not create one.
+
+nil Never use an ID to make a link, instead link using a text search for
+ the headline text."
+ :group 'org-link-store
+ :group 'org-id
+ :version "24.3"
+ :type '(choice
+ (const :tag "Create ID to make link" t)
+ (const :tag "Create if storing link interactively"
+ create-if-interactive)
+ (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
+ create-if-interactive-and-no-custom-id)
+ (const :tag "Only use existing" use-existing)
+ (const :tag "Do not use ID to create link" nil)))
+
+(defcustom org-id-uuid-program "uuidgen"
+ "The uuidgen program."
+ :group 'org-id
+ :type 'string)
+
+(defcustom org-id-method 'uuid
+ "The method that should be used to create new IDs.
+
+An ID will consist of the optional prefix specified in `org-id-prefix',
+and a unique part created by the method this variable specifies.
+
+Allowed values are:
+
+org Org's own internal method, using an encoding of the current time to
+ microsecond accuracy, and optionally the current domain of the
+ computer. See the variable `org-id-include-domain'.
+
+uuid Create random (version 4) UUIDs. If the program defined in
+ `org-id-uuid-program' is available it is used to create the ID.
+ Otherwise an internal functions is used."
+ :group 'org-id
+ :type '(choice
+ (const :tag "Org's internal method" org)
+ (const :tag "external: uuidgen" uuid)))
+
+(defcustom org-id-prefix nil
+ "The prefix for IDs.
+
+This may be a string, or it can be nil to indicate that no prefix is required.
+When a string, the string should have no space characters as IDs are expected
+to have no space characters in them."
+ :group 'org-id
+ :type '(choice
+ (const :tag "No prefix")
+ (string :tag "Prefix")))
+
+(defcustom org-id-include-domain nil
+ "Non-nil means add the domain name to new IDs.
+This ensures global uniqueness of IDs, and is also suggested by
+RFC 2445 in combination with RFC 822. This is only relevant if
+`org-id-method' is `org'. When uuidgen is used, the domain will never
+be added.
+The default is to not use this because we have no really good way to get
+the true domain, and Org entries will normally not be shared with enough
+people to make this necessary."
+ :group 'org-id
+ :type 'boolean)
+
+(defcustom org-id-track-globally t
+ "Non-nil means track IDs through files, so that links work globally.
+This work by maintaining a hash table for IDs and writing this table
+to disk when exiting Emacs. Because of this, it works best if you use
+a single Emacs process, not many.
+
+When nil, IDs are not tracked. Links to IDs will still work within
+a buffer, but not if the entry is located in another file.
+IDs can still be used if the entry with the id is in the same file as
+the link."
+ :group 'org-id
+ :type 'boolean)
+
+(defcustom org-id-locations-file (convert-standard-filename
+ (concat user-emacs-directory ".org-id-locations"))
+ "The file for remembering in which file an ID was defined.
+This variable is only relevant when `org-id-track-globally' is set."
+ :group 'org-id
+ :type 'file)
+
+(defvar org-id-locations nil
+ "List of files with IDs in those files.")
+
+(defvar org-id-files nil
+ "List of files that contain IDs.")
+
+(defcustom org-id-extra-files 'org-agenda-text-search-extra-files
+ "Files to be searched for IDs, besides the agenda files.
+When Org reparses files to remake the list of files and IDs it is tracking,
+it will normally scan the agenda files, the archives related to agenda files,
+any files that are listed as ID containing in the current register, and
+any Org file currently visited by Emacs.
+You can list additional files here.
+This variable is only relevant when `org-id-track-globally' is set."
+ :group 'org-id
+ :type
+ '(choice
+ (symbol :tag "Variable")
+ (repeat :tag "List of files"
+ (file))))
+
+(defcustom org-id-search-archives t
+ "Non-nil means search also the archive files of agenda files for entries.
+This is a possibility to reduce overhead, but it means that entries moved
+to the archives can no longer be found by ID.
+This variable is only relevant when `org-id-track-globally' is set."
+ :group 'org-id
+ :type 'boolean)
+
+;;; The API functions
+
+;;;###autoload
+(defun org-id-get-create (&optional force)
+ "Create an ID for the current entry and return it.
+If the entry already has an ID, just return it.
+With optional argument FORCE, force the creation of a new ID."
+ (interactive "P")
+ (when force
+ (org-entry-put (point) "ID" nil))
+ (org-id-get (point) 'create))
+
+;;;###autoload
+(defun org-id-copy ()
+ "Copy the ID of the entry at point to the kill ring.
+Create an ID if necessary."
+ (interactive)
+ (org-kill-new (org-id-get nil 'create)))
+
+;;;###autoload
+(defun org-id-get (&optional pom create prefix)
+ "Get the ID property of the entry at point-or-marker POM.
+If POM is nil, refer to the entry at point.
+If the entry does not have an ID, the function returns nil.
+However, when CREATE is non nil, create an ID if none is present already.
+PREFIX will be passed through to `org-id-new'.
+In any case, the ID of the entry is returned."
+ (org-with-point-at pom
+ (let ((id (org-entry-get nil "ID")))
+ (cond
+ ((and id (stringp id) (string-match "\\S-" id))
+ id)
+ (create
+ (setq id (org-id-new prefix))
+ (org-entry-put pom "ID" id)
+ (org-id-add-location id (buffer-file-name (buffer-base-buffer)))
+ id)))))
+
+;;;###autoload
+(defun org-id-get-with-outline-path-completion (&optional targets)
+ "Use `outline-path-completion' to retrieve the ID of an entry.
+TARGETS may be a setting for `org-refile-targets' to define
+eligible headlines. When omitted, all headlines in the current
+file are eligible. This function returns the ID of the entry.
+If necessary, the ID is created."
+ (let* ((org-refile-targets (or targets '((nil . (:maxlevel . 10)))))
+ (org-refile-use-outline-path
+ (if (caar org-refile-targets) 'file t))
+ (org-refile-target-verify-function nil)
+ (spos (org-refile-get-location "Entry"))
+ (pom (and spos (move-marker (make-marker) (nth 3 spos)
+ (get-file-buffer (nth 1 spos))))))
+ (prog1 (org-id-get pom 'create)
+ (move-marker pom nil))))
+
+;;;###autoload
+(defun org-id-get-with-outline-drilling ()
+ "Use an outline-cycling interface to retrieve the ID of an entry.
+This only finds entries in the current buffer, using `org-get-location'.
+It returns the ID of the entry. If necessary, the ID is created."
+ (let* ((spos (org-get-location (current-buffer) org-goto-help))
+ (pom (and spos (move-marker (make-marker) (car spos)))))
+ (prog1 (org-id-get pom 'create)
+ (move-marker pom nil))))
+
+;;;###autoload
+(defun org-id-goto (id)
+ "Switch to the buffer containing the entry with id ID.
+Move the cursor to that entry in that buffer."
+ (interactive "sID: ")
+ (let ((m (org-id-find id 'marker)))
+ (unless m
+ (error "Cannot find entry with ID \"%s\"" id))
+ (pop-to-buffer-same-window (marker-buffer m))
+ (goto-char m)
+ (move-marker m nil)
+ (org-show-context)))
+
+;;;###autoload
+(defun org-id-find (id &optional markerp)
+ "Return the location of the entry with the id ID.
+The return value is a cons cell (file-name . position), or nil
+if there is no entry with that ID.
+With optional argument MARKERP, return the position as a new marker."
+ (cond
+ ((symbolp id) (setq id (symbol-name id)))
+ ((numberp id) (setq id (number-to-string id))))
+ (let ((file (org-id-find-id-file id))
+ org-agenda-new-buffers where)
+ (when file
+ (setq where (org-id-find-id-in-file id file markerp)))
+ (unless where
+ (org-id-update-id-locations nil t)
+ (setq file (org-id-find-id-file id))
+ (when file
+ (setq where (org-id-find-id-in-file id file markerp))))
+ where))
+
+;;; Internal functions
+
+;; Creating new IDs
+
+;;;###autoload
+(defun org-id-new (&optional prefix)
+ "Create a new globally unique ID.
+
+An ID consists of two parts separated by a colon:
+- a prefix
+- a unique part that will be created according to `org-id-method'.
+
+PREFIX can specify the prefix, the default is given by the variable
+`org-id-prefix'. However, if PREFIX is the symbol `none', don't use any
+prefix even if `org-id-prefix' specifies one.
+
+So a typical ID could look like \"Org:4nd91V40HI\"."
+ (let* ((prefix (if (eq prefix 'none)
+ ""
+ (concat (or prefix org-id-prefix) ":")))
+ unique)
+ (if (equal prefix ":") (setq prefix ""))
+ (cond
+ ((memq org-id-method '(uuidgen uuid))
+ (setq unique (org-trim (shell-command-to-string org-id-uuid-program)))
+ (unless (org-uuidgen-p unique)
+ (setq unique (org-id-uuid))))
+ ((eq org-id-method 'org)
+ (let* ((etime (org-reverse-string (org-id-time-to-b36)))
+ (postfix (if org-id-include-domain
+ (progn
+ (require 'message)
+ (concat "@" (message-make-fqdn))))))
+ (setq unique (concat etime postfix))))
+ (t (error "Invalid `org-id-method'")))
+ (concat prefix unique)))
+
+(defun org-id-uuid ()
+ "Return string with random (version 4) UUID."
+ (let ((rnd (md5 (format "%s%s%s%s%s%s%s"
+ (random)
+ (current-time)
+ (user-uid)
+ (emacs-pid)
+ (user-full-name)
+ user-mail-address
+ (recent-keys)))))
+ (format "%s-%s-4%s-%s%s-%s"
+ (substring rnd 0 8)
+ (substring rnd 8 12)
+ (substring rnd 13 16)
+ (format "%x"
+ (logior
+ #b10000000
+ (logand
+ #b10111111
+ (string-to-number
+ (substring rnd 16 18) 16))))
+ (substring rnd 18 20)
+ (substring rnd 20 32))))
+
+(defun org-id-int-to-b36-one-digit (i)
+ "Turn an integer between 0 and 61 into a single character 0..9, A..Z, a..z."
+ (cond
+ ((< i 10) (+ ?0 i))
+ ((< i 36) (+ ?a i -10))
+ (t (error "Larger that 35"))))
+
+(defun org-id-b36-to-int-one-digit (i)
+ "Turn a character 0..9, A..Z, a..z into a number 0..61.
+The input I may be a character, or a single-letter string."
+ (and (stringp i) (setq i (string-to-char i)))
+ (cond
+ ((and (>= i ?0) (<= i ?9)) (- i ?0))
+ ((and (>= i ?a) (<= i ?z)) (+ (- i ?a) 10))
+ (t (error "Invalid b36 letter"))))
+
+(defun org-id-int-to-b36 (i &optional length)
+ "Convert an integer to a base-36 number represented as a string."
+ (let ((s ""))
+ (while (> i 0)
+ (setq s (concat (char-to-string
+ (org-id-int-to-b36-one-digit (mod i 36))) s)
+ i (/ i 36)))
+ (setq length (max 1 (or length 1)))
+ (if (< (length s) length)
+ (setq s (concat (make-string (- length (length s)) ?0) s)))
+ s))
+
+(defun org-id-b36-to-int (s)
+ "Convert a base-36 string into the corresponding integer."
+ (let ((r 0))
+ (mapc (lambda (i) (setq r (+ (* r 36) (org-id-b36-to-int-one-digit i))))
+ s)
+ r))
+
+(defun org-id-time-to-b36 (&optional time)
+ "Encode TIME as a 10-digit string.
+This string holds the time to micro-second accuracy, and can be decoded
+using `org-id-decode'."
+ (setq time (or time (current-time)))
+ (concat (org-id-int-to-b36 (nth 0 time) 4)
+ (org-id-int-to-b36 (nth 1 time) 4)
+ (org-id-int-to-b36 (or (nth 2 time) 0) 4)))
+
+(defun org-id-decode (id)
+ "Split ID into the prefix and the time value that was used to create it.
+The return value is (prefix . time) where PREFIX is nil or a string,
+and time is the usual three-integer representation of time."
+ (let (prefix time parts)
+ (setq parts (org-split-string id ":"))
+ (if (= 2 (length parts))
+ (setq prefix (car parts) time (nth 1 parts))
+ (setq prefix nil time (nth 0 parts)))
+ (setq time (org-reverse-string time))
+ (setq time (list (org-id-b36-to-int (substring time 0 4))
+ (org-id-b36-to-int (substring time 4 8))
+ (org-id-b36-to-int (substring time 8 12))))
+ (cons prefix time)))
+
+;; Storing ID locations (files)
+
+;;;###autoload
+(defun org-id-update-id-locations (&optional files silent)
+ "Scan relevant files for IDs.
+Store the relation between files and corresponding IDs.
+This will scan all agenda files, all associated archives, and all
+files currently mentioned in `org-id-locations'.
+When FILES is given, scan these files instead."
+ (interactive)
+ (if (not org-id-track-globally)
+ (error "Please turn on `org-id-track-globally' if you want to track IDs")
+ (let* ((org-id-search-archives
+ (or org-id-search-archives
+ (and (symbolp org-id-extra-files)
+ (symbol-value org-id-extra-files)
+ (member 'agenda-archives org-id-extra-files))))
+ (files
+ (or files
+ (append
+ ;; Agenda files and all associated archives
+ (org-agenda-files t org-id-search-archives)
+ ;; Explicit extra files
+ (if (symbolp org-id-extra-files)
+ (symbol-value org-id-extra-files)
+ org-id-extra-files)
+ ;; Files associated with live Org buffers
+ (delq nil
+ (mapcar (lambda (b)
+ (with-current-buffer b
+ (and (derived-mode-p 'org-mode) (buffer-file-name))))
+ (buffer-list)))
+ ;; All files known to have IDs
+ org-id-files)))
+ org-agenda-new-buffers
+ file nfiles tfile ids reg found id seen (ndup 0))
+ (when (member 'agenda-archives files)
+ (setq files (delq 'agenda-archives (copy-sequence files))))
+ (setq nfiles (length files))
+ (while (setq file (pop files))
+ (unless silent
+ (message "Finding ID locations (%d/%d files): %s"
+ (- nfiles (length files)) nfiles file))
+ (setq tfile (file-truename file))
+ (when (and (file-exists-p file) (not (member tfile seen)))
+ (push tfile seen)
+ (setq ids nil)
+ (with-current-buffer (org-get-agenda-file-buffer file)
+ (save-excursion
+ (save-restriction
+ (widen)
+ (goto-char (point-min))
+ (while (re-search-forward "^[ \t]*:ID:[ \t]+\\(\\S-+\\)[ \t]*$"
+ nil t)
+ (setq id (match-string-no-properties 1))
+ (if (member id found)
+ (progn
+ (message "Duplicate ID \"%s\", also in file %s"
+ id (or (car (delq
+ nil
+ (mapcar
+ (lambda (x)
+ (if (member id (cdr x))
+ (car x)))
+ reg)))
+ (buffer-file-name)))
+ (when (= ndup 0)
+ (ding)
+ (sit-for 2))
+ (setq ndup (1+ ndup)))
+ (push id found)
+ (push id ids)))
+ (push (cons (abbreviate-file-name file) ids) reg))))))
+ (org-release-buffers org-agenda-new-buffers)
+ (setq org-agenda-new-buffers nil)
+ (setq org-id-locations reg)
+ (setq org-id-files (mapcar 'car org-id-locations))
+ (org-id-locations-save) ;; this function can also handle the alist form
+ ;; now convert to a hash
+ (setq org-id-locations (org-id-alist-to-hash org-id-locations))
+ (if (> ndup 0)
+ (message "WARNING: %d duplicate IDs found, check *Messages* buffer" ndup)
+ (message "%d unique files scanned for IDs" (length org-id-files)))
+ org-id-locations)))
+
+(defun org-id-locations-save ()
+ "Save `org-id-locations' in `org-id-locations-file'."
+ (when (and org-id-track-globally org-id-locations)
+ (let ((out (if (hash-table-p org-id-locations)
+ (org-id-hash-to-alist org-id-locations)
+ org-id-locations)))
+ (with-temp-file org-id-locations-file
+ (let ((print-level nil)
+ (print-length nil))
+ (print out (current-buffer)))))))
+
+(defun org-id-locations-load ()
+ "Read the data from `org-id-locations-file'."
+ (setq org-id-locations nil)
+ (when org-id-track-globally
+ (with-temp-buffer
+ (condition-case nil
+ (progn
+ (insert-file-contents-literally org-id-locations-file)
+ (goto-char (point-min))
+ (setq org-id-locations (read (current-buffer))))
+ (error
+ (message "Could not read org-id-values from %s. Setting it to nil."
+ org-id-locations-file))))
+ (setq org-id-files (mapcar 'car org-id-locations))
+ (setq org-id-locations (org-id-alist-to-hash org-id-locations))))
+
+(defun org-id-add-location (id file)
+ "Add the ID with location FILE to the database of ID locations."
+ ;; Only if global tracking is on, and when the buffer has a file
+ (when (and org-id-track-globally id file)
+ (unless org-id-locations (org-id-locations-load))
+ (puthash id (abbreviate-file-name file) org-id-locations)
+ (add-to-list 'org-id-files (abbreviate-file-name file))))
+
+(unless noninteractive
+ (add-hook 'kill-emacs-hook 'org-id-locations-save))
+
+(defun org-id-hash-to-alist (hash)
+ "Turn an org-id hash into an alist, so that it can be written to a file."
+ (let (res x)
+ (maphash
+ (lambda (k v)
+ (if (setq x (member v res))
+ (setcdr x (cons k (cdr x)))
+ (push (list v k) res)))
+ hash)
+ res))
+
+(defun org-id-alist-to-hash (list)
+ "Turn an org-id location list into a hash table."
+ (let ((res (make-hash-table
+ :test 'equal
+ :size (apply '+ (mapcar 'length list))))
+ f)
+ (mapc
+ (lambda (x)
+ (setq f (car x))
+ (mapc (lambda (i) (puthash i f res)) (cdr x)))
+ list)
+ res))
+
+(defun org-id-paste-tracker (txt &optional buffer-or-file)
+ "Update any IDs in TXT and assign BUFFER-OR-FILE to them."
+ (when org-id-track-globally
+ (save-match-data
+ (setq buffer-or-file (or buffer-or-file (current-buffer)))
+ (when (bufferp buffer-or-file)
+ (setq buffer-or-file (or (buffer-base-buffer buffer-or-file)
+ buffer-or-file))
+ (setq buffer-or-file (buffer-file-name buffer-or-file)))
+ (when buffer-or-file
+ (let ((fname (abbreviate-file-name buffer-or-file))
+ (s 0))
+ (while (string-match "^[ \t]*:ID:[ \t]+\\([^ \t\n\r]+\\)" txt s)
+ (setq s (match-end 0))
+ (org-id-add-location (match-string 1 txt) fname)))))))
+
+;; Finding entries with specified id
+
+;;;###autoload
+(defun org-id-find-id-file (id)
+ "Query the id database for the file in which this ID is located."
+ (unless org-id-locations (org-id-locations-load))
+ (or (and org-id-locations
+ (hash-table-p org-id-locations)
+ (gethash id org-id-locations))
+ ;; ball back on current buffer
+ (buffer-file-name (or (buffer-base-buffer (current-buffer))
+ (current-buffer)))))
+
+(defun org-id-find-id-in-file (id file &optional markerp)
+ "Return the position of the entry ID in FILE.
+If that files does not exist, or if it does not contain this ID,
+return nil.
+The position is returned as a cons cell (file-name . position). With
+optional argument MARKERP, return the position as a new marker."
+ (let (org-agenda-new-buffers buf pos)
+ (cond
+ ((not file) nil)
+ ((not (file-exists-p file)) nil)
+ (t (with-current-buffer (setq buf (org-get-agenda-file-buffer file))
+ (setq pos (org-find-entry-with-id id))
+ (when pos
+ (if markerp
+ (move-marker (make-marker) pos buf)
+ (cons file pos))))))))
+
+;; id link type
+
+;; Calling the following function is hard-coded into `org-store-link',
+;; so we do have to add it to `org-store-link-functions'.
+
+;;;###autoload
+(defun org-id-store-link ()
+ "Store a link to the current entry, using its ID."
+ (interactive)
+ (when (and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
+ (let* ((link (concat "id:" (org-id-get-create)))
+ (case-fold-search nil)
+ (desc (save-excursion
+ (org-back-to-heading t)
+ (or (and (looking-at org-complex-heading-regexp)
+ (if (match-end 4)
+ (match-string 4)
+ (match-string 0)))
+ link))))
+ (org-store-link-props :link link :description desc :type "id")
+ link)))
+
+(defun org-id-open (id)
+ "Go to the entry with id ID."
+ (org-mark-ring-push)
+ (let ((m (org-id-find id 'marker))
+ cmd)
+ (unless m
+ (error "Cannot find entry with ID \"%s\"" id))
+ ;; Use a buffer-switching command in analogy to finding files
+ (setq cmd
+ (or
+ (cdr
+ (assq
+ (cdr (assq 'file org-link-frame-setup))
+ '((find-file . switch-to-buffer)
+ (find-file-other-window . switch-to-buffer-other-window)
+ (find-file-other-frame . switch-to-buffer-other-frame))))
+ 'switch-to-buffer-other-window))
+ (if (not (equal (current-buffer) (marker-buffer m)))
+ (funcall cmd (marker-buffer m)))
+ (goto-char m)
+ (move-marker m nil)
+ (org-show-context)))
+
+(org-link-set-parameters "id" :follow #'org-id-open)
+
+(provide 'org-id)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-id.el ends here
diff --git a/lisp/org-indent.el b/lisp/org-indent.el
new file mode 100644
index 0000000..10c9617
--- /dev/null
+++ b/lisp/org-indent.el
@@ -0,0 +1,412 @@
+;;; org-indent.el --- Dynamic indentation for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+;;
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This is an implementation of dynamic virtual indentation. It works
+;; by adding text properties to a buffer to make sure lines are
+;; indented according to outline structure.
+;;
+;; The process is synchronous, toggled at every buffer modification.
+;; Though, the initialization (indentation of text already in the
+;; buffer), which can take a few seconds in large buffers, happens on
+;; idle time.
+;;
+;;; Code:
+
+(require 'org-macs)
+(require 'org-compat)
+(require 'org)
+
+(require 'cl-lib)
+
+(declare-function org-inlinetask-get-task-level "org-inlinetask" ())
+(declare-function org-inlinetask-in-task-p "org-inlinetask" ())
+(declare-function org-list-item-body-column "org-list" (item))
+(defvar org-inlinetask-show-first-star)
+
+(defgroup org-indent nil
+ "Options concerning dynamic virtual outline indentation."
+ :tag "Org Indent"
+ :group 'org)
+
+(defvar org-indent-inlinetask-first-star (org-add-props "*" '(face org-warning))
+ "First star of inline tasks, with correct face.")
+(defvar org-indent-agent-timer nil
+ "Timer running the initialize agent.")
+(defvar org-indent-agentized-buffers nil
+ "List of buffers watched by the initialize agent.")
+(defvar org-indent-agent-resume-timer nil
+ "Timer to reschedule agent after switching to other idle processes.")
+(defvar org-indent-agent-active-delay '(0 2 0)
+ "Time to run agent before switching to other idle processes.
+Delay used when the buffer to initialize is current.")
+(defvar org-indent-agent-passive-delay '(0 0 400000)
+ "Time to run agent before switching to other idle processes.
+Delay used when the buffer to initialize isn't current.")
+(defvar org-indent-agent-resume-delay '(0 0 100000)
+ "Minimal time for other idle processes before switching back to agent.")
+(defvar org-indent--initial-marker nil
+ "Position of initialization before interrupt.
+This is used locally in each buffer being initialized.")
+(defvar org-hide-leading-stars-before-indent-mode nil
+ "Used locally.")
+(defvar org-indent-modified-headline-flag nil
+ "Non-nil means the last deletion operated on a headline.
+It is modified by `org-indent-notify-modified-headline'.")
+
+
+(defcustom org-indent-boundary-char ?\s
+ "The end of the virtual indentation strings, a single-character string.
+The default is just a space, but if you wish, you can use \"|\" or so.
+This can be useful on a terminal window - under a windowing system,
+it may be prettier to customize the `org-indent' face."
+ :group 'org-indent
+ :type 'character)
+
+(defcustom org-indent-mode-turns-off-org-adapt-indentation t
+ "Non-nil means setting the variable `org-indent-mode' will \
+turn off indentation adaptation.
+For details see the variable `org-adapt-indentation'."
+ :group 'org-indent
+ :type 'boolean)
+
+(defcustom org-indent-mode-turns-on-hiding-stars t
+ "Non-nil means setting the variable `org-indent-mode' will \
+turn on `org-hide-leading-stars'."
+ :group 'org-indent
+ :type 'boolean)
+
+(defcustom org-indent-indentation-per-level 2
+ "Indentation per level in number of characters."
+ :group 'org-indent
+ :type 'integer)
+
+(defface org-indent '((t (:inherit org-hide)))
+ "Face for outline indentation.
+The default is to make it look like whitespace. But you may find it
+useful to make it ever so slightly different."
+ :group 'org-faces)
+
+(defvar org-indent--text-line-prefixes nil
+ "Vector containing line prefixes strings for regular text.")
+
+(defvar org-indent--heading-line-prefixes nil
+ "Vector containing line prefix strings for headlines.")
+
+(defvar org-indent--inlinetask-line-prefixes nil
+ "Vector containing line prefix strings for inline tasks.")
+
+(defconst org-indent--deepest-level 50
+ "Maximum theoretical headline depth.")
+
+(defun org-indent--compute-prefixes ()
+ "Compute prefix strings for regular text and headlines."
+ (setq org-indent--heading-line-prefixes
+ (make-vector org-indent--deepest-level nil))
+ (setq org-indent--inlinetask-line-prefixes
+ (make-vector org-indent--deepest-level nil))
+ (setq org-indent--text-line-prefixes
+ (make-vector org-indent--deepest-level nil))
+ (dotimes (n org-indent--deepest-level)
+ (let ((indentation (if (<= n 1) 0
+ (* (1- org-indent-indentation-per-level)
+ (1- n)))))
+ ;; Headlines line prefixes.
+ (let ((heading-prefix (make-string indentation ?*)))
+ (aset org-indent--heading-line-prefixes
+ n
+ (org-add-props heading-prefix nil 'face 'org-indent))
+ ;; Inline tasks line prefixes
+ (aset org-indent--inlinetask-line-prefixes
+ n
+ (org-add-props (if (bound-and-true-p org-inlinetask-show-first-star)
+ (concat org-indent-inlinetask-first-star
+ (substring heading-prefix 1))
+ heading-prefix)
+ nil 'face 'org-indent)))
+ ;; Text line prefixes.
+ (aset org-indent--text-line-prefixes
+ n
+ (concat (org-add-props (make-string (+ n indentation) ?\s)
+ nil 'face 'org-indent)
+ (and (> n 0)
+ (char-to-string org-indent-boundary-char)))))))
+
+(defsubst org-indent-remove-properties (beg end)
+ "Remove indentations between BEG and END."
+ (org-with-silent-modifications
+ (remove-text-properties beg end '(line-prefix nil wrap-prefix nil))))
+
+;;;###autoload
+(define-minor-mode org-indent-mode
+ "When active, indent text according to outline structure.
+
+Internally this works by adding `line-prefix' and `wrap-prefix'
+properties, after each buffer modification, on the modified zone.
+
+The process is synchronous. Though, initial indentation of
+buffer, which can take a few seconds on large buffers, is done
+during idle time."
+ nil " Ind" nil
+ (cond
+ (org-indent-mode
+ ;; mode was turned on.
+ (setq-local indent-tabs-mode nil)
+ (setq-local org-indent--initial-marker (copy-marker 1))
+ (when org-indent-mode-turns-off-org-adapt-indentation
+ (setq-local org-adapt-indentation nil))
+ (when org-indent-mode-turns-on-hiding-stars
+ (setq-local org-hide-leading-stars-before-indent-mode
+ org-hide-leading-stars)
+ (setq-local org-hide-leading-stars t))
+ (org-indent--compute-prefixes)
+ (add-hook 'filter-buffer-substring-functions
+ (lambda (fun start end delete)
+ (org-indent-remove-properties-from-string
+ (funcall fun start end delete)))
+ nil t)
+ (add-hook 'after-change-functions 'org-indent-refresh-maybe nil 'local)
+ (add-hook 'before-change-functions
+ 'org-indent-notify-modified-headline nil 'local)
+ (and font-lock-mode (org-restart-font-lock))
+ (org-indent-remove-properties (point-min) (point-max))
+ ;; Submit current buffer to initialize agent. If it's the first
+ ;; buffer submitted, also start the agent. Current buffer is
+ ;; pushed in both cases to avoid a race condition.
+ (if org-indent-agentized-buffers
+ (push (current-buffer) org-indent-agentized-buffers)
+ (push (current-buffer) org-indent-agentized-buffers)
+ (setq org-indent-agent-timer
+ (run-with-idle-timer 0.2 t #'org-indent-initialize-agent))))
+ (t
+ ;; mode was turned off (or we refused to turn it on)
+ (kill-local-variable 'org-adapt-indentation)
+ (setq org-indent-agentized-buffers
+ (delq (current-buffer) org-indent-agentized-buffers))
+ (when (markerp org-indent--initial-marker)
+ (set-marker org-indent--initial-marker nil))
+ (when (boundp 'org-hide-leading-stars-before-indent-mode)
+ (setq-local org-hide-leading-stars
+ org-hide-leading-stars-before-indent-mode))
+ (remove-hook 'filter-buffer-substring-functions
+ (lambda (fun start end delete)
+ (org-indent-remove-properties-from-string
+ (funcall fun start end delete))))
+ (remove-hook 'after-change-functions 'org-indent-refresh-maybe 'local)
+ (remove-hook 'before-change-functions
+ 'org-indent-notify-modified-headline 'local)
+ (org-with-wide-buffer
+ (org-indent-remove-properties (point-min) (point-max)))
+ (and font-lock-mode (org-restart-font-lock))
+ (redraw-display))))
+
+(defun org-indent-indent-buffer ()
+ "Add indentation properties to the accessible part of the buffer."
+ (interactive)
+ (if (not (derived-mode-p 'org-mode))
+ (error "Not in Org mode")
+ (message "Setting buffer indentation. It may take a few seconds...")
+ (org-indent-remove-properties (point-min) (point-max))
+ (org-indent-add-properties (point-min) (point-max))
+ (message "Indentation of buffer set.")))
+
+(defun org-indent-remove-properties-from-string (string)
+ "Remove indentation properties from STRING."
+ (remove-text-properties 0 (length string)
+ '(line-prefix nil wrap-prefix nil) string)
+ string)
+
+(defun org-indent-initialize-agent ()
+ "Start or resume current buffer initialization.
+Only buffers in `org-indent-agentized-buffers' trigger an action.
+When no more buffer is being watched, the agent suppress itself."
+ (when org-indent-agent-resume-timer
+ (cancel-timer org-indent-agent-resume-timer))
+ (setq org-indent-agentized-buffers
+ (cl-remove-if-not #'buffer-live-p org-indent-agentized-buffers))
+ (cond
+ ;; Job done: kill agent.
+ ((not org-indent-agentized-buffers) (cancel-timer org-indent-agent-timer))
+ ;; Current buffer is agentized: start/resume initialization
+ ;; somewhat aggressively.
+ ((memq (current-buffer) org-indent-agentized-buffers)
+ (org-indent-initialize-buffer (current-buffer)
+ org-indent-agent-active-delay))
+ ;; Else, start/resume initialization of the last agentized buffer,
+ ;; softly.
+ (t (org-indent-initialize-buffer (car org-indent-agentized-buffers)
+ org-indent-agent-passive-delay))))
+
+(defun org-indent-initialize-buffer (buffer delay)
+ "Set virtual indentation for the buffer BUFFER, asynchronously.
+Give hand to other idle processes if it takes longer than DELAY,
+a time value."
+ (with-current-buffer buffer
+ (when org-indent-mode
+ (org-with-wide-buffer
+ (let ((interruptp
+ ;; Always nil unless interrupted.
+ (catch 'interrupt
+ (and org-indent--initial-marker
+ (marker-position org-indent--initial-marker)
+ (equal (marker-buffer org-indent--initial-marker)
+ buffer)
+ (org-indent-add-properties org-indent--initial-marker
+ (point-max)
+ delay)
+ nil))))
+ (move-marker org-indent--initial-marker interruptp)
+ ;; Job is complete: un-agentize buffer.
+ (unless interruptp
+ (setq org-indent-agentized-buffers
+ (delq buffer org-indent-agentized-buffers))))))))
+
+(defun org-indent-set-line-properties (level indentation &optional heading)
+ "Set prefix properties on current line an move to next one.
+
+LEVEL is the current level of heading. INDENTATION is the
+expected indentation when wrapping line.
+
+When optional argument HEADING is non-nil, assume line is at
+a heading. Moreover, if is is `inlinetask', the first star will
+have `org-warning' face."
+ (let* ((line (aref (pcase heading
+ (`nil org-indent--text-line-prefixes)
+ (`inlinetask org-indent--inlinetask-line-prefixes)
+ (_ org-indent--heading-line-prefixes))
+ level))
+ (wrap
+ (org-add-props
+ (concat line
+ (if heading (concat (make-string level ?*) " ")
+ (make-string indentation ?\s)))
+ nil 'face 'org-indent)))
+ ;; Add properties down to the next line to indent empty lines.
+ (add-text-properties (line-beginning-position) (line-beginning-position 2)
+ `(line-prefix ,line wrap-prefix ,wrap)))
+ (forward-line))
+
+(defun org-indent-add-properties (beg end &optional delay)
+ "Add indentation properties between BEG and END.
+
+When DELAY is non-nil, it must be a time value. In that case,
+the process is asynchronous and can be interrupted, either by
+user request, or after DELAY. This is done by throwing the
+`interrupt' tag along with the buffer position where the process
+stopped."
+ (save-match-data
+ (org-with-wide-buffer
+ (goto-char beg)
+ (beginning-of-line)
+ ;; Initialize prefix at BEG, according to current entry's level.
+ (let* ((case-fold-search t)
+ (limited-re (org-get-limited-outline-regexp))
+ (level (or (org-current-level) 0))
+ (time-limit (and delay (time-add (current-time) delay))))
+ ;; For each line, set `line-prefix' and `wrap-prefix'
+ ;; properties depending on the type of line (headline, inline
+ ;; task, item or other).
+ (org-with-silent-modifications
+ (while (and (<= (point) end) (not (eobp)))
+ (cond
+ ;; When in asynchronous mode, check if interrupt is
+ ;; required.
+ ((and delay (input-pending-p)) (throw 'interrupt (point)))
+ ;; In asynchronous mode, take a break of
+ ;; `org-indent-agent-resume-delay' every DELAY to avoid
+ ;; blocking any other idle timer or process output.
+ ((and delay (time-less-p time-limit (current-time)))
+ (setq org-indent-agent-resume-timer
+ (run-with-idle-timer
+ (time-add (current-idle-time) org-indent-agent-resume-delay)
+ nil #'org-indent-initialize-agent))
+ (throw 'interrupt (point)))
+ ;; Headline or inline task.
+ ((looking-at org-outline-regexp)
+ (let* ((nstars (- (match-end 0) (match-beginning 0) 1))
+ (type (or (looking-at-p limited-re) 'inlinetask)))
+ (org-indent-set-line-properties nstars 0 type)
+ ;; At an headline, define new value for LEVEL.
+ (unless (eq type 'inlinetask) (setq level nstars))))
+ ;; List item: `wrap-prefix' is set where body starts.
+ ((org-at-item-p)
+ (org-indent-set-line-properties
+ level (org-list-item-body-column (point))))
+ ;; Regular line.
+ (t
+ (org-indent-set-line-properties level (org-get-indentation))))))))))
+
+(defun org-indent-notify-modified-headline (beg end)
+ "Set `org-indent-modified-headline-flag' depending on context.
+
+BEG and END are the positions of the beginning and end of the
+range of deleted text.
+
+This function is meant to be called by `before-change-functions'.
+Flag will be non-nil if command is going to modify or delete an
+headline."
+ (when org-indent-mode
+ (setq org-indent-modified-headline-flag
+ (org-with-wide-buffer
+ (goto-char beg)
+ (save-match-data
+ (or (and (org-at-heading-p) (< beg (match-end 0)))
+ (re-search-forward
+ (org-with-limited-levels org-outline-regexp-bol) end t)))))))
+
+(defun org-indent-refresh-maybe (beg end _)
+ "Refresh indentation properties in an adequate portion of buffer.
+BEG and END are the positions of the beginning and end of the
+range of inserted text. DUMMY is an unused argument.
+
+This function is meant to be called by `after-change-functions'."
+ (when org-indent-mode
+ (save-match-data
+ ;; If a headline was modified or inserted, set properties until
+ ;; next headline.
+ (org-with-wide-buffer
+ (if (or org-indent-modified-headline-flag
+ (save-excursion
+ (goto-char beg)
+ (beginning-of-line)
+ (re-search-forward
+ (org-with-limited-levels org-outline-regexp-bol) end t)))
+ (let ((end (save-excursion
+ (goto-char end)
+ (org-with-limited-levels (outline-next-heading))
+ (point))))
+ (setq org-indent-modified-headline-flag nil)
+ (org-indent-add-properties beg end))
+ ;; Otherwise, only set properties on modified area.
+ (org-indent-add-properties beg end))))))
+
+(provide 'org-indent)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-indent.el ends here
diff --git a/lisp/org-info.el b/lisp/org-info.el
new file mode 100644
index 0000000..79b9bcc
--- /dev/null
+++ b/lisp/org-info.el
@@ -0,0 +1,144 @@
+;;; org-info.el --- Support for Links to Info Nodes -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to Info nodes from within Org mode.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+
+;; Declare external functions and variables
+
+(declare-function Info-find-node "info"
+ (filename nodename &optional no-going-back strict-case))
+(defvar Info-current-file)
+(defvar Info-current-node)
+
+;; Install the link type
+(org-link-set-parameters "info"
+ :follow #'org-info-open
+ :export #'org-info-export
+ :store #'org-info-store-link)
+
+;; Implementation
+(defun org-info-store-link ()
+ "Store a link to an Info file and node."
+ (when (eq major-mode 'Info-mode)
+ (let ((link (concat "info:"
+ (file-name-nondirectory Info-current-file)
+ "#" Info-current-node))
+ (desc (concat (file-name-nondirectory Info-current-file)
+ "#" Info-current-node)))
+ (org-store-link-props :type "info" :file Info-current-file
+ :node Info-current-node
+ :link link :desc desc)
+ link)))
+
+(defun org-info-open (path)
+ "Follow an Info file and node link specified by PATH."
+ (org-info-follow-link path))
+
+
+(defun org-info-follow-link (name)
+ "Follow an Info file and node link specified by NAME."
+ (if (or (string-match "\\(.*\\)[#:]:?\\(.*\\)" name)
+ (string-match "\\(.*\\)" name))
+ (let ((filename (match-string 1 name))
+ (nodename-or-index (or (match-string 2 name) "Top")))
+ (require 'info)
+ ;; If nodename-or-index is invalid node name, then look it up
+ ;; in the index.
+ (condition-case nil
+ (Info-find-node filename nodename-or-index)
+ (user-error (Info-find-node filename "Top")
+ (condition-case nil
+ (Info-index nodename-or-index)
+ (user-error "Could not find '%s' node or index entry"
+ nodename-or-index)))))
+ (user-error "Could not open: %s" name)))
+
+(defconst org-info-emacs-documents
+ '("ada-mode" "auth" "autotype" "bovine" "calc" "ccmode" "cl" "dbus" "dired-x"
+ "ebrowse" "ede" "ediff" "edt" "efaq-w32" "efaq" "eieio" "eintr" "elisp"
+ "emacs-gnutls" "emacs-mime" "emacs" "epa" "erc" "ert" "eshell" "eudc" "eww"
+ "flymake" "forms" "gnus" "htmlfontify" "idlwave" "ido" "info" "mairix-el"
+ "message" "mh-e" "newsticker" "nxml-mode" "octave-mode" "org" "pcl-cvs"
+ "pgg" "rcirc" "reftex" "remember" "sasl" "sc" "semantic" "ses" "sieve"
+ "smtpmail" "speedbar" "srecode" "todo-mode" "tramp" "url" "vip" "viper"
+ "widget" "wisent" "woman")
+ "List of emacs documents available.
+Taken from <http://www.gnu.org/software/emacs/manual/html_mono/.>")
+
+(defconst org-info-other-documents
+ '(("libc" . "http://www.gnu.org/software/libc/manual/html_mono/libc.html")
+ ("make" . "http://www.gnu.org/software/make/manual/make.html"))
+ "Alist of documents generated from Texinfo source.
+When converting info links to HTML, links to any one of these manuals are
+converted to use these URL.")
+
+(defun org-info-map-html-url (filename)
+ "Return URL or HTML file associated to Info FILENAME.
+If FILENAME refers to an official GNU document, return a URL pointing to
+the official page for that document, e.g., use \"gnu.org\" for all Emacs
+related documents. Otherwise, append \".html\" extension to FILENAME.
+See `org-info-emacs-documents' and `org-info-other-documents' for details."
+ (cond ((member filename org-info-emacs-documents)
+ (format "http://www.gnu.org/software/emacs/manual/html_mono/%s.html"
+ filename))
+ ((cdr (assoc filename org-info-other-documents)))
+ (t (concat filename ".html"))))
+
+(defun org-info--expand-node-name (node)
+ "Expand Info NODE to HTML cross reference."
+ ;; See (info "(texinfo) HTML Xref Node Name Expansion") for the
+ ;; expansion rule.
+ (let ((node (replace-regexp-in-string
+ "\\([ \t\n\r]+\\)\\|\\([^a-zA-Z0-9]\\)"
+ (lambda (m)
+ (if (match-end 1) "-" (format "_%04x" (string-to-char m))))
+ (org-trim node))))
+ (cond ((string= node "") "")
+ ((string-match-p "\\`[0-9]" node) (concat "g_t" node))
+ (t node))))
+
+(defun org-info-export (path desc format)
+ "Export an info link.
+See `org-link-parameters' for details about PATH, DESC and FORMAT."
+ (when (eq format 'html)
+ (or (string-match "\\(.*\\)[#:]:?\\(.*\\)" path)
+ (string-match "\\(.*\\)" path))
+ (let ((filename (match-string 1 path))
+ (node (or (match-string 2 path) "Top")))
+ (format "<a href=\"%s#%s\">%s</a>"
+ (org-info-map-html-url filename)
+ (org-info--expand-node-name node)
+ (or desc path)))))
+
+(provide 'org-info)
+
+;;; org-info.el ends here
diff --git a/lisp/org-inlinetask.el b/lisp/org-inlinetask.el
new file mode 100644
index 0000000..2918d40
--- /dev/null
+++ b/lisp/org-inlinetask.el
@@ -0,0 +1,348 @@
+;;; org-inlinetask.el --- Tasks Independent of Outline Hierarchy -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This module implements inline tasks in Org mode. Inline tasks are
+;; tasks that have all the properties of normal outline nodes,
+;; including the ability to store meta data like scheduling dates,
+;; TODO state, tags and properties. However, these nodes are treated
+;; specially by the visibility cycling.
+;;
+;; Visibility cycling exempts these nodes from cycling. So whenever
+;; their parent is opened, so are these tasks. This will only work
+;; with `org-cycle', so if you are also using other commands to
+;; show/hide entries, you will occasionally find these tasks to behave
+;; like all other outline nodes, seemingly splitting the text of the
+;; parent into children.
+;;
+;; Special fontification of inline tasks, so that they can be
+;; immediately recognized. From the stars of the headline, only the
+;; first and the last two will be visible, the others will be hidden
+;; using the `org-hide' face.
+;;
+;; An inline task is identified solely by a minimum outline level,
+;; given by the variable `org-inlinetask-min-level', default 15.
+;;
+;; If you need to have a time planning line (DEADLINE etc), drawers,
+;; for example LOGBOOK of PROPERTIES, or even normal text as part of
+;; the inline task, you must add an "END" headline with the same
+;; number of stars.
+;;
+;; As an example, here are two valid inline tasks:
+;;
+;; **************** TODO a small task
+;;
+;; and
+;;
+;; **************** TODO another small task
+;; DEADLINE: <2009-03-30 Mon>
+;; :PROPERTIES:
+;; :SOMETHING: or other
+;; :END:
+;; And here is some extra text
+;; **************** END
+;;
+;; Also, if you want to use refiling and archiving for inline tasks,
+;; The END line must be present to make things work properly.
+;;
+;; Note that you should not try to use inline tasks within plain list,
+;; visibility cycling is known to be problematic when doing so.
+;;
+;; This package installs one new command:
+;;
+;; C-c C-x t Insert a new inline task with END line
+
+;;; Code:
+
+(require 'org)
+
+(defgroup org-inlinetask nil
+ "Options concerning inline tasks in Org mode."
+ :tag "Org Inline Tasks"
+ :group 'org-structure)
+
+(defcustom org-inlinetask-min-level 15
+ "Minimum level a headline must have before it is treated as an inline task.
+Don't set it to something higher than `29' or clocking will break since this
+is the hardcoded maximum number of stars `org-clock-sum' will work with.
+
+It is strongly recommended that you set `org-cycle-max-level' not at all,
+or to a number smaller than this one. In fact, when `org-cycle-max-level' is
+not set, it will be assumed to be one less than the value of smaller than
+the value of this variable."
+ :group 'org-inlinetask
+ :type '(choice
+ (const :tag "Off" nil)
+ (integer)))
+
+(defcustom org-inlinetask-show-first-star nil
+ "Non-nil means display the first star of an inline task as additional marker.
+When nil, the first star is not shown."
+ :tag "Org Inline Tasks"
+ :group 'org-structure
+ :type 'boolean)
+
+(defvar org-odd-levels-only)
+(defvar org-keyword-time-regexp)
+(defvar org-complex-heading-regexp)
+(defvar org-property-end-re)
+
+(defcustom org-inlinetask-default-state nil
+ "Non-nil means make inline tasks have a TODO keyword initially.
+This should be the state `org-inlinetask-insert-task' should use by
+default, or nil of no state should be assigned."
+ :group 'org-inlinetask
+ :version "24.1"
+ :type '(choice
+ (const :tag "No state" nil)
+ (string :tag "Specific state")))
+
+(defun org-inlinetask-insert-task (&optional no-state)
+ "Insert an inline task.
+If prefix arg NO-STATE is set, ignore `org-inlinetask-default-state'."
+ (interactive "P")
+ ;; Error when inside an inline task, except if point was at its very
+ ;; beginning, in which case the new inline task will be inserted
+ ;; before this one.
+ (when (and (org-inlinetask-in-task-p)
+ (not (and (org-inlinetask-at-task-p) (bolp))))
+ (error "Cannot nest inline tasks"))
+ (or (bolp) (newline))
+ (let* ((indent (if org-odd-levels-only
+ (1- (* 2 org-inlinetask-min-level))
+ org-inlinetask-min-level))
+ (indent-string (concat (make-string indent ?*) " ")))
+ (insert indent-string
+ (if (or no-state (not org-inlinetask-default-state))
+ "\n"
+ (concat org-inlinetask-default-state " \n"))
+ indent-string "END\n"))
+ (end-of-line -1))
+(define-key org-mode-map "\C-c\C-xt" 'org-inlinetask-insert-task)
+
+(defun org-inlinetask-outline-regexp ()
+ "Return string matching an inline task heading.
+The number of levels is controlled by `org-inlinetask-min-level'."
+ (let ((nstars (if org-odd-levels-only
+ (1- (* org-inlinetask-min-level 2))
+ org-inlinetask-min-level)))
+ (format "^\\(\\*\\{%d,\\}\\)[ \t]+" nstars)))
+
+(defun org-inlinetask-at-task-p ()
+ "Return true if point is at beginning of an inline task."
+ (save-excursion
+ (beginning-of-line)
+ (and (looking-at (concat (org-inlinetask-outline-regexp) "\\(.*\\)"))
+ (not (string-match "^end[ \t]*$" (downcase (match-string 2)))))))
+
+(defun org-inlinetask-in-task-p ()
+ "Return true if point is inside an inline task."
+ (save-excursion
+ (beginning-of-line)
+ (let* ((case-fold-search t)
+ (stars-re (org-inlinetask-outline-regexp))
+ (task-beg-re (concat stars-re "\\(?:.*\\)"))
+ (task-end-re (concat stars-re "END[ \t]*$")))
+ (or (looking-at-p task-beg-re)
+ (and (re-search-forward "^\\*+[ \t]+" nil t)
+ (progn (beginning-of-line) (looking-at-p task-end-re)))))))
+
+(defun org-inlinetask-goto-beginning ()
+ "Go to the beginning of the inline task at point."
+ (end-of-line)
+ (let ((case-fold-search t)
+ (inlinetask-re (org-inlinetask-outline-regexp)))
+ (re-search-backward inlinetask-re nil t)
+ (when (looking-at-p (concat inlinetask-re "END[ \t]*$"))
+ (re-search-backward inlinetask-re nil t))))
+
+(defun org-inlinetask-goto-end ()
+ "Go to the end of the inline task at point.
+Return point."
+ (save-match-data
+ (beginning-of-line)
+ (let* ((case-fold-search t)
+ (inlinetask-re (org-inlinetask-outline-regexp))
+ (task-end-re (concat inlinetask-re "END[ \t]*$")))
+ (cond
+ ((looking-at task-end-re))
+ ((looking-at inlinetask-re)
+ (forward-line)
+ (cond
+ ((looking-at task-end-re))
+ ((looking-at inlinetask-re))
+ ((org-inlinetask-in-task-p)
+ (re-search-forward inlinetask-re nil t))))
+ (t (re-search-forward inlinetask-re nil t)))
+ (end-of-line)
+ (point))))
+
+(defun org-inlinetask-get-task-level ()
+ "Get the level of the inline task around.
+This assumes the point is inside an inline task."
+ (save-excursion
+ (end-of-line)
+ (re-search-backward (org-inlinetask-outline-regexp) nil t)
+ (- (match-end 1) (match-beginning 1))))
+
+(defun org-inlinetask-promote ()
+ "Promote the inline task at point.
+If the task has an end part, promote it. Also, prevents level from
+going below `org-inlinetask-min-level'."
+ (interactive)
+ (if (not (org-inlinetask-in-task-p))
+ (error "Not in an inline task")
+ (save-excursion
+ (let* ((lvl (org-inlinetask-get-task-level))
+ (next-lvl (org-get-valid-level lvl -1))
+ (diff (- next-lvl lvl))
+ (down-task (concat (make-string next-lvl ?*)))
+ beg)
+ (if (< next-lvl org-inlinetask-min-level)
+ (error "Cannot promote an inline task at minimum level")
+ (org-inlinetask-goto-beginning)
+ (setq beg (point))
+ (replace-match down-task nil t nil 1)
+ (org-inlinetask-goto-end)
+ (if (eobp) (beginning-of-line) (forward-line -1))
+ (unless (= (point) beg)
+ (replace-match down-task nil t nil 1)
+ (when org-adapt-indentation
+ (goto-char beg)
+ (org-fixup-indentation diff))))))))
+
+(defun org-inlinetask-demote ()
+ "Demote the inline task at point.
+If the task has an end part, also demote it."
+ (interactive)
+ (if (not (org-inlinetask-in-task-p))
+ (error "Not in an inline task")
+ (save-excursion
+ (let* ((lvl (org-inlinetask-get-task-level))
+ (next-lvl (org-get-valid-level lvl 1))
+ (diff (- next-lvl lvl))
+ (down-task (concat (make-string next-lvl ?*)))
+ beg)
+ (org-inlinetask-goto-beginning)
+ (setq beg (point))
+ (replace-match down-task nil t nil 1)
+ (org-inlinetask-goto-end)
+ (if (eobp) (beginning-of-line) (forward-line -1))
+ (unless (= (point) beg)
+ (replace-match down-task nil t nil 1)
+ (when org-adapt-indentation
+ (goto-char beg)
+ (org-fixup-indentation diff)))))))
+
+(defun org-inlinetask-get-current-indentation ()
+ "Get the indentation of the last non-while line above this one."
+ (save-excursion
+ (beginning-of-line 1)
+ (skip-chars-backward " \t\n")
+ (beginning-of-line 1)
+ (or (org-at-item-p)
+ (looking-at "[ \t]*"))
+ (goto-char (match-end 0))
+ (current-column)))
+
+(defvar org-indent-indentation-per-level) ; defined in org-indent.el
+
+(defface org-inlinetask '((t :inherit shadow))
+ "Face for inlinetask headlines."
+ :group 'org-faces)
+
+(defun org-inlinetask-fontify (limit)
+ "Fontify the inline tasks down to LIMIT."
+ (let* ((nstars (if org-odd-levels-only
+ (1- (* 2 (or org-inlinetask-min-level 200)))
+ (or org-inlinetask-min-level 200)))
+ (re (concat "^\\(\\*\\)\\(\\*\\{"
+ (format "%d" (- nstars 3))
+ ",\\}\\)\\(\\*\\* .*\\)"))
+ ;; Virtual indentation will add the warning face on the first
+ ;; star. Thus, in that case, only hide it.
+ (start-face (if (and (bound-and-true-p org-indent-mode)
+ (> org-indent-indentation-per-level 1))
+ 'org-hide
+ 'org-warning)))
+ (while (re-search-forward re limit t)
+ (if org-inlinetask-show-first-star
+ (add-text-properties (match-beginning 1) (match-end 1)
+ `(face ,start-face font-lock-fontified t)))
+ (add-text-properties (match-beginning
+ (if org-inlinetask-show-first-star 2 1))
+ (match-end 2)
+ '(face org-hide font-lock-fontified t))
+ (add-text-properties (match-beginning 3) (match-end 3)
+ '(face org-inlinetask font-lock-fontified t)))))
+
+(defun org-inlinetask-toggle-visibility ()
+ "Toggle visibility of inline task at point."
+ (let ((end (save-excursion
+ (org-inlinetask-goto-end)
+ (if (bolp) (1- (point)) (point))))
+ (start (save-excursion
+ (org-inlinetask-goto-beginning)
+ (point-at-eol))))
+ (cond
+ ;; Nothing to show/hide.
+ ((= end start))
+ ;; Inlinetask was folded: expand it.
+ ((eq (get-char-property (1+ start) 'invisible) 'outline)
+ (outline-flag-region start end nil)
+ (org-cycle-hide-drawers 'children))
+ (t (outline-flag-region start end t)))))
+
+(defun org-inlinetask-hide-tasks (state)
+ "Hide inline tasks in buffer when STATE is `contents' or `children'.
+This function is meant to be used in `org-cycle-hook'."
+ (pcase state
+ (`contents
+ (let ((regexp (org-inlinetask-outline-regexp)))
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (org-inlinetask-toggle-visibility)
+ (org-inlinetask-goto-end)))))
+ (`children
+ (save-excursion
+ (while (and (outline-next-heading) (org-inlinetask-at-task-p))
+ (org-inlinetask-toggle-visibility)
+ (org-inlinetask-goto-end))))))
+
+(defun org-inlinetask-remove-END-maybe ()
+ "Remove an END line when present."
+ (when (looking-at (format "\\([ \t]*\n\\)*\\*\\{%d,\\}[ \t]+END[ \t]*$"
+ org-inlinetask-min-level))
+ (replace-match "")))
+
+(add-hook 'org-font-lock-hook 'org-inlinetask-fontify)
+(add-hook 'org-cycle-hook 'org-inlinetask-hide-tasks)
+
+(provide 'org-inlinetask)
+
+;;; org-inlinetask.el ends here
diff --git a/lisp/org-install.el b/lisp/org-install.el
new file mode 100644
index 0000000..5835959
--- /dev/null
+++ b/lisp/org-install.el
@@ -0,0 +1,17 @@
+;;; org-install.el --- backward compatibility file for obsolete configuration
+;;
+;;; Code:
+;;
+;; The file org-install is obsolete.
+;;
+;; It is provided here so that (require 'org-install) does not
+;; trigger an error for users with obsolete Emacs configuration.
+;; You can safely remove (require 'org-install) from your config."
+
+(provide 'org-install)
+
+;; Local Variables:
+;; no-byte-compile: t
+;; coding: utf-8
+;; End:
+;;; org-install.el ends here
diff --git a/lisp/org-irc.el b/lisp/org-irc.el
new file mode 100644
index 0000000..3a6a7f4
--- /dev/null
+++ b/lisp/org-irc.el
@@ -0,0 +1,253 @@
+;;; org-irc.el --- Store Links to IRC Sessions -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Philip Jackson <emacs@shellarchive.co.uk>
+;; Keywords: erc, irc, link, org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This file implements links to an IRC session from within Org mode.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+;;
+;; Please customize the variable `org-modules' to select
+;; extensions you would like to use, and to deselect those which you don't
+;; want.
+;;
+;; Please note that at the moment only ERC is supported. Other clients
+;; shouldn't be difficult to add though.
+;;
+;; Then set `org-irc-link-to-logs' to non-nil if you would like a
+;; file:/ type link to be created to the current line in the logs or
+;; to t if you would like to create an irc:/ style link.
+;;
+;; Links within an org buffer might look like this:
+;;
+;; [[irc:/irc.freenode.net/#emacs/bob][chat with bob in #emacs on freenode]]
+;; [[irc:/irc.freenode.net/#emacs][#emacs on freenode]]
+;; [[irc:/irc.freenode.net/]]
+;;
+;; If, when the resulting link is visited, there is no connection to a
+;; requested server then one will be created.
+
+;;; Code:
+
+(require 'org)
+
+;; Declare the function form ERC that we use.
+(declare-function erc-current-logfile "erc-log" (&optional buffer))
+(declare-function erc-prompt "erc" ())
+(declare-function erc-default-target "erc" ())
+(declare-function erc-channel-p "erc" (channel))
+(declare-function erc-buffer-filter "erc" (predicate &optional proc))
+(declare-function erc-server-buffer "erc" ())
+(declare-function erc-get-server-nickname-list "erc" ())
+(declare-function erc-cmd-JOIN "erc" (channel &optional key))
+
+(defvar org-irc-client 'erc
+ "The IRC client to act on.")
+(defvar org-irc-link-to-logs nil
+ "Non-nil will store a link to the logs, nil will store an irc: style link.")
+
+(defvar erc-default-port) ; dynamically scoped from erc.el
+(defvar erc-session-port) ; dynamically scoped form erc-backend.el
+(defvar erc-session-server) ; dynamically scoped form erc-backend.el
+
+;; Generic functions/config (extend these for other clients)
+
+(org-link-set-parameters "irc" :follow #'org-irc-visit :store #'org-irc-store-link)
+
+(defun org-irc-visit (link)
+ "Parse LINK and dispatch to the correct function based on the client found."
+ (let ((link (org-irc-parse-link link)))
+ (cond
+ ((eq org-irc-client 'erc)
+ (org-irc-visit-erc link))
+ (t
+ (error "ERC only known client")))))
+
+(defun org-irc-parse-link (link)
+ "Parse an IRC LINK and return the attributes found.
+Parse a LINK that looks like server:port/chan/user (port, chan
+and user being optional) and return any of the port, channel or user
+attributes that are found."
+ (let* ((parts (split-string link "/" t))
+ (len (length parts)))
+ (when (or (< len 1) (> len 3))
+ (error "Failed to parse link needed 1-3 parts, got %d" len))
+ (setcar parts (split-string (car parts) ":" t))
+ parts))
+
+;;;###autoload
+(defun org-irc-store-link ()
+ "Dispatch to the appropriate function to store a link to an IRC session."
+ (cond
+ ((eq major-mode 'erc-mode)
+ (org-irc-erc-store-link))))
+
+(defun org-irc-ellipsify-description (string &optional after)
+ "Remove unnecessary white space from STRING and add ellipses if necessary.
+Strip starting and ending white space from STRING and replace any
+chars that the value AFTER with `...'"
+ (let* ((after (number-to-string (or after 30)))
+ (replace-map (list (cons "^[ \t]*" "")
+ (cons "[ \t]*$" "")
+ (cons (concat "^\\(.\\{" after
+ "\\}\\).*") "\\1..."))))
+ (dolist (x replace-map string)
+ (when (string-match (car x) string)
+ (setq string (replace-match (cdr x) nil nil string))))))
+
+;; ERC specific functions
+
+(defun org-irc-erc-get-line-from-log (erc-line)
+ "Find the best line to link to from the ERC logs given ERC-LINE as a start.
+If the user is on the ERC-prompt then search backward for the
+first non-blank line, otherwise return the current line. The
+result is a cons of the filename and search string."
+ (erc-save-buffer-in-logs)
+ (require 'erc-log)
+ (with-current-buffer (find-file-noselect (erc-current-logfile))
+ (goto-char (point-max))
+ (list
+ (abbreviate-file-name buffer-file-name)
+ ;; can we get a '::' part?
+ (if (string= erc-line (erc-prompt))
+ (progn
+ (goto-char (point-at-bol))
+ (when (search-backward-regexp "^[^ ]" nil t)
+ (buffer-substring-no-properties (point-at-bol)
+ (point-at-eol))))
+ (when (search-backward erc-line nil t)
+ (buffer-substring-no-properties (point-at-bol)
+ (point-at-eol)))))))
+
+(defun org-irc-erc-store-link ()
+ "Store a link to the IRC log file or the session itself.
+Depending on the variable `org-irc-link-to-logs' store either a
+link to the log file for the current session or an irc: link to
+the session itself."
+ (require 'erc-log)
+ (if org-irc-link-to-logs
+ (let* ((erc-line (buffer-substring-no-properties
+ (point-at-bol) (point-at-eol)))
+ (parsed-line (org-irc-erc-get-line-from-log erc-line)))
+ (if (erc-logging-enabled nil)
+ (progn
+ (org-store-link-props
+ :type "file"
+ :description (concat "'" (org-irc-ellipsify-description
+ (cadr parsed-line) 20)
+ "' from an IRC conversation")
+ :link (concat "file:" (car parsed-line) "::"
+ (cadr parsed-line)))
+ t)
+ (error "This ERC session is not being logged")))
+ (let* ((link-text (org-irc-get-erc-link))
+ (link (org-irc-parse-link link-text)))
+ (if link-text
+ (progn
+ (org-store-link-props
+ :type "irc"
+ :link (concat "irc:/" link-text)
+ :description (concat "irc session `" link-text "'")
+ :server (car (car link))
+ :port (or (string-to-number (cadr (pop link))) erc-default-port)
+ :nick (pop link))
+ t)
+ (error "Failed to create ('irc:/' style) ERC link")))))
+
+(defun org-irc-get-erc-link ()
+ "Return an org compatible irc:/ link from an ERC buffer."
+ (let* ((session-port (if (numberp erc-session-port)
+ (number-to-string erc-session-port)
+ erc-session-port))
+ (link (concat erc-session-server ":" session-port)))
+ (concat link "/"
+ (if (and (erc-default-target)
+ (erc-channel-p (erc-default-target))
+ (car (get-text-property (point) 'erc-data)))
+ ;; we can get a nick
+ (let ((nick (car (get-text-property (point) 'erc-data))))
+ (concat (erc-default-target) "/" nick))
+ (erc-default-target)))))
+
+(defun org-irc-get-current-erc-port ()
+ "Return the current port as a number.
+Return the current port number or, if none is set, return the ERC
+default."
+ (cond
+ ((stringp erc-session-port)
+ (string-to-number erc-session-port))
+ ((numberp erc-session-port)
+ erc-session-port)
+ (t
+ erc-default-port)))
+
+(defun org-irc-visit-erc (link)
+ "Visit an ERC buffer based on criteria found in LINK."
+ (require 'erc)
+ (require 'erc-log)
+ (let* ((server (car (car link)))
+ (port (or (string-to-number (cadr (pop link))) erc-default-port))
+ (server-buffer)
+ (buffer-list
+ (erc-buffer-filter
+ (lambda nil
+ (let ((tmp-server-buf (erc-server-buffer)))
+ (and tmp-server-buf
+ (with-current-buffer tmp-server-buf
+ (and
+ (eq (org-irc-get-current-erc-port) port)
+ (string= erc-session-server server)
+ (setq server-buffer tmp-server-buf)))))))))
+ (if buffer-list
+ (let ((chan-name (pop link)))
+ ;; if we got a channel name then switch to it or join it
+ (if chan-name
+ (let ((chan-buf (catch 'found
+ (dolist (x buffer-list)
+ (if (string= (buffer-name x) chan-name)
+ (throw 'found x))))))
+ (if chan-buf
+ (progn
+ (pop-to-buffer-same-window chan-buf)
+ ;; if we got a nick, and they're in the chan,
+ ;; then start a chat with them
+ (let ((nick (pop link)))
+ (when nick
+ (if (member nick (erc-get-server-nickname-list))
+ (progn
+ (goto-char (point-max))
+ (insert (concat nick ": ")))
+ (error "%s not found in %s" nick chan-name)))))
+ (progn
+ (pop-to-buffer-same-window server-buffer)
+ (erc-cmd-JOIN chan-name))))
+ (pop-to-buffer-same-window server-buffer)))
+ ;; no server match, make new connection
+ (erc-select :server server :port port))))
+
+(provide 'org-irc)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-irc.el ends here
diff --git a/lisp/org-lint.el b/lisp/org-lint.el
new file mode 100644
index 0000000..89aed4b
--- /dev/null
+++ b/lisp/org-lint.el
@@ -0,0 +1,1225 @@
+;;; org-lint.el --- Linting for Org documents -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2015-2017 Free Software Foundation
+
+;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This program is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements linting for Org syntax. The sole public
+;; function is `org-lint', which see.
+
+;; Internally, the library defines a new structure:
+;; `org-lint-checker', with the following slots:
+
+;; - NAME: Unique check identifier, as a non-nil symbol that doesn't
+;; start with an hyphen.
+;;
+;; The check is done calling the function `org-lint-NAME' with one
+;; mandatory argument, the parse tree describing the current Org
+;; buffer. Such function calls are wrapped within
+;; a `save-excursion' and point is always at `point-min'. Its
+;; return value has to be an alist (POSITION MESSAGE) when
+;; POSITION refer to the buffer position of the error, as an
+;; integer, and MESSAGE is a string describing the error.
+
+;; - DESCRIPTION: Summary about the check, as a string.
+
+;; - CATEGORIES: Categories relative to the check, as a list of
+;; symbol. They are used for filtering when calling `org-lint'.
+;; Checkers not explicitly associated to a category are collected
+;; in the `default' one.
+
+;; - TRUST: The trust level one can have in the check. It is either
+;; `low' or `high', depending on the heuristics implemented and
+;; the nature of the check. This has an indicative value only and
+;; is displayed along reports.
+
+;; All checks have to be listed in `org-lint--checkers'.
+
+;; Results are displayed in a special "*Org Lint*" buffer with
+;; a dedicated major mode, derived from `tabulated-list-mode'.
+;;
+;; In addition to the usual key-bindings inherited from it, "C-j" and
+;; "TAB" display problematic line reported under point whereas "RET"
+;; jumps to it. Also, "h" hides all reports similar to the current
+;; one. Additionally, "i" removes them from subsequent reports.
+
+;; Checks currently implemented are:
+
+;; - duplicate CUSTOM_ID properties
+;; - duplicate NAME values
+;; - duplicate targets
+;; - duplicate footnote definitions
+;; - orphaned affiliated keywords
+;; - obsolete affiliated keywords
+;; - missing language in src blocks
+;; - missing back-end in export blocks
+;; - invalid Babel call blocks
+;; - NAME values with a colon
+;; - deprecated export block syntax
+;; - deprecated Babel header properties
+;; - wrong header arguments in src blocks
+;; - misuse of CATEGORY keyword
+;; - "coderef" links with unknown destination
+;; - "custom-id" links with unknown destination
+;; - "fuzzy" links with unknown destination
+;; - "id" links with unknown destination
+;; - links to non-existent local files
+;; - SETUPFILE keywords with non-existent file parameter
+;; - INCLUDE keywords with wrong link parameter
+;; - obsolete markup in INCLUDE keyword
+;; - unknown items in OPTIONS keyword
+;; - spurious macro arguments or invalid macro templates
+;; - special properties in properties drawer
+;; - obsolete syntax for PROPERTIES drawers
+;; - missing definition for footnote references
+;; - missing reference for footnote definitions
+;; - non-footnote definitions in footnote section
+;; - probable invalid keywords
+;; - invalid blocks
+;; - misplaced planning info line
+;; - incomplete drawers
+;; - indented diary-sexps
+;; - obsolete QUOTE section
+;; - obsolete "file+application" link
+;; - blank headlines with tags
+
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-element)
+(require 'org-macro)
+(require 'ox)
+(require 'ob)
+
+
+;;; Checkers
+
+(cl-defstruct (org-lint-checker (:copier nil))
+ (name 'missing-checker-name)
+ (description "")
+ (categories '(default))
+ (trust 'high)) ; `low' or `high'
+
+(defun org-lint-missing-checker-name (_)
+ (error
+ "`A checker has no `:name' property. Please verify `org-lint--checkers'"))
+
+(defconst org-lint--checkers
+ (list
+ (make-org-lint-checker
+ :name 'duplicate-custom-id
+ :description "Report duplicates CUSTOM_ID properties"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'duplicate-name
+ :description "Report duplicate NAME values"
+ :categories '(babel link))
+ (make-org-lint-checker
+ :name 'duplicate-target
+ :description "Report duplicate targets"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'duplicate-footnote-definition
+ :description "Report duplicate footnote definitions"
+ :categories '(footnote))
+ (make-org-lint-checker
+ :name 'orphaned-affiliated-keywords
+ :description "Report orphaned affiliated keywords"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'obsolete-affiliated-keywords
+ :description "Report obsolete affiliated keywords"
+ :categories '(obsolete))
+ (make-org-lint-checker
+ :name 'deprecated-export-blocks
+ :description "Report deprecated export block syntax"
+ :categories '(obsolete export)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'deprecated-header-syntax
+ :description "Report deprecated Babel header syntax"
+ :categories '(obsolete babel)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'missing-language-in-src-block
+ :description "Report missing language in src blocks"
+ :categories '(babel))
+ (make-org-lint-checker
+ :name 'missing-backend-in-export-block
+ :description "Report missing back-end in export blocks"
+ :categories '(export))
+ (make-org-lint-checker
+ :name 'invalid-babel-call-block
+ :description "Report invalid Babel call blocks"
+ :categories '(babel))
+ (make-org-lint-checker
+ :name 'colon-in-name
+ :description "Report NAME values with a colon"
+ :categories '(babel))
+ (make-org-lint-checker
+ :name 'wrong-header-argument
+ :description "Report wrong babel headers"
+ :categories '(babel))
+ (make-org-lint-checker
+ :name 'wrong-header-value
+ :description "Report invalid value in babel headers"
+ :categories '(babel)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'deprecated-category-setup
+ :description "Report misuse of CATEGORY keyword"
+ :categories '(obsolete))
+ (make-org-lint-checker
+ :name 'invalid-coderef-link
+ :description "Report \"coderef\" links with unknown destination"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'invalid-custom-id-link
+ :description "Report \"custom-id\" links with unknown destination"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'invalid-fuzzy-link
+ :description "Report \"fuzzy\" links with unknown destination"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'invalid-id-link
+ :description "Report \"id\" links with unknown destination"
+ :categories '(link))
+ (make-org-lint-checker
+ :name 'link-to-local-file
+ :description "Report links to non-existent local files"
+ :categories '(link)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'non-existent-setupfile-parameter
+ :description "Report SETUPFILE keywords with non-existent file parameter"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'wrong-include-link-parameter
+ :description "Report INCLUDE keywords with misleading link parameter"
+ :categories '(export)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'obsolete-include-markup
+ :description "Report obsolete markup in INCLUDE keyword"
+ :categories '(obsolete export)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'unknown-options-item
+ :description "Report unknown items in OPTIONS keyword"
+ :categories '(export)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'invalid-macro-argument-and-template
+ :description "Report spurious macro arguments or invalid macro templates"
+ :categories '(export)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'special-property-in-properties-drawer
+ :description "Report special properties in properties drawers"
+ :categories '(properties))
+ (make-org-lint-checker
+ :name 'obsolete-properties-drawer
+ :description "Report obsolete syntax for properties drawers"
+ :categories '(obsolete properties))
+ (make-org-lint-checker
+ :name 'undefined-footnote-reference
+ :description "Report missing definition for footnote references"
+ :categories '(footnote))
+ (make-org-lint-checker
+ :name 'unreferenced-footnote-definition
+ :description "Report missing reference for footnote definitions"
+ :categories '(footnote))
+ (make-org-lint-checker
+ :name 'extraneous-element-in-footnote-section
+ :description "Report non-footnote definitions in footnote section"
+ :categories '(footnote))
+ (make-org-lint-checker
+ :name 'invalid-keyword-syntax
+ :description "Report probable invalid keywords"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'invalid-block
+ :description "Report invalid blocks"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'misplaced-planning-info
+ :description "Report misplaced planning info line"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'incomplete-drawer
+ :description "Report probable incomplete drawers"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'indented-diary-sexp
+ :description "Report probable indented diary-sexps"
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'quote-section
+ :description "Report obsolete QUOTE section"
+ :categories '(obsolete)
+ :trust 'low)
+ (make-org-lint-checker
+ :name 'file-application
+ :description "Report obsolete \"file+application\" link"
+ :categories '(link obsolete))
+ (make-org-lint-checker
+ :name 'empty-headline-with-tags
+ :description "Report ambiguous empty headlines with tags"
+ :categories '(headline)
+ :trust 'low))
+ "List of all available checkers.")
+
+(defun org-lint--collect-duplicates
+ (ast type extract-key extract-position build-message)
+ "Helper function to collect duplicates in parse tree AST.
+
+EXTRACT-KEY is a function extracting key. It is called with
+a single argument: the element or object. Comparison is done
+with `equal'.
+
+EXTRACT-POSITION is a function returning position for the report.
+It is called with two arguments, the object or element, and the
+key.
+
+BUILD-MESSAGE is a function creating the report message. It is
+called with one argument, the key used for comparison."
+ (let* (keys
+ originals
+ reports
+ (make-report
+ (lambda (position value)
+ (push (list position (funcall build-message value)) reports))))
+ (org-element-map ast type
+ (lambda (datum)
+ (let ((key (funcall extract-key datum)))
+ (cond
+ ((not key))
+ ((assoc key keys) (cl-pushnew (assoc key keys) originals)
+ (funcall make-report (funcall extract-position datum key) key))
+ (t (push (cons key (funcall extract-position datum key)) keys))))))
+ (dolist (e originals reports) (funcall make-report (cdr e) (car e)))))
+
+(defun org-lint-duplicate-custom-id (ast)
+ (org-lint--collect-duplicates
+ ast
+ 'node-property
+ (lambda (property)
+ (and (eq (compare-strings "CUSTOM_ID" nil nil
+ (org-element-property :key property) nil nil
+ t)
+ t)
+ (org-element-property :value property)))
+ (lambda (property _) (org-element-property :begin property))
+ (lambda (key) (format "Duplicate CUSTOM_ID property \"%s\"" key))))
+
+(defun org-lint-duplicate-name (ast)
+ (org-lint--collect-duplicates
+ ast
+ org-element-all-elements
+ (lambda (datum) (org-element-property :name datum))
+ (lambda (datum name)
+ (goto-char (org-element-property :begin datum))
+ (re-search-forward
+ (format "^[ \t]*#\\+[A-Za-z]+: +%s *$" (regexp-quote name)))
+ (match-beginning 0))
+ (lambda (key) (format "Duplicate NAME \"%s\"" key))))
+
+(defun org-lint-duplicate-target (ast)
+ (org-lint--collect-duplicates
+ ast
+ 'target
+ (lambda (target) (org-split-string (org-element-property :value target)))
+ (lambda (target _) (org-element-property :begin target))
+ (lambda (key)
+ (format "Duplicate target <<%s>>" (mapconcat #'identity key " ")))))
+
+(defun org-lint-duplicate-footnote-definition (ast)
+ (org-lint--collect-duplicates
+ ast
+ 'footnote-definition
+ (lambda (definition) (org-element-property :label definition))
+ (lambda (definition _) (org-element-property :post-affiliated definition))
+ (lambda (key) (format "Duplicate footnote definition \"%s\"" key))))
+
+(defun org-lint-orphaned-affiliated-keywords (ast)
+ ;; Ignore orphan RESULTS keywords, which could be generated from
+ ;; a source block returning no value.
+ (let ((keywords (cl-set-difference org-element-affiliated-keywords
+ '("RESULT" "RESULTS")
+ :test #'equal)))
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (let ((key (org-element-property :key k)))
+ (and (or (let ((case-fold-search t))
+ (string-match-p "\\`ATTR_[-_A-Za-z0-9]+\\'" key))
+ (member key keywords))
+ (list (org-element-property :post-affiliated k)
+ (format "Orphaned affiliated keyword: \"%s\"" key))))))))
+
+(defun org-lint-obsolete-affiliated-keywords (_)
+ (let ((regexp (format "^[ \t]*#\\+%s:"
+ (regexp-opt '("DATA" "LABEL" "RESNAME" "SOURCE"
+ "SRCNAME" "TBLNAME" "RESULT" "HEADERS")
+ t)))
+ reports)
+ (while (re-search-forward regexp nil t)
+ (let ((key (upcase (match-string-no-properties 1))))
+ (when (< (point)
+ (org-element-property :post-affiliated (org-element-at-point)))
+ (push
+ (list (line-beginning-position)
+ (format
+ "Obsolete affiliated keyword: \"%s\". Use \"%s\" instead"
+ key
+ (pcase key
+ ("HEADERS" "HEADER")
+ ("RESULT" "RESULTS")
+ (_ "NAME"))))
+ reports))))
+ reports))
+
+(defun org-lint-deprecated-export-blocks (ast)
+ (let ((deprecated '("ASCII" "BEAMER" "HTML" "LATEX" "MAN" "MARKDOWN" "MD"
+ "ODT" "ORG" "TEXINFO")))
+ (org-element-map ast 'special-block
+ (lambda (b)
+ (let ((type (org-element-property :type b)))
+ (when (member-ignore-case type deprecated)
+ (list
+ (org-element-property :post-affiliated b)
+ (format
+ "Deprecated syntax for export block. Use \"BEGIN_EXPORT %s\" \
+instead"
+ type))))))))
+
+(defun org-lint-deprecated-header-syntax (ast)
+ (let* ((deprecated-babel-properties
+ (mapcar (lambda (arg) (symbol-name (car arg)))
+ org-babel-common-header-args-w-values))
+ (deprecated-re
+ (format "\\`%s[ \t]" (regexp-opt deprecated-babel-properties t))))
+ (org-element-map ast '(keyword node-property)
+ (lambda (datum)
+ (let ((key (org-element-property :key datum)))
+ (pcase (org-element-type datum)
+ (`keyword
+ (let ((value (org-element-property :value datum)))
+ (and (string= key "PROPERTY")
+ (string-match deprecated-re value)
+ (list (org-element-property :begin datum)
+ (format "Deprecated syntax for \"%s\". \
+Use header-args instead"
+ (match-string-no-properties 1 value))))))
+ (`node-property
+ (and (member-ignore-case key deprecated-babel-properties)
+ (list
+ (org-element-property :begin datum)
+ (format "Deprecated syntax for \"%s\". \
+Use :header-args: instead"
+ key))))))))))
+
+(defun org-lint-missing-language-in-src-block (ast)
+ (org-element-map ast 'src-block
+ (lambda (b)
+ (unless (org-element-property :language b)
+ (list (org-element-property :post-affiliated b)
+ "Missing language in source block")))))
+
+(defun org-lint-missing-backend-in-export-block (ast)
+ (org-element-map ast 'export-block
+ (lambda (b)
+ (unless (org-element-property :type b)
+ (list (org-element-property :post-affiliated b)
+ "Missing back-end in export block")))))
+
+(defun org-lint-invalid-babel-call-block (ast)
+ (org-element-map ast 'babel-call
+ (lambda (b)
+ (cond
+ ((not (org-element-property :call b))
+ (list (org-element-property :post-affiliated b)
+ "Invalid syntax in babel call block"))
+ ((let ((h (org-element-property :end-header b)))
+ (and h (string-match-p "\\`\\[.*\\]\\'" h)))
+ (list
+ (org-element-property :post-affiliated b)
+ "Babel call's end header must not be wrapped within brackets"))))))
+
+(defun org-lint-deprecated-category-setup (ast)
+ (org-element-map ast 'keyword
+ (let (category-flag)
+ (lambda (k)
+ (cond
+ ((not (string= (org-element-property :key k) "CATEGORY")) nil)
+ (category-flag
+ (list (org-element-property :post-affiliated k)
+ "Spurious CATEGORY keyword. Set :CATEGORY: property instead"))
+ (t (setf category-flag t) nil))))))
+
+(defun org-lint-invalid-coderef-link (ast)
+ (let ((info (list :parse-tree ast)))
+ (org-element-map ast 'link
+ (lambda (link)
+ (let ((ref (org-element-property :path link)))
+ (and (equal (org-element-property :type link) "coderef")
+ (not (ignore-errors (org-export-resolve-coderef ref info)))
+ (list (org-element-property :begin link)
+ (format "Unknown coderef \"%s\"" ref))))))))
+
+(defun org-lint-invalid-custom-id-link (ast)
+ (let ((info (list :parse-tree ast)))
+ (org-element-map ast 'link
+ (lambda (link)
+ (and (equal (org-element-property :type link) "custom-id")
+ (not (ignore-errors (org-export-resolve-id-link link info)))
+ (list (org-element-property :begin link)
+ (format "Unknown custom ID \"%s\""
+ (org-element-property :path link))))))))
+
+(defun org-lint-invalid-fuzzy-link (ast)
+ (let ((info (list :parse-tree ast)))
+ (org-element-map ast 'link
+ (lambda (link)
+ (and (equal (org-element-property :type link) "fuzzy")
+ (not (ignore-errors (org-export-resolve-fuzzy-link link info)))
+ (list (org-element-property :begin link)
+ (format "Unknown fuzzy location \"%s\""
+ (let ((path (org-element-property :path link)))
+ (if (string-prefix-p "*" path)
+ (substring path 1)
+ path)))))))))
+
+(defun org-lint-invalid-id-link (ast)
+ (org-element-map ast 'link
+ (lambda (link)
+ (let ((id (org-element-property :path link)))
+ (and (equal (org-element-property :type link) "id")
+ (not (org-id-find id))
+ (list (org-element-property :begin link)
+ (format "Unknown ID \"%s\"" id)))))))
+
+(defun org-lint-special-property-in-properties-drawer (ast)
+ (org-element-map ast 'node-property
+ (lambda (p)
+ (let ((key (org-element-property :key p)))
+ (and (member-ignore-case key org-special-properties)
+ (list (org-element-property :begin p)
+ (format
+ "Special property \"%s\" found in a properties drawer"
+ key)))))))
+
+(defun org-lint-obsolete-properties-drawer (ast)
+ (org-element-map ast 'drawer
+ (lambda (d)
+ (when (equal (org-element-property :drawer-name d) "PROPERTIES")
+ (let ((section (org-element-lineage d '(section))))
+ (unless (org-element-map section 'property-drawer #'identity nil t)
+ (list (org-element-property :post-affiliated d)
+ (if (save-excursion
+ (goto-char (org-element-property :post-affiliated d))
+ (forward-line -1)
+ (or (org-at-heading-p) (org-at-planning-p)))
+ "Incorrect contents for PROPERTIES drawer"
+ "Incorrect location for PROPERTIES drawer"))))))))
+
+(defun org-lint-link-to-local-file (ast)
+ (org-element-map ast 'link
+ (lambda (l)
+ (when (equal (org-element-property :type l) "file")
+ (let ((file (org-link-unescape (org-element-property :path l))))
+ (and (not (file-remote-p file))
+ (not (file-exists-p file))
+ (list (org-element-property :begin l)
+ (format (if (org-element-lineage l '(link))
+ "Link to non-existent image file \"%s\"\
+ in link description"
+ "Link to non-existent local file \"%s\"")
+ file))))))))
+
+(defun org-lint-non-existent-setupfile-parameter (ast)
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (when (equal (org-element-property :key k) "SETUPFILE")
+ (let ((file (org-unbracket-string
+ "\"" "\""
+ (org-element-property :value k))))
+ (and (not (file-remote-p file))
+ (not (file-exists-p file))
+ (list (org-element-property :begin k)
+ (format "Non-existent setup file \"%s\"" file))))))))
+
+(defun org-lint-wrong-include-link-parameter (ast)
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (when (equal (org-element-property :key k) "INCLUDE")
+ (let* ((value (org-element-property :value k))
+ (path
+ (and (string-match "^\\(\".+\"\\|\\S-+\\)[ \t]*" value)
+ (save-match-data
+ (org-unbracket-string "\"" "\"" (match-string 1 value))))))
+ (if (not path)
+ (list (org-element-property :post-affiliated k)
+ "Missing location argument in INCLUDE keyword")
+ (let* ((file (org-string-nw-p
+ (if (string-match "::\\(.*\\)\\'" path)
+ (substring path 0 (match-beginning 0))
+ path)))
+ (search (and (not (equal file path))
+ (org-string-nw-p (match-string 1 path)))))
+ (if (and file
+ (not (file-remote-p file))
+ (not (file-exists-p file)))
+ (list (org-element-property :post-affiliated k)
+ "Non-existent file argument in INCLUDE keyword")
+ (let* ((visiting (if file (find-buffer-visiting file)
+ (current-buffer)))
+ (buffer (or visiting (find-file-noselect file))))
+ (unwind-protect
+ (with-current-buffer buffer
+ (when (and search
+ (not
+ (ignore-errors
+ (let ((org-link-search-inhibit-query t))
+ (org-link-search search nil t)))))
+ (list (org-element-property :post-affiliated k)
+ (format
+ "Invalid search part \"%s\" in INCLUDE keyword"
+ search))))
+ (unless visiting (kill-buffer buffer))))))))))))
+
+(defun org-lint-obsolete-include-markup (ast)
+ (let ((regexp (format "\\`\\(?:\".+\"\\|\\S-+\\)[ \t]+%s"
+ (regexp-opt
+ '("ASCII" "BEAMER" "HTML" "LATEX" "MAN" "MARKDOWN" "MD"
+ "ODT" "ORG" "TEXINFO")
+ t))))
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (when (equal (org-element-property :key k) "INCLUDE")
+ (let ((case-fold-search t)
+ (value (org-element-property :value k)))
+ (when (string-match regexp value)
+ (let ((markup (match-string-no-properties 1 value)))
+ (list (org-element-property :post-affiliated k)
+ (format "Obsolete markup \"%s\" in INCLUDE keyword. \
+Use \"export %s\" instead"
+ markup
+ markup))))))))))
+
+(defun org-lint-unknown-options-item (ast)
+ (let ((allowed (delq nil
+ (append
+ (mapcar (lambda (o) (nth 2 o)) org-export-options-alist)
+ (cl-mapcan
+ (lambda (b)
+ (mapcar (lambda (o) (nth 2 o))
+ (org-export-backend-options b)))
+ org-export-registered-backends))))
+ reports)
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (when (string= (org-element-property :key k) "OPTIONS")
+ (let ((value (org-element-property :value k))
+ (start 0))
+ (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*"
+ value
+ start)
+ (setf start (match-end 0))
+ (let ((item (match-string 1 value)))
+ (unless (member item allowed)
+ (push (list (org-element-property :post-affiliated k)
+ (format "Unknown OPTIONS item \"%s\"" item))
+ reports))))))))
+ reports))
+
+(defun org-lint-invalid-macro-argument-and-template (ast)
+ (let ((extract-placeholders
+ (lambda (template)
+ (let ((start 0)
+ args)
+ (while (string-match "\\$\\([1-9][0-9]*\\)" template start)
+ (setf start (match-end 0))
+ (push (string-to-number (match-string 1 template)) args))
+ (sort (org-uniquify args) #'<))))
+ reports)
+ ;; Check arguments for macro templates.
+ (org-element-map ast 'keyword
+ (lambda (k)
+ (when (string= (org-element-property :key k) "MACRO")
+ (let* ((value (org-element-property :value k))
+ (name (and (string-match "^\\S-+" value)
+ (match-string 0 value)))
+ (template (and name
+ (org-trim (substring value (match-end 0))))))
+ (cond
+ ((not name)
+ (push (list (org-element-property :post-affiliated k)
+ "Missing name in MACRO keyword")
+ reports))
+ ((not (org-string-nw-p template))
+ (push (list (org-element-property :post-affiliated k)
+ "Missing template in macro \"%s\"" name)
+ reports))
+ (t
+ (unless (let ((args (funcall extract-placeholders template)))
+ (equal (number-sequence 1 (or (org-last args) 0)) args))
+ (push (list (org-element-property :post-affiliated k)
+ (format "Unused placeholders in macro \"%s\""
+ name))
+ reports))))))))
+ ;; Check arguments for macros.
+ (org-macro-initialize-templates)
+ (let ((templates (append
+ (mapcar (lambda (m) (cons m "$1"))
+ '("author" "date" "email" "title" "results"))
+ org-macro-templates)))
+ (org-element-map ast 'macro
+ (lambda (macro)
+ (let* ((name (org-element-property :key macro))
+ (template (cdr (assoc-string name templates t))))
+ (if (not template)
+ (push (list (org-element-property :begin macro)
+ (format "Undefined macro \"%s\"" name))
+ reports)
+ (let ((arg-numbers (funcall extract-placeholders template)))
+ (when arg-numbers
+ (let ((spurious-args
+ (nthcdr (apply #'max arg-numbers)
+ (org-element-property :args macro))))
+ (when spurious-args
+ (push
+ (list (org-element-property :begin macro)
+ (format "Unused argument%s in macro \"%s\": %s"
+ (if (> (length spurious-args) 1) "s" "")
+ name
+ (mapconcat (lambda (a) (format "\"%s\"" a))
+ spurious-args
+ ", ")))
+ reports))))))))))
+ reports))
+
+(defun org-lint-undefined-footnote-reference (ast)
+ (let ((definitions (org-element-map ast 'footnote-definition
+ (lambda (f) (org-element-property :label f)))))
+ (org-element-map ast 'footnote-reference
+ (lambda (f)
+ (let ((label (org-element-property :label f)))
+ (and label
+ (not (member label definitions))
+ (list (org-element-property :begin f)
+ (format "Missing definition for footnote [%s]"
+ label))))))))
+
+(defun org-lint-unreferenced-footnote-definition (ast)
+ (let ((references (org-element-map ast 'footnote-reference
+ (lambda (f) (org-element-property :label f)))))
+ (org-element-map ast 'footnote-definition
+ (lambda (f)
+ (let ((label (org-element-property :label f)))
+ (and label
+ (not (member label references))
+ (list (org-element-property :post-affiliated f)
+ (format "No reference for footnote definition [%s]"
+ label))))))))
+
+(defun org-lint-colon-in-name (ast)
+ (org-element-map ast org-element-all-elements
+ (lambda (e)
+ (let ((name (org-element-property :name e)))
+ (and name
+ (string-match-p ":" name)
+ (list (progn
+ (goto-char (org-element-property :begin e))
+ (re-search-forward
+ (format "^[ \t]*#\\+\\w+: +%s *$" (regexp-quote name)))
+ (match-beginning 0))
+ (format
+ "Name \"%s\" contains a colon; Babel cannot use it as input"
+ name)))))))
+
+(defun org-lint-misplaced-planning-info (_)
+ (let ((case-fold-search t)
+ reports)
+ (while (re-search-forward org-planning-line-re nil t)
+ (unless (memq (org-element-type (org-element-at-point))
+ '(comment-block example-block export-block planning
+ src-block verse-block))
+ (push (list (line-beginning-position) "Misplaced planning info line")
+ reports)))
+ reports))
+
+(defun org-lint-incomplete-drawer (_)
+ (let (reports)
+ (while (re-search-forward org-drawer-regexp nil t)
+ (let ((name (org-trim (match-string-no-properties 0)))
+ (element (org-element-at-point)))
+ (pcase (org-element-type element)
+ ((or `drawer `property-drawer)
+ (goto-char (org-element-property :end element))
+ nil)
+ ((or `comment-block `example-block `export-block `src-block
+ `verse-block)
+ nil)
+ (_
+ (push (list (line-beginning-position)
+ (format "Possible incomplete drawer \"%s\"" name))
+ reports)))))
+ reports))
+
+(defun org-lint-indented-diary-sexp (_)
+ (let (reports)
+ (while (re-search-forward "^[ \t]+%%(" nil t)
+ (unless (memq (org-element-type (org-element-at-point))
+ '(comment-block diary-sexp example-block export-block
+ src-block verse-block))
+ (push (list (line-beginning-position) "Possible indented diary-sexp")
+ reports)))
+ reports))
+
+(defun org-lint-invalid-block (_)
+ (let ((case-fold-search t)
+ (regexp "^[ \t]*#\\+\\(BEGIN\\|END\\)\\(?::\\|_[^[:space:]]*\\)?[ \t]*")
+ reports)
+ (while (re-search-forward regexp nil t)
+ (let ((name (org-trim (buffer-substring-no-properties
+ (line-beginning-position) (line-end-position)))))
+ (cond
+ ((and (string-prefix-p "END" (match-string 1) t)
+ (not (eolp)))
+ (push (list (line-beginning-position)
+ (format "Invalid block closing line \"%s\"" name))
+ reports))
+ ((not (memq (org-element-type (org-element-at-point))
+ '(center-block comment-block dynamic-block example-block
+ export-block quote-block special-block
+ src-block verse-block)))
+ (push (list (line-beginning-position)
+ (format "Possible incomplete block \"%s\""
+ name))
+ reports)))))
+ reports))
+
+(defun org-lint-invalid-keyword-syntax (_)
+ (let ((regexp "^[ \t]*#\\+\\([^[:space:]:]*\\)\\(?: \\|$\\)")
+ (exception-re
+ (format "[ \t]*#\\+%s\\(\\[.*\\]\\)?:\\(?: \\|$\\)"
+ (regexp-opt org-element-dual-keywords)))
+ reports)
+ (while (re-search-forward regexp nil t)
+ (let ((name (match-string-no-properties 1)))
+ (unless (or (string-prefix-p "BEGIN" name t)
+ (string-prefix-p "END" name t)
+ (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search t)) (looking-at exception-re))))
+ (push (list (match-beginning 0)
+ (format "Possible missing colon in keyword \"%s\"" name))
+ reports))))
+ reports))
+
+(defun org-lint-extraneous-element-in-footnote-section (ast)
+ (org-element-map ast 'headline
+ (lambda (h)
+ (and (org-element-property :footnote-section-p h)
+ (org-element-map (org-element-contents h)
+ (cl-remove-if
+ (lambda (e)
+ (memq e '(comment comment-block footnote-definition
+ property-drawer section)))
+ org-element-all-elements)
+ (lambda (e)
+ (not (and (eq (org-element-type e) 'headline)
+ (org-element-property :commentedp e))))
+ nil t '(footnote-definition property-drawer))
+ (list (org-element-property :begin h)
+ "Extraneous elements in footnote section are not exported")))))
+
+(defun org-lint-quote-section (ast)
+ (org-element-map ast '(headline inlinetask)
+ (lambda (h)
+ (let ((title (org-element-property :raw-value h)))
+ (and (or (string-prefix-p "QUOTE " title)
+ (string-prefix-p (concat org-comment-string " QUOTE ") title))
+ (list (org-element-property :begin h)
+ "Deprecated QUOTE section"))))))
+
+(defun org-lint-file-application (ast)
+ (org-element-map ast 'link
+ (lambda (l)
+ (let ((app (org-element-property :application l)))
+ (and app
+ (list (org-element-property :begin l)
+ (format "Deprecated \"file+%s\" link type" app)))))))
+
+(defun org-lint-wrong-header-argument (ast)
+ (let* ((reports)
+ (verify
+ (lambda (datum language headers)
+ (let ((allowed
+ ;; If LANGUAGE is specified, restrict allowed
+ ;; headers to both LANGUAGE-specific and default
+ ;; ones. Otherwise, accept headers from any loaded
+ ;; language.
+ (append
+ org-babel-header-arg-names
+ (cl-mapcan
+ (lambda (l)
+ (let ((v (intern (format "org-babel-header-args:%s" l))))
+ (and (boundp v) (mapcar #'car (symbol-value v)))))
+ (if language (list language)
+ (mapcar #'car org-babel-load-languages))))))
+ (dolist (header headers)
+ (let ((h (symbol-name (car header)))
+ (p (or (org-element-property :post-affiliated datum)
+ (org-element-property :begin datum))))
+ (cond
+ ((not (string-prefix-p ":" h))
+ (push
+ (list p
+ (format "Missing colon in header argument \"%s\"" h))
+ reports))
+ ((assoc-string (substring h 1) allowed))
+ (t (push (list p (format "Unknown header argument \"%s\"" h))
+ reports)))))))))
+ (org-element-map ast '(babel-call inline-babel-call inline-src-block keyword
+ node-property src-block)
+ (lambda (datum)
+ (pcase (org-element-type datum)
+ ((or `babel-call `inline-babel-call)
+ (funcall verify
+ datum
+ nil
+ (cl-mapcan #'org-babel-parse-header-arguments
+ (list
+ (org-element-property :inside-header datum)
+ (org-element-property :end-header datum)))))
+ (`inline-src-block
+ (funcall verify
+ datum
+ (org-element-property :language datum)
+ (org-babel-parse-header-arguments
+ (org-element-property :parameters datum))))
+ (`keyword
+ (when (string= (org-element-property :key datum) "PROPERTY")
+ (let ((value (org-element-property :value datum)))
+ (when (string-match "\\`header-args\\(?::\\(\\S-+\\)\\)?\\+? *"
+ value)
+ (funcall verify
+ datum
+ (match-string 1 value)
+ (org-babel-parse-header-arguments
+ (substring value (match-end 0))))))))
+ (`node-property
+ (let ((key (org-element-property :key datum)))
+ (when (let ((case-fold-search t))
+ (string-match "\\`HEADER-ARGS\\(?::\\(\\S-+\\)\\)?\\+?"
+ key))
+ (funcall verify
+ datum
+ (match-string 1 key)
+ (org-babel-parse-header-arguments
+ (org-element-property :value datum))))))
+ (`src-block
+ (funcall verify
+ datum
+ (org-element-property :language datum)
+ (cl-mapcan #'org-babel-parse-header-arguments
+ (cons (org-element-property :parameters datum)
+ (org-element-property :header datum))))))))
+ reports))
+
+(defun org-lint-wrong-header-value (ast)
+ (let (reports)
+ (org-element-map ast
+ '(babel-call inline-babel-call inline-src-block src-block)
+ (lambda (datum)
+ (let* ((type (org-element-type datum))
+ (language (org-element-property :language datum))
+ (allowed-header-values
+ (append (and language
+ (let ((v (intern (concat "org-babel-header-args:"
+ language))))
+ (and (boundp v) (symbol-value v))))
+ org-babel-common-header-args-w-values))
+ (datum-header-values
+ (org-babel-parse-header-arguments
+ (org-trim
+ (pcase type
+ (`src-block
+ (mapconcat
+ #'identity
+ (cons (org-element-property :parameters datum)
+ (org-element-property :header datum))
+ " "))
+ (`inline-src-block
+ (or (org-element-property :parameters datum) ""))
+ (_
+ (concat
+ (org-element-property :inside-header datum)
+ " "
+ (org-element-property :end-header datum))))))))
+ (dolist (header datum-header-values)
+ (let ((allowed-values
+ (cdr (assoc-string (substring (symbol-name (car header)) 1)
+ allowed-header-values))))
+ (unless (memq allowed-values '(:any nil))
+ (let ((values (cdr header))
+ groups-alist)
+ (dolist (v (if (stringp values) (org-split-string values)
+ (list values)))
+ (let ((valid-value nil))
+ (catch 'exit
+ (dolist (group allowed-values)
+ (cond
+ ((not (funcall
+ (if (stringp v) #'assoc-string #'assoc)
+ v group))
+ (when (memq :any group)
+ (setf valid-value t)
+ (push (cons group v) groups-alist)))
+ ((assq group groups-alist)
+ (push
+ (list
+ (or (org-element-property :post-affiliated datum)
+ (org-element-property :begin datum))
+ (format
+ "Forbidden combination in header \"%s\": %s, %s"
+ (car header)
+ (cdr (assq group groups-alist))
+ v))
+ reports)
+ (throw 'exit nil))
+ (t (push (cons group v) groups-alist)
+ (setf valid-value t))))
+ (unless valid-value
+ (push
+ (list
+ (or (org-element-property :post-affiliated datum)
+ (org-element-property :begin datum))
+ (format "Unknown value \"%s\" for header \"%s\""
+ v
+ (car header)))
+ reports))))))))))))
+ reports))
+
+(defun org-lint-empty-headline-with-tags (ast)
+ (org-element-map ast '(headline inlinetask)
+ (lambda (h)
+ (let ((title (org-element-property :raw-value h)))
+ (and (string-match-p "\\`:[[:alnum:]_@#%:]+:\\'" title)
+ (list (org-element-property :begin h)
+ (format "Headline containing only tags is ambiguous: %S"
+ title)))))))
+
+
+;;; Reports UI
+
+(defvar org-lint--report-mode-map
+ (let ((map (make-sparse-keymap)))
+ (set-keymap-parent map tabulated-list-mode-map)
+ (define-key map (kbd "RET") 'org-lint--jump-to-source)
+ (define-key map (kbd "TAB") 'org-lint--show-source)
+ (define-key map (kbd "C-j") 'org-lint--show-source)
+ (define-key map (kbd "h") 'org-lint--hide-checker)
+ (define-key map (kbd "i") 'org-lint--ignore-checker)
+ map)
+ "Local keymap for `org-lint--report-mode' buffers.")
+
+(define-derived-mode org-lint--report-mode tabulated-list-mode "OrgLint"
+ "Major mode used to display reports emitted during linting.
+\\{org-lint--report-mode-map}"
+ (setf tabulated-list-format
+ `[("Line" 6
+ (lambda (a b)
+ (< (string-to-number (aref (cadr a) 0))
+ (string-to-number (aref (cadr b) 0))))
+ :right-align t)
+ ("Trust" 5 t)
+ ("Warning" 0 t)])
+ (tabulated-list-init-header))
+
+(defun org-lint--generate-reports (buffer checkers)
+ "Generate linting report for BUFFER.
+
+CHECKERS is the list of checkers used.
+
+Return an alist (ID [LINE TRUST DESCRIPTION CHECKER]), suitable
+for `tabulated-list-printer'."
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char (point-min))
+ (let ((ast (org-element-parse-buffer))
+ (id 0)
+ (last-line 1)
+ (last-pos 1))
+ ;; Insert unique ID for each report. Replace buffer positions
+ ;; with line numbers.
+ (mapcar
+ (lambda (report)
+ (list
+ (cl-incf id)
+ (apply #'vector
+ (cons
+ (progn
+ (goto-char (car report))
+ (beginning-of-line)
+ (prog1 (number-to-string
+ (cl-incf last-line
+ (count-lines last-pos (point))))
+ (setf last-pos (point))))
+ (cdr report)))))
+ ;; Insert trust level in generated reports. Also sort them
+ ;; by buffer position in order to optimize lines computation.
+ (sort (cl-mapcan
+ (lambda (c)
+ (let ((trust (symbol-name (org-lint-checker-trust c))))
+ (mapcar
+ (lambda (report)
+ (list (car report) trust (nth 1 report) c))
+ (save-excursion
+ (funcall
+ (intern (format "org-lint-%s"
+ (org-lint-checker-name c)))
+ ast)))))
+ checkers)
+ #'car-less-than-car))))))
+
+(defvar-local org-lint--source-buffer nil
+ "Source buffer associated to current report buffer.")
+
+(defvar-local org-lint--local-checkers nil
+ "List of checkers used to build current report.")
+
+(defun org-lint--refresh-reports ()
+ (setq tabulated-list-entries
+ (org-lint--generate-reports org-lint--source-buffer
+ org-lint--local-checkers))
+ (tabulated-list-print))
+
+(defun org-lint--current-line ()
+ "Return current report line, as a number."
+ (string-to-number (aref (tabulated-list-get-entry) 0)))
+
+(defun org-lint--current-checker (&optional entry)
+ "Return current report checker.
+When optional argument ENTRY is non-nil, use this entry instead
+of current one."
+ (aref (if entry (nth 1 entry) (tabulated-list-get-entry)) 3))
+
+(defun org-lint--display-reports (source checkers)
+ "Display linting reports for buffer SOURCE.
+CHECKERS is the list of checkers used."
+ (let ((buffer (get-buffer-create "*Org Lint*")))
+ (with-current-buffer buffer
+ (org-lint--report-mode)
+ (setf org-lint--source-buffer source)
+ (setf org-lint--local-checkers checkers)
+ (org-lint--refresh-reports)
+ (tabulated-list-print)
+ (add-hook 'tabulated-list-revert-hook #'org-lint--refresh-reports nil t))
+ (pop-to-buffer buffer)))
+
+(defun org-lint--jump-to-source ()
+ "Move to source line that generated the report at point."
+ (interactive)
+ (let ((l (org-lint--current-line)))
+ (switch-to-buffer-other-window org-lint--source-buffer)
+ (org-goto-line l)
+ (org-show-set-visibility 'local)
+ (recenter)))
+
+(defun org-lint--show-source ()
+ "Show source line that generated the report at point."
+ (interactive)
+ (let ((buffer (current-buffer)))
+ (org-lint--jump-to-source)
+ (switch-to-buffer-other-window buffer)))
+
+(defun org-lint--hide-checker ()
+ "Hide all reports from checker that generated the report at point."
+ (interactive)
+ (let ((c (org-lint--current-checker)))
+ (setf tabulated-list-entries
+ (cl-remove-if (lambda (e) (equal c (org-lint--current-checker e)))
+ tabulated-list-entries))
+ (tabulated-list-print)))
+
+(defun org-lint--ignore-checker ()
+ "Ignore all reports from checker that generated the report at point.
+Checker will also be ignored in all subsequent reports."
+ (interactive)
+ (setf org-lint--local-checkers
+ (remove (org-lint--current-checker) org-lint--local-checkers))
+ (org-lint--hide-checker))
+
+
+;;; Public function
+
+;;;###autoload
+(defun org-lint (&optional arg)
+ "Check current Org buffer for syntax mistakes.
+
+By default, run all checkers. With a `\\[universal-argument]' prefix ARG, \
+select one
+category of checkers only. With a `\\[universal-argument] \
+\\[universal-argument]' prefix, run one precise
+checker by its name.
+
+ARG can also be a list of checker names, as symbols, to run."
+ (interactive "P")
+ (unless (derived-mode-p 'org-mode) (user-error "Not in an Org buffer"))
+ (when (called-interactively-p 'any)
+ (message "Org linting process starting..."))
+ (let ((checkers
+ (pcase arg
+ (`nil org-lint--checkers)
+ (`(4)
+ (let ((category
+ (completing-read
+ "Checker category: "
+ (mapcar #'org-lint-checker-categories org-lint--checkers)
+ nil t)))
+ (cl-remove-if-not
+ (lambda (c)
+ (assoc-string (org-lint-checker-categories c) category))
+ org-lint--checkers)))
+ (`(16)
+ (list
+ (let ((name (completing-read
+ "Checker name: "
+ (mapcar #'org-lint-checker-name org-lint--checkers)
+ nil t)))
+ (catch 'exit
+ (dolist (c org-lint--checkers)
+ (when (string= (org-lint-checker-name c) name)
+ (throw 'exit c)))))))
+ ((pred consp)
+ (cl-remove-if-not (lambda (c) (memq (org-lint-checker-name c) arg))
+ org-lint--checkers))
+ (_ (user-error "Invalid argument `%S' for `org-lint'" arg)))))
+ (if (not (called-interactively-p 'any))
+ (org-lint--generate-reports (current-buffer) checkers)
+ (org-lint--display-reports (current-buffer) checkers)
+ (message "Org linting process completed"))))
+
+
+(provide 'org-lint)
+;;; org-lint.el ends here
diff --git a/lisp/org-list.el b/lisp/org-list.el
new file mode 100644
index 0000000..a3e2625
--- /dev/null
+++ b/lisp/org-list.el
@@ -0,0 +1,3591 @@
+;;; org-list.el --- Plain lists for Org -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Bastien Guerry <bzg@gnu.org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code dealing with plain lists in Org mode.
+
+;; The core concept behind lists is their structure. A structure is
+;; a snapshot of the list, in the shape of a data tree (see
+;; `org-list-struct').
+
+;; Once the list structure is stored, it is possible to make changes
+;; on it that will be mirrored to the real list or to get information
+;; about the list, using accessors and methods provided in the
+;; library. Most of them require the use of one or two helper
+;; functions, namely `org-list-parents-alist' and
+;; `org-list-prevs-alist'.
+
+;; Structure is eventually applied to the buffer with
+;; `org-list-write-struct'. This function repairs (bullets,
+;; indentation, checkboxes) the list in the process. It should be
+;; called near the end of any function working on structures.
+
+;; Thus, a function applying to lists should usually follow this
+;; template:
+
+;; 1. Verify point is in a list and grab item beginning (with the same
+;; function `org-in-item-p'). If the function requires the cursor
+;; to be at item's bullet, `org-at-item-p' is more selective. It
+;; is also possible to move point to the closest item with
+;; `org-list-search-backward', or `org-list-search-forward',
+;; applied to the function `org-item-beginning-re'.
+
+;; 2. Get list structure with `org-list-struct'.
+
+;; 3. Compute one, or both, helper functions,
+;; (`org-list-parents-alist', `org-list-prevs-alist') depending on
+;; needed accessors.
+
+;; 4. Proceed with the modifications, using methods and accessors.
+
+;; 5. Verify and apply structure to buffer, using
+;; `org-list-write-struct'.
+
+;; 6. If changes made to the list might have modified check-boxes,
+;; call `org-update-checkbox-count-maybe'.
+
+;; Computing a structure can be a costly operation on huge lists (a
+;; few thousand lines long). Thus, code should follow the rule:
+;; "collect once, use many". As a corollary, it is usually a bad idea
+;; to use directly an interactive function inside the code, as those,
+;; being independent entities, read the whole list structure another
+;; time.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-macs)
+(require 'org-compat)
+
+(defvar org-M-RET-may-split-line)
+(defvar org-auto-align-tags)
+(defvar org-blank-before-new-entry)
+(defvar org-clock-string)
+(defvar org-closed-string)
+(defvar org-deadline-string)
+(defvar org-description-max-indent)
+(defvar org-done-keywords)
+(defvar org-drawer-regexp)
+(defvar org-element-all-objects)
+(defvar org-inhibit-startup)
+(defvar org-odd-levels-only)
+(defvar org-outline-regexp-bol)
+(defvar org-scheduled-string)
+(defvar org-todo-line-regexp)
+(defvar org-ts-regexp)
+(defvar org-ts-regexp-both)
+
+(declare-function org-at-heading-p "org" (&optional invisible-ok))
+(declare-function org-back-to-heading "org" (&optional invisible-ok))
+(declare-function org-before-first-heading-p "org" ())
+(declare-function org-combine-plists "org" (&rest plists))
+(declare-function org-current-level "org" ())
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-interpret-data "org-element" (data))
+(declare-function
+ org-element-lineage "org-element" (blob &optional types with-self))
+(declare-function org-element-macro-interpreter "org-element" (macro ##))
+(declare-function
+ org-element-map "org-element"
+ (data types fun &optional info first-match no-recursion with-affiliated))
+(declare-function org-element-normalize-string "org-element" (s))
+(declare-function org-element-parse-buffer "org-element"
+ (&optional granularity visible-only))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-put-property "org-element"
+ (element property value))
+(declare-function org-element-set-element "org-element" (old new))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-element-update-syntax "org-element" ())
+(declare-function org-entry-get "org"
+ (pom property &optional inherit literal-nil))
+(declare-function org-export-create-backend "ox" (&rest rest) t)
+(declare-function org-export-data-with-backend "ox" (data backend info))
+(declare-function org-export-get-backend "ox" (name))
+(declare-function org-export-get-environment "ox"
+ (&optional backend subtreep ext-plist))
+(declare-function org-export-get-next-element "ox"
+ (blob info &optional n))
+(declare-function org-export-with-backend "ox"
+ (backend data &optional contents info))
+(declare-function org-fix-tags-on-the-fly "org" ())
+(declare-function org-get-indentation "org" (&optional line))
+(declare-function org-get-todo-state "org" ())
+(declare-function org-in-block-p "org" (names))
+(declare-function org-in-regexp "org" (re &optional nlines visually))
+(declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
+(declare-function org-inlinetask-goto-end "org-inlinetask" ())
+(declare-function org-inlinetask-in-task-p "org-inlinetask" ())
+(declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
+(declare-function org-level-increment "org" ())
+(declare-function org-narrow-to-subtree "org" ())
+(declare-function org-outline-level "org" ())
+(declare-function org-previous-line-empty-p "org" ())
+(declare-function org-reduced-level "org" (L))
+(declare-function org-remove-indentation "org" (code &optional n))
+(declare-function org-show-subtree "org" ())
+(declare-function org-sort-remove-invisible "org" (S))
+(declare-function org-time-string-to-seconds "org" (s))
+(declare-function org-timer-hms-to-secs "org-timer" (hms))
+(declare-function org-timer-item "org-timer" (&optional arg))
+(declare-function org-trim "org" (s &optional keep-lead))
+(declare-function org-uniquify "org" (list))
+(declare-function org-invisible-p "org" (&optional pos))
+(declare-function outline-flag-region "outline" (from to flag))
+(declare-function outline-next-heading "outline" ())
+(declare-function outline-previous-heading "outline" ())
+
+
+
+;;; Configuration variables
+
+(defgroup org-plain-lists nil
+ "Options concerning plain lists in Org mode."
+ :tag "Org Plain lists"
+ :group 'org-structure)
+
+(defcustom org-cycle-include-plain-lists t
+ "When t, make TAB cycle visibility on plain list items.
+Cycling plain lists works only when the cursor is on a plain list
+item. When the cursor is on an outline heading, plain lists are
+treated as text. This is the most stable way of handling this,
+which is why it is the default.
+
+When this is the symbol `integrate', then integrate plain list
+items when cycling, as if they were children of outline headings.
+
+This setting can lead to strange effects when switching visibility
+to `children', because the first \"child\" in a subtree decides
+what children should be listed. If that first \"child\" is a
+plain list item with an implied large level number, all true
+children and grand children of the outline heading will be
+exposed in a children' view."
+ :group 'org-plain-lists
+ :group 'org-cycle
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "With cursor in plain list (recommended)" t)
+ (const :tag "As children of outline headings" integrate)))
+
+(defcustom org-list-demote-modify-bullet nil
+ "Default bullet type installed when demoting an item.
+This is an association list, for each bullet type, this alist will point
+to the bullet that should be used when this item is demoted.
+For example,
+
+ (setq org-list-demote-modify-bullet
+ \\='((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
+
+will make
+
+ + Movies
+ + Silence of the Lambs
+ + My Cousin Vinny
+ + Books
+ + The Hunt for Red October
+ + The Road to Omaha
+
+into
+
+ + Movies
+ - Silence of the Lambs
+ - My Cousin Vinny
+ + Books
+ - The Hunt for Red October
+ - The Road to Omaha"
+ :group 'org-plain-lists
+ :type '(repeat
+ (cons
+ (choice :tag "If the current bullet is "
+ (const "-")
+ (const "+")
+ (const "*")
+ (const "1.")
+ (const "1)"))
+ (choice :tag "demotion will change it to"
+ (const "-")
+ (const "+")
+ (const "*")
+ (const "1.")
+ (const "1)")))))
+
+(defcustom org-plain-list-ordered-item-terminator t
+ "The character that makes a line with leading number an ordered list item.
+Valid values are ?. and ?\). To get both terminators, use t.
+
+This variable needs to be set before org.el is loaded. If you
+need to make a change while Emacs is running, use the customize
+interface or run the following code after updating it:
+
+ `\\[org-element-update-syntax]'"
+ :group 'org-plain-lists
+ :type '(choice (const :tag "dot like in \"2.\"" ?.)
+ (const :tag "paren like in \"2)\"" ?\))
+ (const :tag "both" t))
+ :set (lambda (var val) (set var val)
+ (when (featurep 'org-element) (org-element-update-syntax))))
+
+(defcustom org-list-allow-alphabetical nil
+ "Non-nil means single character alphabetical bullets are allowed.
+
+Both uppercase and lowercase are handled. Lists with more than
+26 items will fallback to standard numbering. Alphabetical
+counters like \"[@c]\" will be recognized.
+
+This variable needs to be set before org.el is loaded. If you
+need to make a change while Emacs is running, use the customize
+interface or run the following code after updating it:
+
+ `\\[org-element-update-syntax]'"
+ :group 'org-plain-lists
+ :version "24.1"
+ :type 'boolean
+ :set (lambda (var val) (set var val)
+ (when (featurep 'org-element) (org-element-update-syntax))))
+
+(defcustom org-list-two-spaces-after-bullet-regexp nil
+ "A regular expression matching bullets that should have 2 spaces after them.
+When nil, no bullet will have two spaces after them. When
+a string, it will be used as a regular expression. When the
+bullet type of a list is changed, the new bullet type will be
+matched against this regexp. If it matches, there will be two
+spaces instead of one after the bullet in each item of the list."
+ :group 'org-plain-lists
+ :type '(choice
+ (const :tag "never" nil)
+ (regexp)))
+
+(defcustom org-list-automatic-rules '((checkbox . t)
+ (indent . t))
+ "Non-nil means apply set of rules when acting on lists.
+\\<org-mode-map>
+By default, automatic actions are taken when using
+ `\\[org-meta-return]',
+ `\\[org-metaright]',
+ `\\[org-metaleft]',
+ `\\[org-shiftmetaright]',
+ `\\[org-shiftmetaleft]',
+ `\\[org-ctrl-c-minus]',
+ `\\[org-toggle-checkbox]',
+ `\\[org-insert-todo-heading]'.
+
+You can disable individually these rules by setting them to nil.
+Valid rules are:
+
+checkbox when non-nil, checkbox statistics is updated each time
+ you either insert a new checkbox or toggle a checkbox.
+indent when non-nil, indenting or outdenting list top-item
+ with its subtree will move the whole list and
+ outdenting a list whose bullet is * to column 0 will
+ change that bullet to \"-\"."
+ :group 'org-plain-lists
+ :version "24.1"
+ :type '(alist :tag "Sets of rules"
+ :key-type
+ (choice
+ (const :tag "Checkbox" checkbox)
+ (const :tag "Indent" indent))
+ :value-type
+ (boolean :tag "Activate" :value t)))
+
+(defcustom org-list-use-circular-motion nil
+ "Non-nil means commands implying motion in lists should be cyclic.
+\\<org-mode-map>
+In that case, the item following the last item is the first one,
+and the item preceding the first item is the last one.
+
+This affects the behavior of
+ `\\[org-move-item-up]',
+ `\\[org-move-item-down]',
+ `\\[org-next-item]',
+ `\\[org-previous-item]'."
+ :group 'org-plain-lists
+ :version "24.1"
+ :type 'boolean)
+
+(defvar org-checkbox-statistics-hook nil
+ "Hook that is run whenever Org thinks checkbox statistics should be updated.
+This hook runs even if checkbox rule in
+`org-list-automatic-rules' does not apply, so it can be used to
+implement alternative ways of collecting statistics
+information.")
+
+(defcustom org-checkbox-hierarchical-statistics t
+ "Non-nil means checkbox statistics counts only the state of direct children.
+When nil, all boxes below the cookie are counted.
+This can be set to nil on a per-node basis using a COOKIE_DATA property
+with the word \"recursive\" in the value."
+ :group 'org-plain-lists
+ :type 'boolean)
+
+(defcustom org-list-description-max-indent 20
+ "Maximum indentation for the second line of a description list.
+When the indentation would be larger than this, it will become
+5 characters instead."
+ :group 'org-plain-lists
+ :type 'integer)
+
+(defcustom org-list-indent-offset 0
+ "Additional indentation for sub-items in a list.
+By setting this to a small number, usually 1 or 2, one can more
+clearly distinguish sub-items in a list."
+ :group 'org-plain-lists
+ :version "24.1"
+ :type 'integer)
+
+(defcustom org-list-radio-list-templates
+ '((latex-mode "% BEGIN RECEIVE ORGLST %n
+% END RECEIVE ORGLST %n
+\\begin{comment}
+#+ORGLST: SEND %n org-list-to-latex
+-
+\\end{comment}\n")
+ (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
+@c END RECEIVE ORGLST %n
+@ignore
+#+ORGLST: SEND %n org-list-to-texinfo
+-
+@end ignore\n")
+ (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
+<!-- END RECEIVE ORGLST %n -->
+<!--
+#+ORGLST: SEND %n org-list-to-html
+-
+-->\n"))
+ "Templates for radio lists in different major modes.
+All occurrences of %n in a template will be replaced with the name of the
+list, obtained by prompting the user."
+ :group 'org-plain-lists
+ :type '(repeat
+ (list (symbol :tag "Major mode")
+ (string :tag "Format"))))
+
+(defvar org-list-forbidden-blocks '("example" "verse" "src" "export")
+ "Names of blocks where lists are not allowed.
+Names must be in lower case.")
+
+(defvar org-list-export-context '(block inlinetask)
+ "Context types where lists will be interpreted during export.
+
+Valid types are `drawer', `inlinetask' and `block'. More
+specifically, type `block' is determined by the variable
+`org-list-forbidden-blocks'.")
+
+
+
+;;; Predicates and regexps
+
+(defconst org-list-end-re "^[ \t]*\n[ \t]*\n"
+ "Regex matching the end of a plain list.")
+
+(defconst org-list-full-item-re
+ (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)\\(?:[ \t]+\\|$\\)\\)"
+ "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
+ "\\(?:\\(\\[[ X-]\\]\\)\\(?:[ \t]+\\|$\\)\\)?"
+ "\\(?:\\(.*\\)[ \t]+::\\(?:[ \t]+\\|$\\)\\)?")
+ "Matches a list item and puts everything into groups:
+group 1: bullet
+group 2: counter
+group 3: checkbox
+group 4: description tag")
+
+(defun org-item-re ()
+ "Return the correct regular expression for plain lists."
+ (let ((term (cond
+ ((eq org-plain-list-ordered-item-terminator t) "[.)]")
+ ((= org-plain-list-ordered-item-terminator ?\)) ")")
+ ((= org-plain-list-ordered-item-terminator ?.) "\\.")
+ (t "[.)]")))
+ (alpha (if org-list-allow-alphabetical "\\|[A-Za-z]" "")))
+ (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
+ "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
+
+(defsubst org-item-beginning-re ()
+ "Regexp matching the beginning of a plain list item."
+ (concat "^" (org-item-re)))
+
+(defun org-list-at-regexp-after-bullet-p (regexp)
+ "Is point at a list item with REGEXP after bullet?"
+ (and (org-at-item-p)
+ (save-excursion
+ (goto-char (match-end 0))
+ (let ((counter-re (concat "\\(?:\\[@\\(?:start:\\)?"
+ (if org-list-allow-alphabetical
+ "\\([0-9]+\\|[A-Za-z]\\)"
+ "[0-9]+")
+ "\\][ \t]*\\)")))
+ ;; Ignore counter if any
+ (when (looking-at counter-re) (goto-char (match-end 0))))
+ (looking-at regexp))))
+
+(defun org-list-in-valid-context-p ()
+ "Is point in a context where lists are allowed?"
+ (not (org-in-block-p org-list-forbidden-blocks)))
+
+(defun org-in-item-p ()
+ "Return item beginning position when in a plain list, nil otherwise."
+ (save-excursion
+ (beginning-of-line)
+ (let* ((case-fold-search t)
+ (context (org-list-context))
+ (lim-up (car context))
+ (inlinetask-re (and (featurep 'org-inlinetask)
+ (org-inlinetask-outline-regexp)))
+ (item-re (org-item-re))
+ ;; Indentation isn't meaningful when point starts at an empty
+ ;; line or an inline task.
+ (ind-ref (if (or (looking-at "^[ \t]*$")
+ (and inlinetask-re (looking-at inlinetask-re)))
+ 10000
+ (org-get-indentation))))
+ (cond
+ ((eq (nth 2 context) 'invalid) nil)
+ ((looking-at item-re) (point))
+ (t
+ ;; Detect if cursor in amidst `org-list-end-re'. First, count
+ ;; number HL of hard lines it takes, then call `org-in-regexp'
+ ;; to compute its boundaries END-BOUNDS. When point is
+ ;; in-between, move cursor before regexp beginning.
+ (let ((hl 0) (i -1) end-bounds)
+ (when (and (progn
+ (while (setq i (string-match
+ "[\r\n]" org-list-end-re (1+ i)))
+ (setq hl (1+ hl)))
+ (setq end-bounds (org-in-regexp org-list-end-re hl)))
+ (>= (point) (car end-bounds))
+ (< (point) (cdr end-bounds)))
+ (goto-char (car end-bounds))
+ (forward-line -1)))
+ ;; Look for an item, less indented that reference line.
+ (catch 'exit
+ (while t
+ (let ((ind (org-get-indentation)))
+ (cond
+ ;; This is exactly what we want.
+ ((and (looking-at item-re) (< ind ind-ref))
+ (throw 'exit (point)))
+ ;; At upper bound of search or looking at the end of a
+ ;; previous list: search is over.
+ ((<= (point) lim-up) (throw 'exit nil))
+ ((looking-at org-list-end-re) (throw 'exit nil))
+ ;; Skip blocks, drawers, inline-tasks, blank lines
+ ((and (looking-at "^[ \t]*#\\+end_")
+ (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
+ ((and (looking-at "^[ \t]*:END:")
+ (re-search-backward org-drawer-regexp lim-up t))
+ (beginning-of-line))
+ ((and inlinetask-re (looking-at inlinetask-re))
+ (org-inlinetask-goto-beginning)
+ (forward-line -1))
+ ((looking-at "^[ \t]*$") (forward-line -1))
+ ;; Text at column 0 cannot belong to a list: stop.
+ ((zerop ind) (throw 'exit nil))
+ ;; Normal text less indented than reference line, take
+ ;; it as new reference.
+ ((< ind ind-ref)
+ (setq ind-ref ind)
+ (forward-line -1))
+ (t (forward-line -1)))))))))))
+
+(defun org-at-item-p ()
+ "Is point in a line starting a hand-formatted item?"
+ (save-excursion
+ (beginning-of-line)
+ (and (looking-at (org-item-re)) (org-list-in-valid-context-p))))
+
+(defun org-at-item-bullet-p ()
+ "Is point at the bullet of a plain list item?"
+ (and (org-at-item-p)
+ (not (member (char-after) '(?\ ?\t)))
+ (< (point) (match-end 0))))
+
+(defun org-at-item-timer-p ()
+ "Is point at a line starting a plain list item with a timer?"
+ (org-list-at-regexp-after-bullet-p
+ "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
+
+(defun org-at-item-description-p ()
+ "Is point at a description list item?"
+ (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::\\([ \t]+\\|$\\)"))
+
+(defun org-at-item-checkbox-p ()
+ "Is point at a line starting a plain-list item with a checklet?"
+ (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
+
+(defun org-at-item-counter-p ()
+ "Is point at a line starting a plain-list item with a counter?"
+ (and (org-at-item-p)
+ (looking-at org-list-full-item-re)
+ (match-string 2)))
+
+
+
+;;; Structures and helper functions
+
+(defun org-list-context ()
+ "Determine context, and its boundaries, around point.
+
+Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX
+are boundaries and CONTEXT is a symbol among `drawer', `block',
+`invalid', `inlinetask' and nil.
+
+Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
+ (save-match-data
+ (save-excursion
+ (org-with-limited-levels
+ (beginning-of-line)
+ (let ((case-fold-search t) (pos (point)) beg end context-type
+ ;; Get positions of surrounding headings. This is the
+ ;; default context.
+ (lim-up (or (save-excursion (and (ignore-errors (org-back-to-heading t))
+ (point)))
+ (point-min)))
+ (lim-down (or (save-excursion (outline-next-heading)) (point-max))))
+ ;; Is point inside a drawer?
+ (let ((end-re "^[ \t]*:END:")
+ (beg-re org-drawer-regexp))
+ (when (save-excursion
+ (and (not (looking-at beg-re))
+ (not (looking-at end-re))
+ (setq beg (and (re-search-backward beg-re lim-up t)
+ (1+ (point-at-eol))))
+ (setq end (or (and (re-search-forward end-re lim-down t)
+ (1- (match-beginning 0)))
+ lim-down))
+ (>= end pos)))
+ (setq lim-up beg lim-down end context-type 'drawer)))
+ ;; Is point strictly in a block, and of which type?
+ (let ((block-re "^[ \t]*#\\+\\(begin\\|end\\)_") type)
+ (when (save-excursion
+ (and (not (looking-at block-re))
+ (setq beg (and (re-search-backward block-re lim-up t)
+ (1+ (point-at-eol))))
+ (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)")
+ (setq type (downcase (match-string 1)))
+ (goto-char beg)
+ (setq end (or (and (re-search-forward block-re lim-down t)
+ (1- (point-at-bol)))
+ lim-down))
+ (>= end pos)
+ (equal (downcase (match-string 1)) "end")))
+ (setq lim-up beg lim-down end
+ context-type (if (member type org-list-forbidden-blocks)
+ 'invalid 'block))))
+ ;; Is point in an inlinetask?
+ (when (and (featurep 'org-inlinetask)
+ (save-excursion
+ (let* ((beg-re (org-inlinetask-outline-regexp))
+ (end-re (concat beg-re "END[ \t]*$")))
+ (and (not (looking-at "^\\*+"))
+ (setq beg (and (re-search-backward beg-re lim-up t)
+ (1+ (point-at-eol))))
+ (not (looking-at end-re))
+ (setq end (and (re-search-forward end-re lim-down t)
+ (1- (match-beginning 0))))
+ (> (point) pos)))))
+ (setq lim-up beg lim-down end context-type 'inlinetask))
+ ;; Return context boundaries and type.
+ (list lim-up lim-down context-type))))))
+
+(defun org-list-struct ()
+ "Return structure of list at point.
+
+A list structure is an alist where key is point at item, and
+values are:
+1. indentation,
+2. bullet with trailing whitespace,
+3. bullet counter, if any,
+4. checkbox, if any,
+5. description tag, if any,
+6. position at item end.
+
+Thus the following list, where numbers in parens are
+point-at-bol:
+
+- [X] first item (1)
+ 1. sub-item 1 (18)
+ 5. [@5] sub-item 2 (34)
+ some other text belonging to first item (55)
+- last item (97)
+ + tag :: description (109)
+ (131)
+
+will get the following structure:
+
+ ((1 0 \"- \" nil \"[X]\" nil 97)
+ (18 2 \"1. \" nil nil nil 34)
+ (34 2 \"5. \" \"5\" nil nil 55)
+ (97 0 \"- \" nil nil nil 131)
+ (109 2 \"+ \" nil nil \"tag\" 131))
+
+Assume point is at an item."
+ (save-excursion
+ (beginning-of-line)
+ (let* ((case-fold-search t)
+ (context (org-list-context))
+ (lim-up (car context))
+ (lim-down (nth 1 context))
+ (text-min-ind 10000)
+ (item-re (org-item-re))
+ (inlinetask-re (and (featurep 'org-inlinetask)
+ (org-inlinetask-outline-regexp)))
+ (beg-cell (cons (point) (org-get-indentation)))
+ itm-lst itm-lst-2 end-lst end-lst-2 struct
+ (assoc-at-point
+ (function
+ ;; Return association at point.
+ (lambda (ind)
+ (looking-at org-list-full-item-re)
+ (let ((bullet (match-string-no-properties 1)))
+ (list (point)
+ ind
+ bullet
+ (match-string-no-properties 2) ; counter
+ (match-string-no-properties 3) ; checkbox
+ ;; Description tag.
+ (and (string-match-p "[-+*]" bullet)
+ (match-string-no-properties 4)))))))
+ (end-before-blank
+ (function
+ ;; Ensure list ends at the first blank line.
+ (lambda ()
+ (skip-chars-backward " \r\t\n")
+ (min (1+ (point-at-eol)) lim-down)))))
+ ;; 1. Read list from starting item to its beginning, and save
+ ;; top item position and indentation in BEG-CELL. Also store
+ ;; ending position of items in END-LST.
+ (save-excursion
+ (catch 'exit
+ (while t
+ (let ((ind (org-get-indentation)))
+ (cond
+ ((<= (point) lim-up)
+ ;; At upward limit: if we ended at an item, store it,
+ ;; else dismiss useless data recorded above BEG-CELL.
+ ;; Jump to part 2.
+ (throw 'exit
+ (setq itm-lst
+ (if (not (looking-at item-re))
+ (memq (assq (car beg-cell) itm-lst) itm-lst)
+ (setq beg-cell (cons (point) ind))
+ (cons (funcall assoc-at-point ind) itm-lst)))))
+ ;; Looking at a list ending regexp. Dismiss useless
+ ;; data recorded above BEG-CELL. Jump to part 2.
+ ((looking-at org-list-end-re)
+ (throw 'exit
+ (setq itm-lst
+ (memq (assq (car beg-cell) itm-lst) itm-lst))))
+ ;; Point is at an item. Add data to ITM-LST. It may
+ ;; also end a previous item: save it in END-LST. If
+ ;; ind is less or equal than BEG-CELL and there is no
+ ;; end at this ind or lesser, this item becomes the new
+ ;; BEG-CELL.
+ ((looking-at item-re)
+ (push (funcall assoc-at-point ind) itm-lst)
+ (push (cons ind (point)) end-lst)
+ (when (< ind text-min-ind) (setq beg-cell (cons (point) ind)))
+ (forward-line -1))
+ ;; Skip blocks, drawers, inline tasks, blank lines.
+ ((and (looking-at "^[ \t]*#\\+end_")
+ (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
+ ((and (looking-at "^[ \t]*:END:")
+ (re-search-backward org-drawer-regexp lim-up t))
+ (beginning-of-line))
+ ((and inlinetask-re (looking-at inlinetask-re))
+ (org-inlinetask-goto-beginning)
+ (forward-line -1))
+ ((looking-at "^[ \t]*$")
+ (forward-line -1))
+ ;; From there, point is not at an item. Interpret
+ ;; line's indentation:
+ ;; - text at column 0 is necessarily out of any list.
+ ;; Dismiss data recorded above BEG-CELL. Jump to
+ ;; part 2.
+ ;; - any other case may be an ending position for an
+ ;; hypothetical item above. Store it and proceed.
+ ((zerop ind)
+ (throw 'exit
+ (setq itm-lst
+ (memq (assq (car beg-cell) itm-lst) itm-lst))))
+ (t
+ (when (< ind text-min-ind) (setq text-min-ind ind))
+ (push (cons ind (point)) end-lst)
+ (forward-line -1)))))))
+ ;; 2. Read list from starting point to its end, that is until we
+ ;; get out of context, or that a non-item line is less or
+ ;; equally indented than BEG-CELL's cdr. Also, store ending
+ ;; position of items in END-LST-2.
+ (catch 'exit
+ (while t
+ (let ((ind (org-get-indentation)))
+ (cond
+ ((>= (point) lim-down)
+ ;; At downward limit: this is de facto the end of the
+ ;; list. Save point as an ending position, and jump to
+ ;; part 3.
+ (throw 'exit
+ (push (cons 0 (funcall end-before-blank)) end-lst-2)))
+ ;; Looking at a list ending regexp. Save point as an
+ ;; ending position and jump to part 3.
+ ((looking-at org-list-end-re)
+ (throw 'exit (push (cons 0 (point)) end-lst-2)))
+ ((looking-at item-re)
+ ;; Point is at an item. Add data to ITM-LST-2. It may
+ ;; also end a previous item, so save it in END-LST-2.
+ (push (funcall assoc-at-point ind) itm-lst-2)
+ (push (cons ind (point)) end-lst-2)
+ (forward-line 1))
+ ;; Skip inline tasks and blank lines along the way
+ ((and inlinetask-re (looking-at inlinetask-re))
+ (org-inlinetask-goto-end))
+ ((looking-at "^[ \t]*$")
+ (forward-line 1))
+ ;; Ind is lesser or equal than BEG-CELL's. The list is
+ ;; over: store point as an ending position and jump to
+ ;; part 3.
+ ((<= ind (cdr beg-cell))
+ (throw 'exit
+ (push (cons 0 (funcall end-before-blank)) end-lst-2)))
+ ;; Else, if ind is lesser or equal than previous item's,
+ ;; this is an ending position: store it. In any case,
+ ;; skip block or drawer at point, and move to next line.
+ (t
+ (when (<= ind (nth 1 (car itm-lst-2)))
+ (push (cons ind (point)) end-lst-2))
+ (cond
+ ((and (looking-at "^[ \t]*#\\+begin_")
+ (re-search-forward "^[ \t]*#\\+end_" lim-down t)))
+ ((and (looking-at org-drawer-regexp)
+ (re-search-forward "^[ \t]*:END:" lim-down t))))
+ (forward-line 1))))))
+ (setq struct (append itm-lst (cdr (nreverse itm-lst-2)))
+ end-lst (append end-lst (cdr (nreverse end-lst-2))))
+ ;; 3. Associate each item to its end position.
+ (org-list-struct-assoc-end struct end-lst)
+ ;; 4. Return STRUCT
+ struct)))
+
+(defun org-list-struct-assoc-end (struct end-list)
+ "Associate proper ending point to items in STRUCT.
+
+END-LIST is a pseudo-alist where car is indentation and cdr is
+ending position.
+
+This function modifies STRUCT."
+ (let ((endings end-list))
+ (mapc
+ (lambda (elt)
+ (let ((pos (car elt))
+ (ind (nth 1 elt)))
+ ;; Remove end candidates behind current item.
+ (while (or (<= (cdar endings) pos))
+ (pop endings))
+ ;; Add end position to item assoc.
+ (let ((old-end (nthcdr 6 elt))
+ (new-end (assoc-default ind endings '<=)))
+ (if old-end
+ (setcar old-end new-end)
+ (setcdr elt (append (cdr elt) (list new-end)))))))
+ struct)))
+
+(defun org-list-prevs-alist (struct)
+ "Return alist between item and previous item in STRUCT."
+ (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
+ struct)))
+ (mapcar (lambda (e)
+ (let ((prev (car (rassq (car e) item-end-alist))))
+ (cons (car e) prev)))
+ struct)))
+
+(defun org-list-parents-alist (struct)
+ "Return alist between item and parent in STRUCT."
+ (let* ((ind-to-ori (list (list (nth 1 (car struct)))))
+ (top-item (org-list-get-top-point struct))
+ (prev-pos (list top-item)))
+ (cons prev-pos
+ (mapcar (lambda (item)
+ (let ((pos (car item))
+ (ind (nth 1 item))
+ (prev-ind (caar ind-to-ori)))
+ (push pos prev-pos)
+ (cond
+ ((> prev-ind ind)
+ ;; A sub-list is over. Find the associated
+ ;; origin in IND-TO-ORI. If it cannot be
+ ;; found (ill-formed list), set its parent as
+ ;; the first item less indented. If there is
+ ;; none, make it a top-level item.
+ (setq ind-to-ori
+ (or (member (assq ind ind-to-ori) ind-to-ori)
+ (catch 'exit
+ (mapc
+ (lambda (e)
+ (when (< (car e) ind)
+ (throw 'exit (member e ind-to-ori))))
+ ind-to-ori)
+ (list (list ind)))))
+ (cons pos (cdar ind-to-ori)))
+ ;; A sub-list starts. Every item at IND will
+ ;; have previous item as its parent.
+ ((< prev-ind ind)
+ (let ((origin (nth 1 prev-pos)))
+ (push (cons ind origin) ind-to-ori)
+ (cons pos origin)))
+ ;; Another item in the same sub-list: it shares
+ ;; the same parent as the previous item.
+ (t (cons pos (cdar ind-to-ori))))))
+ (cdr struct)))))
+
+
+
+;;; Accessors
+
+(defsubst org-list-get-nth (n key struct)
+ "Return the Nth value of KEY in STRUCT."
+ (nth n (assq key struct)))
+
+(defun org-list-set-nth (n key struct new)
+ "Set the Nth value of KEY in STRUCT to NEW.
+\nThis function modifies STRUCT."
+ (setcar (nthcdr n (assq key struct)) new))
+
+(defsubst org-list-get-ind (item struct)
+ "Return indentation of ITEM in STRUCT."
+ (org-list-get-nth 1 item struct))
+
+(defun org-list-set-ind (item struct ind)
+ "Set indentation of ITEM in STRUCT to IND.
+\nThis function modifies STRUCT."
+ (org-list-set-nth 1 item struct ind))
+
+(defsubst org-list-get-bullet (item struct)
+ "Return bullet of ITEM in STRUCT."
+ (org-list-get-nth 2 item struct))
+
+(defun org-list-set-bullet (item struct bullet)
+ "Set bullet of ITEM in STRUCT to BULLET.
+\nThis function modifies STRUCT."
+ (org-list-set-nth 2 item struct bullet))
+
+(defsubst org-list-get-counter (item struct)
+ "Return counter of ITEM in STRUCT."
+ (org-list-get-nth 3 item struct))
+
+(defsubst org-list-get-checkbox (item struct)
+ "Return checkbox of ITEM in STRUCT or nil."
+ (org-list-get-nth 4 item struct))
+
+(defun org-list-set-checkbox (item struct checkbox)
+ "Set checkbox of ITEM in STRUCT to CHECKBOX.
+\nThis function modifies STRUCT."
+ (org-list-set-nth 4 item struct checkbox))
+
+(defsubst org-list-get-tag (item struct)
+ "Return end position of ITEM in STRUCT."
+ (org-list-get-nth 5 item struct))
+
+(defun org-list-get-item-end (item struct)
+ "Return end position of ITEM in STRUCT."
+ (org-list-get-nth 6 item struct))
+
+(defun org-list-get-item-end-before-blank (item struct)
+ "Return point at end of ITEM in STRUCT, before any blank line.
+Point returned is at end of line."
+ (save-excursion
+ (goto-char (org-list-get-item-end item struct))
+ (skip-chars-backward " \r\t\n")
+ (point-at-eol)))
+
+(defun org-list-get-parent (item struct parents)
+ "Return parent of ITEM or nil.
+STRUCT is the list structure. PARENTS is the alist of parents,
+as returned by `org-list-parents-alist'."
+ (let ((parents (or parents (org-list-parents-alist struct))))
+ (cdr (assq item parents))))
+
+(defun org-list-has-child-p (item struct)
+ "Non-nil if ITEM has a child.
+
+STRUCT is the list structure.
+
+Value returned is the position of the first child of ITEM."
+ (let ((ind (org-list-get-ind item struct))
+ (child-maybe (car (nth 1 (member (assq item struct) struct)))))
+ (when (and child-maybe
+ (< ind (org-list-get-ind child-maybe struct)))
+ child-maybe)))
+
+(defun org-list-get-next-item (item _struct prevs)
+ "Return next item in same sub-list as ITEM, or nil.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (car (rassq item prevs)))
+
+(defun org-list-get-prev-item (item _struct prevs)
+ "Return previous item in same sub-list as ITEM, or nil.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (cdr (assq item prevs)))
+
+(defun org-list-get-subtree (item struct)
+ "List all items having ITEM as a common ancestor, or nil.
+STRUCT is the list structure."
+ (let* ((item-end (org-list-get-item-end item struct))
+ (sub-struct (cdr (member (assq item struct) struct)))
+ subtree)
+ (catch 'exit
+ (mapc (lambda (e)
+ (let ((pos (car e)))
+ (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
+ sub-struct))
+ (nreverse subtree)))
+
+(defun org-list-get-all-items (item struct prevs)
+ "List all items in the same sub-list as ITEM.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (let ((prev-item item)
+ (next-item item)
+ before-item after-item)
+ (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
+ (push prev-item before-item))
+ (while (setq next-item (org-list-get-next-item next-item struct prevs))
+ (push next-item after-item))
+ (append before-item (list item) (nreverse after-item))))
+
+(defun org-list-get-children (item _struct parents)
+ "List all children of ITEM, or nil.
+STRUCT is the list structure. PARENTS is the alist of parents,
+as returned by `org-list-parents-alist'."
+ (let (all child)
+ (while (setq child (car (rassq item parents)))
+ (setq parents (cdr (member (assq child parents) parents)))
+ (push child all))
+ (nreverse all)))
+
+(defun org-list-get-top-point (struct)
+ "Return point at beginning of list.
+STRUCT is the list structure."
+ (caar struct))
+
+(defun org-list-get-bottom-point (struct)
+ "Return point at bottom of list.
+STRUCT is the list structure."
+ (apply #'max
+ (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
+
+(defun org-list-get-list-begin (item struct prevs)
+ "Return point at beginning of sub-list ITEM belongs.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (let ((first-item item) prev-item)
+ (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
+ (setq first-item prev-item))
+ first-item))
+
+(defalias 'org-list-get-first-item 'org-list-get-list-begin)
+
+(defun org-list-get-last-item (item struct prevs)
+ "Return point at last item of sub-list ITEM belongs.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (let ((last-item item) next-item)
+ (while (setq next-item (org-list-get-next-item last-item struct prevs))
+ (setq last-item next-item))
+ last-item))
+
+(defun org-list-get-list-end (item struct prevs)
+ "Return point at end of sub-list ITEM belongs.
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'."
+ (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
+
+(defun org-list-get-list-type (item struct prevs)
+ "Return the type of the list containing ITEM, as a symbol.
+
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'.
+
+Possible types are `descriptive', `ordered' and `unordered'. The
+type is determined by the first item of the list."
+ (let ((first (org-list-get-list-begin item struct prevs)))
+ (cond
+ ((string-match-p "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
+ ((org-list-get-tag first struct) 'descriptive)
+ (t 'unordered))))
+
+(defun org-list-get-item-number (item struct prevs parents)
+ "Return ITEM's sequence number.
+
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'. PARENTS is the
+alist of ancestors, as returned by `org-list-parents-alist'.
+
+Return value is a list of integers. Counters have an impact on
+that value."
+ (let ((get-relative-number
+ (function
+ (lambda (item struct prevs)
+ ;; Return relative sequence number of ITEM in the sub-list
+ ;; it belongs. STRUCT is the list structure. PREVS is
+ ;; the alist of previous items.
+ (let ((seq 0) (pos item) counter)
+ (while (and (not (setq counter (org-list-get-counter pos struct)))
+ (setq pos (org-list-get-prev-item pos struct prevs)))
+ (cl-incf seq))
+ (if (not counter) (1+ seq)
+ (cond
+ ((string-match "[A-Za-z]" counter)
+ (+ (- (string-to-char (upcase (match-string 0 counter))) 64)
+ seq))
+ ((string-match "[0-9]+" counter)
+ (+ (string-to-number (match-string 0 counter)) seq))
+ (t (1+ seq)))))))))
+ ;; Cons each parent relative number into return value (OUT).
+ (let ((out (list (funcall get-relative-number item struct prevs)))
+ (parent item))
+ (while (setq parent (org-list-get-parent parent struct parents))
+ (push (funcall get-relative-number parent struct prevs) out))
+ ;; Return value.
+ out)))
+
+
+
+;;; Searching
+
+(defun org-list-search-generic (search re bound noerr)
+ "Search a string in valid contexts for lists.
+Arguments SEARCH, RE, BOUND and NOERR are similar to those used
+in `re-search-forward'."
+ (catch 'exit
+ (let ((origin (point)))
+ (while t
+ ;; 1. No match: return to origin or bound, depending on NOERR.
+ (unless (funcall search re bound noerr)
+ (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
+ nil)))
+ ;; 2. Match in valid context: return point. Else, continue
+ ;; searching.
+ (when (org-list-in-valid-context-p) (throw 'exit (point)))))))
+
+(defun org-list-search-backward (regexp &optional bound noerror)
+ "Like `re-search-backward' but stop only where lists are recognized.
+Arguments REGEXP, BOUND and NOERROR are similar to those used in
+`re-search-backward'."
+ (org-list-search-generic #'re-search-backward
+ regexp (or bound (point-min)) noerror))
+
+(defun org-list-search-forward (regexp &optional bound noerror)
+ "Like `re-search-forward' but stop only where lists are recognized.
+Arguments REGEXP, BOUND and NOERROR are similar to those used in
+`re-search-forward'."
+ (org-list-search-generic #'re-search-forward
+ regexp (or bound (point-max)) noerror))
+
+
+
+;;; Methods on structures
+
+(defsubst org-list-bullet-string (bullet)
+ "Return BULLET with the correct number of whitespaces.
+It determines the number of whitespaces to append by looking at
+`org-list-two-spaces-after-bullet-regexp'."
+ (save-match-data
+ (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp
+ (string-match
+ org-list-two-spaces-after-bullet-regexp bullet))
+ " "
+ " ")))
+ (if (string-match "\\S-+\\([ \t]*\\)" bullet)
+ (replace-match spaces nil nil bullet 1)
+ bullet))))
+
+(defun org-list-swap-items (beg-A beg-B struct)
+ "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
+
+Blank lines at the end of items are left in place. Item
+visibility is preserved. Return the new structure after the
+changes.
+
+Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
+to the same sub-list.
+
+This function modifies STRUCT."
+ (save-excursion
+ (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
+ (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
+ (end-A (org-list-get-item-end beg-A struct))
+ (end-B (org-list-get-item-end beg-B struct))
+ (size-A (- end-A-no-blank beg-A))
+ (size-B (- end-B-no-blank beg-B))
+ (body-A (buffer-substring beg-A end-A-no-blank))
+ (body-B (buffer-substring beg-B end-B-no-blank))
+ (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
+ (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
+ (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
+ ;; Store overlays responsible for visibility status. We
+ ;; also need to store their boundaries as they will be
+ ;; removed from buffer.
+ (overlays
+ (cons
+ (delq nil
+ (mapcar (lambda (o)
+ (and (>= (overlay-start o) beg-A)
+ (<= (overlay-end o) end-A)
+ (list o (overlay-start o) (overlay-end o))))
+ (overlays-in beg-A end-A)))
+ (delq nil
+ (mapcar (lambda (o)
+ (and (>= (overlay-start o) beg-B)
+ (<= (overlay-end o) end-B)
+ (list o (overlay-start o) (overlay-end o))))
+ (overlays-in beg-B end-B))))))
+ ;; 1. Move effectively items in buffer.
+ (goto-char beg-A)
+ (delete-region beg-A end-B-no-blank)
+ (insert (concat body-B between-A-no-blank-and-B body-A))
+ ;; 2. Now modify struct. No need to re-read the list, the
+ ;; transformation is just a shift of positions. Some special
+ ;; attention is required for items ending at END-A and END-B
+ ;; as empty spaces are not moved there. In others words,
+ ;; item BEG-A will end with whitespaces that were at the end
+ ;; of BEG-B and the same applies to BEG-B.
+ (dolist (e struct)
+ (let ((pos (car e)))
+ (cond
+ ((< pos beg-A))
+ ((memq pos sub-A)
+ (let ((end-e (nth 6 e)))
+ (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
+ (setcar (nthcdr 6 e)
+ (+ end-e (- end-B-no-blank end-A-no-blank)))
+ (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
+ ((memq pos sub-B)
+ (let ((end-e (nth 6 e)))
+ (setcar e (- (+ pos beg-A) beg-B))
+ (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
+ (when (= end-e end-B)
+ (setcar (nthcdr 6 e)
+ (+ beg-A size-B (- end-A end-A-no-blank))))))
+ ((< pos beg-B)
+ (let ((end-e (nth 6 e)))
+ (setcar e (+ pos (- size-B size-A)))
+ (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
+ (setq struct (sort struct #'car-less-than-car))
+ ;; Restore visibility status, by moving overlays to their new
+ ;; position.
+ (dolist (ov (car overlays))
+ (move-overlay
+ (car ov)
+ (+ (nth 1 ov) (- (+ beg-B (- size-B size-A)) beg-A))
+ (+ (nth 2 ov) (- (+ beg-B (- size-B size-A)) beg-A))))
+ (dolist (ov (cdr overlays))
+ (move-overlay (car ov)
+ (+ (nth 1 ov) (- beg-A beg-B))
+ (+ (nth 2 ov) (- beg-A beg-B))))
+ ;; Return structure.
+ struct)))
+
+(defun org-list-separating-blank-lines-number (pos struct prevs)
+ "Return number of blank lines that should separate items in list.
+
+POS is the position of point where `org-list-insert-item' was called.
+
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'.
+
+Assume point is at item's beginning. If the item is alone, apply
+some heuristics to guess the result."
+ (save-excursion
+ (let ((item (point))
+ (insert-blank-p
+ (cdr (assq 'plain-list-item org-blank-before-new-entry)))
+ usr-blank
+ (count-blanks
+ (function
+ (lambda ()
+ ;; Count blank lines above beginning of line.
+ (save-excursion
+ (count-lines (goto-char (point-at-bol))
+ (progn (skip-chars-backward " \r\t\n")
+ (forward-line)
+ (point))))))))
+ (cond
+ ;; Trivial cases where there should be none.
+ ((not insert-blank-p) 0)
+ ;; When `org-blank-before-new-entry' says so, it is 1.
+ ((eq insert-blank-p t) 1)
+ ;; `plain-list-item' is 'auto. Count blank lines separating
+ ;; neighbors' items in list.
+ (t (let ((next-p (org-list-get-next-item item struct prevs)))
+ (cond
+ ;; Is there a next item?
+ (next-p (goto-char next-p)
+ (funcall count-blanks))
+ ;; Is there a previous item?
+ ((org-list-get-prev-item item struct prevs)
+ (funcall count-blanks))
+ ;; User inserted blank lines, trust him.
+ ((and (> pos (org-list-get-item-end-before-blank item struct))
+ (> (save-excursion (goto-char pos)
+ (setq usr-blank (funcall count-blanks)))
+ 0))
+ usr-blank)
+ ;; Are there blank lines inside the list so far?
+ ((save-excursion
+ (goto-char (org-list-get-top-point struct))
+ ;; Do not use `org-list-search-forward' so blank lines
+ ;; in blocks can be counted in.
+ (re-search-forward
+ "^[ \t]*$" (org-list-get-item-end-before-blank item struct) t))
+ 1)
+ ;; Default choice: no blank line.
+ (t 0))))))))
+
+(defun org-list-insert-item (pos struct prevs &optional checkbox after-bullet)
+ "Insert a new list item at POS and return the new structure.
+If POS is before first character after bullet of the item, the
+new item will be created before the current one.
+
+STRUCT is the list structure. PREVS is the alist of previous
+items, as returned by `org-list-prevs-alist'.
+
+Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
+after the bullet. Cursor will be after this text once the
+function ends.
+
+This function modifies STRUCT."
+ (let ((case-fold-search t))
+ ;; 1. Get information about list: position of point with regards
+ ;; to item start (BEFOREP), blank lines number separating items
+ ;; (BLANK-NB), if we're allowed to (SPLIT-LINE-P).
+ (let* ((item (progn (goto-char pos) (goto-char (org-list-get-item-begin))))
+ (item-end (org-list-get-item-end item struct))
+ (item-end-no-blank (org-list-get-item-end-before-blank item struct))
+ (beforep
+ (progn
+ (looking-at org-list-full-item-re)
+ (<= pos
+ (cond
+ ((not (match-beginning 4)) (match-end 0))
+ ;; Ignore tag in a non-descriptive list.
+ ((save-match-data (string-match "[.)]" (match-string 1)))
+ (match-beginning 4))
+ (t (save-excursion
+ (goto-char (match-end 4))
+ (skip-chars-forward " \t")
+ (point)))))))
+ (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
+ (blank-nb (org-list-separating-blank-lines-number
+ pos struct prevs))
+ ;; 2. Build the new item to be created. Concatenate same
+ ;; bullet as item, checkbox, text AFTER-BULLET if
+ ;; provided, and text cut from point to end of item
+ ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on
+ ;; BEFOREP and SPLIT-LINE-P. The difference of size
+ ;; between what was cut and what was inserted in buffer
+ ;; is stored in SIZE-OFFSET.
+ (ind (org-list-get-ind item struct))
+ (ind-size (if indent-tabs-mode
+ (+ (/ ind tab-width) (mod ind tab-width))
+ ind))
+ (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
+ (box (when checkbox "[ ]"))
+ (text-cut
+ (and (not beforep) split-line-p
+ (progn
+ (goto-char pos)
+ ;; If POS is greater than ITEM-END, then point is
+ ;; in some white lines after the end of the list.
+ ;; Those must be removed, or they will be left,
+ ;; stacking up after the list.
+ (when (< item-end pos)
+ (delete-region (1- item-end) (point-at-eol)))
+ (skip-chars-backward " \r\t\n")
+ (setq pos (point))
+ (delete-and-extract-region pos item-end-no-blank))))
+ (body (concat bullet (when box (concat box " ")) after-bullet
+ (and text-cut
+ (if (string-match "\\`[ \t]+" text-cut)
+ (replace-match "" t t text-cut)
+ text-cut))))
+ (item-sep (make-string (1+ blank-nb) ?\n))
+ (item-size (+ ind-size (length body) (length item-sep)))
+ (size-offset (- item-size (length text-cut))))
+ ;; 4. Insert effectively item into buffer.
+ (goto-char item)
+ (indent-to-column ind)
+ (insert body item-sep)
+ ;; 5. Add new item to STRUCT.
+ (mapc (lambda (e)
+ (let ((p (car e)) (end (nth 6 e)))
+ (cond
+ ;; Before inserted item, positions don't change but
+ ;; an item ending after insertion has its end shifted
+ ;; by SIZE-OFFSET.
+ ((< p item)
+ (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset))))
+ ;; Trivial cases where current item isn't split in
+ ;; two. Just shift every item after new one by
+ ;; ITEM-SIZE.
+ ((or beforep (not split-line-p))
+ (setcar e (+ p item-size))
+ (setcar (nthcdr 6 e) (+ end item-size)))
+ ;; Item is split in two: elements before POS are just
+ ;; shifted by ITEM-SIZE. In the case item would end
+ ;; after split POS, ending is only shifted by
+ ;; SIZE-OFFSET.
+ ((< p pos)
+ (setcar e (+ p item-size))
+ (if (< end pos)
+ (setcar (nthcdr 6 e) (+ end item-size))
+ (setcar (nthcdr 6 e) (+ end size-offset))))
+ ;; Elements after POS are moved into new item.
+ ;; Length of ITEM-SEP has to be removed as ITEM-SEP
+ ;; doesn't appear in buffer yet.
+ ((< p item-end)
+ (setcar e (+ p size-offset (- item pos (length item-sep))))
+ (if (= end item-end)
+ (setcar (nthcdr 6 e) (+ item item-size))
+ (setcar (nthcdr 6 e)
+ (+ end size-offset
+ (- item pos (length item-sep))))))
+ ;; Elements at ITEM-END or after are only shifted by
+ ;; SIZE-OFFSET.
+ (t (setcar e (+ p size-offset))
+ (setcar (nthcdr 6 e) (+ end size-offset))))))
+ struct)
+ (push (list item ind bullet nil box nil (+ item item-size)) struct)
+ (setq struct (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))
+ ;; 6. If not BEFOREP, new item must appear after ITEM, so
+ ;; exchange ITEM with the next item in list. Position cursor
+ ;; after bullet, counter, checkbox, and label.
+ (if beforep
+ (goto-char item)
+ (setq struct (org-list-swap-items item (+ item item-size) struct))
+ (goto-char (org-list-get-next-item
+ item struct (org-list-prevs-alist struct))))
+ struct)))
+
+(defun org-list-delete-item (item struct)
+ "Remove ITEM from the list and return the new structure.
+
+STRUCT is the list structure."
+ (let* ((end (org-list-get-item-end item struct))
+ (beg (if (= (org-list-get-bottom-point struct) end)
+ ;; If ITEM ends with the list, delete blank lines
+ ;; before it.
+ (save-excursion
+ (goto-char item)
+ (skip-chars-backward " \r\t\n")
+ (min (1+ (point-at-eol)) (point-max)))
+ item)))
+ ;; Remove item from buffer.
+ (delete-region beg end)
+ ;; Remove item from structure and shift others items accordingly.
+ ;; Don't forget to shift also ending position when appropriate.
+ (let ((size (- end beg)))
+ (delq nil (mapcar (lambda (e)
+ (let ((pos (car e)))
+ (cond
+ ((< pos item)
+ (let ((end-e (nth 6 e)))
+ (cond
+ ((< end-e item) e)
+ ((= end-e item)
+ (append (butlast e) (list beg)))
+ (t
+ (append (butlast e) (list (- end-e size)))))))
+ ((< pos end) nil)
+ (t
+ (cons (- pos size)
+ (append (butlast (cdr e))
+ (list (- (nth 6 e) size))))))))
+ struct)))))
+
+(defun org-list-send-item (item dest struct)
+ "Send ITEM to destination DEST.
+
+STRUCT is the list structure.
+
+DEST can have various values.
+
+If DEST is a buffer position, the function will assume it points
+to another item in the same list as ITEM, and will move the
+latter just before the former.
+
+If DEST is `begin' (respectively `end'), ITEM will be moved at
+the beginning (respectively end) of the list it belongs to.
+
+If DEST is a string like \"N\", where N is an integer, ITEM will
+be moved at the Nth position in the list.
+
+If DEST is `kill', ITEM will be deleted and its body will be
+added to the kill-ring.
+
+If DEST is `delete', ITEM will be deleted.
+
+Visibility of item is preserved.
+
+This function returns, destructively, the new list structure."
+ (let* ((prevs (org-list-prevs-alist struct))
+ (item-end (org-list-get-item-end item struct))
+ ;; Grab full item body minus its bullet.
+ (body (org-trim
+ (buffer-substring
+ (save-excursion
+ (goto-char item)
+ (looking-at
+ (concat "[ \t]*"
+ (regexp-quote (org-list-get-bullet item struct))))
+ (match-end 0))
+ item-end)))
+ ;; Change DEST into a buffer position. A trick is needed
+ ;; when ITEM is meant to be sent at the end of the list.
+ ;; Indeed, by setting locally `org-M-RET-may-split-line' to
+ ;; nil and insertion point (INS-POINT) to the first line's
+ ;; end of the last item, we ensure the new item will be
+ ;; inserted after the last item, and not after any of its
+ ;; hypothetical sub-items.
+ (ins-point (cond
+ ((or (eq dest 'kill) (eq dest 'delete)))
+ ((eq dest 'begin)
+ (setq dest (org-list-get-list-begin item struct prevs)))
+ ((eq dest 'end)
+ (setq dest (org-list-get-list-end item struct prevs))
+ (save-excursion
+ (goto-char (org-list-get-last-item item struct prevs))
+ (point-at-eol)))
+ ((string-match-p "\\`[0-9]+\\'" dest)
+ (let* ((all (org-list-get-all-items item struct prevs))
+ (len (length all))
+ (index (mod (string-to-number dest) len)))
+ (if (not (zerop index))
+ (setq dest (nth (1- index) all))
+ ;; Send ITEM at the end of the list.
+ (setq dest (org-list-get-list-end item struct prevs))
+ (save-excursion
+ (goto-char
+ (org-list-get-last-item item struct prevs))
+ (point-at-eol)))))
+ (t dest)))
+ (org-M-RET-may-split-line nil)
+ ;; Store inner overlays (to preserve visibility).
+ (overlays (cl-remove-if (lambda (o) (or (< (overlay-start o) item)
+ (> (overlay-end o) item)))
+ (overlays-in item item-end))))
+ (cond
+ ((eq dest 'delete) (org-list-delete-item item struct))
+ ((eq dest 'kill)
+ (kill-new body)
+ (org-list-delete-item item struct))
+ ((and (integerp dest) (/= item ins-point))
+ (setq item (copy-marker item))
+ (setq struct (org-list-insert-item ins-point struct prevs nil body))
+ ;; 1. Structure returned by `org-list-insert-item' may not be
+ ;; accurate, as it cannot see sub-items included in BODY.
+ ;; Thus, first compute the real structure so far.
+ (let ((moved-items
+ (cons (marker-position item)
+ (org-list-get-subtree (marker-position item) struct)))
+ (new-end (org-list-get-item-end (point) struct))
+ (old-end (org-list-get-item-end (marker-position item) struct))
+ (new-item (point))
+ (shift (- (point) item)))
+ ;; 1.1. Remove the item just created in structure.
+ (setq struct (delete (assq new-item struct) struct))
+ ;; 1.2. Copy ITEM and any of its sub-items at NEW-ITEM.
+ (setq struct (sort
+ (append
+ struct
+ (mapcar (lambda (e)
+ (let* ((cell (assq e struct))
+ (pos (car cell))
+ (end (nth 6 cell)))
+ (cons (+ pos shift)
+ (append (butlast (cdr cell))
+ (list (if (= end old-end)
+ new-end
+ (+ end shift)))))))
+ moved-items))
+ #'car-less-than-car)))
+ ;; 2. Restore inner overlays.
+ (dolist (o overlays)
+ (move-overlay o
+ (+ (overlay-start o) (- (point) item))
+ (+ (overlay-end o) (- (point) item))))
+ ;; 3. Eventually delete extra copy of the item and clean marker.
+ (prog1 (org-list-delete-item (marker-position item) struct)
+ (move-marker item nil)))
+ (t struct))))
+
+(defun org-list-struct-outdent (start end struct parents)
+ "Outdent items between positions START and END.
+
+STRUCT is the list structure. PARENTS is the alist of items'
+parents, as returned by `org-list-parents-alist'.
+
+START is included, END excluded."
+ (let* (acc
+ (out (lambda (cell)
+ (let* ((item (car cell))
+ (parent (cdr cell)))
+ (cond
+ ;; Item not yet in zone: keep association.
+ ((< item start) cell)
+ ;; Item out of zone: follow associations in ACC.
+ ((>= item end)
+ (let ((convert (and parent (assq parent acc))))
+ (if convert (cons item (cdr convert)) cell)))
+ ;; Item has no parent: error
+ ((not parent)
+ (error "Cannot outdent top-level items"))
+ ;; Parent is outdented: keep association.
+ ((>= parent start)
+ (push (cons parent item) acc) cell)
+ (t
+ ;; Parent isn't outdented: reparent to grand-parent.
+ (let ((grand-parent (org-list-get-parent
+ parent struct parents)))
+ (push (cons parent item) acc)
+ (cons item grand-parent))))))))
+ (mapcar out parents)))
+
+(defun org-list-struct-indent (start end struct parents prevs)
+ "Indent items between positions START and END.
+
+STRUCT is the list structure. PARENTS is the alist of parents
+and PREVS is the alist of previous items, returned by,
+respectively, `org-list-parents-alist' and
+`org-list-prevs-alist'.
+
+START is included and END excluded.
+
+STRUCT may be modified if `org-list-demote-modify-bullet' matches
+bullets between START and END."
+ (let* (acc
+ (set-assoc (lambda (cell) (push cell acc) cell))
+ (change-bullet-maybe
+ (function
+ (lambda (item)
+ (let ((new-bul-p
+ (cdr (assoc
+ ;; Normalize ordered bullets.
+ (let ((bul (org-trim
+ (org-list-get-bullet item struct))))
+ (cond ((string-match "[A-Z]\\." bul) "A.")
+ ((string-match "[A-Z])" bul) "A)")
+ ((string-match "[a-z]\\." bul) "a.")
+ ((string-match "[a-z])" bul) "a)")
+ ((string-match "[0-9]\\." bul) "1.")
+ ((string-match "[0-9])" bul) "1)")
+ (t bul)))
+ org-list-demote-modify-bullet))))
+ (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
+ (ind
+ (lambda (cell)
+ (let* ((item (car cell))
+ (parent (cdr cell)))
+ (cond
+ ;; Item not yet in zone: keep association.
+ ((< item start) cell)
+ ((>= item end)
+ ;; Item out of zone: follow associations in ACC.
+ (let ((convert (assq parent acc)))
+ (if convert (cons item (cdr convert)) cell)))
+ (t
+ ;; Item is in zone...
+ (let ((prev (org-list-get-prev-item item struct prevs)))
+ ;; Check if bullet needs to be changed.
+ (funcall change-bullet-maybe item)
+ (cond
+ ;; First item indented but not parent: error
+ ((and (not prev) (< parent start))
+ (error "Cannot indent the first item of a list"))
+ ;; First item and parent indented: keep same
+ ;; parent.
+ ((not prev) (funcall set-assoc cell))
+ ;; Previous item not indented: reparent to it.
+ ((< prev start) (funcall set-assoc (cons item prev)))
+ ;; Previous item indented: reparent like it.
+ (t
+ (funcall set-assoc
+ (cons item (cdr (assq prev acc)))))))))))))
+ (mapcar ind parents)))
+
+
+
+;;; Repairing structures
+
+(defun org-list-use-alpha-bul-p (first struct prevs)
+ "Non-nil if list starting at FIRST can have alphabetical bullets.
+
+STRUCT is list structure. PREVS is the alist of previous items,
+as returned by `org-list-prevs-alist'."
+ (and org-list-allow-alphabetical
+ (catch 'exit
+ (let ((item first) (ascii 64) (case-fold-search nil))
+ ;; Pretend that bullets are uppercase and check if alphabet
+ ;; is sufficient, taking counters into account.
+ (while item
+ (let ((count (org-list-get-counter item struct)))
+ ;; Virtually determine current bullet
+ (if (and count (string-match-p "[a-zA-Z]" count))
+ ;; Counters are not case-sensitive.
+ (setq ascii (string-to-char (upcase count)))
+ (setq ascii (1+ ascii)))
+ ;; Test if bullet would be over z or Z.
+ (if (> ascii 90)
+ (throw 'exit nil)
+ (setq item (org-list-get-next-item item struct prevs)))))
+ ;; All items checked. All good.
+ t))))
+
+(defun org-list-inc-bullet-maybe (bullet)
+ "Increment BULLET if applicable."
+ (let ((case-fold-search nil))
+ (cond
+ ;; Num bullet: increment it.
+ ((string-match "[0-9]+" bullet)
+ (replace-match
+ (number-to-string (1+ (string-to-number (match-string 0 bullet))))
+ nil nil bullet))
+ ;; Alpha bullet: increment it.
+ ((string-match "[A-Za-z]" bullet)
+ (replace-match
+ (char-to-string (1+ (string-to-char (match-string 0 bullet))))
+ nil nil bullet))
+ ;; Unordered bullet: leave it.
+ (t bullet))))
+
+(defun org-list-struct-fix-bul (struct prevs)
+ "Verify and correct bullets in STRUCT.
+PREVS is the alist of previous items, as returned by
+`org-list-prevs-alist'.
+
+This function modifies STRUCT."
+ (let ((case-fold-search nil)
+ (fix-bul
+ (function
+ ;; Set bullet of ITEM in STRUCT, depending on the type of
+ ;; first item of the list, the previous bullet and counter
+ ;; if any.
+ (lambda (item)
+ (let* ((prev (org-list-get-prev-item item struct prevs))
+ (prev-bul (and prev (org-list-get-bullet prev struct)))
+ (counter (org-list-get-counter item struct))
+ (bullet (org-list-get-bullet item struct))
+ (alphap (and (not prev)
+ (org-list-use-alpha-bul-p item struct prevs))))
+ (org-list-set-bullet
+ item struct
+ (org-list-bullet-string
+ (cond
+ ;; Alpha counter in alpha list: use counter.
+ ((and prev counter
+ (string-match "[a-zA-Z]" counter)
+ (string-match "[a-zA-Z]" prev-bul))
+ ;; Use cond to be sure `string-match' is used in
+ ;; both cases.
+ (let ((real-count
+ (cond
+ ((string-match "[a-z]" prev-bul) (downcase counter))
+ ((string-match "[A-Z]" prev-bul) (upcase counter)))))
+ (replace-match real-count nil nil prev-bul)))
+ ;; Num counter in a num list: use counter.
+ ((and prev counter
+ (string-match "[0-9]+" counter)
+ (string-match "[0-9]+" prev-bul))
+ (replace-match counter nil nil prev-bul))
+ ;; No counter: increase, if needed, previous bullet.
+ (prev
+ (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
+ ;; Alpha counter at first item: use counter.
+ ((and counter (org-list-use-alpha-bul-p item struct prevs)
+ (string-match "[A-Za-z]" counter)
+ (string-match "[A-Za-z]" bullet))
+ (let ((real-count
+ (cond
+ ((string-match "[a-z]" bullet) (downcase counter))
+ ((string-match "[A-Z]" bullet) (upcase counter)))))
+ (replace-match real-count nil nil bullet)))
+ ;; Num counter at first item: use counter.
+ ((and counter
+ (string-match "[0-9]+" counter)
+ (string-match "[0-9]+" bullet))
+ (replace-match counter nil nil bullet))
+ ;; First bullet is alpha uppercase: use "A".
+ ((and alphap (string-match "[A-Z]" bullet))
+ (replace-match "A" nil nil bullet))
+ ;; First bullet is alpha lowercase: use "a".
+ ((and alphap (string-match "[a-z]" bullet))
+ (replace-match "a" nil nil bullet))
+ ;; First bullet is num: use "1".
+ ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
+ (replace-match "1" nil nil bullet))
+ ;; Not an ordered list: keep bullet.
+ (t bullet)))))))))
+ (mapc fix-bul (mapcar #'car struct))))
+
+(defun org-list-struct-fix-ind (struct parents &optional bullet-size)
+ "Verify and correct indentation in STRUCT.
+
+PARENTS is the alist of parents, as returned by
+`org-list-parents-alist'.
+
+If numeric optional argument BULLET-SIZE is set, assume all
+bullets in list have this length to determine new indentation.
+
+This function modifies STRUCT."
+ (let* ((ancestor (org-list-get-top-point struct))
+ (top-ind (org-list-get-ind ancestor struct))
+ (new-ind
+ (lambda (item)
+ (let ((parent (org-list-get-parent item struct parents)))
+ (if parent
+ ;; Indent like parent + length of parent's bullet +
+ ;; sub-list offset.
+ (org-list-set-ind
+ item struct (+ (or bullet-size
+ (length
+ (org-list-get-bullet parent struct)))
+ (org-list-get-ind parent struct)
+ org-list-indent-offset))
+ ;; If no parent, indent like top-point.
+ (org-list-set-ind item struct top-ind))))))
+ (mapc new-ind (mapcar #'car (cdr struct)))))
+
+(defun org-list-struct-fix-box (struct parents prevs &optional ordered)
+ "Verify and correct checkboxes in STRUCT.
+
+PARENTS is the alist of parents and PREVS is the alist of
+previous items, as returned by, respectively,
+`org-list-parents-alist' and `org-list-prevs-alist'.
+
+If ORDERED is non-nil, a checkbox can only be checked when every
+checkbox before it is checked too. If there was an attempt to
+break this rule, the function will return the blocking item. In
+all others cases, the return value will be nil.
+
+This function modifies STRUCT."
+ (let ((all-items (mapcar #'car struct))
+ (set-parent-box
+ (function
+ (lambda (item)
+ (let* ((box-list
+ (mapcar (lambda (child)
+ (org-list-get-checkbox child struct))
+ (org-list-get-children item struct parents))))
+ (org-list-set-checkbox
+ item struct
+ (cond
+ ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
+ ((member "[-]" box-list) "[-]")
+ ((member "[X]" box-list) "[X]")
+ ((member "[ ]" box-list) "[ ]")
+ ;; Parent has no boxed child: leave box as-is.
+ (t (org-list-get-checkbox item struct))))))))
+ parent-list)
+ ;; 1. List all parents with a checkbox.
+ (mapc
+ (lambda (e)
+ (let* ((parent (org-list-get-parent e struct parents))
+ (parent-box-p (org-list-get-checkbox parent struct)))
+ (when (and parent-box-p (not (memq parent parent-list)))
+ (push parent parent-list))))
+ all-items)
+ ;; 2. Sort those parents by decreasing indentation.
+ (setq parent-list (sort parent-list
+ (lambda (e1 e2)
+ (> (org-list-get-ind e1 struct)
+ (org-list-get-ind e2 struct)))))
+ ;; 3. For each parent, get all children's checkboxes to determine
+ ;; and set its checkbox accordingly.
+ (mapc set-parent-box parent-list)
+ ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
+ (when ordered
+ (let* ((box-list
+ (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
+ (after-unchecked (member "[ ]" box-list)))
+ ;; There are boxes checked after an unchecked one: fix that.
+ (when (member "[X]" after-unchecked)
+ (let ((index (- (length struct) (length after-unchecked))))
+ (mapc (lambda (e)
+ (when (org-list-get-checkbox e struct)
+ (org-list-set-checkbox e struct "[ ]")))
+ (nthcdr index all-items))
+ ;; Verify once again the structure, without ORDERED.
+ (org-list-struct-fix-box struct parents prevs nil)
+ ;; Return blocking item.
+ (nth index all-items)))))))
+
+(defun org-list-struct-fix-item-end (struct)
+ "Verify and correct each item end position in STRUCT.
+
+This function modifies STRUCT."
+ (let (end-list acc-end)
+ (mapc (lambda (e)
+ (let* ((pos (car e))
+ (ind-pos (org-list-get-ind pos struct))
+ (end-pos (org-list-get-item-end pos struct)))
+ (unless (assq end-pos struct)
+ ;; To determine real ind of an ending position that is
+ ;; not at an item, we have to find the item it belongs
+ ;; to: it is the last item (ITEM-UP), whose ending is
+ ;; further than the position we're interested in.
+ (let ((item-up (assoc-default end-pos acc-end '>)))
+ (push (cons
+ ;; Else part is for the bottom point.
+ (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
+ end-pos)
+ end-list)))
+ (push (cons ind-pos pos) end-list)
+ (push (cons end-pos pos) acc-end)))
+ struct)
+ (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
+ (org-list-struct-assoc-end struct end-list)))
+
+(defun org-list-struct-apply-struct (struct old-struct)
+ "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
+
+OLD-STRUCT is the structure before any modifications, and STRUCT
+the structure to be applied. The function will only modify parts
+of the list which have changed.
+
+Initial position of cursor is restored after the changes."
+ (let* ((origin (point-marker))
+ (inlinetask-re (and (featurep 'org-inlinetask)
+ (org-inlinetask-outline-regexp)))
+ (item-re (org-item-re))
+ (shift-body-ind
+ (function
+ ;; Shift the indentation between END and BEG by DELTA.
+ ;; Start from the line before END.
+ (lambda (end beg delta)
+ (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (beginning-of-line)
+ (while (or (> (point) beg)
+ (and (= (point) beg)
+ (not (looking-at item-re))))
+ (cond
+ ;; Skip inline tasks.
+ ((and inlinetask-re (looking-at inlinetask-re))
+ (org-inlinetask-goto-beginning))
+ ;; Shift only non-empty lines.
+ ((looking-at-p "^[ \t]*\\S-")
+ (indent-line-to (+ (org-get-indentation) delta))))
+ (forward-line -1)))))
+ (modify-item
+ (function
+ ;; Replace ITEM first line elements with new elements from
+ ;; STRUCT, if appropriate.
+ (lambda (item)
+ (goto-char item)
+ (let* ((new-ind (org-list-get-ind item struct))
+ (old-ind (org-get-indentation))
+ (new-bul (org-list-bullet-string
+ (org-list-get-bullet item struct)))
+ (old-bul (org-list-get-bullet item old-struct))
+ (new-box (org-list-get-checkbox item struct)))
+ (looking-at org-list-full-item-re)
+ ;; a. Replace bullet
+ (unless (equal old-bul new-bul)
+ (replace-match new-bul nil nil nil 1))
+ ;; b. Replace checkbox.
+ (cond
+ ((equal (match-string 3) new-box))
+ ((and (match-string 3) new-box)
+ (replace-match new-box nil nil nil 3))
+ ((match-string 3)
+ (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)")
+ (replace-match "" nil nil nil 1))
+ (t (let ((counterp (match-end 2)))
+ (goto-char (if counterp (1+ counterp) (match-end 1)))
+ (insert (concat new-box (unless counterp " "))))))
+ ;; c. Indent item to appropriate column.
+ (unless (= new-ind old-ind)
+ (delete-region (goto-char (point-at-bol))
+ (progn (skip-chars-forward " \t") (point)))
+ (indent-to new-ind)))))))
+ ;; 1. First get list of items and position endings. We maintain
+ ;; two alists: ITM-SHIFT, determining indentation shift needed
+ ;; at item, and END-LIST, a pseudo-alist where key is ending
+ ;; position and value point.
+ (let (end-list acc-end itm-shift all-ends sliced-struct)
+ (dolist (e old-struct)
+ (let* ((pos (car e))
+ (ind-pos (org-list-get-ind pos struct))
+ (ind-old (org-list-get-ind pos old-struct))
+ (bul-pos (org-list-get-bullet pos struct))
+ (bul-old (org-list-get-bullet pos old-struct))
+ (ind-shift (- (+ ind-pos (length bul-pos))
+ (+ ind-old (length bul-old))))
+ (end-pos (org-list-get-item-end pos old-struct)))
+ (push (cons pos ind-shift) itm-shift)
+ (unless (assq end-pos old-struct)
+ ;; To determine real ind of an ending position that
+ ;; is not at an item, we have to find the item it
+ ;; belongs to: it is the last item (ITEM-UP), whose
+ ;; ending is further than the position we're
+ ;; interested in.
+ (let ((item-up (assoc-default end-pos acc-end #'>)))
+ (push (cons end-pos item-up) end-list)))
+ (push (cons end-pos pos) acc-end)))
+ ;; 2. Slice the items into parts that should be shifted by the
+ ;; same amount of indentation. Each slice follow the pattern
+ ;; (END BEG DELTA). Slices are returned in reverse order.
+ (setq all-ends (sort (append (mapcar #'car itm-shift)
+ (org-uniquify (mapcar #'car end-list)))
+ #'<)
+ acc-end (nreverse acc-end))
+ (while (cdr all-ends)
+ (let* ((up (pop all-ends))
+ (down (car all-ends))
+ (itemp (assq up struct))
+ (delta
+ (if itemp (cdr (assq up itm-shift))
+ ;; If we're not at an item, there's a child of the
+ ;; item point belongs to above. Make sure the less
+ ;; indented line in this slice has the same column
+ ;; as that child.
+ (let* ((child (cdr (assq up acc-end)))
+ (ind (org-list-get-ind child struct))
+ (min-ind most-positive-fixnum))
+ (save-excursion
+ (goto-char up)
+ (while (< (point) down)
+ ;; Ignore empty lines. Also ignore blocks and
+ ;; drawers contents.
+ (unless (looking-at-p "[ \t]*$")
+ (setq min-ind (min (org-get-indentation) min-ind))
+ (cond
+ ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
+ (re-search-forward
+ (format "^[ \t]*#\\+END%s[ \t]*$"
+ (match-string 1))
+ down t)))
+ ((and (looking-at org-drawer-regexp)
+ (re-search-forward "^[ \t]*:END:[ \t]*$"
+ down t)))))
+ (forward-line)))
+ (- ind min-ind)))))
+ (push (list down up delta) sliced-struct)))
+ ;; 3. Shift each slice in buffer, provided delta isn't 0, from
+ ;; end to beginning. Take a special action when beginning is
+ ;; at item bullet.
+ (dolist (e sliced-struct)
+ (unless (zerop (nth 2 e)) (apply shift-body-ind e))
+ (let* ((beg (nth 1 e))
+ (cell (assq beg struct)))
+ (unless (or (not cell) (equal cell (assq beg old-struct)))
+ (funcall modify-item beg)))))
+ ;; 4. Go back to initial position and clean marker.
+ (goto-char origin)
+ (move-marker origin nil)))
+
+(defun org-list-write-struct (struct parents &optional old-struct)
+ "Correct bullets, checkboxes and indentation in list at point.
+
+STRUCT is the list structure. PARENTS is the alist of parents,
+as returned by `org-list-parents-alist'.
+
+When non-nil, optional argument OLD-STRUCT is the reference
+structure of the list. It should be provided whenever STRUCT
+doesn't correspond anymore to the real list in buffer."
+ ;; Order of functions matters here: checkboxes and endings need
+ ;; correct indentation to be set, and indentation needs correct
+ ;; bullets.
+ ;;
+ ;; 0. Save a copy of structure before modifications
+ (let ((old-struct (or old-struct (copy-tree struct))))
+ ;; 1. Set a temporary, but coherent with PARENTS, indentation in
+ ;; order to get items endings and bullets properly
+ (org-list-struct-fix-ind struct parents 2)
+ ;; 2. Fix each item end to get correct prevs alist.
+ (org-list-struct-fix-item-end struct)
+ ;; 3. Get bullets right.
+ (let ((prevs (org-list-prevs-alist struct)))
+ (org-list-struct-fix-bul struct prevs)
+ ;; 4. Now get real indentation.
+ (org-list-struct-fix-ind struct parents)
+ ;; 5. Eventually fix checkboxes.
+ (org-list-struct-fix-box struct parents prevs))
+ ;; 6. Apply structure modifications to buffer.
+ (org-list-struct-apply-struct struct old-struct)))
+
+
+
+;;; Misc Tools
+
+(defun org-apply-on-list (function init-value &rest args)
+ "Call FUNCTION on each item of the list at point.
+FUNCTION must be called with at least one argument: INIT-VALUE,
+that will contain the value returned by the function at the
+previous item, plus ARGS extra arguments.
+
+FUNCTION is applied on items in reverse order.
+
+As an example, \(org-apply-on-list \(lambda \(result) \(1+ result)) 0)
+will return the number of items in the current list.
+
+Sublists of the list are skipped. Cursor is always at the
+beginning of the item."
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (item (copy-marker (point-at-bol)))
+ (all (org-list-get-all-items (marker-position item) struct prevs))
+ (value init-value))
+ (mapc (lambda (e)
+ (goto-char e)
+ (setq value (apply function value args)))
+ (nreverse all))
+ (goto-char item)
+ (move-marker item nil)
+ value))
+
+(defun org-list-set-item-visibility (item struct view)
+ "Set visibility of ITEM in STRUCT to VIEW.
+
+Possible values are: `folded', `children' or `subtree'. See
+`org-cycle' for more information."
+ (cond
+ ((eq view 'folded)
+ (let ((item-end (org-list-get-item-end-before-blank item struct)))
+ ;; Hide from eol
+ (outline-flag-region (save-excursion (goto-char item) (point-at-eol))
+ item-end t)))
+ ((eq view 'children)
+ ;; First show everything.
+ (org-list-set-item-visibility item struct 'subtree)
+ ;; Then fold every child.
+ (let* ((parents (org-list-parents-alist struct))
+ (children (org-list-get-children item struct parents)))
+ (mapc (lambda (e)
+ (org-list-set-item-visibility e struct 'folded))
+ children)))
+ ((eq view 'subtree)
+ ;; Show everything
+ (let ((item-end (org-list-get-item-end item struct)))
+ (outline-flag-region item item-end nil)))))
+
+(defun org-list-item-body-column (item)
+ "Return column at which body of ITEM should start."
+ (save-excursion
+ (goto-char item)
+ (if (save-excursion
+ (end-of-line)
+ (re-search-backward
+ "[ \t]::\\([ \t]\\|$\\)" (line-beginning-position) t))
+ ;; Descriptive list item. Body starts after item's tag, if
+ ;; possible.
+ (let ((start (1+ (- (match-beginning 1) (line-beginning-position))))
+ (ind (org-get-indentation)))
+ (if (> start (+ ind org-list-description-max-indent))
+ (+ ind 5)
+ start))
+ ;; Regular item. Body starts after bullet.
+ (looking-at "[ \t]*\\(\\S-+\\)")
+ (+ (progn (goto-char (match-end 1)) (current-column))
+ (if (and org-list-two-spaces-after-bullet-regexp
+ (string-match-p org-list-two-spaces-after-bullet-regexp
+ (match-string 1)))
+ 2
+ 1)))))
+
+
+
+;;; Interactive functions
+
+(defalias 'org-list-get-item-begin 'org-in-item-p)
+
+(defun org-beginning-of-item ()
+ "Go to the beginning of the current item.
+Throw an error when not in a list."
+ (interactive)
+ (let ((begin (org-in-item-p)))
+ (if begin (goto-char begin) (error "Not in an item"))))
+
+(defun org-beginning-of-item-list ()
+ "Go to the beginning item of the current list or sublist.
+Throw an error when not in a list."
+ (interactive)
+ (let ((begin (org-in-item-p)))
+ (if (not begin)
+ (error "Not in an item")
+ (goto-char begin)
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct)))
+ (goto-char (org-list-get-list-begin begin struct prevs))))))
+
+(defun org-end-of-item-list ()
+ "Go to the end of the current list or sublist.
+Throw an error when not in a list."
+ (interactive)
+ (let ((begin (org-in-item-p)))
+ (if (not begin)
+ (error "Not in an item")
+ (goto-char begin)
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct)))
+ (goto-char (org-list-get-list-end begin struct prevs))))))
+
+(defun org-end-of-item ()
+ "Go to the end of the current item.
+Throw an error when not in a list."
+ (interactive)
+ (let ((begin (org-in-item-p)))
+ (if (not begin)
+ (error "Not in an item")
+ (goto-char begin)
+ (let ((struct (org-list-struct)))
+ (goto-char (org-list-get-item-end begin struct))))))
+
+(defun org-previous-item ()
+ "Move to the beginning of the previous item.
+Throw an error when not in a list. Also throw an error when at
+first item, unless `org-list-use-circular-motion' is non-nil."
+ (interactive)
+ (let ((item (org-in-item-p)))
+ (if (not item)
+ (error "Not in an item")
+ (goto-char item)
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (prevp (org-list-get-prev-item item struct prevs)))
+ (cond
+ (prevp (goto-char prevp))
+ (org-list-use-circular-motion
+ (goto-char (org-list-get-last-item item struct prevs)))
+ (t (error "On first item")))))))
+
+(defun org-next-item ()
+ "Move to the beginning of the next item.
+Throw an error when not in a list. Also throw an error when at
+last item, unless `org-list-use-circular-motion' is non-nil."
+ (interactive)
+ (let ((item (org-in-item-p)))
+ (if (not item)
+ (error "Not in an item")
+ (goto-char item)
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (prevp (org-list-get-next-item item struct prevs)))
+ (cond
+ (prevp (goto-char prevp))
+ (org-list-use-circular-motion
+ (goto-char (org-list-get-first-item item struct prevs)))
+ (t (error "On last item")))))))
+
+(defun org-move-item-down ()
+ "Move the item at point down, i.e. swap with following item.
+Sub-items (items with larger indentation) are considered part of
+the item, so this really moves item trees."
+ (interactive)
+ (unless (org-at-item-p) (error "Not at an item"))
+ (let* ((col (current-column))
+ (item (point-at-bol))
+ (struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
+ (unless (or next-item org-list-use-circular-motion)
+ (user-error "Cannot move this item further down"))
+ (if (not next-item)
+ (setq struct (org-list-send-item item 'begin struct))
+ (setq struct (org-list-swap-items item next-item struct))
+ (goto-char
+ (org-list-get-next-item item struct (org-list-prevs-alist struct))))
+ (org-list-write-struct struct (org-list-parents-alist struct))
+ (org-move-to-column col)))
+
+(defun org-move-item-up ()
+ "Move the item at point up, i.e. swap with previous item.
+Sub-items (items with larger indentation) are considered part of
+the item, so this really moves item trees."
+ (interactive)
+ (unless (org-at-item-p) (error "Not at an item"))
+ (let* ((col (current-column))
+ (item (point-at-bol))
+ (struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
+ (unless (or prev-item org-list-use-circular-motion)
+ (user-error "Cannot move this item further up"))
+ (if (not prev-item)
+ (setq struct (org-list-send-item item 'end struct))
+ (setq struct (org-list-swap-items prev-item item struct)))
+ (org-list-write-struct struct (org-list-parents-alist struct))
+ (org-move-to-column col)))
+
+(defun org-insert-item (&optional checkbox)
+ "Insert a new item at the current level.
+If cursor is before first character after bullet of the item, the
+new item will be created before the current one.
+
+If CHECKBOX is non-nil, add a checkbox next to the bullet.
+
+Return t when things worked, nil when we are not in an item, or
+item is invisible."
+ (let ((itemp (org-in-item-p))
+ (pos (point)))
+ ;; If cursor isn't is a list or if list is invisible, return nil.
+ (unless (or (not itemp)
+ (save-excursion
+ (goto-char itemp)
+ (org-invisible-p)))
+ (if (save-excursion
+ (goto-char itemp)
+ (org-at-item-timer-p))
+ ;; Timer list: delegate to `org-timer-item'.
+ (progn (org-timer-item) t)
+ (let* ((struct (save-excursion (goto-char itemp)
+ (org-list-struct)))
+ (prevs (org-list-prevs-alist struct))
+ ;; If we're in a description list, ask for the new term.
+ (desc (when (eq (org-list-get-list-type itemp struct prevs)
+ 'descriptive)
+ " :: ")))
+ (setq struct (org-list-insert-item pos struct prevs checkbox desc))
+ (org-list-write-struct struct (org-list-parents-alist struct))
+ (when checkbox (org-update-checkbox-count-maybe))
+ (looking-at org-list-full-item-re)
+ (goto-char (if (and (match-beginning 4)
+ (save-match-data
+ (string-match "[.)]" (match-string 1))))
+ (match-beginning 4)
+ (match-end 0)))
+ (if desc (backward-char 1))
+ t)))))
+
+(defun org-list-repair ()
+ "Fix indentation, bullets and checkboxes in the list at point."
+ (interactive)
+ (unless (org-at-item-p) (error "This is not a list"))
+ (let* ((struct (org-list-struct))
+ (parents (org-list-parents-alist struct)))
+ (org-list-write-struct struct parents)))
+
+(defun org-cycle-list-bullet (&optional which)
+ "Cycle through the different itemize/enumerate bullets.
+This cycle the entire list level through the sequence:
+
+ `-' -> `+' -> `*' -> `1.' -> `1)'
+
+If WHICH is a valid string, use that as the new bullet. If WHICH
+is an integer, 0 means `-', 1 means `+' etc. If WHICH is
+`previous', cycle backwards."
+ (interactive "P")
+ (unless (org-at-item-p) (error "Not at an item"))
+ (save-excursion
+ (beginning-of-line)
+ (let* ((struct (org-list-struct))
+ (parents (org-list-parents-alist struct))
+ (prevs (org-list-prevs-alist struct))
+ (list-beg (org-list-get-first-item (point) struct prevs))
+ (bullet (org-list-get-bullet list-beg struct))
+ (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
+ (case-fold-search nil)
+ (current (cond
+ ((string-match "[a-z]\\." bullet) "a.")
+ ((string-match "[a-z])" bullet) "a)")
+ ((string-match "[A-Z]\\." bullet) "A.")
+ ((string-match "[A-Z])" bullet) "A)")
+ ((string-match "\\." bullet) "1.")
+ ((string-match ")" bullet) "1)")
+ (t (org-trim bullet))))
+ ;; Compute list of possible bullets, depending on context.
+ (bullet-list
+ (append '("-" "+" )
+ ;; *-bullets are not allowed at column 0.
+ (unless (looking-at "\\S-") '("*"))
+ ;; Description items cannot be numbered.
+ (unless (or (eq org-plain-list-ordered-item-terminator ?\))
+ (org-at-item-description-p))
+ '("1."))
+ (unless (or (eq org-plain-list-ordered-item-terminator ?.)
+ (org-at-item-description-p))
+ '("1)"))
+ (unless (or (not alpha-p)
+ (eq org-plain-list-ordered-item-terminator ?\))
+ (org-at-item-description-p))
+ '("a." "A."))
+ (unless (or (not alpha-p)
+ (eq org-plain-list-ordered-item-terminator ?.)
+ (org-at-item-description-p))
+ '("a)" "A)"))))
+ (len (length bullet-list))
+ (item-index (- len (length (member current bullet-list))))
+ (get-value (lambda (index) (nth (mod index len) bullet-list)))
+ (new (cond
+ ((member which bullet-list) which)
+ ((numberp which) (funcall get-value which))
+ ((eq 'previous which) (funcall get-value (1- item-index)))
+ (t (funcall get-value (1+ item-index))))))
+ ;; Use a short variation of `org-list-write-struct' as there's
+ ;; no need to go through all the steps.
+ (let ((old-struct (copy-tree struct)))
+ (org-list-set-bullet list-beg struct (org-list-bullet-string new))
+ (org-list-struct-fix-bul struct prevs)
+ (org-list-struct-fix-ind struct parents)
+ (org-list-struct-apply-struct struct old-struct)))))
+
+(defun org-toggle-checkbox (&optional toggle-presence)
+ "Toggle the checkbox in the current line.
+With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
+double prefix, set checkbox to [-].
+
+When there is an active region, toggle status or presence of the
+first checkbox there, and make every item inside have the same
+status or presence, respectively.
+
+If the cursor is in a headline, apply this to all checkbox items
+in the text below the heading, taking as reference the first item
+in subtree, ignoring drawers."
+ (interactive "P")
+ (save-excursion
+ (let* (singlep
+ block-item
+ lim-up
+ lim-down
+ (keyword-re (concat "^[ \t]*\\<\\(" org-scheduled-string
+ "\\|" org-deadline-string
+ "\\|" org-closed-string
+ "\\|" org-clock-string "\\)"
+ " *[[<]\\([^]>]+\\)[]>]"))
+ (orderedp (org-entry-get nil "ORDERED"))
+ (_bounds
+ ;; In a region, start at first item in region.
+ (cond
+ ((org-region-active-p)
+ (let ((limit (region-end)))
+ (goto-char (region-beginning))
+ (if (org-list-search-forward (org-item-beginning-re) limit t)
+ (setq lim-up (point-at-bol))
+ (error "No item in region"))
+ (setq lim-down (copy-marker limit))))
+ ((org-at-heading-p)
+ ;; On an heading, start at first item after drawers and
+ ;; time-stamps (scheduled, etc.).
+ (let ((limit (save-excursion (outline-next-heading) (point))))
+ (forward-line 1)
+ (while (or (looking-at org-drawer-regexp)
+ (looking-at keyword-re))
+ (if (looking-at keyword-re)
+ (forward-line 1)
+ (re-search-forward "^[ \t]*:END:" limit nil)))
+ (if (org-list-search-forward (org-item-beginning-re) limit t)
+ (setq lim-up (point-at-bol))
+ (error "No item in subtree"))
+ (setq lim-down (copy-marker limit))))
+ ;; Just one item: set SINGLEP flag.
+ ((org-at-item-p)
+ (setq singlep t)
+ (setq lim-up (point-at-bol)
+ lim-down (copy-marker (point-at-eol))))
+ (t (error "Not at an item or heading, and no active region"))))
+ ;; Determine the checkbox going to be applied to all items
+ ;; within bounds.
+ (ref-checkbox
+ (progn
+ (goto-char lim-up)
+ (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
+ (cond
+ ((equal toggle-presence '(16)) "[-]")
+ ((equal toggle-presence '(4))
+ (unless cbox "[ ]"))
+ ((equal "[X]" cbox) "[ ]")
+ (t "[X]"))))))
+ ;; When an item is found within bounds, grab the full list at
+ ;; point structure, then: (1) set check-box of all its items
+ ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
+ ;; whole list, (3) move point after the list.
+ (goto-char lim-up)
+ (while (and (< (point) lim-down)
+ (org-list-search-forward (org-item-beginning-re)
+ lim-down 'move))
+ (let* ((struct (org-list-struct))
+ (struct-copy (copy-tree struct))
+ (parents (org-list-parents-alist struct))
+ (prevs (org-list-prevs-alist struct))
+ (bottom (copy-marker (org-list-get-bottom-point struct)))
+ (items-to-toggle (cl-remove-if
+ (lambda (e) (or (< e lim-up) (> e lim-down)))
+ (mapcar #'car struct))))
+ (mapc (lambda (e) (org-list-set-checkbox
+ e struct
+ ;; If there is no box at item, leave as-is
+ ;; unless function was called with C-u prefix.
+ (let ((cur-box (org-list-get-checkbox e struct)))
+ (if (or cur-box (equal toggle-presence '(4)))
+ ref-checkbox
+ cur-box))))
+ items-to-toggle)
+ (setq block-item (org-list-struct-fix-box
+ struct parents prevs orderedp))
+ ;; Report some problems due to ORDERED status of subtree.
+ ;; If only one box was being checked, throw an error, else,
+ ;; only signal problems.
+ (cond
+ ((and singlep block-item (> lim-up block-item))
+ (error
+ "Checkbox blocked because of unchecked box at line %d"
+ (org-current-line block-item)))
+ (block-item
+ (message
+ "Checkboxes were removed due to unchecked box at line %d"
+ (org-current-line block-item))))
+ (goto-char bottom)
+ (move-marker bottom nil)
+ (org-list-struct-apply-struct struct struct-copy)))
+ (move-marker lim-down nil)))
+ (org-update-checkbox-count-maybe))
+
+(defun org-reset-checkbox-state-subtree ()
+ "Reset all checkboxes in an entry subtree."
+ (interactive "*")
+ (if (org-before-first-heading-p)
+ (error "Not inside a tree")
+ (save-restriction
+ (save-excursion
+ (org-narrow-to-subtree)
+ (org-show-subtree)
+ (goto-char (point-min))
+ (let ((end (point-max)))
+ (while (< (point) end)
+ (when (org-at-item-checkbox-p)
+ (replace-match "[ ]" t t nil 1))
+ (beginning-of-line 2)))
+ (org-update-checkbox-count-maybe 'all)))))
+
+(defun org-update-checkbox-count (&optional all)
+ "Update the checkbox statistics in the current section.
+
+This will find all statistic cookies like [57%] and [6/12] and
+update them with the current numbers.
+
+With optional prefix argument ALL, do this for the whole buffer."
+ (interactive "P")
+ (org-with-wide-buffer
+ (let* ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
+ (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\
+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
+ (recursivep
+ (or (not org-checkbox-hierarchical-statistics)
+ (string-match "\\<recursive\\>"
+ (or (org-entry-get nil "COOKIE_DATA") ""))))
+ (within-inlinetask (and (not all)
+ (featurep 'org-inlinetask)
+ (org-inlinetask-in-task-p)))
+ (end (cond (all (point-max))
+ (within-inlinetask
+ (save-excursion (outline-next-heading) (point)))
+ (t (save-excursion
+ (org-with-limited-levels (outline-next-heading))
+ (point)))))
+ (count-boxes
+ (lambda (item structs recursivep)
+ ;; Return number of checked boxes and boxes of all types
+ ;; in all structures in STRUCTS. If RECURSIVEP is
+ ;; non-nil, also count boxes in sub-lists. If ITEM is
+ ;; nil, count across the whole structure, else count only
+ ;; across subtree whose ancestor is ITEM.
+ (let ((c-on 0) (c-all 0))
+ (dolist (s structs (list c-on c-all))
+ (let* ((pre (org-list-prevs-alist s))
+ (par (org-list-parents-alist s))
+ (items
+ (cond
+ ((and recursivep item) (org-list-get-subtree item s))
+ (recursivep (mapcar #'car s))
+ (item (org-list-get-children item s par))
+ (t (org-list-get-all-items
+ (org-list-get-top-point s) s pre))))
+ (cookies (delq nil (mapcar
+ (lambda (e)
+ (org-list-get-checkbox e s))
+ items))))
+ (cl-incf c-all (length cookies))
+ (cl-incf c-on (cl-count "[X]" cookies :test #'equal)))))))
+ cookies-list cache)
+ ;; Move to start.
+ (cond (all (goto-char (point-min)))
+ (within-inlinetask (org-back-to-heading t))
+ (t (org-with-limited-levels (outline-previous-heading))))
+ ;; Build an alist for each cookie found. The key is the position
+ ;; at beginning of cookie and values ending position, format of
+ ;; cookie, number of checked boxes to report and total number of
+ ;; boxes.
+ (while (re-search-forward cookie-re end t)
+ (let ((context (save-excursion (backward-char)
+ (save-match-data (org-element-context)))))
+ (when (eq (org-element-type context) 'statistics-cookie)
+ (push
+ (append
+ (list (match-beginning 1) (match-end 1) (match-end 2))
+ (let* ((container
+ (org-element-lineage
+ context
+ '(drawer center-block dynamic-block inlinetask item
+ quote-block special-block verse-block)))
+ (beg (if container
+ (org-element-property :contents-begin container)
+ (save-excursion
+ (org-with-limited-levels
+ (outline-previous-heading))
+ (point)))))
+ (or (cdr (assq beg cache))
+ (save-excursion
+ (goto-char beg)
+ (let ((end
+ (if container
+ (org-element-property :contents-end container)
+ (save-excursion
+ (org-with-limited-levels (outline-next-heading))
+ (point))))
+ structs)
+ (while (re-search-forward box-re end t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'item)
+ (push (org-element-property :structure element)
+ structs)
+ ;; Skip whole list since we have its
+ ;; structure anyway.
+ (while (setq element (org-element-lineage
+ element '(plain-list)))
+ (goto-char
+ (min (org-element-property :end element)
+ end))))))
+ ;; Cache count for cookies applying to the same
+ ;; area. Then return it.
+ (let ((count
+ (funcall count-boxes
+ (and (eq (org-element-type container)
+ 'item)
+ (org-element-property
+ :begin container))
+ structs
+ recursivep)))
+ (push (cons beg count) cache)
+ count))))))
+ cookies-list))))
+ ;; Apply alist to buffer.
+ (dolist (cookie cookies-list)
+ (let* ((beg (car cookie))
+ (end (nth 1 cookie))
+ (percent (nth 2 cookie))
+ (checked (nth 3 cookie))
+ (total (nth 4 cookie)))
+ (goto-char beg)
+ (insert
+ (if percent (format "[%d%%]" (floor (* 100.0 checked)
+ (max 1 total)))
+ (format "[%d/%d]" checked total)))
+ (delete-region (point) (+ (point) (- end beg)))
+ (when org-auto-align-tags (org-fix-tags-on-the-fly)))))))
+
+(defun org-get-checkbox-statistics-face ()
+ "Select the face for checkbox statistics.
+The face will be `org-done' when all relevant boxes are checked.
+Otherwise it will be `org-todo'."
+ (if (match-end 1)
+ (if (equal (match-string 1) "100%")
+ 'org-checkbox-statistics-done
+ 'org-checkbox-statistics-todo)
+ (if (and (> (match-end 2) (match-beginning 2))
+ (equal (match-string 2) (match-string 3)))
+ 'org-checkbox-statistics-done
+ 'org-checkbox-statistics-todo)))
+
+(defun org-update-checkbox-count-maybe (&optional all)
+ "Update checkbox statistics unless turned off by user.
+With an optional argument ALL, update them in the whole buffer."
+ (when (cdr (assq 'checkbox org-list-automatic-rules))
+ (org-update-checkbox-count all))
+ (run-hooks 'org-checkbox-statistics-hook))
+
+(defvar org-last-indent-begin-marker (make-marker))
+(defvar org-last-indent-end-marker (make-marker))
+(defun org-list-indent-item-generic (arg no-subtree struct)
+ "Indent a local list item including its children.
+When number ARG is a negative, item will be outdented, otherwise
+it will be indented.
+
+If a region is active, all items inside will be moved.
+
+If NO-SUBTREE is non-nil, only indent the item itself, not its
+children.
+
+STRUCT is the list structure.
+
+Return t if successful."
+ (save-excursion
+ (let* ((regionp (org-region-active-p))
+ (rbeg (and regionp (region-beginning)))
+ (rend (and regionp (region-end)))
+ (top (org-list-get-top-point struct))
+ (parents (org-list-parents-alist struct))
+ (prevs (org-list-prevs-alist struct))
+ ;; Are we going to move the whole list?
+ (specialp
+ (and (not regionp)
+ (= top (point-at-bol))
+ (cdr (assq 'indent org-list-automatic-rules))
+ (if no-subtree
+ (error
+ "First item of list cannot move without its subtree")
+ t))))
+ ;; Determine begin and end points of zone to indent. If moving
+ ;; more than one item, save them for subsequent moves.
+ (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
+ (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
+ (if regionp
+ (progn
+ (set-marker org-last-indent-begin-marker rbeg)
+ (set-marker org-last-indent-end-marker rend))
+ (set-marker org-last-indent-begin-marker (point-at-bol))
+ (set-marker org-last-indent-end-marker
+ (cond
+ (specialp (org-list-get-bottom-point struct))
+ (no-subtree (1+ (point-at-bol)))
+ (t (org-list-get-item-end (point-at-bol) struct))))))
+ (let* ((beg (marker-position org-last-indent-begin-marker))
+ (end (marker-position org-last-indent-end-marker)))
+ (cond
+ ;; Special case: moving top-item with indent rule.
+ (specialp
+ (let* ((level-skip (org-level-increment))
+ (offset (if (< arg 0) (- level-skip) level-skip))
+ (top-ind (org-list-get-ind beg struct))
+ (old-struct (copy-tree struct)))
+ (if (< (+ top-ind offset) 0)
+ (error "Cannot outdent beyond margin")
+ ;; Change bullet if necessary.
+ (when (and (= (+ top-ind offset) 0)
+ (string-match "*"
+ (org-list-get-bullet beg struct)))
+ (org-list-set-bullet beg struct
+ (org-list-bullet-string "-")))
+ ;; Shift every item by OFFSET and fix bullets. Then
+ ;; apply changes to buffer.
+ (mapc (lambda (e)
+ (let ((ind (org-list-get-ind (car e) struct)))
+ (org-list-set-ind (car e) struct (+ ind offset))))
+ struct)
+ (org-list-struct-fix-bul struct prevs)
+ (org-list-struct-apply-struct struct old-struct))))
+ ;; Forbidden move:
+ ((and (< arg 0)
+ ;; If only one item is moved, it mustn't have a child.
+ (or (and no-subtree
+ (not regionp)
+ (org-list-has-child-p beg struct))
+ ;; If a subtree or region is moved, the last item
+ ;; of the subtree mustn't have a child.
+ (let ((last-item (caar
+ (reverse
+ (cl-remove-if
+ (lambda (e) (>= (car e) end))
+ struct)))))
+ (org-list-has-child-p last-item struct))))
+ (error "Cannot outdent an item without its children"))
+ ;; Normal shifting
+ (t
+ (let* ((new-parents
+ (if (< arg 0)
+ (org-list-struct-outdent beg end struct parents)
+ (org-list-struct-indent beg end struct parents prevs))))
+ (org-list-write-struct struct new-parents))
+ (org-update-checkbox-count-maybe))))))
+ t)
+
+(defun org-outdent-item ()
+ "Outdent a local list item, but not its children.
+If a region is active, all items inside will be moved."
+ (interactive)
+ (let ((regionp (org-region-active-p)))
+ (cond
+ ((or (org-at-item-p)
+ (and regionp
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p))))
+ (let ((struct (if (not regionp) (org-list-struct)
+ (save-excursion (goto-char (region-beginning))
+ (org-list-struct)))))
+ (org-list-indent-item-generic -1 t struct)))
+ (regionp (error "Region not starting at an item"))
+ (t (error "Not at an item")))))
+
+(defun org-indent-item ()
+ "Indent a local list item, but not its children.
+If a region is active, all items inside will be moved."
+ (interactive)
+ (let ((regionp (org-region-active-p)))
+ (cond
+ ((or (org-at-item-p)
+ (and regionp
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p))))
+ (let ((struct (if (not regionp) (org-list-struct)
+ (save-excursion (goto-char (region-beginning))
+ (org-list-struct)))))
+ (org-list-indent-item-generic 1 t struct)))
+ (regionp (error "Region not starting at an item"))
+ (t (error "Not at an item")))))
+
+(defun org-outdent-item-tree ()
+ "Outdent a local list item including its children.
+If a region is active, all items inside will be moved."
+ (interactive)
+ (let ((regionp (org-region-active-p)))
+ (cond
+ ((or (org-at-item-p)
+ (and regionp
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p))))
+ (let ((struct (if (not regionp) (org-list-struct)
+ (save-excursion (goto-char (region-beginning))
+ (org-list-struct)))))
+ (org-list-indent-item-generic -1 nil struct)))
+ (regionp (error "Region not starting at an item"))
+ (t (error "Not at an item")))))
+
+(defun org-indent-item-tree ()
+ "Indent a local list item including its children.
+If a region is active, all items inside will be moved."
+ (interactive)
+ (let ((regionp (org-region-active-p)))
+ (cond
+ ((or (org-at-item-p)
+ (and regionp
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p))))
+ (let ((struct (if (not regionp) (org-list-struct)
+ (save-excursion (goto-char (region-beginning))
+ (org-list-struct)))))
+ (org-list-indent-item-generic 1 nil struct)))
+ (regionp (error "Region not starting at an item"))
+ (t (error "Not at an item")))))
+
+(defvar org-tab-ind-state)
+(defvar org-adapt-indentation)
+(defun org-cycle-item-indentation ()
+ "Cycle levels of indentation of an empty item.
+The first run indents the item, if applicable. Subsequent runs
+outdent it at meaningful levels in the list. When done, item is
+put back at its original position with its original bullet.
+
+Return t at each successful move."
+ (when (org-at-item-p)
+ (let* ((org-adapt-indentation nil)
+ (struct (org-list-struct))
+ (ind (org-list-get-ind (point-at-bol) struct))
+ (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol)))))
+ ;; Accept empty items or if cycle has already started.
+ (when (or (eq last-command 'org-cycle-item-indentation)
+ (and (save-excursion
+ (beginning-of-line)
+ (looking-at org-list-full-item-re))
+ (>= (match-end 0) (save-excursion
+ (goto-char (org-list-get-item-end
+ (point-at-bol) struct))
+ (skip-chars-backward " \r\t\n")
+ (point)))))
+ (setq this-command 'org-cycle-item-indentation)
+ ;; When in the middle of the cycle, try to outdent first. If
+ ;; it fails, and point is still at initial position, indent.
+ ;; Else, re-create it at its original position.
+ (if (eq last-command 'org-cycle-item-indentation)
+ (cond
+ ((ignore-errors (org-list-indent-item-generic -1 t struct)))
+ ((and (= ind (car org-tab-ind-state))
+ (ignore-errors (org-list-indent-item-generic 1 t struct))))
+ (t (delete-region (point-at-bol) (point-at-eol))
+ (indent-to-column (car org-tab-ind-state))
+ (insert (cdr org-tab-ind-state) " ")
+ ;; Break cycle
+ (setq this-command 'identity)))
+ ;; If a cycle is starting, remember indentation and bullet,
+ ;; then try to indent. If it fails, try to outdent.
+ (setq org-tab-ind-state (cons ind bullet))
+ (cond
+ ((ignore-errors (org-list-indent-item-generic 1 t struct)))
+ ((ignore-errors (org-list-indent-item-generic -1 t struct)))
+ (t (user-error "Cannot move item"))))
+ t))))
+
+(defun org-sort-list
+ (&optional with-case sorting-type getkey-func compare-func interactive?)
+ "Sort list items.
+The cursor may be at any item of the list that should be sorted.
+Sublists are not sorted. Checkboxes, if any, are ignored.
+
+Sorting can be alphabetically, numerically, by date/time as given
+by a time stamp, by a property or by priority.
+
+Comparing entries ignores case by default. However, with an
+optional argument WITH-CASE, the sorting considers case as well.
+
+The command prompts for the sorting type unless it has been given
+to the function through the SORTING-TYPE argument, which needs to
+be a character, \(?n ?N ?a ?A ?t ?T ?f ?F ?x ?X). Here is the
+detailed meaning of each character:
+
+n Numerically, by converting the beginning of the item to a number.
+a Alphabetically. Only the first line of item is checked.
+t By date/time, either the first active time stamp in the entry, if
+ any, or by the first inactive one. In a timer list, sort the timers.
+x By \"checked\" status of a check list.
+
+Capital letters will reverse the sort order.
+
+If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
+a function to be called with point at the beginning of the
+record. It must return a value that is compatible with COMPARE-FUNC,
+the function used to compare entries.
+
+Sorting is done against the visible part of the headlines, it
+ignores hidden links.
+
+A non-nil value for INTERACTIVE? is used to signal that this
+function is being called interactively."
+ (interactive (list current-prefix-arg nil nil nil t))
+ (let* ((case-func (if with-case 'identity 'downcase))
+ (struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (start (org-list-get-list-begin (point-at-bol) struct prevs))
+ (end (org-list-get-list-end (point-at-bol) struct prevs))
+ (sorting-type
+ (or sorting-type
+ (progn
+ (message
+ "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc [x]checked A/N/T/F/X means reversed:")
+ (read-char-exclusive))))
+ (dcst (downcase sorting-type))
+ (getkey-func
+ (and (= dcst ?f)
+ (or getkey-func
+ (and interactive?
+ (org-read-function "Function for extracting keys: "))
+ (error "Missing key extractor"))))
+ (sort-func
+ (cond
+ ((= dcst ?a) #'string<)
+ ((= dcst ?f)
+ (or compare-func
+ (and interactive?
+ (org-read-function
+ (concat "Function for comparing keys "
+ "(empty for default `sort-subr' predicate): ")
+ 'allow-empty))))
+ ((= dcst ?t) #'<)
+ ((= dcst ?x) #'string<))))
+ (message "Sorting items...")
+ (save-restriction
+ (narrow-to-region start end)
+ (goto-char (point-min))
+ (let* ((case-fold-search nil)
+ (now (current-time))
+ (next-record (lambda ()
+ (skip-chars-forward " \r\t\n")
+ (or (eobp) (beginning-of-line))))
+ (end-record (lambda ()
+ (goto-char (org-list-get-item-end-before-blank
+ (point) struct))))
+ (value-to-sort
+ (lambda ()
+ (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
+ (cond
+ ((= dcst ?n)
+ (string-to-number
+ (org-sort-remove-invisible
+ (buffer-substring (match-end 0) (point-at-eol)))))
+ ((= dcst ?a)
+ (funcall case-func
+ (org-sort-remove-invisible
+ (buffer-substring
+ (match-end 0) (point-at-eol)))))
+ ((= dcst ?t)
+ (cond
+ ;; If it is a timer list, convert timer to seconds
+ ((org-at-item-timer-p)
+ (org-timer-hms-to-secs (match-string 1)))
+ ((or (save-excursion
+ (re-search-forward org-ts-regexp (point-at-eol) t))
+ (save-excursion (re-search-forward org-ts-regexp-both
+ (point-at-eol) t)))
+ (org-time-string-to-seconds (match-string 0)))
+ (t (float-time now))))
+ ((= dcst ?x) (or (and (stringp (match-string 1))
+ (match-string 1))
+ ""))
+ ((= dcst ?f)
+ (if getkey-func
+ (let ((value (funcall getkey-func)))
+ (if (stringp value)
+ (funcall case-func value)
+ value))
+ (error "Invalid key function `%s'" getkey-func)))
+ (t (error "Invalid sorting type `%c'" sorting-type)))))))
+ (sort-subr (/= dcst sorting-type)
+ next-record
+ end-record
+ value-to-sort
+ nil
+ sort-func)
+ ;; Read and fix list again, as `sort-subr' probably destroyed
+ ;; its structure.
+ (org-list-repair)
+ (run-hooks 'org-after-sorting-entries-or-items-hook)
+ (message "Sorting items...done")))))
+
+(defun org-toggle-item (arg)
+ "Convert headings or normal lines to items, items to normal lines.
+If there is no active region, only the current line is considered.
+
+If the first non blank line in the region is a headline, convert
+all headlines to items, shifting text accordingly.
+
+If it is an item, convert all items to normal lines.
+
+If it is normal text, change region into a list of items.
+With a prefix argument ARG, change the region in a single item."
+ (interactive "P")
+ (let ((shift-text
+ (lambda (ind end)
+ ;; Shift text in current section to IND, from point to END.
+ ;; The function leaves point to END line.
+ (let ((min-i 1000) (end (copy-marker end)))
+ ;; First determine the minimum indentation (MIN-I) of
+ ;; the text.
+ (save-excursion
+ (catch 'exit
+ (while (< (point) end)
+ (let ((i (org-get-indentation)))
+ (cond
+ ;; Skip blank lines and inline tasks.
+ ((looking-at "^[ \t]*$"))
+ ((looking-at org-outline-regexp-bol))
+ ;; We can't find less than 0 indentation.
+ ((zerop i) (throw 'exit (setq min-i 0)))
+ ((< i min-i) (setq min-i i))))
+ (forward-line))))
+ ;; Then indent each line so that a line indented to
+ ;; MIN-I becomes indented to IND. Ignore blank lines
+ ;; and inline tasks in the process.
+ (let ((delta (- ind min-i)))
+ (while (< (point) end)
+ (unless (or (looking-at "^[ \t]*$")
+ (looking-at org-outline-regexp-bol))
+ (indent-line-to (+ (org-get-indentation) delta)))
+ (forward-line))))))
+ (skip-blanks
+ (lambda (pos)
+ ;; Return beginning of first non-blank line, starting from
+ ;; line at POS.
+ (save-excursion
+ (goto-char pos)
+ (skip-chars-forward " \r\t\n")
+ (point-at-bol))))
+ beg end)
+ ;; Determine boundaries of changes.
+ (if (org-region-active-p)
+ (setq beg (funcall skip-blanks (region-beginning))
+ end (copy-marker (region-end)))
+ (setq beg (funcall skip-blanks (point-at-bol))
+ end (copy-marker (point-at-eol))))
+ ;; Depending on the starting line, choose an action on the text
+ ;; between BEG and END.
+ (org-with-limited-levels
+ (save-excursion
+ (goto-char beg)
+ (cond
+ ;; Case 1. Start at an item: de-itemize. Note that it only
+ ;; happens when a region is active: `org-ctrl-c-minus'
+ ;; would call `org-cycle-list-bullet' otherwise.
+ ((org-at-item-p)
+ (while (< (point) end)
+ (when (org-at-item-p)
+ (skip-chars-forward " \t")
+ (delete-region (point) (match-end 0)))
+ (forward-line)))
+ ;; Case 2. Start at an heading: convert to items.
+ ((org-at-heading-p)
+ (let* ((bul (org-list-bullet-string "-"))
+ (bul-len (length bul))
+ ;; Indentation of the first heading. It should be
+ ;; relative to the indentation of its parent, if any.
+ (start-ind (save-excursion
+ (cond
+ ((not org-adapt-indentation) 0)
+ ((not (outline-previous-heading)) 0)
+ (t (length (match-string 0))))))
+ ;; Level of first heading. Further headings will be
+ ;; compared to it to determine hierarchy in the list.
+ (ref-level (org-reduced-level (org-outline-level))))
+ (while (< (point) end)
+ (let* ((level (org-reduced-level (org-outline-level)))
+ (delta (max 0 (- level ref-level)))
+ (todo-state (org-get-todo-state)))
+ ;; If current headline is less indented than the first
+ ;; one, set it as reference, in order to preserve
+ ;; subtrees.
+ (when (< level ref-level) (setq ref-level level))
+ ;; Remove stars and TODO keyword.
+ (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
+ (delete-region (point) (or (match-beginning 3)
+ (line-end-position)))
+ (insert bul)
+ (indent-line-to (+ start-ind (* delta bul-len)))
+ ;; Turn TODO keyword into a check box.
+ (when todo-state
+ (let* ((struct (org-list-struct))
+ (old (copy-tree struct)))
+ (org-list-set-checkbox
+ (line-beginning-position)
+ struct
+ (if (member todo-state org-done-keywords)
+ "[X]"
+ "[ ]"))
+ (org-list-write-struct struct
+ (org-list-parents-alist struct)
+ old)))
+ ;; Ensure all text down to END (or SECTION-END) belongs
+ ;; to the newly created item.
+ (let ((section-end (save-excursion
+ (or (outline-next-heading) (point)))))
+ (forward-line)
+ (funcall shift-text
+ (+ start-ind (* (1+ delta) bul-len))
+ (min end section-end)))))))
+ ;; Case 3. Normal line with ARG: make the first line of region
+ ;; an item, and shift indentation of others lines to
+ ;; set them as item's body.
+ (arg (let* ((bul (org-list-bullet-string "-"))
+ (bul-len (length bul))
+ (ref-ind (org-get-indentation)))
+ (skip-chars-forward " \t")
+ (insert bul)
+ (forward-line)
+ (while (< (point) end)
+ ;; Ensure that lines less indented than first one
+ ;; still get included in item body.
+ (funcall shift-text
+ (+ ref-ind bul-len)
+ (min end (save-excursion (or (outline-next-heading)
+ (point)))))
+ (forward-line))))
+ ;; Case 4. Normal line without ARG: turn each non-item line
+ ;; into an item.
+ (t
+ (while (< (point) end)
+ (unless (or (org-at-heading-p) (org-at-item-p))
+ (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
+ (replace-match
+ (concat "\\1" (org-list-bullet-string "-") "\\2"))))
+ (forward-line))))))))
+
+
+;;; Send and receive lists
+
+(defun org-list-to-lisp (&optional delete)
+ "Parse the list at point and maybe DELETE it.
+
+Return a list whose car is a symbol of list type, among
+`ordered', `unordered' and `descriptive'. Then, each item is
+a list of strings and other sub-lists.
+
+For example, the following list:
+
+ 1. first item
+ + sub-item one
+ + [X] sub-item two
+ more text in first item
+ 2. [@3] last item
+
+is parsed as
+
+ (ordered
+ (\"first item\"
+ (unordered
+ (\"sub-item one\")
+ (\"[X] sub-item two\"))
+ \"more text in first item\")
+ (\"[@3] last item\"))
+
+Point is left at list's end."
+ (letrec ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (parents (org-list-parents-alist struct))
+ (top (org-list-get-top-point struct))
+ (bottom (org-list-get-bottom-point struct))
+ (trim
+ (lambda (text)
+ ;; Remove indentation and final newline from TEXT.
+ (org-remove-indentation
+ (if (string-match-p "\n\\'" text)
+ (substring text 0 -1)
+ text))))
+ (parse-sublist
+ (lambda (e)
+ ;; Return a list whose car is list type and cdr a list
+ ;; of items' body.
+ (cons (org-list-get-list-type (car e) struct prevs)
+ (mapcar parse-item e))))
+ (parse-item
+ (lambda (e)
+ ;; Return a list containing counter of item, if any,
+ ;; text and any sublist inside it.
+ (let* ((end (org-list-get-item-end e struct))
+ (children (org-list-get-children e struct parents))
+ (body
+ (save-excursion
+ (goto-char e)
+ (looking-at "[ \t]*\\S-+[ \t]*")
+ (list
+ (funcall
+ trim
+ (concat
+ (make-string (string-width (match-string 0)) ?\s)
+ (buffer-substring-no-properties
+ (match-end 0) (or (car children) end))))))))
+ (while children
+ (let* ((child (car children))
+ (sub (org-list-get-all-items child struct prevs))
+ (last-in-sub (car (last sub))))
+ (push (funcall parse-sublist sub) body)
+ ;; Remove whole sub-list from children.
+ (setq children (cdr (memq last-in-sub children)))
+ ;; There is a chunk of text belonging to the item
+ ;; if last child doesn't end where next child
+ ;; starts or where item ends.
+ (let ((sub-end (org-list-get-item-end last-in-sub struct))
+ (next (or (car children) end)))
+ (when (/= sub-end next)
+ (push (funcall
+ trim
+ (buffer-substring-no-properties sub-end next))
+ body)))))
+ (nreverse body)))))
+ ;; Store output, take care of cursor position and deletion of
+ ;; list, then return output.
+ (prog1 (funcall parse-sublist (org-list-get-all-items top struct prevs))
+ (goto-char top)
+ (when delete
+ (delete-region top bottom)
+ (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
+ (replace-match ""))))))
+
+(defun org-list-make-subtree ()
+ "Convert the plain list at point into a subtree."
+ (interactive)
+ (if (not (ignore-errors (goto-char (org-in-item-p))))
+ (error "Not in a list")
+ (let ((list (save-excursion (org-list-to-lisp t))))
+ (insert (org-list-to-subtree list)))))
+
+(defun org-list-insert-radio-list ()
+ "Insert a radio list template appropriate for this major mode."
+ (interactive)
+ (let* ((e (cl-assoc-if #'derived-mode-p org-list-radio-list-templates))
+ (txt (nth 1 e))
+ name pos)
+ (unless e (error "No radio list setup defined for %s" major-mode))
+ (setq name (read-string "List name: "))
+ (while (string-match "%n" txt)
+ (setq txt (replace-match name t t txt)))
+ (or (bolp) (insert "\n"))
+ (setq pos (point))
+ (insert txt)
+ (goto-char pos)))
+
+(defun org-list-send-list (&optional maybe)
+ "Send a transformed version of this list to the receiver position.
+With argument MAYBE, fail quietly if no transformation is defined
+for this list."
+ (interactive)
+ (catch 'exit
+ (unless (org-at-item-p) (error "Not at a list item"))
+ (save-excursion
+ (let ((case-fold-search t))
+ (re-search-backward "^[ \t]*#\\+ORGLST:" nil t)
+ (unless (looking-at
+ "[ \t]*#\\+ORGLST:[ \t]+SEND[ \t]+\\(\\S-+\\)[ \t]+\\([^ \t\n]+\\)")
+ (if maybe (throw 'exit nil)
+ (error "Don't know how to transform this list")))))
+ (let* ((name (regexp-quote (match-string 1)))
+ (transform (intern (match-string 2)))
+ (bottom-point
+ (save-excursion
+ (re-search-forward
+ "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
+ (match-beginning 0)))
+ (top-point
+ (progn
+ (re-search-backward "#\\+ORGLST" nil t)
+ (re-search-forward (org-item-beginning-re) bottom-point t)
+ (match-beginning 0)))
+ (plain-list (save-excursion
+ (goto-char top-point)
+ (org-list-to-lisp))))
+ (unless (fboundp transform)
+ (error "No such transformation function %s" transform))
+ (let ((txt (funcall transform plain-list)))
+ ;; Find the insertion(s) place(s).
+ (save-excursion
+ (goto-char (point-min))
+ (let ((receiver-count 0)
+ (begin-re (format "BEGIN +RECEIVE +ORGLST +%s\\([ \t]\\|$\\)"
+ name))
+ (end-re (format "END +RECEIVE +ORGLST +%s\\([ \t]\\|$\\)"
+ name)))
+ (while (re-search-forward begin-re nil t)
+ (cl-incf receiver-count)
+ (let ((beg (line-beginning-position 2)))
+ (unless (re-search-forward end-re nil t)
+ (user-error "Cannot find end of receiver location at %d" beg))
+ (beginning-of-line)
+ (delete-region beg (point))
+ (insert txt "\n")))
+ (cond
+ ((> receiver-count 1)
+ (message "List converted and installed at receiver locations"))
+ ((= receiver-count 1)
+ (message "List converted and installed at receiver location"))
+ (t (user-error "No valid receiver location found")))))))))
+
+(defun org-list-to-generic (list params)
+ "Convert a LIST parsed through `org-list-to-lisp' to a custom format.
+
+LIST is a list as returned by `org-list-to-lisp', which see.
+PARAMS is a property list of parameters used to tweak the output
+format.
+
+Valid parameters are:
+
+:backend, :raw
+
+ Export back-end used as a basis to transcode elements of the
+ list, when no specific parameter applies to it. It is also
+ used to translate its contents. You can prevent this by
+ setting :raw property to a non-nil value.
+
+:splice
+
+ When non-nil, only export the contents of the top most plain
+ list, effectively ignoring its opening and closing lines.
+
+:ustart, :uend
+
+ Strings to start and end an unordered list. They can also be
+ set to a function returning a string or nil, which will be
+ called with the depth of the list, counting from 1.
+
+:ostart, :oend
+
+ Strings to start and end an ordered list. They can also be set
+ to a function returning a string or nil, which will be called
+ with the depth of the list, counting from 1.
+
+:dstart, :dend
+
+ Strings to start and end a descriptive list. They can also be
+ set to a function returning a string or nil, which will be
+ called with the depth of the list, counting from 1.
+
+:dtstart, :dtend, :ddstart, :ddend
+
+ Strings to start and end a descriptive term.
+
+:istart, :iend
+
+ Strings to start or end a list item, and to start a list item
+ with a counter. They can also be set to a function returning
+ a string or nil, which will be called with the depth of the
+ item, counting from 1.
+
+:icount
+
+ Strings to start a list item with a counter. It can also be
+ set to a function returning a string or nil, which will be
+ called with two arguments: the depth of the item, counting from
+ 1, and the counter. Its value, when non-nil, has precedence
+ over `:istart'.
+
+:isep
+
+ String used to separate items. It can also be set to
+ a function returning a string or nil, which will be called with
+ the depth of the items, counting from 1. It always start on
+ a new line.
+
+:cbon, :cboff, :cbtrans
+
+ String to insert, respectively, an un-checked check-box,
+ a checked check-box and a check-box in transitional state."
+ (require 'ox)
+ (let* ((backend (plist-get params :backend))
+ (custom-backend
+ (org-export-create-backend
+ :parent (or backend 'org)
+ :transcoders
+ `((plain-list . ,(org-list--to-generic-plain-list params))
+ (item . ,(org-list--to-generic-item params))
+ (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
+ data info)
+ ;; Write LIST back into Org syntax and parse it.
+ (with-temp-buffer
+ (let ((org-inhibit-startup t)) (org-mode))
+ (letrec ((insert-list
+ (lambda (l)
+ (dolist (i (cdr l))
+ (funcall insert-item i (car l)))))
+ (insert-item
+ (lambda (i type)
+ (let ((start (point)))
+ (insert (if (eq type 'ordered) "1. " "- "))
+ (dolist (e i)
+ (if (consp e) (funcall insert-list e)
+ (insert e)
+ (insert "\n")))
+ (beginning-of-line)
+ (save-excursion
+ (let ((ind (if (eq type 'ordered) 3 2)))
+ (while (> (point) start)
+ (unless (looking-at-p "[ \t]*$")
+ (indent-to ind))
+ (forward-line -1))))))))
+ (funcall insert-list list))
+ (setf data
+ (org-element-map (org-element-parse-buffer) 'plain-list
+ #'identity nil t))
+ (setf info (org-export-get-environment backend nil params)))
+ (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
+ (user-error "Unknown :backend value"))
+ (unless backend (require 'ox-org))
+ ;; When`:raw' property has a non-nil value, turn all objects back
+ ;; into Org syntax.
+ (when (and backend (plist-get params :raw))
+ (org-element-map data org-element-all-objects
+ (lambda (object)
+ (org-element-set-element
+ object (org-element-interpret-data object)))))
+ ;; We use a low-level mechanism to export DATA so as to skip all
+ ;; usual pre-processing and post-processing, i.e., hooks, filters,
+ ;; Babel code evaluation, include keywords and macro expansion,
+ ;; and filters.
+ (let ((output (org-export-data-with-backend data custom-backend info)))
+ ;; Remove final newline.
+ (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
+
+(defun org-list--depth (element)
+ "Return the level of ELEMENT within current plain list.
+ELEMENT is either an item or a plain list."
+ (cl-count-if (lambda (ancestor) (eq (org-element-type ancestor) 'plain-list))
+ (org-element-lineage element nil t)))
+
+(defun org-list--trailing-newlines (string)
+ "Return the number of trailing newlines in STRING."
+ (with-temp-buffer
+ (insert string)
+ (skip-chars-backward " \t\n")
+ (count-lines (line-beginning-position 2) (point-max))))
+
+(defun org-list--generic-eval (value &rest args)
+ "Evaluate VALUE according to its type.
+VALUE is either nil, a string or a function. In the latter case,
+it is called with arguments ARGS."
+ (cond ((null value) nil)
+ ((stringp value) value)
+ ((functionp value) (apply value args))
+ (t (error "Wrong value: %s" value))))
+
+(defun org-list--to-generic-plain-list (params)
+ "Return a transcoder for `plain-list' elements.
+PARAMS is a plist used to tweak the behavior of the transcoder."
+ (let ((ustart (plist-get params :ustart))
+ (uend (plist-get params :uend))
+ (ostart (plist-get params :ostart))
+ (oend (plist-get params :oend))
+ (dstart (plist-get params :dstart))
+ (dend (plist-get params :dend))
+ (splice (plist-get params :splice))
+ (backend (plist-get params :backend)))
+ (lambda (plain-list contents info)
+ (let* ((type (org-element-property :type plain-list))
+ (depth (org-list--depth plain-list))
+ (start (and (not splice)
+ (org-list--generic-eval
+ (pcase type
+ (`ordered ostart)
+ (`unordered ustart)
+ (_ dstart))
+ depth)))
+ (end (and (not splice)
+ (org-list--generic-eval
+ (pcase type
+ (`ordered oend)
+ (`unordered uend)
+ (_ dend))
+ depth))))
+ ;; Make sure trailing newlines in END appear in the output by
+ ;; setting `:post-blank' property to their number.
+ (when end
+ (org-element-put-property
+ plain-list :post-blank (org-list--trailing-newlines end)))
+ ;; Build output.
+ (concat (and start (concat start "\n"))
+ (if (or start end splice (not backend))
+ contents
+ (org-export-with-backend backend plain-list contents info))
+ end)))))
+
+(defun org-list--to-generic-item (params)
+ "Return a transcoder for `item' elements.
+PARAMS is a plist used to tweak the behavior of the transcoder."
+ (let ((backend (plist-get params :backend))
+ (istart (plist-get params :istart))
+ (iend (plist-get params :iend))
+ (isep (plist-get params :isep))
+ (icount (plist-get params :icount))
+ (cboff (plist-get params :cboff))
+ (cbon (plist-get params :cbon))
+ (cbtrans (plist-get params :cbtrans))
+ (dtstart (plist-get params :dtstart))
+ (dtend (plist-get params :dtend))
+ (ddstart (plist-get params :ddstart))
+ (ddend (plist-get params :ddend)))
+ (lambda (item contents info)
+ (let* ((type
+ (org-element-property :type (org-element-property :parent item)))
+ (tag (org-element-property :tag item))
+ (depth (org-list--depth item))
+ (separator (and (org-export-get-next-element item info)
+ (org-list--generic-eval isep depth)))
+ (closing (pcase (org-list--generic-eval iend depth)
+ ((or `nil `"") "\n")
+ ((and (guard separator) s)
+ (if (equal (substring s -1) "\n") s (concat s "\n")))
+ (s s))))
+ ;; When a closing line or a separator is provided, make sure
+ ;; its trailing newlines are taken into account when building
+ ;; output. This is done by setting `:post-blank' property to
+ ;; the number of such lines in the last line to be added.
+ (let ((last-string (or separator closing)))
+ (when last-string
+ (org-element-put-property
+ item
+ :post-blank
+ (max (1- (org-list--trailing-newlines last-string)) 0))))
+ ;; Build output.
+ (concat
+ (let ((c (org-element-property :counter item)))
+ (if c (org-list--generic-eval icount depth c)
+ (org-list--generic-eval istart depth)))
+ (let ((body
+ (if (or istart iend icount cbon cboff cbtrans (not backend)
+ (and (eq type 'descriptive)
+ (or dtstart dtend ddstart ddend)))
+ (concat
+ (pcase (org-element-property :checkbox item)
+ (`on cbon)
+ (`off cboff)
+ (`trans cbtrans))
+ (and tag
+ (concat dtstart
+ (if backend
+ (org-export-data-with-backend
+ tag backend info)
+ (org-element-interpret-data tag))
+ dtend))
+ (and tag ddstart)
+ (if (= (length contents) 0) "" (substring contents 0 -1))
+ (and tag ddend))
+ (org-export-with-backend backend item contents info))))
+ ;; Remove final newline.
+ (if (equal body "") ""
+ (substring (org-element-normalize-string body) 0 -1)))
+ closing
+ separator)))))
+
+(defun org-list-to-latex (list &optional params)
+ "Convert LIST into a LaTeX list.
+LIST is a parsed plain list, as returned by `org-list-to-lisp'.
+PARAMS is a property list with overruling parameters for
+`org-list-to-generic'. Return converted list as a string."
+ (require 'ox-latex)
+ (org-list-to-generic list (org-combine-plists '(:backend latex) params)))
+
+(defun org-list-to-html (list &optional params)
+ "Convert LIST into a HTML list.
+LIST is a parsed plain list, as returned by `org-list-to-lisp'.
+PARAMS is a property list with overruling parameters for
+`org-list-to-generic'. Return converted list as a string."
+ (require 'ox-html)
+ (org-list-to-generic list (org-combine-plists '(:backend html) params)))
+
+(defun org-list-to-texinfo (list &optional params)
+ "Convert LIST into a Texinfo list.
+LIST is a parsed plain list, as returned by `org-list-to-lisp'.
+PARAMS is a property list with overruling parameters for
+`org-list-to-generic'. Return converted list as a string."
+ (require 'ox-texinfo)
+ (org-list-to-generic list (org-combine-plists '(:backend texinfo) params)))
+
+(defun org-list-to-subtree (list &optional params)
+ "Convert LIST into an Org subtree.
+LIST is as returned by `org-list-to-lisp'. PARAMS is a property
+list with overruling parameters for `org-list-to-generic'."
+ (let* ((blank (pcase (cdr (assq 'heading org-blank-before-new-entry))
+ (`t t)
+ (`auto (save-excursion
+ (org-with-limited-levels (outline-previous-heading))
+ (org-previous-line-empty-p)))))
+ (level (org-reduced-level (or (org-current-level) 0)))
+ (make-stars
+ (lambda (depth)
+ ;; Return the string for the heading, depending on DEPTH
+ ;; of current sub-list.
+ (let ((oddeven-level (+ level depth)))
+ (concat (make-string (if org-odd-levels-only
+ (1- (* 2 oddeven-level))
+ oddeven-level)
+ ?*)
+ " ")))))
+ (org-list-to-generic
+ list
+ (org-combine-plists
+ (list :splice t
+ :istart make-stars
+ :icount make-stars
+ :dtstart " " :dtend " "
+ :isep (if blank "\n\n" "\n")
+ :cbon "DONE " :cboff "TODO " :cbtrans "TODO ")
+ params))))
+
+(provide 'org-list)
+
+;;; org-list.el ends here
diff --git a/lisp/org-loaddefs.el b/lisp/org-loaddefs.el
new file mode 100644
index 0000000..6b8d11b
--- /dev/null
+++ b/lisp/org-loaddefs.el
@@ -0,0 +1,3829 @@
+;;; org-loaddefs.el --- autogenerated file, do not edit
+;;
+;;; Code:
+
+;;;### (autoloads nil "ob-C" "ob-C.el" (0 0 0 0))
+;;; Generated autoloads from ob-C.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-C" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-J" "ob-J.el" (0 0 0 0))
+;;; Generated autoloads from ob-J.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-J" '("obj-" "org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-R" "ob-R.el" (0 0 0 0))
+;;; Generated autoloads from ob-R.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-R" '("ob-R-" "org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-abc" "ob-abc.el" (0 0 0 0))
+;;; Generated autoloads from ob-abc.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-abc" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-asymptote" "ob-asymptote.el" (0 0 0 0))
+;;; Generated autoloads from ob-asymptote.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-asymptote" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-awk" "ob-awk.el" (0 0 0 0))
+;;; Generated autoloads from ob-awk.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-awk" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-calc" "ob-calc.el" (0 0 0 0))
+;;; Generated autoloads from ob-calc.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-calc" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-clojure" "ob-clojure.el" (0 0 0 0))
+;;; Generated autoloads from ob-clojure.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-clojure" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-comint" "ob-comint.el" (0 0 0 0))
+;;; Generated autoloads from ob-comint.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-comint" '("org-babel-comint-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-coq" "ob-coq.el" (0 0 0 0))
+;;; Generated autoloads from ob-coq.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-coq" '("org-babel-" "coq-program-name")))
+
+;;;***
+
+;;;### (autoloads nil "ob-core" "ob-core.el" (0 0 0 0))
+;;; Generated autoloads from ob-core.el
+
+(autoload 'org-babel-execute-safely-maybe "ob-core" "\
+
+
+\(fn)" nil nil)
+
+(autoload 'org-babel-execute-maybe "ob-core" "\
+
+
+\(fn)" t nil)
+
+(autoload 'org-babel-view-src-block-info "ob-core" "\
+Display information on the current source block.
+This includes header arguments, language and name, and is largely
+a window into the `org-babel-get-src-block-info' function.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-expand-src-block-maybe "ob-core" "\
+Conditionally expand a source block.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-expand-src-block'.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-load-in-session-maybe "ob-core" "\
+Conditionally load a source block in a session.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-load-in-session'.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-pop-to-session-maybe "ob-core" "\
+Conditionally pop to a session.
+Detect if this is context for a org-babel src-block and if so
+then run `org-babel-switch-to-session'.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-execute-src-block "ob-core" "\
+Execute the current source code block.
+Insert the results of execution into the buffer. Source code
+execution and the collection and formatting of results can be
+controlled through a variety of header arguments.
+
+With prefix argument ARG, force re-execution even if an existing
+result cached in the buffer would otherwise have been returned.
+
+Optionally supply a value for INFO in the form returned by
+`org-babel-get-src-block-info'.
+
+Optionally supply a value for PARAMS which will be merged with
+the header arguments specified at the front of the source code
+block.
+
+\(fn &optional ARG INFO PARAMS)" t nil)
+
+(autoload 'org-babel-expand-src-block "ob-core" "\
+Expand the current source code block.
+Expand according to the source code block's header
+arguments and pop open the results in a preview buffer.
+
+\(fn &optional ARG INFO PARAMS)" t nil)
+
+(autoload 'org-babel-check-src-block "ob-core" "\
+Check for misspelled header arguments in the current code block.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-insert-header-arg "ob-core" "\
+Insert a header argument selecting from lists of common args and values.
+
+\(fn &optional HEADER-ARG VALUE)" t nil)
+
+(autoload 'org-babel-load-in-session "ob-core" "\
+Load the body of the current source-code block.
+Evaluate the header arguments for the source block before
+entering the session. After loading the body this pops open the
+session.
+
+\(fn &optional ARG INFO)" t nil)
+
+(autoload 'org-babel-initiate-session "ob-core" "\
+Initiate session for current code block.
+If called with a prefix argument then resolve any variable
+references in the header arguments and assign these variables in
+the session. Copy the body of the code block to the kill ring.
+
+\(fn &optional ARG INFO)" t nil)
+
+(autoload 'org-babel-switch-to-session "ob-core" "\
+Switch to the session of the current code block.
+Uses `org-babel-initiate-session' to start the session. If called
+with a prefix argument then this is passed on to
+`org-babel-initiate-session'.
+
+\(fn &optional ARG INFO)" t nil)
+
+(autoload 'org-babel-switch-to-session-with-code "ob-core" "\
+Switch to code buffer and display session.
+
+\(fn &optional ARG INFO)" t nil)
+
+(autoload 'org-babel-do-in-edit-buffer "ob-core" "\
+Evaluate BODY in edit buffer if there is a code block at point.
+Return t if a code block was found at point, nil otherwise.
+
+\(fn &rest BODY)" nil t)
+
+(autoload 'org-babel-open-src-block-result "ob-core" "\
+If `point' is on a src block then open the results of the
+source code block, otherwise return nil. With optional prefix
+argument RE-RUN the source-code block is evaluated even if
+results already exist.
+
+\(fn &optional RE-RUN)" t nil)
+
+(autoload 'org-babel-map-src-blocks "ob-core" "\
+Evaluate BODY forms on each source-block in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer. During evaluation of BODY the following local variables
+are set relative to the currently matched code block.
+
+full-block ------- string holding the entirety of the code block
+beg-block -------- point at the beginning of the code block
+end-block -------- point at the end of the matched code block
+lang ------------- string holding the language of the code block
+beg-lang --------- point at the beginning of the lang
+end-lang --------- point at the end of the lang
+switches --------- string holding the switches
+beg-switches ----- point at the beginning of the switches
+end-switches ----- point at the end of the switches
+header-args ------ string holding the header-args
+beg-header-args -- point at the beginning of the header-args
+end-header-args -- point at the end of the header-args
+body ------------- string holding the body of the code block
+beg-body --------- point at the beginning of the body
+end-body --------- point at the end of the body
+
+\(fn FILE &rest BODY)" nil t)
+
+(function-put 'org-babel-map-src-blocks 'lisp-indent-function '1)
+
+(autoload 'org-babel-map-inline-src-blocks "ob-core" "\
+Evaluate BODY forms on each inline source block in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer.
+
+\(fn FILE &rest BODY)" nil t)
+
+(function-put 'org-babel-map-inline-src-blocks 'lisp-indent-function '1)
+
+(autoload 'org-babel-map-call-lines "ob-core" "\
+Evaluate BODY forms on each call line in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer.
+
+\(fn FILE &rest BODY)" nil t)
+
+(function-put 'org-babel-map-call-lines 'lisp-indent-function '1)
+
+(autoload 'org-babel-map-executables "ob-core" "\
+Evaluate BODY forms on each active Babel code in FILE.
+If FILE is nil evaluate BODY forms on source blocks in current
+buffer.
+
+\(fn FILE &rest BODY)" nil t)
+
+(function-put 'org-babel-map-executables 'lisp-indent-function '1)
+
+(autoload 'org-babel-execute-buffer "ob-core" "\
+Execute source code blocks in a buffer.
+Call `org-babel-execute-src-block' on every source block in
+the current buffer.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-babel-execute-subtree "ob-core" "\
+Execute source code blocks in a subtree.
+Call `org-babel-execute-src-block' on every source block in
+the current subtree.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-babel-sha1-hash "ob-core" "\
+Generate an sha1 hash based on the value of info.
+
+\(fn &optional INFO)" t nil)
+
+(autoload 'org-babel-hide-result-toggle-maybe "ob-core" "\
+Toggle visibility of result at point.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-goto-src-block-head "ob-core" "\
+Go to the beginning of the current code block.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-goto-named-src-block "ob-core" "\
+Go to a named source-code block.
+
+\(fn NAME)" t nil)
+
+(autoload 'org-babel-goto-named-result "ob-core" "\
+Go to a named result.
+
+\(fn NAME)" t nil)
+
+(autoload 'org-babel-next-src-block "ob-core" "\
+Jump to the next source block.
+With optional prefix argument ARG, jump forward ARG many source blocks.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-babel-previous-src-block "ob-core" "\
+Jump to the previous source block.
+With optional prefix argument ARG, jump backward ARG many source blocks.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-babel-mark-block "ob-core" "\
+Mark current src block.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-core" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-css" "ob-css.el" (0 0 0 0))
+;;; Generated autoloads from ob-css.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-css" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ditaa" "ob-ditaa.el" (0 0 0 0))
+;;; Generated autoloads from ob-ditaa.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ditaa" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-dot" "ob-dot.el" (0 0 0 0))
+;;; Generated autoloads from ob-dot.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-dot" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ebnf" "ob-ebnf.el" (0 0 0 0))
+;;; Generated autoloads from ob-ebnf.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ebnf" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-emacs-lisp" "ob-emacs-lisp.el" (0 0 0 0))
+;;; Generated autoloads from ob-emacs-lisp.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-emacs-lisp" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-eval" "ob-eval.el" (0 0 0 0))
+;;; Generated autoloads from ob-eval.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-eval" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-exp" "ob-exp.el" (0 0 0 0))
+;;; Generated autoloads from ob-exp.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-exp" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-forth" "ob-forth.el" (0 0 0 0))
+;;; Generated autoloads from ob-forth.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-forth" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-fortran" "ob-fortran.el" (0 0 0 0))
+;;; Generated autoloads from ob-fortran.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-fortran" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-gnuplot" "ob-gnuplot.el" (0 0 0 0))
+;;; Generated autoloads from ob-gnuplot.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-gnuplot" '("org-babel-" "*org-babel-gnuplot-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-groovy" "ob-groovy.el" (0 0 0 0))
+;;; Generated autoloads from ob-groovy.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-groovy" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-haskell" "ob-haskell.el" (0 0 0 0))
+;;; Generated autoloads from ob-haskell.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-haskell" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-io" "ob-io.el" (0 0 0 0))
+;;; Generated autoloads from ob-io.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-io" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-java" "ob-java.el" (0 0 0 0))
+;;; Generated autoloads from ob-java.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-java" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-js" "ob-js.el" (0 0 0 0))
+;;; Generated autoloads from ob-js.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-js" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-keys" "ob-keys.el" (0 0 0 0))
+;;; Generated autoloads from ob-keys.el
+
+(autoload 'org-babel-describe-bindings "ob-keys" "\
+Describe all keybindings behind `org-babel-key-prefix'.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-keys" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-latex" "ob-latex.el" (0 0 0 0))
+;;; Generated autoloads from ob-latex.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-latex" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ledger" "ob-ledger.el" (0 0 0 0))
+;;; Generated autoloads from ob-ledger.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ledger" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-lilypond" "ob-lilypond.el" (0 0 0 0))
+;;; Generated autoloads from ob-lilypond.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lilypond" '("org-babel-" "lilypond-mode")))
+
+;;;***
+
+;;;### (autoloads nil "ob-lisp" "ob-lisp.el" (0 0 0 0))
+;;; Generated autoloads from ob-lisp.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lisp" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-lob" "ob-lob.el" (0 0 0 0))
+;;; Generated autoloads from ob-lob.el
+
+(autoload 'org-babel-lob-execute-maybe "ob-lob" "\
+Execute a Library of Babel source block, if appropriate.
+Detect if this is context for a Library Of Babel source block and
+if so then run the appropriate source block from the Library.
+
+\(fn)" t nil)
+
+(autoload 'org-babel-lob-get-info "ob-lob" "\
+Return internal representation for Library of Babel function call.
+Consider DATUM, when provided, or element at point. Return nil
+when not on an appropriate location. Otherwise return a list
+compatible with `org-babel-get-src-block-info', which see.
+
+\(fn &optional DATUM)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lob" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-lua" "ob-lua.el" (0 0 0 0))
+;;; Generated autoloads from ob-lua.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lua" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-makefile" "ob-makefile.el" (0 0 0 0))
+;;; Generated autoloads from ob-makefile.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-makefile" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-maxima" "ob-maxima.el" (0 0 0 0))
+;;; Generated autoloads from ob-maxima.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-maxima" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-mscgen" "ob-mscgen.el" (0 0 0 0))
+;;; Generated autoloads from ob-mscgen.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-mscgen" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ocaml" "ob-ocaml.el" (0 0 0 0))
+;;; Generated autoloads from ob-ocaml.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ocaml" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-octave" "ob-octave.el" (0 0 0 0))
+;;; Generated autoloads from ob-octave.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-octave" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-org" "ob-org.el" (0 0 0 0))
+;;; Generated autoloads from ob-org.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-org" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-perl" "ob-perl.el" (0 0 0 0))
+;;; Generated autoloads from ob-perl.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-perl" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-picolisp" "ob-picolisp.el" (0 0 0 0))
+;;; Generated autoloads from ob-picolisp.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-picolisp" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-plantuml" "ob-plantuml.el" (0 0 0 0))
+;;; Generated autoloads from ob-plantuml.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-plantuml" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-processing" "ob-processing.el" (0 0 0 0))
+;;; Generated autoloads from ob-processing.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-processing" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-python" "ob-python.el" (0 0 0 0))
+;;; Generated autoloads from ob-python.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-python" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ref" "ob-ref.el" (0 0 0 0))
+;;; Generated autoloads from ob-ref.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ref" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-ruby" "ob-ruby.el" (0 0 0 0))
+;;; Generated autoloads from ob-ruby.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ruby" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-sass" "ob-sass.el" (0 0 0 0))
+;;; Generated autoloads from ob-sass.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sass" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-scala" "ob-scala.el" (0 0 0 0))
+;;; Generated autoloads from ob-scala.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-scala" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-scheme" "ob-scheme.el" (0 0 0 0))
+;;; Generated autoloads from ob-scheme.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-scheme" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-screen" "ob-screen.el" (0 0 0 0))
+;;; Generated autoloads from ob-screen.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-screen" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-sed" "ob-sed.el" (0 0 0 0))
+;;; Generated autoloads from ob-sed.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sed" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-shell" "ob-shell.el" (0 0 0 0))
+;;; Generated autoloads from ob-shell.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-shell" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-shen" "ob-shen.el" (0 0 0 0))
+;;; Generated autoloads from ob-shen.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-shen" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-sql" "ob-sql.el" (0 0 0 0))
+;;; Generated autoloads from ob-sql.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sql" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-sqlite" "ob-sqlite.el" (0 0 0 0))
+;;; Generated autoloads from ob-sqlite.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sqlite" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-stan" "ob-stan.el" (0 0 0 0))
+;;; Generated autoloads from ob-stan.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-stan" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-table" "ob-table.el" (0 0 0 0))
+;;; Generated autoloads from ob-table.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-table" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "ob-tangle" "ob-tangle.el" (0 0 0 0))
+;;; Generated autoloads from ob-tangle.el
+
+(autoload 'org-babel-tangle-file "ob-tangle" "\
+Extract the bodies of source code blocks in FILE.
+Source code blocks are extracted with `org-babel-tangle'.
+Optional argument TARGET-FILE can be used to specify a default
+export file for all source blocks. Optional argument LANG can be
+used to limit the exported source code blocks by language.
+Return a list whose CAR is the tangled file name.
+
+\(fn FILE &optional TARGET-FILE LANG)" t nil)
+
+(autoload 'org-babel-tangle "ob-tangle" "\
+Write code blocks to source-specific files.
+Extract the bodies of all source code blocks from the current
+file into their own source-specific files.
+With one universal prefix argument, only tangle the block at point.
+When two universal prefix arguments, only tangle blocks for the
+tangle file of the block at point.
+Optional argument TARGET-FILE can be used to specify a default
+export file for all source blocks. Optional argument LANG can be
+used to limit the exported source code blocks by language.
+
+\(fn &optional ARG TARGET-FILE LANG)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-tangle" '("org-babel-")))
+
+;;;***
+
+;;;### (autoloads nil "org-agenda" "org-agenda.el" (0 0 0 0))
+;;; Generated autoloads from org-agenda.el
+
+(autoload 'org-toggle-sticky-agenda "org-agenda" "\
+Toggle `org-agenda-sticky'.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-agenda "org-agenda" "\
+Dispatch agenda commands to collect entries to the agenda buffer.
+Prompts for a command to execute. Any prefix arg will be passed
+on to the selected command. The default selections are:
+
+a Call `org-agenda-list' to display the agenda for current day or week.
+t Call `org-todo-list' to display the global todo list.
+T Call `org-todo-list' to display the global todo list, select only
+ entries with a specific TODO keyword (the user gets a prompt).
+m Call `org-tags-view' to display headlines with tags matching
+ a condition (the user is prompted for the condition).
+M Like `m', but select only TODO entries, no ordinary headlines.
+L Create a timeline for the current buffer.
+e Export views to associated files.
+s Search entries for keywords.
+S Search entries for keywords, only with TODO keywords.
+/ Multi occur across all agenda files and also files listed
+ in `org-agenda-text-search-extra-files'.
+< Restrict agenda commands to buffer, subtree, or region.
+ Press several times to get the desired effect.
+> Remove a previous restriction.
+# List \"stuck\" projects.
+! Configure what \"stuck\" means.
+C Configure custom agenda commands.
+
+More commands can be added by configuring the variable
+`org-agenda-custom-commands'. In particular, specific tags and TODO keyword
+searches can be pre-defined in this way.
+
+If the current buffer is in Org mode and visiting a file, you can also
+first press `<' once to indicate that the agenda should be temporarily
+\(until the next use of `\\[org-agenda]') restricted to the current file.
+Pressing `<' twice means to restrict to the current subtree or region
+\(if active).
+
+\(fn &optional ARG ORG-KEYS RESTRICTION)" t nil)
+
+(autoload 'org-batch-agenda "org-agenda" "\
+Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command. If it is a
+longer string it is used as a tags/todo match string.
+Parameters are alternating variable names and values that will be bound
+before running the agenda command.
+
+\(fn CMD-KEY &rest PARAMETERS)" nil t)
+
+(autoload 'org-batch-agenda-csv "org-agenda" "\
+Run an agenda command in batch mode and send the result to STDOUT.
+If CMD-KEY is a string of length 1, it is used as a key in
+`org-agenda-custom-commands' and triggers this command. If it is a
+longer string it is used as a tags/todo match string.
+Parameters are alternating variable names and values that will be bound
+before running the agenda command.
+
+The output gives a line for each selected agenda item. Each
+item is a list of comma-separated values, like this:
+
+category,head,type,todo,tags,date,time,extra,priority-l,priority-n
+
+category The category of the item
+head The headline, without TODO kwd, TAGS and PRIORITY
+type The type of the agenda entry, can be
+ todo selected in TODO match
+ tagsmatch selected in tags match
+ diary imported from diary
+ deadline a deadline on given date
+ scheduled scheduled on given date
+ timestamp entry has timestamp on given date
+ closed entry was closed on given date
+ upcoming-deadline warning about deadline
+ past-scheduled forwarded scheduled item
+ block entry has date block including g. date
+todo The todo keyword, if any
+tags All tags including inherited ones, separated by colons
+date The relevant date, like 2007-2-14
+time The time, like 15:00-16:50
+extra Sting with extra planning info
+priority-l The priority letter if any was given
+priority-n The computed numerical priority
+agenda-day The day in the agenda where this is listed
+
+\(fn CMD-KEY &rest PARAMETERS)" nil t)
+
+(autoload 'org-store-agenda-views "org-agenda" "\
+Store agenda views.
+
+\(fn &rest PARAMETERS)" t nil)
+
+(autoload 'org-batch-store-agenda-views "org-agenda" "\
+Run all custom agenda commands that have a file argument.
+
+\(fn &rest PARAMETERS)" nil t)
+
+(autoload 'org-agenda-list "org-agenda" "\
+Produce a daily/weekly view from all files in variable `org-agenda-files'.
+The view will be for the current day or week, but from the overview buffer
+you will be able to go to other days/weeks.
+
+With a numeric prefix argument in an interactive call, the agenda will
+span ARG days. Lisp programs should instead specify SPAN to change
+the number of days. SPAN defaults to `org-agenda-span'.
+
+START-DAY defaults to TODAY, or to the most recent match for the weekday
+given in `org-agenda-start-on-weekday'.
+
+When WITH-HOUR is non-nil, only include scheduled and deadline
+items if they have an hour specification like [h]h:mm.
+
+\(fn &optional ARG START-DAY SPAN WITH-HOUR)" t nil)
+
+(autoload 'org-search-view "org-agenda" "\
+Show all entries that contain a phrase or words or regular expressions.
+
+With optional prefix argument TODO-ONLY, only consider entries that are
+TODO entries. The argument STRING can be used to pass a default search
+string into this function. If EDIT-AT is non-nil, it means that the
+user should get a chance to edit this string, with cursor at position
+EDIT-AT.
+
+The search string can be viewed either as a phrase that should be found as
+is, or it can be broken into a number of snippets, each of which must match
+in a Boolean way to select an entry. The default depends on the variable
+`org-agenda-search-view-always-boolean'.
+Even if this is turned off (the default) you can always switch to
+Boolean search dynamically by preceding the first word with \"+\" or \"-\".
+
+The default is a direct search of the whole phrase, where each space in
+the search string can expand to an arbitrary amount of whitespace,
+including newlines.
+
+If using a Boolean search, the search string is split on whitespace and
+each snippet is searched separately, with logical AND to select an entry.
+Words prefixed with a minus must *not* occur in the entry. Words without
+a prefix or prefixed with a plus must occur in the entry. Matching is
+case-insensitive. Words are enclosed by word delimiters (i.e. they must
+match whole words, not parts of a word) if
+`org-agenda-search-view-force-full-words' is set (default is nil).
+
+Boolean search snippets enclosed by curly braces are interpreted as
+regular expressions that must or (when preceded with \"-\") must not
+match in the entry. Snippets enclosed into double quotes will be taken
+as a whole, to include whitespace.
+
+- If the search string starts with an asterisk, search only in headlines.
+- If (possibly after the leading star) the search string starts with an
+ exclamation mark, this also means to look at TODO entries only, an effect
+ that can also be achieved with a prefix argument.
+- If (possibly after star and exclamation mark) the search string starts
+ with a colon, this will mean that the (non-regexp) snippets of the
+ Boolean search must match as full words.
+
+This command searches the agenda files, and in addition the files listed
+in `org-agenda-text-search-extra-files'.
+
+\(fn &optional TODO-ONLY STRING EDIT-AT)" t nil)
+
+(autoload 'org-todo-list "org-agenda" "\
+Show all (not done) TODO entries from all agenda file in a single list.
+The prefix arg can be used to select a specific TODO keyword and limit
+the list to these. When using `\\[universal-argument]', you will be prompted
+for a keyword. A numeric prefix directly selects the Nth keyword in
+`org-todo-keywords-1'.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-tags-view "org-agenda" "\
+Show all headlines for all `org-agenda-files' matching a TAGS criterion.
+The prefix arg TODO-ONLY limits the search to TODO entries.
+
+\(fn &optional TODO-ONLY MATCH)" t nil)
+
+(autoload 'org-agenda-list-stuck-projects "org-agenda" "\
+Create agenda view for projects that are stuck.
+Stuck projects are project that have no next actions. For the definitions
+of what a project is and how to check if it stuck, customize the variable
+`org-stuck-projects'.
+
+\(fn &rest IGNORE)" t nil)
+
+(autoload 'org-diary "org-agenda" "\
+Return diary information from org files.
+This function can be used in a \"sexp\" diary entry in the Emacs calendar.
+It accesses org files and extracts information from those files to be
+listed in the diary. The function accepts arguments specifying what
+items should be listed. For a list of arguments allowed here, see the
+variable `org-agenda-entry-types'.
+
+The call in the diary file should look like this:
+
+ &%%(org-diary) ~/path/to/some/orgfile.org
+
+Use a separate line for each org file to check. Or, if you omit the file name,
+all files listed in `org-agenda-files' will be checked automatically:
+
+ &%%(org-diary)
+
+If you don't give any arguments (as in the example above), the default value
+of `org-agenda-entry-types' is used: (:deadline :scheduled :timestamp :sexp).
+So the example above may also be written as
+
+ &%%(org-diary :deadline :timestamp :sexp :scheduled)
+
+The function expects the lisp variables `entry' and `date' to be provided
+by the caller, because this is how the calendar works. Don't use this
+function from a program - use `org-agenda-get-day-entries' instead.
+
+\(fn &rest ARGS)" nil nil)
+
+(autoload 'org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item "org-agenda" "\
+Do we have a reason to ignore this TODO entry because it has a time stamp?
+
+\(fn &optional END)" nil nil)
+
+(autoload 'org-agenda-set-restriction-lock "org-agenda" "\
+Set restriction lock for agenda, to current subtree or file.
+Restriction will be the file if TYPE is `file', or if type is the
+universal prefix \\='(4), or if the cursor is before the first headline
+in the file. Otherwise, restriction will be to the current subtree.
+
+\(fn &optional TYPE)" t nil)
+
+(autoload 'org-calendar-goto-agenda "org-agenda" "\
+Compute the Org agenda for the calendar date displayed at the cursor.
+This is a command that has to be installed in `calendar-mode-map'.
+
+\(fn)" t nil)
+
+(autoload 'org-agenda-to-appt "org-agenda" "\
+Activate appointments found in `org-agenda-files'.
+
+With a `\\[universal-argument]' prefix, refresh the list of appointments.
+
+If FILTER is t, interactively prompt the user for a regular
+expression, and filter out entries that don't match it.
+
+If FILTER is a string, use this string as a regular expression
+for filtering entries out.
+
+If FILTER is a function, filter out entries against which
+calling the function returns nil. This function takes one
+argument: an entry from `org-agenda-get-day-entries'.
+
+FILTER can also be an alist with the car of each cell being
+either `headline' or `category'. For example:
+
+ \\='((headline \"IMPORTANT\")
+ (category \"Work\"))
+
+will only add headlines containing IMPORTANT or headlines
+belonging to the \"Work\" category.
+
+ARGS are symbols indicating what kind of entries to consider.
+By default `org-agenda-to-appt' will use :deadline*, :scheduled*
+\(i.e., deadlines and scheduled items with a hh:mm specification)
+and :timestamp entries. See the docstring of `org-diary' for
+details and examples.
+
+If an entry has a APPT_WARNTIME property, its value will be used
+to override `appt-message-warning-time'.
+
+\(fn &optional REFRESH FILTER &rest ARGS)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-agenda" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-archive" "org-archive.el" (0 0 0 0))
+;;; Generated autoloads from org-archive.el
+
+(autoload 'org-add-archive-files "org-archive" "\
+Splice the archive files into the list of files.
+This implies visiting all these files and finding out what the
+archive file is.
+
+\(fn FILES)" nil nil)
+
+(autoload 'org-archive-subtree "org-archive" "\
+Move the current subtree to the archive.
+The archive can be a certain top-level heading in the current
+file, or in a different file. The tree will be moved to that
+location, the subtree heading be marked DONE, and the current
+time will be added.
+
+When called with a single prefix argument FIND-DONE, find whole
+trees without any open TODO items and archive them (after getting
+confirmation from the user). When called with a double prefix
+argument, find whole trees with timestamps before today and
+archive them (after getting confirmation from the user). If the
+cursor is not at a headline when these commands are called, try
+all level 1 trees. If the cursor is on a headline, only try the
+direct children of this heading.
+
+\(fn &optional FIND-DONE)" t nil)
+
+(autoload 'org-archive-to-archive-sibling "org-archive" "\
+Archive the current heading by moving it under the archive sibling.
+
+The archive sibling is a sibling of the heading with the heading name
+`org-archive-sibling-heading' and an `org-archive-tag' tag. If this
+sibling does not exist, it will be created at the end of the subtree.
+
+Archiving time is retained in the ARCHIVE_TIME node property.
+
+\(fn)" t nil)
+
+(autoload 'org-toggle-archive-tag "org-archive" "\
+Toggle the archive tag for the current headline.
+With prefix ARG, check all children of current headline and offer tagging
+the children that do not contain any open TODO items.
+
+\(fn &optional FIND-DONE)" t nil)
+
+(autoload 'org-archive-subtree-default "org-archive" "\
+Archive the current subtree with the default command.
+This command is set with the variable `org-archive-default-command'.
+
+\(fn)" t nil)
+
+(autoload 'org-archive-subtree-default-with-confirmation "org-archive" "\
+Archive the current subtree with the default command.
+This command is set with the variable `org-archive-default-command'.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-archive" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-attach" "org-attach.el" (0 0 0 0))
+;;; Generated autoloads from org-attach.el
+
+(autoload 'org-attach "org-attach" "\
+The dispatcher for attachment commands.
+Shows a list of commands and prompts for another key to execute a command.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-attach" '("org-attach-")))
+
+;;;***
+
+;;;### (autoloads nil "org-bbdb" "org-bbdb.el" (0 0 0 0))
+;;; Generated autoloads from org-bbdb.el
+
+(autoload 'org-bbdb-anniversaries "org-bbdb" "\
+Extract anniversaries from BBDB for display in the agenda.
+
+\(fn)" nil nil)
+
+(autoload 'org-bbdb-anniversaries-future "org-bbdb" "\
+Return list of anniversaries for today and the next n-1 days (default n=7).
+
+\(fn &optional N)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-bbdb" '("org-bbdb-")))
+
+;;;***
+
+;;;### (autoloads nil "org-bibtex" "org-bibtex.el" (0 0 0 0))
+;;; Generated autoloads from org-bibtex.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-bibtex" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-capture" "org-capture.el" (0 0 0 0))
+;;; Generated autoloads from org-capture.el
+
+(autoload 'org-capture-string "org-capture" "\
+Capture STRING with the template selected by KEYS.
+
+\(fn STRING &optional KEYS)" t nil)
+
+(autoload 'org-capture "org-capture" "\
+Capture something.
+\\<org-capture-mode-map>
+This will let you select a template from `org-capture-templates', and
+then file the newly captured information. The text is immediately
+inserted at the target location, and an indirect buffer is shown where
+you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the previous
+state of Emacs, so that you can continue your work.
+
+When called interactively with a `\\[universal-argument]' prefix argument GOTO, don't
+capture anything, just go to the file/headline where the selected
+template stores its notes.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to the last note stored.
+
+When called with a `C-0' (zero) prefix, insert a template at point.
+
+ELisp programs can set KEYS to a string associated with a template
+in `org-capture-templates'. In this case, interactive selection
+will be bypassed.
+
+If `org-capture-use-agenda-date' is non-nil, capturing from the
+agenda will use the date at point as the default date. Then, a
+`C-1' prefix will tell the capture process to use the HH:MM time
+of the day at point (if any) or the current HH:MM time.
+
+\(fn &optional GOTO KEYS)" t nil)
+
+(autoload 'org-capture-import-remember-templates "org-capture" "\
+Set `org-capture-templates' to be similar to `org-remember-templates'.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-capture" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-clock" "org-clock.el" (0 0 0 0))
+;;; Generated autoloads from org-clock.el
+
+(autoload 'org-resolve-clocks "org-clock" "\
+Resolve all currently open Org clocks.
+If `only-dangling-p' is non-nil, only ask to resolve dangling
+\(i.e., not currently open and valid) clocks.
+
+\(fn &optional ONLY-DANGLING-P PROMPT-FN LAST-VALID)" t nil)
+
+(autoload 'org-clock-in "org-clock" "\
+Start the clock on the current item.
+
+If necessary, clock-out of the currently active clock.
+
+With a `\\[universal-argument]' prefix argument SELECT, offer a list of recently clocked
+tasks to clock into.
+
+When SELECT is `\\[universal-argument] \\[universal-argument]', clock into the current task and mark it as
+the default task, a special task that will always be offered in the
+clocking selection, associated with the letter `d'.
+
+When SELECT is `\\[universal-argument] \\[universal-argument] \\[universal-argument]', clock in by using the last clock-out
+time as the start time. See `org-clock-continuously' to make this
+the default behavior.
+
+\(fn &optional SELECT START-TIME)" t nil)
+
+(autoload 'org-clock-in-last "org-clock" "\
+Clock in the last closed clocked item.
+When already clocking in, send an warning.
+With a universal prefix argument, select the task you want to
+clock in from the last clocked in tasks.
+With two universal prefix arguments, start clocking using the
+last clock-out time, if any.
+With three universal prefix arguments, interactively prompt
+for a todo state to switch to, overriding the existing value
+`org-clock-in-switch-to-state'.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-clock-out "org-clock" "\
+Stop the currently running clock.
+Throw an error if there is no running clock and FAIL-QUIETLY is nil.
+With a universal prefix, prompt for a state to switch the clocked out task
+to, overriding the existing value of `org-clock-out-switch-to-state'.
+
+\(fn &optional SWITCH-TO-STATE FAIL-QUIETLY AT-TIME)" t nil)
+
+(autoload 'org-clock-cancel "org-clock" "\
+Cancel the running clock by removing the start timestamp.
+
+\(fn)" t nil)
+
+(autoload 'org-clock-goto "org-clock" "\
+Go to the currently clocked-in entry, or to the most recently clocked one.
+With prefix arg SELECT, offer recently clocked tasks for selection.
+
+\(fn &optional SELECT)" t nil)
+
+(autoload 'org-clock-sum "org-clock" "\
+Sum the times for each subtree.
+Puts the resulting times in minutes as a text property on each headline.
+TSTART and TEND can mark a time range to be considered.
+HEADLINE-FILTER is a zero-arg function that, if specified, is called for
+each headline in the time range with point at the headline. Headlines for
+which HEADLINE-FILTER returns nil are excluded from the clock summation.
+PROPNAME lets you set a custom text property instead of :org-clock-minutes.
+
+\(fn &optional TSTART TEND HEADLINE-FILTER PROPNAME)" nil nil)
+
+(autoload 'org-clock-display "org-clock" "\
+Show subtree times in the entire buffer.
+
+By default, show the total time for the range defined in
+`org-clock-display-default-range'. With `\\[universal-argument]' prefix, show
+the total time for today instead.
+
+With `\\[universal-argument] \\[universal-argument]' prefix, use a custom range, entered at prompt.
+
+With `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix, display the total time in the
+echo area.
+
+Use `\\[org-clock-remove-overlays]' to remove the subtree times.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-clock-remove-overlays "org-clock" "\
+Remove the occur highlights from the buffer.
+If NOREMOVE is nil, remove this function from the
+`before-change-functions' in the current buffer.
+
+\(fn &optional BEG END NOREMOVE)" t nil)
+
+(autoload 'org-clock-get-clocktable "org-clock" "\
+Get a formatted clocktable with parameters according to PROPS.
+The table is created in a temporary buffer, fully formatted and
+fontified, and then returned.
+
+\(fn &rest PROPS)" nil nil)
+
+(autoload 'org-clock-report "org-clock" "\
+Create a table containing a report about clocked time.
+If the cursor is inside an existing clocktable block, then the table
+will be updated. If not, a new clocktable will be inserted. The scope
+of the new clock will be subtree when called from within a subtree, and
+file elsewhere.
+
+When called with a prefix argument, move to the first clock table in the
+buffer and update it.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-clocktable-shift "org-clock" "\
+Try to shift the :block date of the clocktable at point.
+Point must be in the #+BEGIN: line of a clocktable, or this function
+will throw an error.
+DIR is a direction, a symbol `left', `right', `up', or `down'.
+Both `left' and `down' shift the block toward the past, `up' and `right'
+push it toward the future.
+N is the number of shift steps to take. The size of the step depends on
+the currently selected interval size.
+
+\(fn DIR N)" nil nil)
+
+(autoload 'org-dblock-write:clocktable "org-clock" "\
+Write the standard clocktable.
+
+\(fn PARAMS)" nil nil)
+
+(autoload 'org-clock-update-time-maybe "org-clock" "\
+If this is a CLOCK line, update it and return t.
+Otherwise, return nil.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-clock" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-colview" "org-colview.el" (0 0 0 0))
+;;; Generated autoloads from org-colview.el
+
+(autoload 'org-columns-remove-overlays "org-colview" "\
+Remove all currently active column overlays.
+
+\(fn)" t nil)
+
+(autoload 'org-columns-get-format-and-top-level "org-colview" "\
+
+
+\(fn)" nil nil)
+
+(autoload 'org-columns "org-colview" "\
+Turn on column view on an Org mode file.
+
+Column view applies to the whole buffer if point is before the
+first headline. Otherwise, it applies to the first ancestor
+setting \"COLUMNS\" property. If there is none, it defaults to
+the current headline. With a `\\[universal-argument]' prefix argument, turn on column
+view for the whole buffer unconditionally.
+
+When COLUMNS-FMT-STRING is non-nil, use it as the column format.
+
+\(fn &optional GLOBAL COLUMNS-FMT-STRING)" t nil)
+
+(autoload 'org-columns-compute "org-colview" "\
+Summarize the values of PROPERTY hierarchically.
+Also update existing values for PROPERTY according to the first
+column specification.
+
+\(fn PROPERTY)" t nil)
+
+(autoload 'org-dblock-write:columnview "org-colview" "\
+Write the column view table.
+PARAMS is a property list of parameters:
+
+:id the :ID: property of the entry where the columns view
+ should be built. When the symbol `local', call locally.
+ When `global' call column view with the cursor at the beginning
+ of the buffer (usually this means that the whole buffer switches
+ to column view). When \"file:path/to/file.org\", invoke column
+ view at the start of that file. Otherwise, the ID is located
+ using `org-id-find'.
+:hlines When t, insert a hline before each item. When a number, insert
+ a hline before each level <= that number.
+:indent When non-nil, indent each ITEM field according to its level.
+:vlines When t, make each column a colgroup to enforce vertical lines.
+:maxlevel When set to a number, don't capture headlines below this level.
+:skip-empty-rows
+ When t, skip rows where all specifiers other than ITEM are empty.
+:width apply widths specified in columns format using <N> specifiers.
+:format When non-nil, specify the column view format to use.
+
+\(fn PARAMS)" nil nil)
+
+(autoload 'org-columns-insert-dblock "org-colview" "\
+Create a dynamic block capturing a column view table.
+
+\(fn)" t nil)
+
+(autoload 'org-agenda-columns "org-colview" "\
+Turn on or update column view in the agenda.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-colview" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-compat" "org-compat.el" (0 0 0 0))
+;;; Generated autoloads from org-compat.el
+
+(autoload 'org-check-version "org-compat" "\
+Try very hard to provide sensible version strings.
+
+\(fn)" nil t)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-compat" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-crypt" "org-crypt.el" (0 0 0 0))
+;;; Generated autoloads from org-crypt.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-crypt" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-ctags" "org-ctags.el" (0 0 0 0))
+;;; Generated autoloads from org-ctags.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-ctags" '("org-ctags-")))
+
+;;;***
+
+;;;### (autoloads nil "org-datetree" "org-datetree.el" (0 0 0 0))
+;;; Generated autoloads from org-datetree.el
+
+(autoload 'org-datetree-find-date-create "org-datetree" "\
+Find or create an entry for date D.
+If KEEP-RESTRICTION is non-nil, do not widen the buffer.
+When it is nil, the buffer will be widened to make sure an existing date
+tree can be found.
+
+\(fn D &optional KEEP-RESTRICTION)" nil nil)
+
+(autoload 'org-datetree-find-iso-week-create "org-datetree" "\
+Find or create an ISO week entry for date D.
+Compared to `org-datetree-find-date-create' this function creates
+entries ordered by week instead of months.
+If KEEP-RESTRICTION is non-nil, do not widen the buffer. When it
+is nil, the buffer will be widened to make sure an existing date
+tree can be found.
+
+\(fn D &optional KEEP-RESTRICTION)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-datetree" '("org-datetree-")))
+
+;;;***
+
+;;;### (autoloads nil "org-docview" "org-docview.el" (0 0 0 0))
+;;; Generated autoloads from org-docview.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-docview" '("org-docview-")))
+
+;;;***
+
+;;;### (autoloads nil "org-element" "org-element.el" (0 0 0 0))
+;;; Generated autoloads from org-element.el
+
+(autoload 'org-element-update-syntax "org-element" "\
+Update parser internals.
+
+\(fn)" t nil)
+
+(autoload 'org-element-interpret-data "org-element" "\
+Interpret DATA as Org syntax.
+DATA is a parse tree, an element, an object or a secondary string
+to interpret. Return Org syntax as a string.
+
+\(fn DATA)" nil nil)
+
+(autoload 'org-element-cache-reset "org-element" "\
+Reset cache in current buffer.
+When optional argument ALL is non-nil, reset cache in all Org
+buffers.
+
+\(fn &optional ALL)" t nil)
+
+(autoload 'org-element-cache-refresh "org-element" "\
+Refresh cache at position POS.
+
+\(fn POS)" nil nil)
+
+(autoload 'org-element-at-point "org-element" "\
+Determine closest element around point.
+
+Return value is a list like (TYPE PROPS) where TYPE is the type
+of the element and PROPS a plist of properties associated to the
+element.
+
+Possible types are defined in `org-element-all-elements'.
+Properties depend on element or object type, but always include
+`:begin', `:end', `:parent' and `:post-blank' properties.
+
+As a special case, if point is at the very beginning of the first
+item in a list or sub-list, returned element will be that list
+instead of the item. Likewise, if point is at the beginning of
+the first row of a table, returned element will be the table
+instead of the first row.
+
+When point is at the end of the buffer, return the innermost
+element ending there.
+
+\(fn)" nil nil)
+
+(autoload 'org-element-context "org-element" "\
+Return smallest element or object around point.
+
+Return value is a list like (TYPE PROPS) where TYPE is the type
+of the element or object and PROPS a plist of properties
+associated to it.
+
+Possible types are defined in `org-element-all-elements' and
+`org-element-all-objects'. Properties depend on element or
+object type, but always include `:begin', `:end', `:parent' and
+`:post-blank'.
+
+As a special case, if point is right after an object and not at
+the beginning of any other object, return that object.
+
+Optional argument ELEMENT, when non-nil, is the closest element
+containing point, as returned by `org-element-at-point'.
+Providing it allows for quicker computation.
+
+\(fn &optional ELEMENT)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-element" '("org-element-")))
+
+;;;***
+
+;;;### (autoloads nil "org-entities" "org-entities.el" (0 0 0 0))
+;;; Generated autoloads from org-entities.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-entities" '("org-entit")))
+
+;;;***
+
+;;;### (autoloads nil "org-eshell" "org-eshell.el" (0 0 0 0))
+;;; Generated autoloads from org-eshell.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-eshell" '("org-eshell-")))
+
+;;;***
+
+;;;### (autoloads nil "org-eww" "org-eww.el" (0 0 0 0))
+;;; Generated autoloads from org-eww.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-eww" '("org-eww-")))
+
+;;;***
+
+;;;### (autoloads nil "org-faces" "org-faces.el" (0 0 0 0))
+;;; Generated autoloads from org-faces.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-faces" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-feed" "org-feed.el" (0 0 0 0))
+;;; Generated autoloads from org-feed.el
+
+(autoload 'org-feed-update-all "org-feed" "\
+Get inbox items from all feeds in `org-feed-alist'.
+
+\(fn)" t nil)
+
+(autoload 'org-feed-update "org-feed" "\
+Get inbox items from FEED.
+FEED can be a string with an association in `org-feed-alist', or
+it can be a list structured like an entry in `org-feed-alist'.
+
+\(fn FEED &optional RETRIEVE-ONLY)" t nil)
+
+(autoload 'org-feed-goto-inbox "org-feed" "\
+Go to the inbox that captures the feed named FEED.
+
+\(fn FEED)" t nil)
+
+(autoload 'org-feed-show-raw-feed "org-feed" "\
+Show the raw feed buffer of a feed.
+
+\(fn FEED)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-feed" '("org-feed-")))
+
+;;;***
+
+;;;### (autoloads nil "org-footnote" "org-footnote.el" (0 0 0 0))
+;;; Generated autoloads from org-footnote.el
+
+(autoload 'org-footnote-action "org-footnote" "\
+Do the right thing for footnotes.
+
+When at a footnote reference, jump to the definition.
+
+When at a definition, jump to the references if they exist, offer
+to create them otherwise.
+
+When neither at definition or reference, create a new footnote,
+interactively if possible.
+
+With prefix arg SPECIAL, or when no footnote can be created,
+offer additional commands in a menu.
+
+\(fn &optional SPECIAL)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-footnote" '("org-footnote-")))
+
+;;;***
+
+;;;### (autoloads nil "org-gnus" "org-gnus.el" (0 0 0 0))
+;;; Generated autoloads from org-gnus.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-gnus" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-habit" "org-habit.el" (0 0 0 0))
+;;; Generated autoloads from org-habit.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-habit" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-id" "org-id.el" (0 0 0 0))
+;;; Generated autoloads from org-id.el
+
+(autoload 'org-id-get-create "org-id" "\
+Create an ID for the current entry and return it.
+If the entry already has an ID, just return it.
+With optional argument FORCE, force the creation of a new ID.
+
+\(fn &optional FORCE)" t nil)
+
+(autoload 'org-id-copy "org-id" "\
+Copy the ID of the entry at point to the kill ring.
+Create an ID if necessary.
+
+\(fn)" t nil)
+
+(autoload 'org-id-get "org-id" "\
+Get the ID property of the entry at point-or-marker POM.
+If POM is nil, refer to the entry at point.
+If the entry does not have an ID, the function returns nil.
+However, when CREATE is non nil, create an ID if none is present already.
+PREFIX will be passed through to `org-id-new'.
+In any case, the ID of the entry is returned.
+
+\(fn &optional POM CREATE PREFIX)" nil nil)
+
+(autoload 'org-id-get-with-outline-path-completion "org-id" "\
+Use `outline-path-completion' to retrieve the ID of an entry.
+TARGETS may be a setting for `org-refile-targets' to define
+eligible headlines. When omitted, all headlines in the current
+file are eligible. This function returns the ID of the entry.
+If necessary, the ID is created.
+
+\(fn &optional TARGETS)" nil nil)
+
+(autoload 'org-id-get-with-outline-drilling "org-id" "\
+Use an outline-cycling interface to retrieve the ID of an entry.
+This only finds entries in the current buffer, using `org-get-location'.
+It returns the ID of the entry. If necessary, the ID is created.
+
+\(fn)" nil nil)
+
+(autoload 'org-id-goto "org-id" "\
+Switch to the buffer containing the entry with id ID.
+Move the cursor to that entry in that buffer.
+
+\(fn ID)" t nil)
+
+(autoload 'org-id-find "org-id" "\
+Return the location of the entry with the id ID.
+The return value is a cons cell (file-name . position), or nil
+if there is no entry with that ID.
+With optional argument MARKERP, return the position as a new marker.
+
+\(fn ID &optional MARKERP)" nil nil)
+
+(autoload 'org-id-new "org-id" "\
+Create a new globally unique ID.
+
+An ID consists of two parts separated by a colon:
+- a prefix
+- a unique part that will be created according to `org-id-method'.
+
+PREFIX can specify the prefix, the default is given by the variable
+`org-id-prefix'. However, if PREFIX is the symbol `none', don't use any
+prefix even if `org-id-prefix' specifies one.
+
+So a typical ID could look like \"Org:4nd91V40HI\".
+
+\(fn &optional PREFIX)" nil nil)
+
+(autoload 'org-id-update-id-locations "org-id" "\
+Scan relevant files for IDs.
+Store the relation between files and corresponding IDs.
+This will scan all agenda files, all associated archives, and all
+files currently mentioned in `org-id-locations'.
+When FILES is given, scan these files instead.
+
+\(fn &optional FILES SILENT)" t nil)
+
+(autoload 'org-id-find-id-file "org-id" "\
+Query the id database for the file in which this ID is located.
+
+\(fn ID)" nil nil)
+
+(autoload 'org-id-store-link "org-id" "\
+Store a link to the current entry, using its ID.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-id" '("org-id-")))
+
+;;;***
+
+;;;### (autoloads nil "org-indent" "org-indent.el" (0 0 0 0))
+;;; Generated autoloads from org-indent.el
+
+(autoload 'org-indent-mode "org-indent" "\
+When active, indent text according to outline structure.
+
+Internally this works by adding `line-prefix' and `wrap-prefix'
+properties, after each buffer modification, on the modified zone.
+
+The process is synchronous. Though, initial indentation of
+buffer, which can take a few seconds on large buffers, is done
+during idle time.
+
+\(fn &optional ARG)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-indent" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-info" "org-info.el" (0 0 0 0))
+;;; Generated autoloads from org-info.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-info" '("org-info-")))
+
+;;;***
+
+;;;### (autoloads nil "org-inlinetask" "org-inlinetask.el" (0 0 0
+;;;;;; 0))
+;;; Generated autoloads from org-inlinetask.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-inlinetask" '("org-inlinetask-")))
+
+;;;***
+
+;;;### (autoloads nil "org-irc" "org-irc.el" (0 0 0 0))
+;;; Generated autoloads from org-irc.el
+
+(autoload 'org-irc-store-link "org-irc" "\
+Dispatch to the appropriate function to store a link to an IRC session.
+
+\(fn)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-irc" '("org-irc-")))
+
+;;;***
+
+;;;### (autoloads nil "org-lint" "org-lint.el" (0 0 0 0))
+;;; Generated autoloads from org-lint.el
+
+(autoload 'org-lint "org-lint" "\
+Check current Org buffer for syntax mistakes.
+
+By default, run all checkers. With a `\\[universal-argument]' prefix ARG, select one
+category of checkers only. With a `\\[universal-argument] \\[universal-argument]' prefix, run one precise
+checker by its name.
+
+ARG can also be a list of checker names, as symbols, to run.
+
+\(fn &optional ARG)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-lint" '("org-lint-")))
+
+;;;***
+
+;;;### (autoloads nil "org-list" "org-list.el" (0 0 0 0))
+;;; Generated autoloads from org-list.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-list" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-macro" "org-macro.el" (0 0 0 0))
+;;; Generated autoloads from org-macro.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-macro" '("org-macro-")))
+
+;;;***
+
+;;;### (autoloads nil "org-macs" "org-macs.el" (0 0 0 0))
+;;; Generated autoloads from org-macs.el
+
+(autoload 'org-load-noerror-mustsuffix "org-macs" "\
+Load FILE with optional arguments NOERROR and MUSTSUFFIX.
+
+\(fn FILE)" nil t)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-macs" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-mhe" "org-mhe.el" (0 0 0 0))
+;;; Generated autoloads from org-mhe.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mhe" '("org-mhe-")))
+
+;;;***
+
+;;;### (autoloads nil "org-mobile" "org-mobile.el" (0 0 0 0))
+;;; Generated autoloads from org-mobile.el
+
+(autoload 'org-mobile-push "org-mobile" "\
+Push the current state of Org affairs to the target directory.
+This will create the index file, copy all agenda files there, and also
+create all custom agenda views, for upload to the mobile phone.
+
+\(fn)" t nil)
+
+(autoload 'org-mobile-pull "org-mobile" "\
+Pull the contents of `org-mobile-capture-file' and integrate them.
+Apply all flagged actions, flag entries to be flagged and then call an
+agenda view showing the flagged items.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mobile" '("org-mobile-")))
+
+;;;***
+
+;;;### (autoloads nil "org-mouse" "org-mouse.el" (0 0 0 0))
+;;; Generated autoloads from org-mouse.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mouse" '("org-mouse-")))
+
+;;;***
+
+;;;### (autoloads nil "org-pcomplete" "org-pcomplete.el" (0 0 0 0))
+;;; Generated autoloads from org-pcomplete.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-pcomplete" '("org-" "pcomplete/org-mode/")))
+
+;;;***
+
+;;;### (autoloads nil "org-plot" "org-plot.el" (0 0 0 0))
+;;; Generated autoloads from org-plot.el
+
+(autoload 'org-plot/gnuplot "org-plot" "\
+Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
+If not given options will be taken from the +PLOT
+line directly before or after the table.
+
+\(fn &optional PARAMS)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-plot" '("org-plot")))
+
+;;;***
+
+;;;### (autoloads nil "org-protocol" "org-protocol.el" (0 0 0 0))
+;;; Generated autoloads from org-protocol.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-protocol" '("org-protocol-")))
+
+;;;***
+
+;;;### (autoloads nil "org-rmail" "org-rmail.el" (0 0 0 0))
+;;; Generated autoloads from org-rmail.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-rmail" '("org-rmail-")))
+
+;;;***
+
+;;;### (autoloads nil "org-src" "org-src.el" (0 0 0 0))
+;;; Generated autoloads from org-src.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-src" '("org-")))
+
+;;;***
+
+;;;### (autoloads nil "org-table" "org-table.el" (0 0 0 0))
+;;; Generated autoloads from org-table.el
+
+(autoload 'org-table-create-with-table\.el "org-table" "\
+Use the table.el package to insert a new table.
+If there is already a table at point, convert between Org tables
+and table.el tables.
+
+\(fn)" t nil)
+
+(autoload 'org-table-create-or-convert-from-region "org-table" "\
+Convert region to table, or create an empty table.
+If there is an active region, convert it to a table, using the function
+`org-table-convert-region'. See the documentation of that function
+to learn how the prefix argument is interpreted to determine the field
+separator.
+If there is no such region, create an empty table with `org-table-create'.
+
+\(fn ARG)" t nil)
+
+(autoload 'org-table-create "org-table" "\
+Query for a size and insert a table skeleton.
+SIZE is a string Columns x Rows like for example \"3x2\".
+
+\(fn &optional SIZE)" t nil)
+
+(autoload 'org-table-convert-region "org-table" "\
+Convert region to a table.
+
+The region goes from BEG0 to END0, but these borders will be moved
+slightly, to make sure a beginning of line in the first line is included.
+
+SEPARATOR specifies the field separator in the lines. It can have the
+following values:
+
+\(4) Use the comma as a field separator
+\(16) Use a TAB as field separator
+\(64) Prompt for a regular expression as field separator
+integer When a number, use that many spaces, or a TAB, as field separator
+regexp When a regular expression, use it to match the separator
+nil When nil, the command tries to be smart and figure out the
+ separator in the following way:
+ - when each line contains a TAB, assume TAB-separated material
+ - when each line contains a comma, assume CSV material
+ - else, assume one or more SPACE characters as separator.
+
+\(fn BEG0 END0 &optional SEPARATOR)" t nil)
+
+(autoload 'org-table-import "org-table" "\
+Import FILE as a table.
+The file is assumed to be tab-separated. Such files can be produced by most
+spreadsheet and database applications. If no tabs (at least one per line)
+are found, lines will be split on whitespace into fields.
+
+\(fn FILE ARG)" t nil)
+
+(autoload 'org-table-export "org-table" "\
+Export table to a file, with configurable format.
+Such a file can be imported into usual spreadsheet programs.
+
+FILE can be the output file name. If not given, it will be taken
+from a TABLE_EXPORT_FILE property in the current entry or higher
+up in the hierarchy, or the user will be prompted for a file
+name. FORMAT can be an export format, of the same kind as it
+used when `orgtbl-mode' sends a table in a different format.
+
+The command suggests a format depending on TABLE_EXPORT_FORMAT,
+whether it is set locally or up in the hierarchy, then on the
+extension of the given file name, and finally on the variable
+`org-table-export-default-format'.
+
+\(fn &optional FILE FORMAT)" t nil)
+
+(autoload 'org-table-align "org-table" "\
+Align the table at point by aligning all vertical bars.
+
+\(fn)" t nil)
+
+(autoload 'org-table-begin "org-table" "\
+Find the beginning of the table and return its position.
+With a non-nil optional argument TABLE-TYPE, return the beginning
+of a table.el-type table. This function assumes point is on
+a table.
+
+\(fn &optional TABLE-TYPE)" nil nil)
+
+(autoload 'org-table-end "org-table" "\
+Find the end of the table and return its position.
+With a non-nil optional argument TABLE-TYPE, return the end of
+a table.el-type table. This function assumes point is on
+a table.
+
+\(fn &optional TABLE-TYPE)" nil nil)
+
+(autoload 'org-table-justify-field-maybe "org-table" "\
+Justify the current field, text to left, number to right.
+Optional argument NEW may specify text to replace the current field content.
+
+\(fn &optional NEW)" nil nil)
+
+(autoload 'org-table-next-field "org-table" "\
+Go to the next field in the current table, creating new lines as needed.
+Before doing so, re-align the table if necessary.
+
+\(fn)" t nil)
+
+(autoload 'org-table-previous-field "org-table" "\
+Go to the previous field in the table.
+Before doing so, re-align the table if necessary.
+
+\(fn)" t nil)
+
+(autoload 'org-table-next-row "org-table" "\
+Go to the next row (same column) in the current table.
+Before doing so, re-align the table if necessary.
+
+\(fn)" t nil)
+
+(autoload 'org-table-copy-down "org-table" "\
+Copy the value of the current field one row below.
+
+If the field at the cursor is empty, copy the content of the
+nearest non-empty field above. With argument N, use the Nth
+non-empty field.
+
+If the current field is not empty, it is copied down to the next
+row, and the cursor is moved with it. Therefore, repeating this
+command causes the column to be filled row-by-row.
+
+If the variable `org-table-copy-increment' is non-nil and the
+field is an integer or a timestamp, it will be incremented while
+copying. By default, increment by the difference between the
+value in the current field and the one in the field above. To
+increment using a fixed integer, set `org-table-copy-increment'
+to a number. In the case of a timestamp, increment by days.
+
+\(fn N)" t nil)
+
+(autoload 'org-table-blank-field "org-table" "\
+Blank the current table field or active region.
+
+\(fn)" t nil)
+
+(autoload 'org-table-field-info "org-table" "\
+Show info about the current field, and highlight any reference at point.
+
+\(fn ARG)" t nil)
+
+(autoload 'org-table-current-dline "org-table" "\
+Find out what table data line we are in.
+Only data lines count for this.
+
+\(fn)" t nil)
+
+(autoload 'org-table-goto-column "org-table" "\
+Move the cursor to the Nth column in the current table line.
+With optional argument ON-DELIM, stop with point before the left delimiter
+of the field.
+If there are less than N fields, just go to after the last delimiter.
+However, when FORCE is non-nil, create new columns if necessary.
+
+\(fn N &optional ON-DELIM FORCE)" t nil)
+
+(autoload 'org-table-insert-column "org-table" "\
+Insert a new column into the table.
+
+\(fn)" t nil)
+
+(autoload 'org-table-delete-column "org-table" "\
+Delete a column from the table.
+
+\(fn)" t nil)
+
+(autoload 'org-table-move-column-right "org-table" "\
+Move column to the right.
+
+\(fn)" t nil)
+
+(autoload 'org-table-move-column-left "org-table" "\
+Move column to the left.
+
+\(fn)" t nil)
+
+(autoload 'org-table-move-column "org-table" "\
+Move the current column to the right. With arg LEFT, move to the left.
+
+\(fn &optional LEFT)" t nil)
+
+(autoload 'org-table-move-row-down "org-table" "\
+Move table row down.
+
+\(fn)" t nil)
+
+(autoload 'org-table-move-row-up "org-table" "\
+Move table row up.
+
+\(fn)" t nil)
+
+(autoload 'org-table-move-row "org-table" "\
+Move the current table line down. With arg UP, move it up.
+
+\(fn &optional UP)" t nil)
+
+(autoload 'org-table-insert-row "org-table" "\
+Insert a new row above the current line into the table.
+With prefix ARG, insert below the current line.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-table-insert-hline "org-table" "\
+Insert a horizontal-line below the current line into the table.
+With prefix ABOVE, insert above the current line.
+
+\(fn &optional ABOVE)" t nil)
+
+(autoload 'org-table-hline-and-move "org-table" "\
+Insert a hline and move to the row below that line.
+
+\(fn &optional SAME-COLUMN)" t nil)
+
+(autoload 'org-table-kill-row "org-table" "\
+Delete the current row or horizontal line from the table.
+
+\(fn)" t nil)
+
+(autoload 'org-table-sort-lines "org-table" "\
+Sort table lines according to the column at point.
+
+The position of point indicates the column to be used for
+sorting, and the range of lines is the range between the nearest
+horizontal separator lines, or the entire table of no such lines
+exist. If point is before the first column, you will be prompted
+for the sorting column. If there is an active region, the mark
+specifies the first line and the sorting column, while point
+should be in the last line to be included into the sorting.
+
+The command then prompts for the sorting type which can be
+alphabetically, numerically, or by time (as given in a time stamp
+in the field, or as a HH:MM value). Sorting in reverse order is
+also possible.
+
+With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
+
+If SORTING-TYPE is specified when this function is called from a Lisp
+program, no prompting will take place. SORTING-TYPE must be a character,
+any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
+sorting should be done in reverse order.
+
+If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
+a function to be called to extract the key. It must return a value
+that is compatible with COMPARE-FUNC, the function used to compare
+entries.
+
+A non-nil value for INTERACTIVE? is used to signal that this
+function is being called interactively.
+
+\(fn &optional WITH-CASE SORTING-TYPE GETKEY-FUNC COMPARE-FUNC INTERACTIVE\\=\\?)" t nil)
+
+(autoload 'org-table-cut-region "org-table" "\
+Copy region in table to the clipboard and blank all relevant fields.
+If there is no active region, use just the field at point.
+
+\(fn BEG END)" t nil)
+
+(autoload 'org-table-copy-region "org-table" "\
+Copy rectangular region in table to clipboard.
+A special clipboard is used which can only be accessed
+with `org-table-paste-rectangle'.
+
+\(fn BEG END &optional CUT)" t nil)
+
+(autoload 'org-table-paste-rectangle "org-table" "\
+Paste a rectangular region into a table.
+The upper right corner ends up in the current field. All involved fields
+will be overwritten. If the rectangle does not fit into the present table,
+the table is enlarged as needed. The process ignores horizontal separator
+lines.
+
+\(fn)" t nil)
+
+(autoload 'org-table-convert "org-table" "\
+Convert from `org-mode' table to table.el and back.
+Obviously, this only works within limits. When an Org table is converted
+to table.el, all horizontal separator lines get lost, because table.el uses
+these as cell boundaries and has no notion of horizontal lines. A table.el
+table can be converted to an Org table only if it does not do row or column
+spanning. Multiline cells will become multiple cells. Beware, Org mode
+does not test if the table can be successfully converted - it blindly
+applies a recipe that works for simple tables.
+
+\(fn)" t nil)
+
+(autoload 'org-table-wrap-region "org-table" "\
+Wrap several fields in a column like a paragraph.
+This is useful if you'd like to spread the contents of a field over several
+lines, in order to keep the table compact.
+
+If there is an active region, and both point and mark are in the same column,
+the text in the column is wrapped to minimum width for the given number of
+lines. Generally, this makes the table more compact. A prefix ARG may be
+used to change the number of desired lines. For example, `C-2 \\[org-table-wrap-region]'
+formats the selected text to two lines. If the region was longer than two
+lines, the remaining lines remain empty. A negative prefix argument reduces
+the current number of lines by that amount. The wrapped text is pasted back
+into the table. If you formatted it to more lines than it was before, fields
+further down in the table get overwritten - so you might need to make space in
+the table first.
+
+If there is no region, the current field is split at the cursor position and
+the text fragment to the right of the cursor is prepended to the field one
+line down.
+
+If there is no region, but you specify a prefix ARG, the current field gets
+blank, and the content is appended to the field above.
+
+\(fn ARG)" t nil)
+
+(autoload 'org-table-edit-field "org-table" "\
+Edit table field in a different window.
+This is mainly useful for fields that contain hidden parts. When called
+with a `\\[universal-argument]' prefix, just make the full field visible so that it can be
+edited in place.
+
+\(fn ARG)" t nil)
+
+(autoload 'org-table-sum "org-table" "\
+Sum numbers in region of current table column.
+The result will be displayed in the echo area, and will be available
+as kill to be inserted with \\[yank].
+
+If there is an active region, it is interpreted as a rectangle and all
+numbers in that rectangle will be summed. If there is no active
+region and point is located in a table column, sum all numbers in that
+column.
+
+If at least one number looks like a time HH:MM or HH:MM:SS, all other
+numbers are assumed to be times as well (in decimal hours) and the
+numbers are added as such.
+
+If NLAST is a number, only the NLAST fields will actually be summed.
+
+\(fn &optional BEG END NLAST)" t nil)
+
+(autoload 'org-table-get-stored-formulas "org-table" "\
+Return an alist with the stored formulas directly after current table.
+By default, only return active formulas, i.e., formulas located
+on the first line after the table. However, if optional argument
+LOCATION is a buffer position, consider the formulas there.
+
+\(fn &optional NOERROR LOCATION)" nil nil)
+
+(autoload 'org-table-maybe-eval-formula "org-table" "\
+Check if the current field starts with \"=\" or \":=\".
+If yes, store the formula and apply it.
+
+\(fn)" nil nil)
+
+(autoload 'org-table-rotate-recalc-marks "org-table" "\
+Rotate the recalculation mark in the first column.
+If in any row, the first field is not consistent with a mark,
+insert a new column for the markers.
+When there is an active region, change all the lines in the region,
+after prompting for the marking character.
+After each change, a message will be displayed indicating the meaning
+of the new mark.
+
+\(fn &optional NEWCHAR)" t nil)
+
+(autoload 'org-table-analyze "org-table" "\
+Analyze table at point and store results.
+
+This function sets up the following dynamically scoped variables:
+
+ `org-table-column-name-regexp',
+ `org-table-column-names',
+ `org-table-current-begin-pos',
+ `org-table-current-line-types',
+ `org-table-current-ncol',
+ `org-table-dlines',
+ `org-table-hlines',
+ `org-table-local-parameters',
+ `org-table-named-field-locations'.
+
+\(fn)" nil nil)
+
+(autoload 'org-table-maybe-recalculate-line "org-table" "\
+Recompute the current line if marked for it, and if we haven't just done it.
+
+\(fn)" t nil)
+
+(autoload 'org-table-eval-formula "org-table" "\
+Replace the table field value at the cursor by the result of a calculation.
+
+In a table, this command replaces the value in the current field with the
+result of a formula. It also installs the formula as the \"current\" column
+formula, by storing it in a special line below the table. When called
+with a `\\[universal-argument]' prefix the formula is installed as a field formula.
+
+When called with a `\\[universal-argument] \\[universal-argument]' prefix, insert the active equation for the field
+back into the current field, so that it can be edited there. This is useful
+in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to check the referenced fields.
+
+When called, the command first prompts for a formula, which is read in
+the minibuffer. Previously entered formulas are available through the
+history list, and the last used formula is offered as a default.
+These stored formulas are adapted correctly when moving, inserting, or
+deleting columns with the corresponding commands.
+
+The formula can be any algebraic expression understood by the Calc package.
+For details, see the Org mode manual.
+
+This function can also be called from Lisp programs and offers
+additional arguments: EQUATION can be the formula to apply. If this
+argument is given, the user will not be prompted. SUPPRESS-ALIGN is
+used to speed-up recursive calls by by-passing unnecessary aligns.
+SUPPRESS-CONST suppresses the interpretation of constants in the
+formula, assuming that this has been done already outside the function.
+SUPPRESS-STORE means the formula should not be stored, either because
+it is already stored, or because it is a modified equation that should
+not overwrite the stored one. SUPPRESS-ANALYSIS prevents any call to
+`org-table-analyze'.
+
+\(fn &optional ARG EQUATION SUPPRESS-ALIGN SUPPRESS-CONST SUPPRESS-STORE SUPPRESS-ANALYSIS)" t nil)
+
+(autoload 'org-table-recalculate "org-table" "\
+Recalculate the current table line by applying all stored formulas.
+
+With prefix arg ALL, do this for all lines in the table.
+
+When called with a `\\[universal-argument] \\[universal-argument]' prefix, or if ALL is the symbol `iterate',
+recompute the table until it no longer changes.
+
+If NOALIGN is not nil, do not re-align the table after the computations
+are done. This is typically used internally to save time, if it is
+known that the table will be realigned a little later anyway.
+
+\(fn &optional ALL NOALIGN)" t nil)
+
+(autoload 'org-table-iterate "org-table" "\
+Recalculate the table until it does not change anymore.
+The maximum number of iterations is 10, but you can choose a different value
+with the prefix ARG.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-table-recalculate-buffer-tables "org-table" "\
+Recalculate all tables in the current buffer.
+
+\(fn)" t nil)
+
+(autoload 'org-table-iterate-buffer-tables "org-table" "\
+Iterate all tables in the buffer, to converge inter-table dependencies.
+
+\(fn)" t nil)
+
+(autoload 'org-table-edit-formulas "org-table" "\
+Edit the formulas of the current table in a separate buffer.
+
+\(fn)" t nil)
+
+(autoload 'org-table-toggle-coordinate-overlays "org-table" "\
+Toggle the display of Row/Column numbers in tables.
+
+\(fn)" t nil)
+
+(autoload 'org-table-toggle-formula-debugger "org-table" "\
+Toggle the formula debugger in tables.
+
+\(fn)" t nil)
+
+(autoload 'orgtbl-mode "org-table" "\
+The `org-mode' table editor as a minor mode for use in other modes.
+
+\(fn &optional ARG)" t nil)
+
+(defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$" "\
+Regular expression matching exponentials as produced by calc.")
+
+(autoload 'org-table-to-lisp "org-table" "\
+Convert the table at point to a Lisp structure.
+The structure will be a list. Each item is either the symbol `hline'
+for a horizontal separator line, or a list of field values as strings.
+The table is taken from the parameter TXT, or from the buffer at point.
+
+\(fn &optional TXT)" nil nil)
+
+(autoload 'orgtbl-to-generic "org-table" "\
+Convert the orgtbl-mode TABLE to some other format.
+
+This generic routine can be used for many standard cases.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that
+line. PARAMS is a property list of parameters that can
+influence the conversion.
+
+Valid parameters are:
+
+:backend, :raw
+
+ Export back-end used as a basis to transcode elements of the
+ table, when no specific parameter applies to it. It is also
+ used to translate cells contents. You can prevent this by
+ setting :raw property to a non-nil value.
+
+:splice
+
+ When non-nil, only convert rows, not the table itself. This is
+ equivalent to setting to the empty string both :tstart
+ and :tend, which see.
+
+:skip
+
+ When set to an integer N, skip the first N lines of the table.
+ Horizontal separation lines do count for this parameter!
+
+:skipcols
+
+ List of columns that should be skipped. If the table has
+ a column with calculation marks, that column is automatically
+ discarded beforehand.
+
+:hline
+
+ String to be inserted on horizontal separation lines. May be
+ nil to ignore these lines altogether.
+
+:sep
+
+ Separator between two fields, as a string.
+
+Each in the following group may be either a string or a function
+of no arguments returning a string:
+
+:tstart, :tend
+
+ Strings to start and end the table. Ignored when :splice is t.
+
+:lstart, :lend
+
+ Strings to start and end a new table line.
+
+:llstart, :llend
+
+ Strings to start and end the last table line. Default,
+ respectively, to :lstart and :lend.
+
+Each in the following group may be a string or a function of one
+argument (either the cells in the current row, as a list of
+strings, or the current cell) returning a string:
+
+:lfmt
+
+ Format string for an entire row, with enough %s to capture all
+ fields. When non-nil, :lstart, :lend, and :sep are ignored.
+
+:llfmt
+
+ Format for the entire last line, defaults to :lfmt.
+
+:fmt
+
+ A format to be used to wrap the field, should contain %s for
+ the original field value. For example, to wrap everything in
+ dollars, you could use :fmt \"$%s$\". This may also be
+ a property list with column numbers and format strings, or
+ functions, e.g.,
+
+ (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
+
+:hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
+
+ Same as above, specific for the header lines in the table.
+ All lines before the first hline are treated as header. If
+ any of these is not present, the data line value is used.
+
+This may be either a string or a function of two arguments:
+
+:efmt
+
+ Use this format to print numbers with exponential. The format
+ should have %s twice for inserting mantissa and exponent, for
+ example \"%s\\\\times10^{%s}\". This may also be a property
+ list with column numbers and format strings or functions.
+ :fmt will still be applied after :efmt.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-tsv "org-table" "\
+Convert the orgtbl-mode table to TAB separated material.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-csv "org-table" "\
+Convert the orgtbl-mode table to CSV material.
+This does take care of the proper quoting of fields with comma or quotes.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-latex "org-table" "\
+Convert the orgtbl-mode TABLE to LaTeX.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following ones:
+
+:booktabs
+
+ When non-nil, use formal \"booktabs\" style.
+
+:environment
+
+ Specify environment to use, as a string. If you use
+ \"longtable\", you may also want to specify :language property,
+ as a string, to get proper continuation strings.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-html "org-table" "\
+Convert the orgtbl-mode TABLE to HTML.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following one:
+
+:attributes
+
+ Attributes and values, as a plist, which will be used in
+ <table> tag.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-texinfo "org-table" "\
+Convert the orgtbl-mode TABLE to Texinfo.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following one:
+
+:columns
+
+ Column widths, as a string. When providing column fractions,
+ \"@columnfractions\" command can be omitted.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-to-orgtbl "org-table" "\
+Convert the orgtbl-mode TABLE into another orgtbl-mode table.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported.
+
+Useful when slicing one table into many. The :hline, :sep,
+:lstart, and :lend provide orgtbl framing. :tstart and :tend can
+be set to provide ORGTBL directives for the generated table.
+
+\(fn TABLE PARAMS)" nil nil)
+
+(autoload 'orgtbl-ascii-plot "org-table" "\
+Draw an ASCII bar plot in a column.
+
+With cursor in a column containing numerical values, this function
+will draw a plot in a new column.
+
+ASK, if given, is a numeric prefix to override the default 12
+characters width of the plot. ASK may also be the `\\[universal-argument]' prefix,
+which will prompt for the width.
+
+\(fn &optional ASK)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-table" '("org")))
+
+;;;***
+
+;;;### (autoloads nil "org-timer" "org-timer.el" (0 0 0 0))
+;;; Generated autoloads from org-timer.el
+
+(autoload 'org-timer-start "org-timer" "\
+Set the starting time for the relative timer to now.
+When called with prefix argument OFFSET, prompt the user for an offset time,
+with the default taken from a timer stamp at point, if any.
+If OFFSET is a string or an integer, it is directly taken to be the offset
+without user interaction.
+When called with a double prefix arg, all timer strings in the active
+region will be shifted by a specific amount. You will be prompted for
+the amount, with the default to make the first timer string in
+the region 0:00:00.
+
+\(fn &optional OFFSET)" t nil)
+
+(autoload 'org-timer "org-timer" "\
+Insert a H:MM:SS string from the timer into the buffer.
+The first time this command is used, the timer is started.
+
+When used with a `\\[universal-argument]' prefix, force restarting the timer.
+
+When used with a `\\[universal-argument] \\[universal-argument]' prefix, change all the timer strings
+in the region by a fixed amount. This can be used to re-calibrate
+a timer that was not started at the correct moment.
+
+If NO-INSERT is non-nil, return the string instead of inserting
+it in the buffer.
+
+\(fn &optional RESTART NO-INSERT)" t nil)
+
+(autoload 'org-timer-change-times-in-region "org-timer" "\
+Change all h:mm:ss time in region by a DELTA.
+
+\(fn BEG END DELTA)" t nil)
+
+(autoload 'org-timer-item "org-timer" "\
+Insert a description-type item with the current timer value.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-timer-set-timer "org-timer" "\
+Prompt for a duration in minutes or hh:mm:ss and set a timer.
+
+If `org-timer-default-timer' is not \"0\", suggest this value as
+the default duration for the timer. If a timer is already set,
+prompt the user if she wants to replace it.
+
+Called with a numeric prefix argument, use this numeric value as
+the duration of the timer in minutes.
+
+Called with a `C-u' prefix arguments, use `org-timer-default-timer'
+without prompting the user for a duration.
+
+With two `C-u' prefix arguments, use `org-timer-default-timer'
+without prompting the user for a duration and automatically
+replace any running timer.
+
+By default, the timer duration will be set to the number of
+minutes in the Effort property, if any. You can ignore this by
+using three `C-u' prefix arguments.
+
+\(fn &optional OPT)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-timer" '("org-timer-")))
+
+;;;***
+
+;;;### (autoloads nil "org-version" "org-version.el" (0 0 0 0))
+;;; Generated autoloads from org-version.el
+
+(autoload 'org-release "org-version" "\
+The release version of Org.
+Inserted by installing Org mode or when a release is made.
+
+\(fn)" nil nil)
+
+(autoload 'org-git-version "org-version" "\
+The Git version of org-mode.
+Inserted by installing Org or when a release is made.
+
+\(fn)" nil nil)
+
+(defvar org-odt-data-dir "/usr/share/emacs/etc/org" "\
+The location of ODT styles.")
+
+;;;***
+
+;;;### (autoloads nil "org-w3m" "org-w3m.el" (0 0 0 0))
+;;; Generated autoloads from org-w3m.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-w3m" '("org-w3m-")))
+
+;;;***
+
+;;;### (autoloads nil "org" "org.el" (0 0 0 0))
+;;; Generated autoloads from org.el
+
+(autoload 'org-babel-do-load-languages "org" "\
+Load the languages defined in `org-babel-load-languages'.
+
+\(fn SYM VALUE)" nil nil)
+
+(autoload 'org-babel-load-file "org" "\
+Load Emacs Lisp source code blocks in the Org FILE.
+This function exports the source code using `org-babel-tangle'
+and then loads the resulting file using `load-file'. With prefix
+arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
+file to byte-code before it is loaded.
+
+\(fn FILE &optional COMPILE)" t nil)
+
+(autoload 'org-version "org" "\
+Show the Org version.
+Interactively, or when MESSAGE is non-nil, show it in echo area.
+With prefix argument, or when HERE is non-nil, insert it at point.
+In non-interactive uses, a reduced version string is output unless
+FULL is given.
+
+\(fn &optional HERE FULL MESSAGE)" t nil)
+
+(autoload 'turn-on-orgtbl "org" "\
+Unconditionally turn on `orgtbl-mode'.
+
+\(fn)" nil nil)
+
+(autoload 'org-clock-persistence-insinuate "org" "\
+Set up hooks for clock persistence.
+
+\(fn)" nil nil)
+
+(autoload 'org-mode "org" "\
+Outline-based notes management and organizer, alias
+\"Carsten's outline-mode for keeping track of everything.\"
+
+Org mode develops organizational tasks around a NOTES file which
+contains information about projects as plain text. Org mode is
+implemented on top of Outline mode, which is ideal to keep the content
+of large files well structured. It supports ToDo items, deadlines and
+time stamps, which magically appear in the diary listing of the Emacs
+calendar. Tables are easily created with a built-in table editor.
+Plain text URL-like links connect to websites, emails (VM), Usenet
+messages (Gnus), BBDB entries, and any files related to the project.
+For printing and sharing of notes, an Org file (or a part of it)
+can be exported as a structured ASCII or HTML file.
+
+The following commands are available:
+
+\\{org-mode-map}
+
+\(fn)" t nil)
+
+(autoload 'org-cycle "org" "\
+TAB-action and visibility cycling for Org mode.
+
+This is the command invoked in Org mode by the `TAB' key. Its main
+purpose is outline visibility cycling, but it also invokes other actions
+in special contexts.
+
+When this function is called with a `\\[universal-argument]' prefix, rotate the entire
+buffer through 3 states (global cycling)
+ 1. OVERVIEW: Show only top-level headlines.
+ 2. CONTENTS: Show all headlines of all levels, but no body text.
+ 3. SHOW ALL: Show everything.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix argument, switch to the startup visibility,
+determined by the variable `org-startup-folded', and by any VISIBILITY
+properties in the buffer.
+
+With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix argument, show the entire buffer, including
+any drawers.
+
+When inside a table, re-align the table and move to the next field.
+
+When point is at the beginning of a headline, rotate the subtree started
+by this line through 3 different states (local cycling)
+ 1. FOLDED: Only the main headline is shown.
+ 2. CHILDREN: The main headline and the direct children are shown.
+ From this state, you can move to one of the children
+ and zoom in further.
+ 3. SUBTREE: Show the entire subtree, including body text.
+If there is no subtree, switch directly from CHILDREN to FOLDED.
+
+When point is at the beginning of an empty headline and the variable
+`org-cycle-level-after-item/entry-creation' is set, cycle the level
+of the headline by demoting and promoting it to likely levels. This
+speeds up creation document structure by pressing `TAB' once or several
+times right after creating a new headline.
+
+When there is a numeric prefix, go up to a heading with level ARG, do
+a `show-subtree' and return to the previous cursor position. If ARG
+is negative, go up that many levels.
+
+When point is not at the beginning of a headline, execute the global
+binding for `TAB', which is re-indenting the line. See the option
+`org-cycle-emulate-tab' for details.
+
+As a special case, if point is at the beginning of the buffer and there is
+no headline in line 1, this function will act as if called with prefix arg
+\(`\\[universal-argument] TAB', same as `S-TAB') also when called without prefix arg, but only
+if the variable `org-cycle-global-at-bob' is t.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-global-cycle "org" "\
+Cycle the global visibility. For details see `org-cycle'.
+With `\\[universal-argument]' prefix ARG, switch to startup visibility.
+With a numeric prefix, show all headlines up to that level.
+
+\(fn &optional ARG)" t nil)
+(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
+
+(autoload 'orgstruct-mode "org" "\
+Toggle the minor mode `orgstruct-mode'.
+This mode is for using Org mode structure commands in other
+modes. The following keys behave as if Org mode were active, if
+the cursor is on a headline, or on a plain list item (both as
+defined by Org mode).
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'turn-on-orgstruct "org" "\
+Unconditionally turn on `orgstruct-mode'.
+
+\(fn)" nil nil)
+
+(autoload 'turn-on-orgstruct++ "org" "\
+Unconditionally turn on `orgstruct++-mode'.
+
+\(fn)" nil nil)
+
+(autoload 'org-run-like-in-org-mode "org" "\
+Run a command, pretending that the current buffer is in Org mode.
+This will temporarily bind local variables that are typically bound in
+Org mode to the values they have in Org mode, and then interactively
+call CMD.
+
+\(fn CMD)" nil nil)
+
+(autoload 'org-store-link "org" "\
+Store an org-link to the current location.
+\\<org-mode-map>
+This link is added to `org-stored-links' and can later be inserted
+into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
+
+For some link types, a `\\[universal-argument]' prefix ARG is interpreted. A single
+`\\[universal-argument]' negates `org-context-in-file-links' for file links or
+`org-gnus-prefer-web-links' for links to Usenet articles.
+
+A `\\[universal-argument] \\[universal-argument]' prefix ARG forces skipping storing functions that are not
+part of Org core.
+
+A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix ARG forces storing a link for each line in the
+active region.
+
+\(fn ARG)" t nil)
+
+(autoload 'org-insert-link-global "org" "\
+Insert a link like Org mode does.
+This command can be called in any mode to insert a link in Org syntax.
+
+\(fn)" t nil)
+
+(autoload 'org-open-at-point-global "org" "\
+Follow a link or time-stamp like Org mode does.
+This command can be called in any mode to follow an external link
+or a time-stamp that has Org mode syntax. Its behavior is
+undefined when called on internal links (e.g., fuzzy links).
+Raise an error when there is nothing to follow.
+
+\(fn)" t nil)
+
+(autoload 'org-open-link-from-string "org" "\
+Open a link in the string S, as if it was in Org mode.
+
+\(fn S &optional ARG REFERENCE-BUFFER)" t nil)
+
+(autoload 'org-switchb "org" "\
+Switch between Org buffers.
+
+With `\\[universal-argument]' prefix, restrict available buffers to files.
+
+With `\\[universal-argument] \\[universal-argument]' prefix, restrict available buffers to agenda files.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-cycle-agenda-files "org" "\
+Cycle through the files in `org-agenda-files'.
+If the current buffer visits an agenda file, find the next one in the list.
+If the current buffer does not, find the first agenda file.
+
+\(fn)" t nil)
+
+(autoload 'org-submit-bug-report "org" "\
+Submit a bug report on Org via mail.
+
+Don't hesitate to report any problems or inaccurate documentation.
+
+If you don't have setup sending mail from (X)Emacs, please copy the
+output buffer into your mail program, as it gives us important
+information about your Org version and configuration.
+
+\(fn)" t nil)
+
+(autoload 'org-reload "org" "\
+Reload all org lisp files.
+With prefix arg UNCOMPILED, load the uncompiled versions.
+
+\(fn &optional UNCOMPILED)" t nil)
+
+(autoload 'org-customize "org" "\
+Call the customize function with org as argument.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org" '("org" "turn-on-org-cdlatex")))
+
+;;;***
+
+;;;### (autoloads nil "ox-ascii" "ox-ascii.el" (0 0 0 0))
+;;; Generated autoloads from ox-ascii.el
+
+(autoload 'org-ascii-export-as-ascii "ox-ascii" "\
+Export current buffer to a text buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip title and
+table of contents from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org ASCII Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-ascii-export-to-ascii "ox-ascii" "\
+Export current buffer to a text file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip title and
+table of contents from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-ascii-publish-to-ascii "ox-ascii" "\
+Publish an Org file to ASCII.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(autoload 'org-ascii-publish-to-latin1 "ox-ascii" "\
+Publish an Org file to Latin-1.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(autoload 'org-ascii-publish-to-utf8 "ox-ascii" "\
+Publish an org file to UTF-8.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-ascii" '("org-ascii-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-beamer" "ox-beamer.el" (0 0 0 0))
+;;; Generated autoloads from ox-beamer.el
+
+(autoload 'org-beamer-mode "ox-beamer" "\
+Support for editing Beamer oriented Org mode files.
+
+\(fn &optional ARG)" t nil)
+
+(autoload 'org-beamer-export-as-latex "ox-beamer" "\
+Export current buffer as a Beamer buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org BEAMER Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-beamer-export-to-latex "ox-beamer" "\
+Export current buffer as a Beamer presentation (tex).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-beamer-export-to-pdf "ox-beamer" "\
+Export current buffer as a Beamer presentation (PDF).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-beamer-select-environment "ox-beamer" "\
+Select the environment to be used by beamer for this entry.
+While this uses (for convenience) a tag selection interface, the
+result of this command will be that the BEAMER_env *property* of
+the entry is set.
+
+In addition to this, the command will also set a tag as a visual
+aid, but the tag does not have any semantic meaning.
+
+\(fn)" t nil)
+
+(autoload 'org-beamer-publish-to-latex "ox-beamer" "\
+Publish an Org file to a Beamer presentation (LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(autoload 'org-beamer-publish-to-pdf "ox-beamer" "\
+Publish an Org file to a Beamer presentation (PDF, via LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-beamer" '("org-beamer-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-html" "ox-html.el" (0 0 0 0))
+;;; Generated autoloads from ox-html.el
+
+(put 'org-html-head-include-default-style 'safe-local-variable 'booleanp)
+
+(put 'org-html-head 'safe-local-variable 'stringp)
+
+(put 'org-html-head-extra 'safe-local-variable 'stringp)
+
+(autoload 'org-html-htmlize-generate-css "ox-html" "\
+Create the CSS for all font definitions in the current Emacs session.
+Use this to create face definitions in your CSS style file that can then
+be used by code snippets transformed by htmlize.
+This command just produces a buffer that contains class definitions for all
+faces used in the current Emacs session. You can copy and paste the ones you
+need into your CSS file.
+
+If you then set `org-html-htmlize-output-type' to `css', calls
+to the function `org-html-htmlize-region-for-paste' will
+produce code that uses these same face definitions.
+
+\(fn)" t nil)
+
+(autoload 'org-html-export-as-html "ox-html" "\
+Export current buffer to an HTML buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org HTML Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-html-convert-region-to-html "ox-html" "\
+Assume the current region has Org syntax, and convert it to HTML.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an HTML buffer and use this command
+to convert it.
+
+\(fn)" t nil)
+
+(autoload 'org-html-export-to-html "ox-html" "\
+Export current buffer to a HTML file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-html-publish-to-html "ox-html" "\
+Publish an org file to HTML.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-html" '("org-html-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-icalendar" "ox-icalendar.el" (0 0 0 0))
+;;; Generated autoloads from ox-icalendar.el
+
+(autoload 'org-icalendar-export-to-ics "ox-icalendar" "\
+Export current buffer to an iCalendar file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
+
+Return ICS file name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY)" t nil)
+
+(autoload 'org-icalendar-export-agenda-files "ox-icalendar" "\
+Export all agenda files to iCalendar files.
+When optional argument ASYNC is non-nil, export happens in an
+external process.
+
+\(fn &optional ASYNC)" t nil)
+
+(autoload 'org-icalendar-combine-agenda-files "ox-icalendar" "\
+Combine all agenda files into a single iCalendar file.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+The file is stored under the name chosen in
+`org-icalendar-combined-agenda-file'.
+
+\(fn &optional ASYNC)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-icalendar" '("org-icalendar-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-latex" "ox-latex.el" (0 0 0 0))
+;;; Generated autoloads from ox-latex.el
+
+(autoload 'org-latex-make-preamble "ox-latex" "\
+Return a formatted LaTeX preamble.
+INFO is a plist used as a communication channel. Optional
+argument TEMPLATE, when non-nil, is the header template string,
+as expected by `org-splice-latex-header'. When SNIPPET? is
+non-nil, only includes packages relevant to image generation, as
+specified in `org-latex-default-packages-alist' or
+`org-latex-packages-alist'.
+
+\(fn INFO &optional TEMPLATE SNIPPET\\=\\?)" nil nil)
+
+(autoload 'org-latex-export-as-latex "ox-latex" "\
+Export current buffer as a LaTeX buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org LATEX Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-latex-convert-region-to-latex "ox-latex" "\
+Assume the current region has Org syntax, and convert it to LaTeX.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an LaTeX buffer and use this
+command to convert it.
+
+\(fn)" t nil)
+
+(autoload 'org-latex-export-to-latex "ox-latex" "\
+Export current buffer to a LaTeX file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-latex-export-to-pdf "ox-latex" "\
+Export current buffer to LaTeX then process through to PDF.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-latex-publish-to-latex "ox-latex" "\
+Publish an Org file to LaTeX.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(autoload 'org-latex-publish-to-pdf "ox-latex" "\
+Publish an Org file to PDF (via LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-latex" '("org-latex-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-man" "ox-man.el" (0 0 0 0))
+;;; Generated autoloads from ox-man.el
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-man" '("org-man-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-md" "ox-md.el" (0 0 0 0))
+;;; Generated autoloads from ox-md.el
+
+(autoload 'org-md-export-as-markdown "ox-md" "\
+Export current buffer to a Markdown buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Export is done in a buffer named \"*Org MD Export*\", which will
+be displayed when `org-export-show-temporary-export-buffer' is
+non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY)" t nil)
+
+(autoload 'org-md-convert-region-to-md "ox-md" "\
+Assume the current region has Org syntax, and convert it to Markdown.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in a Markdown buffer and use
+this command to convert it.
+
+\(fn)" t nil)
+
+(autoload 'org-md-export-to-markdown "ox-md" "\
+Export current buffer to a Markdown file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Return output file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY)" t nil)
+
+(autoload 'org-md-publish-to-md "ox-md" "\
+Publish an org file to Markdown.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-md" '("org-md-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-odt" "ox-odt.el" (0 0 0 0))
+;;; Generated autoloads from ox-odt.el
+
+(put 'org-odt-preferred-output-format 'safe-local-variable 'stringp)
+
+(autoload 'org-odt-export-as-odf "ox-odt" "\
+Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
+Use `org-create-math-formula' to convert LATEX-FRAG first to
+MathML. When invoked as an interactive command, use
+`org-latex-regexps' to infer LATEX-FRAG from currently active
+region. If no LaTeX fragments are found, prompt for it. Push
+MathML source to kill ring depending on the value of
+`org-export-copy-to-kill-ring'.
+
+\(fn LATEX-FRAG &optional ODF-FILE)" t nil)
+
+(autoload 'org-odt-export-as-odf-and-open "ox-odt" "\
+Export LaTeX fragment as OpenDocument formula and immediately open it.
+Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
+formula file.
+
+\(fn)" t nil)
+
+(autoload 'org-odt-export-to-odt "ox-odt" "\
+Export current buffer to a ODT file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-odt-convert "ox-odt" "\
+Convert IN-FILE to format OUT-FMT using a command line converter.
+IN-FILE is the file to be converted. If unspecified, it defaults
+to variable `buffer-file-name'. OUT-FMT is the desired output
+format. Use `org-odt-convert-process' as the converter. If OPEN
+is non-nil then the newly converted file is opened using
+`org-open-file'.
+
+\(fn &optional IN-FILE OUT-FMT OPEN)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-odt" '("org-odt-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-org" "ox-org.el" (0 0 0 0))
+;;; Generated autoloads from ox-org.el
+
+(autoload 'org-org-export-as-org "ox-org" "\
+Export current buffer to an Org buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip document
+keywords from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org ORG Export*\", which will
+be displayed when `org-export-show-temporary-export-buffer' is
+non-nil.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-org-export-to-org "ox-org" "\
+Export current buffer to an org file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip document
+keywords from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file name.
+
+\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil)
+
+(autoload 'org-org-publish-to-org "ox-org" "\
+Publish an org file to org.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-org" '("org-org-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-publish" "ox-publish.el" (0 0 0 0))
+;;; Generated autoloads from ox-publish.el
+
+(defalias 'org-publish-project 'org-publish)
+
+(autoload 'org-publish "ox-publish" "\
+Publish PROJECT.
+
+PROJECT is either a project name, as a string, or a project
+alist (see `org-publish-project-alist' variable).
+
+When optional argument FORCE is non-nil, force publishing all
+files in PROJECT. With a non-nil optional argument ASYNC,
+publishing will be done asynchronously, in another process.
+
+\(fn PROJECT &optional FORCE ASYNC)" t nil)
+
+(autoload 'org-publish-all "ox-publish" "\
+Publish all projects.
+With prefix argument FORCE, remove all files in the timestamp
+directory and force publishing all projects. With a non-nil
+optional argument ASYNC, publishing will be done asynchronously,
+in another process.
+
+\(fn &optional FORCE ASYNC)" t nil)
+
+(autoload 'org-publish-current-file "ox-publish" "\
+Publish the current file.
+With prefix argument FORCE, force publish the file. When
+optional argument ASYNC is non-nil, publishing will be done
+asynchronously, in another process.
+
+\(fn &optional FORCE ASYNC)" t nil)
+
+(autoload 'org-publish-current-project "ox-publish" "\
+Publish the project associated with the current file.
+With a prefix argument, force publishing of all files in
+the project.
+
+\(fn &optional FORCE ASYNC)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-publish" '("org-publish-")))
+
+;;;***
+
+;;;### (autoloads nil "ox-texinfo" "ox-texinfo.el" (0 0 0 0))
+;;; Generated autoloads from ox-texinfo.el
+
+(autoload 'org-texinfo-publish-to-texinfo "ox-texinfo" "\
+Publish an org file to Texinfo.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name.
+
+\(fn PLIST FILENAME PUB-DIR)" nil nil)
+
+(autoload 'org-texinfo-convert-region-to-texinfo "ox-texinfo" "\
+Assume the current region has Org syntax, and convert it to Texinfo.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an Texinfo buffer and use this
+command to convert it.
+
+\(fn)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-texinfo" '("org-texinfo-")))
+
+;;;***
+
+;;;### (autoloads nil "ox" "ox.el" (0 0 0 0))
+;;; Generated autoloads from ox.el
+
+(autoload 'org-export-get-backend "ox" "\
+Return export back-end named after NAME.
+NAME is a symbol. Return nil if no such back-end is found.
+
+\(fn NAME)" nil nil)
+
+(autoload 'org-export-get-environment "ox" "\
+Collect export options from the current buffer.
+
+Optional argument BACKEND is an export back-end, as returned by
+`org-export-create-backend'.
+
+When optional argument SUBTREEP is non-nil, assume the export is
+done against the current sub-tree.
+
+Third optional argument EXT-PLIST is a property list with
+external parameters overriding Org default settings, but still
+inferior to file-local settings.
+
+\(fn &optional BACKEND SUBTREEP EXT-PLIST)" nil nil)
+
+(autoload 'org-export-as "ox" "\
+Transcode current Org buffer into BACKEND code.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+If narrowing is active in the current buffer, only transcode its
+narrowed part.
+
+If a region is active, transcode that region.
+
+When optional argument SUBTREEP is non-nil, transcode the
+sub-tree at point, extracting information from the headline
+properties first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only return body
+code, without surrounding template.
+
+Optional argument EXT-PLIST, when provided, is a property list
+with external parameters overriding Org default settings, but
+still inferior to file-local settings.
+
+Return code as a string.
+
+\(fn BACKEND &optional SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" nil nil)
+
+(autoload 'org-export-string-as "ox" "\
+Transcode STRING into BACKEND code.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+When optional argument BODY-ONLY is non-nil, only return body
+code, without preamble nor postamble.
+
+Optional argument EXT-PLIST, when provided, is a property list
+with external parameters overriding Org default settings, but
+still inferior to file-local settings.
+
+Return code as a string.
+
+\(fn STRING BACKEND &optional BODY-ONLY EXT-PLIST)" nil nil)
+
+(autoload 'org-export-replace-region-by "ox" "\
+Replace the active region by its export to BACKEND.
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+\(fn BACKEND)" nil nil)
+
+(autoload 'org-export-insert-default-template "ox" "\
+Insert all export keywords with default values at beginning of line.
+
+BACKEND is a symbol referring to the name of a registered export
+back-end, for which specific export options should be added to
+the template, or `default' for default template. When it is nil,
+the user will be prompted for a category.
+
+If SUBTREEP is non-nil, export configuration will be set up
+locally for the subtree through node properties.
+
+\(fn &optional BACKEND SUBTREEP)" t nil)
+
+(autoload 'org-export-to-buffer "ox" "\
+Call `org-export-as' with output to a specified buffer.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+BUFFER is the name of the output buffer. If it already exists,
+it will be erased first, otherwise, it will be created.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should then be accessible
+through the `org-export-stack' interface. When ASYNC is nil, the
+buffer is displayed if `org-export-show-temporary-export-buffer'
+is non-nil.
+
+Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
+EXT-PLIST are similar to those used in `org-export-as', which
+see.
+
+Optional argument POST-PROCESS is a function which should accept
+no argument. It is always called within the current process,
+from BUFFER, with point at its beginning. Export back-ends can
+use it to set a major mode there, e.g,
+
+ (defun org-latex-export-as-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ (interactive)
+ (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
+ async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
+
+This function returns BUFFER.
+
+\(fn BACKEND BUFFER &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil)
+
+(function-put 'org-export-to-buffer 'lisp-indent-function '2)
+
+(autoload 'org-export-to-file "ox" "\
+Call `org-export-as' with output to a specified file.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end. FILE is the name of the output file, as
+a string.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer will then be accessible
+through the `org-export-stack' interface.
+
+Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
+EXT-PLIST are similar to those used in `org-export-as', which
+see.
+
+Optional argument POST-PROCESS is called with FILE as its
+argument and happens asynchronously when ASYNC is non-nil. It
+has to return a file name, or nil. Export back-ends can use this
+to send the output file through additional processing, e.g,
+
+ (defun org-latex-export-to-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ (interactive)
+ (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
+ (org-export-to-file \\='latex outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))
+
+The function returns either a file name returned by POST-PROCESS,
+or FILE.
+
+\(fn BACKEND FILE &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil)
+
+(function-put 'org-export-to-file 'lisp-indent-function '2)
+
+(autoload 'org-export-dispatch "ox" "\
+Export dispatcher for Org mode.
+
+It provides an access to common export related tasks in a buffer.
+Its interface comes in two flavors: standard and expert.
+
+While both share the same set of bindings, only the former
+displays the valid keys associations in a dedicated buffer.
+Scrolling (resp. line-wise motion) in this buffer is done with
+SPC and DEL (resp. C-n and C-p) keys.
+
+Set variable `org-export-dispatch-use-expert-ui' to switch to one
+flavor or the other.
+
+When ARG is `\\[universal-argument]', repeat the last export action, with the same
+set of options used back then, on the current buffer.
+
+When ARG is `\\[universal-argument] \\[universal-argument]', display the asynchronous export stack.
+
+\(fn &optional ARG)" t nil)
+
+(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox" '("org-export-")))
+
+;;;***
+
+(provide 'org-loaddefs)
+
+;; Local Variables:
+;; version-control: never
+;; no-byte-compile: t
+;; no-update-autoloads: t
+;; coding: utf-8
+;; End:
+;;; org-loaddefs.el ends here
diff --git a/lisp/org-macro.el b/lisp/org-macro.el
new file mode 100644
index 0000000..3dc9c54
--- /dev/null
+++ b/lisp/org-macro.el
@@ -0,0 +1,307 @@
+;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Macros are expanded with `org-macro-replace-all', which relies
+;; internally on `org-macro-expand'.
+
+;; Default templates for expansion are stored in the buffer-local
+;; variable `org-macro-templates'. This variable is updated by
+;; `org-macro-initialize-templates', which recursively calls
+;; `org-macro--collect-macros' in order to read setup files.
+
+;; Argument in macros are separated with commas. Proper escaping rules
+;; are implemented in `org-macro-escape-arguments' and arguments can
+;; be extracted from a string with `org-macro-extract-arguments'.
+
+;; Along with macros defined through #+MACRO: keyword, default
+;; templates include the following hard-coded macros:
+;; {{{time(format-string)}}}, {{{property(node-property)}}},
+;; {{{input-file}}} and {{{modification-time(format-string)}}}.
+
+;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
+;; {{{email}}} and {{{title}}} macros.
+
+;;; Code:
+(require 'cl-lib)
+(require 'org-macs)
+(require 'org-compat)
+
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-macro-parser "org-element" ())
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-file-contents "org" (file &optional noerror))
+(declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
+(declare-function org-mode "org" ())
+(declare-function vc-backend "vc-hooks" (f))
+(declare-function vc-call "vc-hooks" (fun file &rest args) t)
+(declare-function vc-exec-after "vc-dispatcher" (code))
+
+;;; Variables
+
+(defvar-local org-macro-templates nil
+ "Alist containing all macro templates in current buffer.
+Associations are in the shape of (NAME . TEMPLATE) where NAME
+stands for macro's name and template for its replacement value,
+both as strings. This is an internal variable. Do not set it
+directly, use instead:
+
+ #+MACRO: name template")
+
+;;; Functions
+
+(defun org-macro--collect-macros ()
+ "Collect macro definitions in current buffer and setup files.
+Return an alist containing all macro templates found."
+ (letrec ((collect-macros
+ (lambda (files templates)
+ ;; Return an alist of macro templates. FILES is a list
+ ;; of setup files names read so far, used to avoid
+ ;; circular dependencies. TEMPLATES is the alist
+ ;; collected so far.
+ (let ((case-fold-search t))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward
+ "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (let ((val (org-element-property :value element)))
+ (if (equal (org-element-property :key element) "MACRO")
+ ;; Install macro in TEMPLATES.
+ (when (string-match
+ "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
+ (let* ((name (match-string 1 val))
+ (template (or (match-string 2 val) ""))
+ (old-cell (assoc name templates)))
+ (if old-cell (setcdr old-cell template)
+ (push (cons name template) templates))))
+ ;; Enter setup file.
+ (let ((file (expand-file-name
+ (org-unbracket-string "\"" "\"" val))))
+ (unless (member file files)
+ (with-temp-buffer
+ (setq default-directory
+ (file-name-directory file))
+ (org-mode)
+ (insert (org-file-contents file 'noerror))
+ (setq templates
+ (funcall collect-macros (cons file files)
+ templates)))))))))))
+ templates))))
+ (funcall collect-macros nil nil)))
+
+(defun org-macro-initialize-templates ()
+ "Collect macro templates defined in current buffer.
+Templates are stored in buffer-local variable
+`org-macro-templates'. In addition to buffer-defined macros, the
+function installs the following ones: \"property\",
+\"time\". and, if the buffer is associated to a file,
+\"input-file\" and \"modification-time\"."
+ (let* ((templates (org-macro--collect-macros))
+ (update-templates
+ (lambda (cell)
+ (let ((old-template (assoc (car cell) templates)))
+ (if old-template (setcdr old-template (cdr cell))
+ (push cell templates))))))
+ ;; Install hard-coded macros.
+ (mapc update-templates
+ (list (cons "property"
+ "(eval (save-excursion
+ (let ((l \"$2\"))
+ (when (org-string-nw-p l)
+ (condition-case _
+ (let ((org-link-search-must-match-exact-headline t))
+ (org-link-search l nil t))
+ (error
+ (error \"Macro property failed: cannot find location %s\"
+ l)))))
+ (org-entry-get nil \"$1\" 'selective)))")
+ (cons "time" "(eval (format-time-string \"$1\"))")))
+ (let ((visited-file (buffer-file-name (buffer-base-buffer))))
+ (when (and visited-file (file-exists-p visited-file))
+ (mapc update-templates
+ (list (cons "input-file" (file-name-nondirectory visited-file))
+ (cons "modification-time"
+ (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
+ (prin1-to-string visited-file)
+ (prin1-to-string
+ (nth 5 (file-attributes visited-file)))))))))
+ (setq org-macro-templates templates)))
+
+(defun org-macro-expand (macro templates)
+ "Return expanded MACRO, as a string.
+MACRO is an object, obtained, for example, with
+`org-element-context'. TEMPLATES is an alist of templates used
+for expansion. See `org-macro-templates' for a buffer-local
+default value. Return nil if no template was found."
+ (let ((template
+ ;; Macro names are case-insensitive.
+ (cdr (assoc-string (org-element-property :key macro) templates t))))
+ (when template
+ (let ((value (replace-regexp-in-string
+ "\\$[0-9]+"
+ (lambda (arg)
+ (or (nth (1- (string-to-number (substring arg 1)))
+ (org-element-property :args macro))
+ ;; No argument: remove place-holder.
+ ""))
+ template nil 'literal)))
+ ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
+ (when (string-match "\\`(eval\\>" value)
+ (setq value (eval (read value))))
+ ;; Return string.
+ (format "%s" (or value ""))))))
+
+(defun org-macro-replace-all (templates &optional finalize keywords)
+ "Replace all macros in current buffer by their expansion.
+
+TEMPLATES is an alist of templates used for expansion. See
+`org-macro-templates' for a buffer-local default value.
+
+If optional arg FINALIZE is non-nil, raise an error if a macro is
+found in the buffer with no definition in TEMPLATES.
+
+Optional argument KEYWORDS, when non-nil is a list of keywords,
+as strings, where macro expansion is allowed."
+ (save-excursion
+ (goto-char (point-min))
+ (let ((properties-regexp
+ (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
+ record)
+ (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
+ (unless (save-match-data (org-in-commented-heading-p))
+ (let* ((datum (save-match-data (org-element-context)))
+ (type (org-element-type datum))
+ (macro
+ (cond
+ ((eq type 'macro) datum)
+ ;; In parsed keywords and associated node
+ ;; properties, force macro recognition.
+ ((or (and (eq type 'keyword)
+ (member (org-element-property :key datum)
+ keywords))
+ (and (eq type 'node-property)
+ (string-match-p properties-regexp
+ (org-element-property :key
+ datum))))
+ (save-excursion
+ (goto-char (match-beginning 0))
+ (org-element-macro-parser))))))
+ (when macro
+ (let* ((value (org-macro-expand macro templates))
+ (begin (org-element-property :begin macro))
+ (signature (list begin
+ macro
+ (org-element-property :args macro))))
+ ;; Avoid circular dependencies by checking if the same
+ ;; macro with the same arguments is expanded at the
+ ;; same position twice.
+ (cond ((member signature record)
+ (error "Circular macro expansion: %s"
+ (org-element-property :key macro)))
+ (value
+ (push signature record)
+ (delete-region
+ begin
+ ;; Preserve white spaces after the macro.
+ (progn (goto-char (org-element-property :end macro))
+ (skip-chars-backward " \t")
+ (point)))
+ ;; Leave point before replacement in case of
+ ;; recursive expansions.
+ (save-excursion (insert value)))
+ (finalize
+ (error "Undefined Org macro: %s; aborting"
+ (org-element-property :key macro))))))))))))
+
+(defun org-macro-escape-arguments (&rest args)
+ "Build macro's arguments string from ARGS.
+ARGS are strings. Return value is a string with arguments
+properly escaped and separated with commas. This is the opposite
+of `org-macro-extract-arguments'."
+ (let ((s ""))
+ (dolist (arg (reverse args) (substring s 1))
+ (setq s
+ (concat
+ ","
+ (replace-regexp-in-string
+ "\\(\\\\*\\),"
+ (lambda (m)
+ (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
+ ","))
+ ;; If a non-terminal argument ends on backslashes, make
+ ;; sure to also escape them as they will be followed by
+ ;; a comma.
+ (concat arg (and (not (equal s ""))
+ (string-match "\\\\+\\'" arg)
+ (match-string 0 arg)))
+ nil t)
+ s)))))
+
+(defun org-macro-extract-arguments (s)
+ "Extract macro arguments from string S.
+S is a string containing comma separated values properly escaped.
+Return a list of arguments, as strings. This is the opposite of
+`org-macro-escape-arguments'."
+ ;; Do not use `org-split-string' since empty strings are
+ ;; meaningful here.
+ (split-string
+ (replace-regexp-in-string
+ "\\(\\\\*\\),"
+ (lambda (str)
+ (let ((len (length (match-string 1 str))))
+ (concat (make-string (/ len 2) ?\\)
+ (if (zerop (mod len 2)) "\000" ","))))
+ s nil t)
+ "\000"))
+
+(defun org-macro--vc-modified-time (file)
+ (save-window-excursion
+ (when (vc-backend file)
+ (let ((buf (get-buffer-create " *org-vc*"))
+ (case-fold-search t)
+ date)
+ (unwind-protect
+ (progn
+ (vc-call print-log file buf nil nil 1)
+ (with-current-buffer buf
+ (vc-exec-after
+ (lambda ()
+ (goto-char (point-min))
+ (when (re-search-forward "Date:?[ \t]*" nil t)
+ (let ((time (parse-time-string
+ (buffer-substring
+ (point) (line-end-position)))))
+ (when (cl-some #'identity time)
+ (setq date (apply #'encode-time time))))))))
+ (let ((proc (get-buffer-process buf)))
+ (while (and proc (accept-process-output proc .5 nil t)))))
+ (kill-buffer buf))
+ date))))
+
+
+(provide 'org-macro)
+;;; org-macro.el ends here
diff --git a/lisp/org-macs.el b/lisp/org-macs.el
new file mode 100644
index 0000000..ca47e5a
--- /dev/null
+++ b/lisp/org-macs.el
@@ -0,0 +1,309 @@
+;;; org-macs.el --- Top-level Definitions for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains macro definitions, defsubst definitions, other
+;; stuff needed for compilation and top-level forms in Org mode, as
+;; well lots of small functions that are not Org mode specific but
+;; simply generally useful stuff.
+
+;;; Code:
+
+(defmacro org-with-gensyms (symbols &rest body)
+ (declare (debug (sexp body)) (indent 1))
+ `(let ,(mapcar (lambda (s)
+ `(,s (make-symbol (concat "--" (symbol-name ',s)))))
+ symbols)
+ ,@body))
+
+(defun org-string-nw-p (s)
+ "Return S if S is a string containing a non-blank character.
+Otherwise, return nil."
+ (and (stringp s)
+ (string-match-p "[^ \r\t\n]" s)
+ s))
+
+(defun org-not-nil (v)
+ "If V not nil, and also not the string \"nil\", then return V.
+Otherwise return nil."
+ (and v (not (equal v "nil")) v))
+
+(defmacro org-preserve-lc (&rest body)
+ (declare (debug (body)))
+ (org-with-gensyms (line col)
+ `(let ((,line (org-current-line))
+ (,col (current-column)))
+ (unwind-protect
+ (progn ,@body)
+ (org-goto-line ,line)
+ (org-move-to-column ,col)))))
+
+;; Use `org-with-silent-modifications' to ignore cosmetic changes and
+;; `org-unmodified' to ignore real text modifications
+(defmacro org-unmodified (&rest body)
+ "Run BODY while preserving the buffer's `buffer-modified-p' state."
+ (declare (debug (body)))
+ (org-with-gensyms (was-modified)
+ `(let ((,was-modified (buffer-modified-p)))
+ (unwind-protect
+ (let ((buffer-undo-list t)
+ (inhibit-modification-hooks t))
+ ,@body)
+ (set-buffer-modified-p ,was-modified)))))
+
+(defmacro org-without-partial-completion (&rest body)
+ (declare (debug (body)))
+ `(if (and (boundp 'partial-completion-mode)
+ partial-completion-mode
+ (fboundp 'partial-completion-mode))
+ (unwind-protect
+ (progn
+ (partial-completion-mode -1)
+ ,@body)
+ (partial-completion-mode 1))
+ ,@body))
+
+(defmacro org-with-point-at (pom &rest body)
+ "Move to buffer and point of point-or-marker POM for the duration of BODY."
+ (declare (debug (form body)) (indent 1))
+ (org-with-gensyms (mpom)
+ `(let ((,mpom ,pom))
+ (save-excursion
+ (if (markerp ,mpom) (set-buffer (marker-buffer ,mpom)))
+ (org-with-wide-buffer
+ (goto-char (or ,mpom (point)))
+ ,@body)))))
+
+(defmacro org-with-remote-undo (buffer &rest body)
+ "Execute BODY while recording undo information in two buffers."
+ (declare (debug (form body)) (indent 1))
+ (org-with-gensyms (cline cmd buf1 buf2 undo1 undo2 c1 c2)
+ `(let ((,cline (org-current-line))
+ (,cmd this-command)
+ (,buf1 (current-buffer))
+ (,buf2 ,buffer)
+ (,undo1 buffer-undo-list)
+ (,undo2 (with-current-buffer ,buffer buffer-undo-list))
+ ,c1 ,c2)
+ ,@body
+ (when org-agenda-allow-remote-undo
+ (setq ,c1 (org-verify-change-for-undo
+ ,undo1 (with-current-buffer ,buf1 buffer-undo-list))
+ ,c2 (org-verify-change-for-undo
+ ,undo2 (with-current-buffer ,buf2 buffer-undo-list)))
+ (when (or ,c1 ,c2)
+ ;; make sure there are undo boundaries
+ (and ,c1 (with-current-buffer ,buf1 (undo-boundary)))
+ (and ,c2 (with-current-buffer ,buf2 (undo-boundary)))
+ ;; remember which buffer to undo
+ (push (list ,cmd ,cline ,buf1 ,c1 ,buf2 ,c2)
+ org-agenda-undo-list))))))
+
+(defmacro org-no-read-only (&rest body)
+ "Inhibit read-only for BODY."
+ (declare (debug (body)))
+ `(let ((inhibit-read-only t)) ,@body))
+
+(defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
+ rear-nonsticky t mouse-map t fontified t
+ org-emphasis t)
+ "Properties to remove when a string without properties is wanted.")
+
+(defsubst org-no-properties (s &optional restricted)
+ "Remove all text properties from string S.
+When RESTRICTED is non-nil, only remove the properties listed
+in `org-rm-props'."
+ (if restricted (remove-text-properties 0 (length s) org-rm-props s)
+ (set-text-properties 0 (length s) nil s))
+ s)
+
+(defsubst org-get-alist-option (option key)
+ (cond ((eq key t) t)
+ ((eq option t) t)
+ ((assoc key option) (cdr (assoc key option)))
+ (t (let ((r (cdr (assq 'default option))))
+ (if (listp r) (delq nil r) r)))))
+
+(defsubst org-check-external-command (cmd &optional use no-error)
+ "Check if external program CMD for USE exists, error if not.
+When the program does exist, return its path.
+When it does not exist and NO-ERROR is set, return nil.
+Otherwise, throw an error. The optional argument USE can describe what this
+program is needed for, so that the error message can be more informative."
+ (or (executable-find cmd)
+ (if no-error
+ nil
+ (error "Can't find `%s'%s" cmd
+ (if use (format " (%s)" use) "")))))
+
+(defsubst org-last (list)
+ "Return the last element of LIST."
+ (car (last list)))
+
+(defun org-let (list &rest body)
+ (eval (cons 'let (cons list body))))
+(put 'org-let 'lisp-indent-function 1)
+
+(defun org-let2 (list1 list2 &rest body)
+ (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
+(put 'org-let2 'lisp-indent-function 2)
+
+(defsubst org-call-with-arg (command arg)
+ "Call COMMAND interactively, but pretend prefix arg was ARG."
+ (let ((current-prefix-arg arg)) (call-interactively command)))
+
+(defsubst org-current-line (&optional pos)
+ (save-excursion
+ (and pos (goto-char pos))
+ ;; works also in narrowed buffer, because we start at 1, not point-min
+ (+ (if (bolp) 1 0) (count-lines 1 (point)))))
+
+(defsubst org-goto-line (N)
+ (save-restriction
+ (widen)
+ (goto-char (point-min))
+ (forward-line (1- N))))
+
+(defsubst org-current-line-string (&optional to-here)
+ (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
+
+(defsubst org-pos-in-match-range (pos n)
+ (and (match-beginning n)
+ (<= (match-beginning n) pos)
+ (>= (match-end n) pos)))
+
+(defun org-match-line (regexp)
+ "Match REGEXP at the beginning of the current line."
+ (save-excursion
+ (beginning-of-line)
+ (looking-at regexp)))
+
+(defun org-plist-delete (plist property)
+ "Delete PROPERTY from PLIST.
+This is in contrast to merely setting it to 0."
+ (let (p)
+ (while plist
+ (if (not (eq property (car plist)))
+ (setq p (plist-put p (car plist) (nth 1 plist))))
+ (setq plist (cddr plist)))
+ p))
+
+(defmacro org-save-outline-visibility (use-markers &rest body)
+ "Save and restore outline visibility around BODY.
+If USE-MARKERS is non-nil, use markers for the positions.
+This means that the buffer may change while running BODY,
+but it also means that the buffer should stay alive
+during the operation, because otherwise all these markers will
+point nowhere."
+ (declare (debug (form body)) (indent 1))
+ (org-with-gensyms (data)
+ `(let ((,data (org-outline-overlay-data ,use-markers)))
+ (unwind-protect
+ (prog1 (progn ,@body)
+ (org-set-outline-overlay-data ,data))
+ (when ,use-markers
+ (dolist (c ,data)
+ (when (markerp (car c)) (move-marker (car c) nil))
+ (when (markerp (cdr c)) (move-marker (cdr c) nil))))))))
+
+(defmacro org-with-wide-buffer (&rest body)
+ "Execute body while temporarily widening the buffer."
+ (declare (debug (body)))
+ `(save-excursion
+ (save-restriction
+ (widen)
+ ,@body)))
+
+(defmacro org-with-limited-levels (&rest body)
+ "Execute BODY with limited number of outline levels."
+ (declare (debug (body)))
+ `(progn
+ (defvar org-called-with-limited-levels)
+ (defvar org-outline-regexp)
+ (defvar outline-regexp)
+ (defvar org-outline-regexp-bol)
+ (let* ((org-called-with-limited-levels t)
+ (org-outline-regexp (org-get-limited-outline-regexp))
+ (outline-regexp org-outline-regexp)
+ (org-outline-regexp-bol (concat "^" org-outline-regexp)))
+ ,@body)))
+
+(defvar org-outline-regexp) ; defined in org.el
+(defvar org-odd-levels-only) ; defined in org.el
+(defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
+(defun org-get-limited-outline-regexp ()
+ "Return outline-regexp with limited number of levels.
+The number of levels is controlled by `org-inlinetask-min-level'"
+ (cond ((not (derived-mode-p 'org-mode))
+ outline-regexp)
+ ((not (featurep 'org-inlinetask))
+ org-outline-regexp)
+ (t
+ (let* ((limit-level (1- org-inlinetask-min-level))
+ (nstars (if org-odd-levels-only
+ (1- (* limit-level 2))
+ limit-level)))
+ (format "\\*\\{1,%d\\} " nstars)))))
+
+(defmacro org-eval-in-environment (environment form)
+ (declare (debug (form form)) (indent 1))
+ `(eval (list 'let ,environment ',form)))
+
+(defun org-make-parameter-alist (flat)
+ "Return alist based on FLAT.
+FLAT is a list with alternating symbol names and values. The
+returned alist is a list of lists with the symbol name in car and
+the value in cdr."
+ (when flat
+ (cons (list (car flat) (cadr flat))
+ (org-make-parameter-alist (cddr flat)))))
+
+;;;###autoload
+(defmacro org-load-noerror-mustsuffix (file)
+ "Load FILE with optional arguments NOERROR and MUSTSUFFIX."
+ `(load ,file 'noerror nil nil 'mustsuffix))
+
+(defun org-unbracket-string (pre post string)
+ "Remove PRE/POST from the beginning/end of STRING.
+Both PRE and POST must be pre-/suffixes of STRING, or neither is
+removed."
+ (if (and (string-prefix-p pre string)
+ (string-suffix-p post string))
+ (substring string (length pre) (- (length post)))
+ string))
+
+(defun org-read-function (prompt &optional allow-empty?)
+ "Prompt for a function.
+If ALLOW-EMPTY? is non-nil, return nil rather than raising an
+error when the user input is empty."
+ (let ((func (completing-read prompt obarray #'fboundp t)))
+ (cond ((not (string= func ""))
+ (intern func))
+ (allow-empty? nil)
+ (t (user-error "Empty input is not valid")))))
+
+(provide 'org-macs)
+
+;;; org-macs.el ends here
diff --git a/lisp/org-mhe.el b/lisp/org-mhe.el
new file mode 100644
index 0000000..4142ae4
--- /dev/null
+++ b/lisp/org-mhe.el
@@ -0,0 +1,219 @@
+;;; org-mhe.el --- Support for Links to MH-E Messages -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Thomas Baumann <thomas dot baumann at ch dot tum dot de>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to MH-E messages from within Org.
+;; Org mode loads this module by default - if this is not what you want,
+;; configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org-macs)
+(require 'org)
+
+;; Customization variables
+
+(defcustom org-mhe-search-all-folders nil
+ "Non-nil means the search for the mh-message may extend to all folders.
+When non-nil, the search for a message will extend to all other
+folders if it cannot be found in the folder given in the link.
+Searching all folders may be slow with the default pick based
+search but is very efficient with one of the other search engines
+supported by MH-E."
+ :group 'org-link-follow
+ :type 'boolean)
+
+;; Declare external functions and variables
+(declare-function mh-display-msg "mh-show" (msg-num folder-name))
+(declare-function mh-find-path "mh-utils" ())
+(declare-function mh-get-header-field "mh-utils" (field))
+(declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
+(declare-function mh-header-display "mh-show" ())
+(declare-function mh-index-previous-folder "mh-search" ())
+(declare-function mh-normalize-folder-name "mh-utils"
+ (folder &optional empty-string-okay dont-remove-trailing-slash
+ return-nil-if-folder-empty))
+(declare-function mh-search "mh-search"
+ (folder search-regexp &optional redo-search-flag
+ window-config))
+(declare-function mh-search-choose "mh-search" (&optional searcher))
+(declare-function mh-show "mh-show" (&optional message redisplay-flag))
+(declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
+(declare-function mh-show-header-display "mh-show" t t)
+(declare-function mh-show-msg "mh-show" (msg))
+(declare-function mh-show-show "mh-show" t t)
+(declare-function mh-visit-folder "mh-folder" (folder &optional
+ range index-data))
+(defvar mh-progs)
+(defvar mh-current-folder)
+(defvar mh-show-folder-buffer)
+(defvar mh-index-folder)
+(defvar mh-searcher)
+(defvar mh-search-regexp-builder)
+
+;; Install the link type
+(org-link-set-parameters "mhe" :follow #'org-mhe-open :store #'org-mhe-store-link)
+
+;; Implementation
+(defun org-mhe-store-link ()
+ "Store a link to an MH-E folder or message."
+ (when (or (eq major-mode 'mh-folder-mode)
+ (eq major-mode 'mh-show-mode))
+ (save-window-excursion
+ (let* ((from (org-mhe-get-header "From:"))
+ (to (org-mhe-get-header "To:"))
+ (message-id (org-mhe-get-header "Message-Id:"))
+ (subject (org-mhe-get-header "Subject:"))
+ (date (org-mhe-get-header "Date:"))
+ link desc)
+ (org-store-link-props :type "mh" :from from :to to :date date
+ :subject subject :message-id message-id)
+ (setq desc (org-email-link-description))
+ (setq link (concat "mhe:" (org-mhe-get-message-real-folder) "#"
+ (org-unbracket-string "<" ">" message-id)))
+ (org-add-link-props :link link :description desc)
+ link))))
+
+(defun org-mhe-open (path)
+ "Follow an MH-E message link specified by PATH."
+ (let (folder article)
+ (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
+ (error "Error in MH-E link"))
+ (setq folder (match-string 1 path)
+ article (match-string 3 path))
+ (org-mhe-follow-link folder article)))
+
+;;; mh-e integration based on planner-mode
+(defun org-mhe-get-message-real-folder ()
+ "Return the name of the real folder for the current message.
+So if you use sequences, it will now work."
+ (save-excursion
+ (let* ((folder
+ (if (eq major-mode 'mh-folder-mode)
+ mh-current-folder
+ ;; Refer to the show buffer
+ mh-show-folder-buffer))
+ (end-index
+ (if (boundp 'mh-index-folder)
+ (min (length mh-index-folder) (length folder))))
+ )
+ ;; a simple test on mh-index-data does not work, because
+ ;; mh-index-data is always nil in a show buffer.
+ (if (and (boundp 'mh-index-folder)
+ (string= mh-index-folder (substring folder 0 end-index)))
+ (if (eq major-mode 'mh-show-mode)
+ (save-window-excursion
+ (let (pop-up-frames)
+ (when (buffer-live-p (get-buffer folder))
+ (progn
+ (pop-to-buffer folder)
+ (org-mhe-get-message-folder-from-index)
+ )
+ )))
+ (org-mhe-get-message-folder-from-index)
+ )
+ folder
+ )
+ )))
+
+(defun org-mhe-get-message-folder-from-index ()
+ "Return the name of the message folder in an index folder buffer."
+ (save-excursion
+ (mh-index-previous-folder)
+ (if (re-search-forward "^\\(+.*\\)$" nil t)
+ (message "%s" (match-string 1)))))
+
+(defun org-mhe-get-message-folder ()
+ "Return the name of the current message folder.
+Be careful if you use sequences."
+ (save-excursion
+ (if (eq major-mode 'mh-folder-mode)
+ mh-current-folder
+ ;; Refer to the show buffer
+ mh-show-folder-buffer)))
+
+(defun org-mhe-get-message-num ()
+ "Return the number of the current message.
+Be careful if you use sequences."
+ (save-excursion
+ (if (eq major-mode 'mh-folder-mode)
+ (mh-get-msg-num nil)
+ ;; Refer to the show buffer
+ (mh-show-buffer-message-number))))
+
+(defun org-mhe-get-header (header)
+ "Return the field for HEADER of the message in folder mode.
+This will create a show buffer for the corresponding message. If
+you have a better idea of how to do this then please let us know."
+ (let* ((folder (org-mhe-get-message-folder))
+ (num (org-mhe-get-message-num))
+ (buffer (get-buffer-create (concat "show-" folder)))
+ (header-field))
+ (with-current-buffer buffer
+ (mh-display-msg num folder)
+ (if (eq major-mode 'mh-folder-mode)
+ (mh-header-display)
+ (mh-show-header-display))
+ (set-buffer buffer)
+ (setq header-field (mh-get-header-field header))
+ (if (eq major-mode 'mh-folder-mode)
+ (mh-show)
+ (mh-show-show))
+ (org-trim header-field))))
+
+(defun org-mhe-follow-link (folder article)
+ "Follow an MH-E link to FOLDER and ARTICLE.
+If ARTICLE is nil FOLDER is shown. If the configuration variable
+`org-mhe-search-all-folders' is t and `mh-searcher' is pick,
+ARTICLE is searched in all folders. Indexed searches (swish++,
+namazu, and others supported by MH-E) will always search in all
+folders."
+ (require 'mh-e)
+ (require 'mh-search)
+ (require 'mh-utils)
+ (mh-find-path)
+ (if (not article)
+ (mh-visit-folder (mh-normalize-folder-name folder))
+ (mh-search-choose)
+ (if (eq mh-searcher 'pick)
+ (progn
+ (setq article (org-add-angle-brackets article))
+ (mh-search folder (list "--message-id" article))
+ (when (and org-mhe-search-all-folders
+ (not (org-mhe-get-message-real-folder)))
+ (kill-buffer)
+ (mh-search "+" (list "--message-id" article))))
+ (if mh-search-regexp-builder
+ (mh-search "+" (funcall mh-search-regexp-builder
+ (list (cons 'message-id article))))
+ (mh-search "+" article)))
+ (if (org-mhe-get-message-real-folder)
+ (mh-show-msg 1)
+ (kill-buffer)
+ (error "Message not found"))))
+
+(provide 'org-mhe)
+
+;;; org-mhe.el ends here
diff --git a/lisp/org-mobile.el b/lisp/org-mobile.el
new file mode 100644
index 0000000..12e6c84
--- /dev/null
+++ b/lisp/org-mobile.el
@@ -0,0 +1,1115 @@
+;;; org-mobile.el --- Code for Asymmetric Sync With a Mobile Device -*- lexical-binding: t; -*-
+;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+;;
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+;;
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+;;
+;; This file contains the code to interact with Richard Moreland's
+;; iPhone application MobileOrg, as well as with the Android version
+;; by Matthew Jones. This code is documented in Appendix B of the Org
+;; manual. The code is not specific for the iPhone and Android - any
+;; external viewer/flagging/editing application that uses the same
+;; conventions could be used.
+
+(require 'org)
+(require 'org-agenda)
+(require 'cl-lib)
+
+(defvar org-agenda-keep-restricted-file-list)
+
+;;; Code:
+
+(defgroup org-mobile nil
+ "Options concerning support for a viewer/editor on a mobile device."
+ :tag "Org Mobile"
+ :group 'org)
+
+(defcustom org-mobile-files '(org-agenda-files)
+ "Files to be staged for MobileOrg.
+This is basically a list of files and directories. Files will be staged
+directly. Directories will be search for files with the extension `.org'.
+In addition to this, the list may also contain the following symbols:
+
+org-agenda-files
+ This means include the complete, unrestricted list of files given in
+ the variable `org-agenda-files'.
+org-agenda-text-search-extra-files
+ Include the files given in the variable
+ `org-agenda-text-search-extra-files'"
+ :group 'org-mobile
+ :type '(list :greedy t
+ (option (const :tag "org-agenda-files" org-agenda-files))
+ (option (const :tag "org-agenda-text-search-extra-files"
+ org-agenda-text-search-extra-files))
+ (repeat :inline t :tag "Additional files"
+ (file))))
+
+(defcustom org-mobile-files-exclude-regexp ""
+ "A regexp to exclude files from `org-mobile-files'."
+ :group 'org-mobile
+ :version "24.1"
+ :type 'regexp)
+
+(defcustom org-mobile-directory ""
+ "The WebDAV directory where the interaction with the mobile takes place."
+ :group 'org-mobile
+ :type 'directory)
+
+(defcustom org-mobile-allpriorities "A B C"
+ "Default set of priority cookies for the index file."
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string
+ :group 'org-mobile)
+
+(defcustom org-mobile-use-encryption nil
+ "Non-nil means keep only encrypted files on the WebDAV server.
+Encryption uses AES-256, with a password given in
+`org-mobile-encryption-password'.
+When nil, plain files are kept on the server.
+Turning on encryption requires setting the same password in the MobileOrg
+application. Before turning this on, check of MobileOrg does already
+support it - at the time of this writing it did not yet."
+ :group 'org-mobile
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-mobile-encryption-tempfile "~/orgtmpcrypt"
+ "File that is being used as a temporary file for encryption.
+This must be local file on your local machine (not on the WebDAV server).
+You might want to put this file into a directory where only you have access."
+ :group 'org-mobile
+ :version "24.1"
+ :type 'directory)
+
+(defcustom org-mobile-encryption-password ""
+ "Password for encrypting files uploaded to the server.
+This is a single password which is used for AES-256 encryption. The same
+password must also be set in the MobileOrg application. All Org files,
+including mobileorg.org will be encrypted using this password.
+
+SECURITY CONSIDERATIONS:
+
+Note that, when Org runs the encryption commands, the password could
+be visible briefly on your system with the `ps' command. So this method is
+only intended to keep the files secure on the server, not on your own machine.
+
+Also, if you set this variable in an init file (.emacs or .emacs.d/init.el
+or custom.el...) and if that file is stored in a way so that other can read
+it, this also limits the security of this approach. You can also leave
+this variable empty - Org will then ask for the password once per Emacs
+session."
+ :group 'org-mobile
+ :version "24.1"
+ :type '(string :tag "Password"))
+
+(defvar org-mobile-encryption-password-session nil)
+
+(defun org-mobile-encryption-password ()
+ (or (org-string-nw-p org-mobile-encryption-password)
+ (org-string-nw-p org-mobile-encryption-password-session)
+ (setq org-mobile-encryption-password-session
+ (read-passwd "Password for MobileOrg: " t))))
+
+(defcustom org-mobile-inbox-for-pull "~/org/from-mobile.org"
+ "The file where captured notes and flags will be appended to.
+During the execution of `org-mobile-pull', the file
+`org-mobile-capture-file' will be emptied it's contents have
+been appended to the file given here. This file should be in
+`org-directory', and not in the staging area or on the web server."
+ :group 'org-mobile
+ :type 'file)
+
+(defconst org-mobile-capture-file "mobileorg.org"
+ "The capture file where the mobile stores captured notes and flags.
+This should not be changed, because MobileOrg assumes this name.")
+
+(defcustom org-mobile-index-file "index.org"
+ "The index file with links to all Org files that should be loaded by MobileOrg.
+Relative to `org-mobile-directory'. The Address field in the MobileOrg setup
+should point to this file."
+ :group 'org-mobile
+ :type 'file)
+
+(defcustom org-mobile-agendas 'all
+ "The agendas that should be pushed to MobileOrg.
+Allowed values:
+
+default the weekly agenda and the global TODO list
+custom all custom agendas defined by the user
+all the custom agendas and the default ones
+list a list of selection key(s) as string."
+ :group 'org-mobile
+ :version "24.1"
+ :type '(choice
+ (const :tag "Default Agendas" default)
+ (const :tag "Custom Agendas" custom)
+ (const :tag "Default and Custom Agendas" all)
+ (repeat :tag "Selected"
+ (string :tag "Selection Keys"))))
+
+(defcustom org-mobile-force-id-on-agenda-items t
+ "Non-nil means make all agenda items carry an ID."
+ :group 'org-mobile
+ :type 'boolean)
+
+(defcustom org-mobile-force-mobile-change nil
+ "Non-nil means force the change made on the mobile device.
+So even if there have been changes to the computer version of the entry,
+force the new value set on the mobile.
+When nil, mark the entry from the mobile with an error message.
+Instead of nil or t, this variable can also be a list of symbols, indicating
+the editing types for which the mobile version should always dominate."
+ :group 'org-mobile
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (set :greedy t :tag "Specify"
+ (const todo)
+ (const tags)
+ (const priority)
+ (const heading)
+ (const body))))
+
+(defcustom org-mobile-checksum-binary (or (executable-find "shasum")
+ (executable-find "sha1sum")
+ (executable-find "md5sum")
+ (executable-find "md5"))
+ "Executable used for computing checksums of agenda files."
+ :group 'org-mobile
+ :type 'string)
+
+(defvar org-mobile-pre-push-hook nil
+ "Hook run before running `org-mobile-push'.
+This could be used to clean up `org-mobile-directory', for example to
+remove files that used to be included in the agenda but no longer are.
+The presence of such files would not really be a problem, but after time
+they may accumulate.")
+
+(defvar org-mobile-post-push-hook nil
+ "Hook run after running `org-mobile-push'.
+If Emacs does not have direct write access to the WebDAV directory used
+by the mobile device, this hook should be used to copy all files from the
+local staging directory `org-mobile-directory' to the WebDAV directory,
+for example using `rsync' or `scp'.")
+
+(defvar org-mobile-pre-pull-hook nil
+ "Hook run before executing `org-mobile-pull'.
+If Emacs does not have direct write access to the WebDAV directory used
+by the mobile device, this hook should be used to copy the capture file
+`mobileorg.org' from the WebDAV location to the local staging
+directory `org-mobile-directory'.")
+
+(defvar org-mobile-post-pull-hook nil
+ "Hook run after running `org-mobile-pull', only if new items were found.
+If Emacs does not have direct write access to the WebDAV directory used
+by the mobile device, this hook should be used to copy the emptied
+capture file `mobileorg.org' back to the WebDAV directory, for example
+using `rsync' or `scp'.")
+
+(defconst org-mobile-action-alist '(("edit" . org-mobile-edit))
+ "Alist with flags and actions for mobile sync.
+When flagging an entry, MobileOrg will create entries that look like
+
+ * F(action:data) [[id:entry-id][entry title]]
+
+This alist defines that the ACTION in the parentheses of F()
+should mean, i.e. what action should be taken. The :data part in
+the parenthesis is optional. If present, the string after the
+colon will be passed to the action function as the first argument
+variable.
+
+The car of each elements of the alist is an actions string. The
+cdr is a function that is called with the cursor on the headline
+of that entry. It should accept three arguments, the :data part,
+the old and new values for the entry.")
+
+(defvar org-mobile-last-flagged-files nil
+ "List of files containing entries flagged in the latest pull.")
+
+(defvar org-mobile-files-alist nil)
+(defvar org-mobile-checksum-files nil)
+
+(defun org-mobile-prepare-file-lists ()
+ (setq org-mobile-files-alist (org-mobile-files-alist))
+ (setq org-mobile-checksum-files nil))
+
+(defun org-mobile-files-alist ()
+ "Expand the list in `org-mobile-files' to a list of existing files.
+Also exclude files matching `org-mobile-files-exclude-regexp'."
+ (let* ((include-archives
+ (and (member 'org-agenda-text-search-extra-files org-mobile-files)
+ (member 'agenda-archives org-agenda-text-search-extra-files)
+ t))
+ (files
+ (apply 'append
+ (mapcar
+ (lambda (f)
+ (cond
+ ((eq f 'org-agenda-files)
+ (org-agenda-files t include-archives))
+ ((eq f 'org-agenda-text-search-extra-files)
+ (delq 'agenda-archives
+ (copy-sequence
+ org-agenda-text-search-extra-files)))
+ ((and (stringp f) (file-directory-p f))
+ (directory-files f 'full "\\.org\\'"))
+ ((and (stringp f) (file-exists-p f))
+ (list f))
+ (t nil)))
+ org-mobile-files)))
+ (files (delq
+ nil
+ (mapcar (lambda (f)
+ (unless (and (not (string= org-mobile-files-exclude-regexp ""))
+ (string-match org-mobile-files-exclude-regexp f))
+ (identity f)))
+ files)))
+ (orgdir-uname (file-name-as-directory (file-truename org-directory)))
+ (orgdir-re (concat "\\`" (regexp-quote orgdir-uname)))
+ uname seen rtn file link-name)
+ ;; Make the files unique, and determine the name under which they will
+ ;; be listed.
+ (while (setq file (pop files))
+ (if (not (file-name-absolute-p file))
+ (setq file (expand-file-name file org-directory)))
+ (setq uname (file-truename file))
+ (unless (member uname seen)
+ (push uname seen)
+ (if (string-match orgdir-re uname)
+ (setq link-name (substring uname (match-end 0)))
+ (setq link-name (file-name-nondirectory uname)))
+ (push (cons file link-name) rtn)))
+ (nreverse rtn)))
+
+;;;###autoload
+(defun org-mobile-push ()
+ "Push the current state of Org affairs to the target directory.
+This will create the index file, copy all agenda files there, and also
+create all custom agenda views, for upload to the mobile phone."
+ (interactive)
+ (let ((org-agenda-buffer-name "*SUMO*")
+ (org-agenda-tag-filter org-agenda-tag-filter)
+ (org-agenda-redo-command org-agenda-redo-command))
+ (save-excursion
+ (save-restriction
+ (save-window-excursion
+ (run-hooks 'org-mobile-pre-push-hook)
+ (org-mobile-check-setup)
+ (org-mobile-prepare-file-lists)
+ (message "Creating agendas...")
+ (let ((inhibit-redisplay t)
+ (org-agenda-files (mapcar 'car org-mobile-files-alist)))
+ (org-mobile-create-sumo-agenda))
+ (message "Creating agendas...done")
+ (org-save-all-org-buffers) ; to save any IDs created by this process
+ (message "Copying files...")
+ (org-mobile-copy-agenda-files)
+ (message "Writing index file...")
+ (org-mobile-create-index-file)
+ (message "Writing checksums...")
+ (org-mobile-write-checksums)
+ (run-hooks 'org-mobile-post-push-hook)))))
+ (org-agenda-maybe-redo)
+ (message "Files for mobile viewer staged"))
+
+(defvar org-mobile-before-process-capture-hook nil
+ "Hook that is run after content was moved to `org-mobile-inbox-for-pull'.
+The inbox file is visited by the current buffer, and the buffer is
+narrowed to the newly captured data.")
+
+;;;###autoload
+(defun org-mobile-pull ()
+ "Pull the contents of `org-mobile-capture-file' and integrate them.
+Apply all flagged actions, flag entries to be flagged and then call an
+agenda view showing the flagged items."
+ (interactive)
+ (org-mobile-check-setup)
+ (run-hooks 'org-mobile-pre-pull-hook)
+ (let ((insertion-marker (org-mobile-move-capture)))
+ (if (not (markerp insertion-marker))
+ (message "No new items")
+ (org-with-point-at insertion-marker
+ (save-restriction
+ (narrow-to-region (point) (point-max))
+ (run-hooks 'org-mobile-before-process-capture-hook)))
+ (org-with-point-at insertion-marker
+ (org-mobile-apply (point) (point-max)))
+ (move-marker insertion-marker nil)
+ (run-hooks 'org-mobile-post-pull-hook)
+ (when org-mobile-last-flagged-files
+ ;; Make an agenda view of flagged entries, but only in the files
+ ;; where stuff has been added.
+ (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files)
+ (let ((org-agenda-keep-restricted-file-list t))
+ (org-agenda nil "?"))))))
+
+(defun org-mobile-check-setup ()
+ "Check if org-mobile-directory has been set up."
+ (org-mobile-cleanup-encryption-tempfile)
+ (unless (and org-directory
+ (stringp org-directory)
+ (string-match "\\S-" org-directory)
+ (file-exists-p org-directory)
+ (file-directory-p org-directory))
+ (error
+ "Please set `org-directory' to the directory where your org files live"))
+ (unless (and org-mobile-directory
+ (stringp org-mobile-directory)
+ (string-match "\\S-" org-mobile-directory)
+ (file-exists-p org-mobile-directory)
+ (file-directory-p org-mobile-directory))
+ (error
+ "Variable `org-mobile-directory' must point to an existing directory"))
+ (unless (and org-mobile-inbox-for-pull
+ (stringp org-mobile-inbox-for-pull)
+ (string-match "\\S-" org-mobile-inbox-for-pull)
+ (file-exists-p
+ (file-name-directory org-mobile-inbox-for-pull)))
+ (error
+ "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory"))
+ (unless (and org-mobile-checksum-binary
+ (string-match "\\S-" org-mobile-checksum-binary))
+ (error "No executable found to compute checksums"))
+ (when org-mobile-use-encryption
+ (unless (string-match "\\S-" (org-mobile-encryption-password))
+ (error
+ "To use encryption, you must set `org-mobile-encryption-password'"))
+ (unless (file-writable-p org-mobile-encryption-tempfile)
+ (error "Cannot write to encryption tempfile %s"
+ org-mobile-encryption-tempfile))
+ (unless (executable-find "openssl")
+ (error "OpenSSL is needed to encrypt files"))))
+
+(defun org-mobile-create-index-file ()
+ "Write the index file in the WebDAV directory."
+ (let ((files-alist (sort (copy-sequence org-mobile-files-alist)
+ (lambda (a b) (string< (cdr a) (cdr b)))))
+ (def-todo (default-value 'org-todo-keywords))
+ (def-tags org-tag-alist)
+ (target-file (expand-file-name org-mobile-index-file
+ org-mobile-directory))
+ todo-kwds done-kwds tags)
+ (when (stringp (car def-todo))
+ (setq def-todo (list (cons 'sequence def-todo))))
+ (org-agenda-prepare-buffers (mapcar 'car files-alist))
+ (setq done-kwds (org-uniquify org-done-keywords-for-agenda))
+ (setq todo-kwds (org-delete-all
+ done-kwds
+ (org-uniquify org-todo-keywords-for-agenda)))
+ (setq tags (mapcar 'car (org-global-tags-completion-table
+ (mapcar 'car files-alist))))
+ (with-temp-file (if org-mobile-use-encryption org-mobile-encryption-tempfile
+ target-file)
+ (insert "#+READONLY\n")
+ (dolist (entry def-todo)
+ (let ((kwds (mapcar (lambda (x)
+ (if (string-match "(" x)
+ (substring x 0 (match-beginning 0))
+ x))
+ (cdr entry))))
+ (insert "#+TODO: " (mapconcat #'identity kwds " ") "\n")
+ (let* ((dwds (or (member "|" kwds) (last kwds)))
+ (twds (org-delete-all dwds kwds)))
+ (setq todo-kwds (org-delete-all twds todo-kwds))
+ (setq done-kwds (org-delete-all dwds done-kwds)))))
+ (when (or todo-kwds done-kwds)
+ (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | "
+ (mapconcat 'identity done-kwds " ") "\n"))
+ (setq def-tags (split-string (org-tag-alist-to-string def-tags t)))
+ (setq tags (org-delete-all def-tags tags))
+ (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b)))))
+ (setq tags (append def-tags tags nil))
+ (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n")
+ (insert "#+ALLPRIORITIES: " org-mobile-allpriorities "\n")
+ (when (file-exists-p (expand-file-name
+ org-mobile-directory "agendas.org"))
+ (insert "* [[file:agendas.org][Agenda Views]]\n"))
+ (pcase-dolist (`(,_ . ,link-name) files-alist)
+ (insert (format "* [[file:%s][%s]]\n" link-name link-name)))
+ (push (cons org-mobile-index-file (md5 (buffer-string)))
+ org-mobile-checksum-files))
+ (when org-mobile-use-encryption
+ (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
+ target-file)
+ (org-mobile-cleanup-encryption-tempfile))))
+
+(defun org-mobile-copy-agenda-files ()
+ "Copy all agenda files to the stage or WebDAV directory."
+ (let ((files-alist org-mobile-files-alist)
+ file buf entry link-name target-path target-dir check)
+ (while (setq entry (pop files-alist))
+ (setq file (car entry) link-name (cdr entry))
+ (when (file-exists-p file)
+ (setq target-path (expand-file-name link-name org-mobile-directory)
+ target-dir (file-name-directory target-path))
+ (unless (file-directory-p target-dir)
+ (make-directory target-dir 'parents))
+ (if org-mobile-use-encryption
+ (org-mobile-encrypt-and-move file target-path)
+ (copy-file file target-path 'ok-if-exists))
+ (setq check (shell-command-to-string
+ (concat (shell-quote-argument org-mobile-checksum-binary)
+ " "
+ (shell-quote-argument (expand-file-name file)))))
+ (when (string-match "[a-fA-F0-9]\\{30,40\\}" check)
+ (push (cons link-name (match-string 0 check))
+ org-mobile-checksum-files))))
+
+ (setq file (expand-file-name org-mobile-capture-file
+ org-mobile-directory))
+ (save-excursion
+ (setq buf (find-file file))
+ (when (and (= (point-min) (point-max)))
+ (insert "\n")
+ (save-buffer)
+ (when org-mobile-use-encryption
+ (write-file org-mobile-encryption-tempfile)
+ (org-mobile-encrypt-and-move org-mobile-encryption-tempfile file)))
+ (push (cons org-mobile-capture-file (md5 (buffer-string)))
+ org-mobile-checksum-files))
+ (org-mobile-cleanup-encryption-tempfile)
+ (kill-buffer buf)))
+
+(defun org-mobile-write-checksums ()
+ "Create checksums for all files in `org-mobile-directory'.
+The table of checksums is written to the file mobile-checksums."
+ (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory))
+ (files org-mobile-checksum-files)
+ entry file sum)
+ (with-temp-file sumfile
+ (set-buffer-file-coding-system 'undecided-unix nil)
+ (while (setq entry (pop files))
+ (setq file (car entry) sum (cdr entry))
+ (insert (format "%s %s\n" sum file))))))
+
+(defun org-mobile-sumo-agenda-command ()
+ "Return an agenda custom command that comprises all custom commands."
+ (let ((custom-list
+ ;; normalize different versions
+ (delq nil
+ (mapcar
+ (lambda (x)
+ (cond ((stringp (cdr x)) nil)
+ ((stringp (nth 1 x)) x)
+ ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
+ (t (cons (car x) (cons "" (cdr x))))))
+ org-agenda-custom-commands)))
+ (default-list '(("a" "Agenda" agenda) ("t" "All TODO" alltodo)))
+ thelist atitle new e key desc type match settings cmds gkey gdesc gsettings cnt)
+ (cond
+ ((eq org-mobile-agendas 'custom)
+ (setq thelist custom-list))
+ ((eq org-mobile-agendas 'default)
+ (setq thelist default-list))
+ ((eq org-mobile-agendas 'all)
+ (setq thelist custom-list)
+ (unless (assoc "t" thelist) (push '("t" "ALL TODO" alltodo) thelist))
+ (unless (assoc "a" thelist) (push '("a" "Agenda" agenda) thelist)))
+ ((listp org-mobile-agendas)
+ (setq thelist (append custom-list default-list))
+ (setq thelist (delq nil (mapcar (lambda (k) (assoc k thelist))
+ org-mobile-agendas)))))
+ (while (setq e (pop thelist))
+ (cond
+ ((stringp (cdr e))
+ ;; this is a description entry - skip it
+ )
+ ((eq (nth 2 e) 'search)
+ ;; Search view is interactive, skip
+ )
+ ((memq (nth 2 e) '(todo-tree tags-tree occur-tree))
+ ;; These are trees, not really agenda commands
+ )
+ ((and (memq (nth 2 e) '(todo tags tags-todo))
+ (or (null (nth 3 e))
+ (not (string-match "\\S-" (nth 3 e)))))
+ ;; These would be interactive because the match string is empty
+ )
+ ((memq (nth 2 e) '(agenda alltodo todo tags tags-todo))
+ ;; a normal command
+ (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e)
+ settings (nth 4 e))
+ (setq settings
+ (cons (list 'org-agenda-title-append
+ (concat "<after>KEYS=" key " TITLE: "
+ (if (and (stringp desc) (> (length desc) 0))
+ desc (symbol-name type))
+ "</after>"))
+ settings))
+ (push (list type match settings) new))
+ ((or (functionp (nth 2 e)) (symbolp (nth 2 e)))
+ ;; A user-defined function, which can do anything, so simply
+ ;; ignore it.
+ )
+ (t
+ ;; a block agenda
+ (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e))
+ (setq cnt 0)
+ (while (setq e (pop cmds))
+ (setq type (car e) match (nth 1 e) settings (nth 2 e))
+ (setq atitle (if (string= "" gdesc) match gdesc))
+ (setq settings (append gsettings settings))
+ (setq settings
+ (cons (list 'org-agenda-title-append
+ (concat "<after>KEYS=" gkey "#" (number-to-string
+ (setq cnt (1+ cnt)))
+ " TITLE: " atitle "</after>"))
+ settings))
+ (push (list type match settings) new)))))
+ (and new (list "X" "SUMO" (reverse new)
+ '((org-agenda-compact-blocks nil))))))
+
+(defvar org-mobile-creating-agendas nil)
+(defun org-mobile-write-agenda-for-mobile (file)
+ (let ((all (buffer-string)) in-date id pl prefix line app short m sexp)
+ (with-temp-file file
+ (org-mode)
+ (insert "#+READONLY\n")
+ (insert all)
+ (goto-char (point-min))
+ (while (not (eobp))
+ (cond
+ ((looking-at "[ \t]*$")) ; keep empty lines
+ ((looking-at "=+$")
+ ;; remove underlining
+ (delete-region (point) (point-at-eol)))
+ ((get-text-property (point) 'org-agenda-structural-header)
+ (setq in-date nil)
+ (setq app (get-text-property (point) 'org-agenda-title-append))
+ (setq short (get-text-property (point) 'short-heading))
+ (when (and short (looking-at ".+"))
+ (replace-match short nil t)
+ (beginning-of-line 1))
+ (when app
+ (end-of-line 1)
+ (insert app)
+ (beginning-of-line 1))
+ (insert "* "))
+ ((get-text-property (point) 'org-agenda-date-header)
+ (setq in-date t)
+ (insert "** "))
+ ((setq m (or (get-text-property (point) 'org-hd-marker)
+ (get-text-property (point) 'org-marker)))
+ (setq sexp (member (get-text-property (point) 'type)
+ '("diary" "sexp")))
+ (if (setq pl (text-property-any (point) (point-at-eol) 'org-heading t))
+ (progn
+ (setq prefix (org-trim (buffer-substring
+ (point) pl))
+ line (org-trim (buffer-substring
+ pl
+ (point-at-eol))))
+ (delete-region (point-at-bol) (point-at-eol))
+ (insert line "<before>" prefix "</before>")
+ (beginning-of-line 1))
+ (and (looking-at "[ \t]+") (replace-match "")))
+ (insert (if in-date "*** " "** "))
+ (end-of-line 1)
+ (insert "\n")
+ (unless sexp
+ (insert (org-agenda-get-some-entry-text
+ m 10 " " 'planning)
+ "\n")
+ (when (setq id
+ (if (bound-and-true-p
+ org-mobile-force-id-on-agenda-items)
+ (org-id-get m 'create)
+ (or (org-entry-get m "ID")
+ (org-mobile-get-outline-path-link m))))
+ (insert " :PROPERTIES:\n :ORIGINAL_ID: " id
+ "\n :END:\n")))))
+ (beginning-of-line 2))
+ (push (cons "agendas.org" (md5 (buffer-string)))
+ org-mobile-checksum-files))
+ (message "Agenda written to Org file %s" file)))
+
+(defun org-mobile-get-outline-path-link (pom)
+ (org-with-point-at pom
+ (concat "olp:"
+ (org-mobile-escape-olp (file-name-nondirectory buffer-file-name))
+ ":"
+ (mapconcat 'org-mobile-escape-olp
+ (org-get-outline-path)
+ "/")
+ "/"
+ (org-mobile-escape-olp (nth 4 (org-heading-components))))))
+
+(defun org-mobile-escape-olp (s)
+ (let ((table '(?: ?/)))
+ (org-link-escape s table)))
+
+(defun org-mobile-create-sumo-agenda ()
+ "Create a file that contains all custom agenda views."
+ (interactive)
+ (let* ((file (expand-file-name "agendas.org"
+ org-mobile-directory))
+ (file1 (if org-mobile-use-encryption
+ org-mobile-encryption-tempfile
+ file))
+ (sumo (org-mobile-sumo-agenda-command))
+ (org-agenda-custom-commands
+ (list (append sumo (list (list file1)))))
+ (org-mobile-creating-agendas t))
+ (unless (file-writable-p file1)
+ (error "Cannot write to file %s" file1))
+ (when sumo
+ (org-store-agenda-views))
+ (when org-mobile-use-encryption
+ (org-mobile-encrypt-and-move file1 file)
+ (delete-file file1)
+ (org-mobile-cleanup-encryption-tempfile))))
+
+(defun org-mobile-encrypt-and-move (infile outfile)
+ "Encrypt INFILE locally to INFILE_enc, then move it to OUTFILE.
+We do this in two steps so that remote paths will work, even if the
+encryption program does not understand them."
+ (let ((encfile (concat infile "_enc")))
+ (org-mobile-encrypt-file infile encfile)
+ (when outfile
+ (copy-file encfile outfile 'ok-if-exists)
+ (delete-file encfile))))
+
+(defun org-mobile-encrypt-file (infile outfile)
+ "Encrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
+ (shell-command
+ (format "openssl enc -aes-256-cbc -salt -pass %s -in %s -out %s"
+ (shell-quote-argument (concat "pass:"
+ (org-mobile-encryption-password)))
+ (shell-quote-argument (expand-file-name infile))
+ (shell-quote-argument (expand-file-name outfile)))))
+
+(defun org-mobile-decrypt-file (infile outfile)
+ "Decrypt INFILE to OUTFILE, using `org-mobile-encryption-password'."
+ (shell-command
+ (format "openssl enc -d -aes-256-cbc -salt -pass %s -in %s -out %s"
+ (shell-quote-argument (concat "pass:"
+ (org-mobile-encryption-password)))
+ (shell-quote-argument (expand-file-name infile))
+ (shell-quote-argument (expand-file-name outfile)))))
+
+(defun org-mobile-cleanup-encryption-tempfile ()
+ "Remove the encryption tempfile if it exists."
+ (and (stringp org-mobile-encryption-tempfile)
+ (file-exists-p org-mobile-encryption-tempfile)
+ (delete-file org-mobile-encryption-tempfile)))
+
+(defun org-mobile-move-capture ()
+ "Move the contents of the capture file to the inbox file.
+Return a marker to the location where the new content has been added.
+If nothing new has been added, return nil."
+ (interactive)
+ (let* ((encfile nil)
+ (capture-file (expand-file-name org-mobile-capture-file
+ org-mobile-directory))
+ (inbox-buffer (find-file-noselect org-mobile-inbox-for-pull))
+ (capture-buffer
+ (if (not org-mobile-use-encryption)
+ (find-file-noselect capture-file)
+ (org-mobile-cleanup-encryption-tempfile)
+ (setq encfile (concat org-mobile-encryption-tempfile "_enc"))
+ (copy-file capture-file encfile)
+ (org-mobile-decrypt-file encfile org-mobile-encryption-tempfile)
+ (find-file-noselect org-mobile-encryption-tempfile)))
+ (insertion-point (make-marker))
+ not-empty content)
+ (with-current-buffer capture-buffer
+ (setq content (buffer-string))
+ (setq not-empty (string-match "\\S-" content))
+ (when not-empty
+ (set-buffer inbox-buffer)
+ (widen)
+ (goto-char (point-max))
+ (or (bolp) (newline))
+ (move-marker insertion-point
+ (prog1 (point) (insert content)))
+ (save-buffer)
+ (set-buffer capture-buffer)
+ (erase-buffer)
+ (save-buffer)
+ (org-mobile-update-checksum-for-capture-file (buffer-string))))
+ (kill-buffer capture-buffer)
+ (when org-mobile-use-encryption
+ (org-mobile-encrypt-and-move org-mobile-encryption-tempfile
+ capture-file)
+ (org-mobile-cleanup-encryption-tempfile))
+ (if not-empty insertion-point)))
+
+(defun org-mobile-update-checksum-for-capture-file (buffer-string)
+ "Find the checksum line and modify it to match BUFFER-STRING."
+ (let* ((file (expand-file-name "checksums.dat" org-mobile-directory))
+ (buffer (find-file-noselect file)))
+ (when buffer
+ (with-current-buffer buffer
+ (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?"
+ (regexp-quote org-mobile-capture-file)
+ "[ \t]*$") nil t)
+ (goto-char (match-beginning 1))
+ (delete-region (match-beginning 1) (match-end 1))
+ (insert (md5 buffer-string))
+ (save-buffer)))
+ (kill-buffer buffer))))
+
+(defun org-mobile-apply (&optional beg end)
+ "Apply all change requests in the current buffer.
+If BEG and END are given, only do this in that region."
+ (interactive)
+ (require 'org-archive)
+ (setq org-mobile-last-flagged-files nil)
+ (setq beg (or beg (point-min)) end (or end (point-max)))
+
+ ;; Remove all Note IDs
+ (goto-char beg)
+ (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t)
+ (replace-match ""))
+
+ ;; Find all the referenced entries, without making any changes yet
+ (let ((marker (make-marker))
+ (bos-marker (make-marker))
+ (end (move-marker (make-marker) end))
+ (cnt-new 0)
+ (cnt-edit 0)
+ (cnt-flag 0)
+ (cnt-error 0)
+ buf-list
+ org-mobile-error)
+
+ ;; Count the new captures
+ (goto-char beg)
+ (while (re-search-forward "^\\* \\(.*\\)" end t)
+ (and (>= (- (match-end 1) (match-beginning 1)) 2)
+ (not (equal (downcase (substring (match-string 1) 0 2)) "f("))
+ (cl-incf cnt-new)))
+
+ ;; Find and apply the edits
+ (goto-char beg)
+ (while (re-search-forward
+ "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t)
+ (catch 'next
+ (let* ((action (match-string 1))
+ (data (and (match-end 3) (match-string 3)))
+ (id-pos (condition-case msg
+ (org-mobile-locate-entry (match-string 4))
+ (error (nth 1 msg))))
+ (bos (line-beginning-position))
+ (eos (save-excursion (org-end-of-subtree t t)))
+ (cmd (if (equal action "")
+ (let ((note (buffer-substring-no-properties
+ (line-beginning-position 2) eos)))
+ (lambda (_data _old _new)
+ (cl-incf cnt-flag)
+ (org-toggle-tag "FLAGGED" 'on)
+ (org-entry-put
+ nil "THEFLAGGINGNOTE"
+ (replace-regexp-in-string "\n" "\\\\n" note))))
+ (cl-incf cnt-edit)
+ (cdr (assoc action org-mobile-action-alist))))
+ ;; Do not take notes interactively.
+ (org-inhibit-logging 'note)
+ old new)
+
+ (goto-char bos)
+ (when (and (markerp id-pos)
+ (not (member (marker-buffer id-pos) buf-list)))
+ (org-mobile-timestamp-buffer (marker-buffer id-pos))
+ (push (marker-buffer id-pos) buf-list))
+ (unless (markerp id-pos)
+ (goto-char (+ 2 (point-at-bol)))
+ (if (stringp id-pos)
+ (insert id-pos " ")
+ (insert "BAD REFERENCE "))
+ (cl-incf cnt-error)
+ (throw 'next t))
+ (unless cmd
+ (insert "BAD FLAG ")
+ (cl-incf cnt-error)
+ (throw 'next t))
+ (move-marker bos-marker (point))
+ (if (re-search-forward "^** Old value[ \t]*$" eos t)
+ (setq old (buffer-substring
+ (1+ (match-end 0))
+ (progn (outline-next-heading) (point)))))
+ (if (re-search-forward "^** New value[ \t]*$" eos t)
+ (setq new (buffer-substring
+ (1+ (match-end 0))
+ (progn (outline-next-heading)
+ (if (eobp) (org-back-over-empty-lines))
+ (point)))))
+ (setq old (org-string-nw-p old))
+ (setq new (org-string-nw-p new))
+ (unless (equal data "body")
+ (setq new (and new (org-trim new)))
+ (setq old (and old (org-trim old))))
+ (goto-char (+ 2 bos-marker))
+ ;; Remember this place so that we can return
+ (move-marker marker (point))
+ (setq org-mobile-error nil)
+ (condition-case msg
+ (org-with-point-at id-pos
+ (funcall cmd data old new)
+ (unless (member data '("delete" "archive" "archive-sibling"
+ "addheading"))
+ (when (member "FLAGGED" (org-get-tags))
+ (add-to-list 'org-mobile-last-flagged-files
+ (buffer-file-name)))))
+ (error (setq org-mobile-error msg)))
+ (when org-mobile-error
+ (pop-to-buffer-same-window (marker-buffer marker))
+ (goto-char marker)
+ (cl-incf cnt-error)
+ (insert (if (stringp (nth 1 org-mobile-error))
+ (nth 1 org-mobile-error)
+ "EXECUTION FAILED")
+ " ")
+ (throw 'next t))
+ ;; If we get here, the action has been applied successfully
+ ;; So remove the entry
+ (goto-char bos-marker)
+ (delete-region (point) (org-end-of-subtree t t)))))
+ (save-buffer)
+ (move-marker marker nil)
+ (move-marker end nil)
+ (message "%d new, %d edits, %d flags, %d errors"
+ cnt-new cnt-edit cnt-flag cnt-error)
+ (sit-for 1)))
+
+(defun org-mobile-timestamp-buffer (buf)
+ "Time stamp buffer BUF, just to make sure its checksum will change."
+ (with-current-buffer buf
+ (save-excursion
+ (save-restriction
+ (widen)
+ (goto-char (point-min))
+ (if (re-search-forward
+ "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t)
+ (progn
+ (goto-char (match-end 1))
+ (delete-region (point) (match-end 0)))
+ (if (looking-at ".*?-\\*-.*-\\*-")
+ (forward-line 1)))
+ (insert "#+LAST_MOBILE_CHANGE: "
+ (format-time-string "%Y-%m-%d %T") "\n")))))
+
+(defun org-mobile-smart-read ()
+ "Parse the entry at point for shortcuts and expand them.
+These shortcuts are meant for fast and easy typing on the limited
+keyboards of a mobile device. Below we show a list of the shortcuts
+currently implemented.
+
+The entry is expected to contain an inactive time stamp indicating when
+the entry was created. When setting dates and
+times (for example for deadlines), the time strings are interpreted
+relative to that creation date.
+Abbreviations are expected to take up entire lines, just because it is so
+easy to type RET on a mobile device. Abbreviations start with one or two
+letters, followed immediately by a dot and then additional information.
+Generally the entire shortcut line is removed after action have been taken.
+Time stamps will be constructed using `org-read-date'. So for example a
+line \"dd. 2tue\" will set a deadline on the second Tuesday after the
+creation date.
+
+Here are the shortcuts currently implemented:
+
+dd. string set deadline
+ss. string set scheduling
+tt. string set time tamp, here.
+ti. string set inactive time
+
+tg. tag1 tag2 tag3 set all these tags, change case where necessary
+td. kwd set this todo keyword, change case where necessary
+
+FIXME: Hmmm, not sure if we can make his work against the
+auto-correction feature. Needs a bit more thinking. So this function
+is currently a noop.")
+
+(defun org-mobile-locate-entry (link)
+ (if (string-match "\\`id:\\(.*\\)$" link)
+ (org-id-find (match-string 1 link) 'marker)
+ (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link))
+ ; not found with path, but maybe it is to be inserted
+ ; in top level of the file?
+ (if (not (string-match "\\`olp:\\(.*?\\)$" link))
+ nil
+ (let ((file (match-string 1 link)))
+ (setq file (org-link-unescape file))
+ (setq file (expand-file-name file org-directory))
+ (save-excursion
+ (find-file file)
+ (goto-char (point-max))
+ (newline)
+ (goto-char (point-max))
+ (point-marker))))
+ (let ((file (match-string 1 link))
+ (path (match-string 2 link)))
+ (setq file (org-link-unescape file))
+ (setq file (expand-file-name file org-directory))
+ (setq path (mapcar 'org-link-unescape
+ (org-split-string path "/")))
+ (org-find-olp (cons file path))))))
+
+(defun org-mobile-edit (what old new)
+ "Edit item WHAT in the current entry by replacing OLD with NEW.
+WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\".
+The edit only takes place if the current value is equal (except for
+white space) the OLD. If this is so, OLD will be replace by NEW
+and the command will return t. If something goes wrong, a string will
+be returned that indicates what went wrong."
+ (let (current old1 new1 level)
+ (if (stringp what) (setq what (intern what)))
+
+ (cond
+
+ ((memq what '(todo todostate))
+ (setq current (org-get-todo-state))
+ (cond
+ ((equal new "DONEARCHIVE")
+ (org-todo 'done)
+ (org-archive-subtree-default))
+ ((equal new current) t) ; nothing needs to be done
+ ((or (equal current old)
+ (eq org-mobile-force-mobile-change t)
+ (memq 'todo org-mobile-force-mobile-change))
+ (org-todo (or new 'none)) t)
+ (t (error "State before change was expected as \"%s\", but is \"%s\""
+ old current))))
+
+ ((eq what 'tags)
+ (setq current (org-get-tags)
+ new1 (and new (org-split-string new ":+"))
+ old1 (and old (org-split-string old ":+")))
+ (cond
+ ((org-mobile-tags-same-p current new1) t) ; no change needed
+ ((or (org-mobile-tags-same-p current old1)
+ (eq org-mobile-force-mobile-change t)
+ (memq 'tags org-mobile-force-mobile-change))
+ (org-set-tags-to new1) t)
+ (t (error "Tags before change were expected as \"%s\", but are \"%s\""
+ (or old "") (or current "")))))
+
+ ((eq what 'priority)
+ (let ((case-fold-search nil))
+ (when (looking-at org-complex-heading-regexp)
+ (let ((current (and (match-end 3) (substring (match-string 3) 2 3))))
+ (cond
+ ((equal current new) t) ;no action required
+ ((or (equal current old)
+ (eq org-mobile-force-mobile-change t)
+ (memq 'tags org-mobile-force-mobile-change))
+ (org-priority (and new (string-to-char new))))
+ (t (error "Priority was expected to be %s, but is %s"
+ old current)))))))
+
+ ((eq what 'heading)
+ (let ((case-fold-search nil))
+ (when (looking-at org-complex-heading-regexp)
+ (let ((current (match-string 4)))
+ (cond
+ ((equal current new) t) ;no action required
+ ((or (equal current old)
+ (eq org-mobile-force-mobile-change t)
+ (memq 'heading org-mobile-force-mobile-change))
+ (goto-char (match-beginning 4))
+ (insert new)
+ (delete-region (point) (+ (point) (length current)))
+ (org-set-tags nil 'align))
+ (t (error "Heading changed in MobileOrg and on the computer")))))))
+
+ ((eq what 'addheading)
+ (if (org-at-heading-p) ; if false we are in top-level of file
+ (progn
+ ;; Workaround a `org-insert-heading-respect-content' bug
+ ;; which prevents correct insertion when point is invisible
+ (org-show-subtree)
+ (end-of-line 1)
+ (org-insert-heading-respect-content t)
+ (org-demote))
+ (beginning-of-line)
+ (insert "* "))
+ (insert new))
+
+ ((eq what 'refile)
+ (org-copy-subtree)
+ (org-with-point-at (org-mobile-locate-entry new)
+ (if (org-at-heading-p) ; if false we are in top-level of file
+ (progn
+ (setq level (org-get-valid-level (funcall outline-level) 1))
+ (org-end-of-subtree t t)
+ (org-paste-subtree level))
+ (org-paste-subtree 1)))
+ (org-cut-subtree))
+
+ ((eq what 'delete)
+ (org-cut-subtree))
+
+ ((eq what 'archive)
+ (org-archive-subtree))
+
+ ((eq what 'archive-sibling)
+ (org-archive-to-archive-sibling))
+
+ ((eq what 'body)
+ (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max))
+ (save-excursion (outline-next-heading)
+ (point))))
+ (if (not (string-match "\\S-" current)) (setq current nil))
+ (cond
+ ((org-mobile-bodies-same-p current new) t) ; no action necessary
+ ((or (org-mobile-bodies-same-p current old)
+ (eq org-mobile-force-mobile-change t)
+ (memq 'body org-mobile-force-mobile-change))
+ (save-excursion
+ (end-of-line 1)
+ (insert "\n" new)
+ (or (bolp) (insert "\n"))
+ (delete-region (point) (progn (org-back-to-heading t)
+ (outline-next-heading)
+ (point))))
+ t)
+ (t (error "Body was changed in MobileOrg and on the computer")))))))
+
+(defun org-mobile-tags-same-p (list1 list2)
+ "Are the two tag lists the same?"
+ (not (or (org-delete-all list1 list2)
+ (org-delete-all list2 list1))))
+
+(defun org-mobile-bodies-same-p (a b)
+ "Compare if A and B are visually equal strings.
+We first remove leading and trailing white space from the entire strings.
+Then we split the strings into lines and remove leading/trailing whitespace
+from each line. Then we compare.
+A and B must be strings or nil."
+ (cond
+ ((and (not a) (not b)) t)
+ ((or (not a) (not b)) nil)
+ (t (setq a (org-trim a) b (org-trim b))
+ (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n"))
+ (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n"))
+ (equal a b))))
+
+(provide 'org-mobile)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-mobile.el ends here
diff --git a/lisp/org-mouse.el b/lisp/org-mouse.el
new file mode 100644
index 0000000..d6a4727
--- /dev/null
+++ b/lisp/org-mouse.el
@@ -0,0 +1,1111 @@
+;;; org-mouse.el --- Better mouse support for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
+
+;; Author: Piotr Zielinski <piotr dot zielinski at gmail dot com>
+;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; Org-mouse provides mouse support for org-mode.
+;;
+;; http://orgmode.org
+;;
+;; Org mouse implements the following features:
+;; * following links with the left mouse button
+;; * subtree expansion/collapse (org-cycle) with the left mouse button
+;; * several context menus on the right mouse button:
+;; + general text
+;; + headlines
+;; + timestamps
+;; + priorities
+;; + links
+;; + tags
+;; * promoting/demoting/moving subtrees with mouse-3
+;; + if the drag starts and ends in the same line then promote/demote
+;; + otherwise move the subtree
+;;
+;; Use
+;; ---
+;;
+;; To use this package, put the following line in your .emacs:
+;;
+;; (require 'org-mouse)
+;;
+
+;; FIXME:
+;; + deal with folding / unfolding issues
+
+;; TODO (This list is only theoretical, if you'd like to have some
+;; feature implemented or a bug fix please send me an email, even if
+;; something similar appears in the list below. This will help me get
+;; the priorities right.):
+;;
+;; + org-store-link, insert link
+;; + org tables
+;; + occur with the current word/tag (same menu item)
+;; + ctrl-c ctrl-c, for example, renumber the current list
+;; + internal links
+
+;; Please email the maintainer with new feature suggestions / bugs
+
+;; History:
+;;
+;; Since version 5.10: Changes are listed in the general Org docs.
+;;
+;; Version 5.09;; + Version number synchronization with Org mode.
+;;
+;; Version 0.25
+;; + made compatible with Org 4.70 (thanks to Carsten for the patch)
+;;
+;; Version 0.24
+;; + minor changes to the table menu
+;;
+;; Version 0.23
+;; + preliminary support for tables and calculation marks
+;; + context menu support for org-agenda-undo & org-sort-entries
+;;
+;; Version 0.22
+;; + handles undo support for the agenda buffer (requires Org >=4.58)
+;;
+;; Version 0.21
+;; + selected text activates its context menu
+;; + shift-middleclick or right-drag inserts the text from the clipboard in the form of a link
+;;
+;; Version 0.20
+;; + the new "TODO Status" submenu replaces the "Cycle TODO" menu item
+;; + the TODO menu can now list occurrences of a specific TODO keyword
+;; + #+STARTUP line is now recognized
+;;
+;; Version 0.19
+;; + added support for dragging URLs to the org-buffer
+;;
+;; Version 0.18
+;; + added support for agenda blocks
+;;
+;; Version 0.17
+;; + toggle checkboxes with a single click
+;;
+;; Version 0.16
+;; + added support for checkboxes
+;;
+;; Version 0.15
+;; + Org now works with the Agenda buffer as well
+;;
+;; Version 0.14
+;; + added a menu option that converts plain list items to outline items
+;;
+;; Version 0.13
+;; + "Insert Heading" now inserts a sibling heading if the point is
+;; on "***" and a child heading otherwise
+;;
+;; Version 0.12
+;; + compatible with Emacs 21
+;; + custom agenda commands added to the main menu
+;; + moving trees should now work between windows in the same frame
+;;
+;; Version 0.11
+;; + fixed org-mouse-at-link (thanks to Carsten)
+;; + removed [follow-link] bindings
+;;
+;; Version 0.10
+;; + added a menu option to remove highlights
+;; + compatible with Org 4.21 now
+;;
+;; Version 0.08:
+;; + trees can be moved/promoted/demoted by dragging with the right
+;; mouse button (mouse-3)
+;; + small changes in the above function
+;;
+;; Versions 0.01 -- 0.07: (I don't remember)
+
+;;; Code:
+
+(require 'org)
+(require 'cl-lib)
+
+(defvar org-agenda-allow-remote-undo)
+(defvar org-agenda-undo-list)
+(defvar org-agenda-custom-commands)
+(declare-function org-agenda-change-all-lines "org-agenda"
+ (newhead hdmarker &optional fixface just-this))
+(declare-function org-verify-change-for-undo "org-agenda" (l1 l2))
+(declare-function org-apply-on-list "org-list" (function init-value &rest args))
+(declare-function org-agenda-earlier "org-agenda" (arg))
+(declare-function org-agenda-later "org-agenda" (arg))
+
+(defvar org-mouse-main-buffer nil
+ "Active buffer for mouse operations.")
+(defvar org-mouse-plain-list-regexp "\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
+ "Regular expression that matches a plain list.")
+(defvar org-mouse-direct t
+ "Internal variable indicating whether the current action is direct.
+
+If t, then the current action has been invoked directly through the buffer
+it is intended to operate on. If nil, then the action has been invoked
+indirectly, for example, through the agenda buffer.")
+
+(defgroup org-mouse nil
+ "Mouse support for org-mode."
+ :tag "Org Mouse"
+ :group 'org)
+
+(defcustom org-mouse-punctuation ":"
+ "Punctuation used when inserting text by drag and drop."
+ :group 'org-mouse
+ :type 'string)
+
+(defcustom org-mouse-features
+ '(context-menu yank-link activate-stars activate-bullets activate-checkboxes)
+ "The features of org-mouse that should be activated.
+Changing this variable requires a restart of Emacs to get activated."
+ :group 'org-mouse
+ :type '(set :greedy t
+ (const :tag "Mouse-3 shows context menu" context-menu)
+ (const :tag "C-mouse-1 and mouse-3 move trees" move-tree)
+ (const :tag "S-mouse-2 and drag-mouse-3 yank link" yank-link)
+ (const :tag "Activate headline stars" activate-stars)
+ (const :tag "Activate item bullets" activate-bullets)
+ (const :tag "Activate checkboxes" activate-checkboxes)))
+
+(defun org-mouse-re-search-line (regexp)
+ "Search the current line for a given regular expression."
+ (beginning-of-line)
+ (re-search-forward regexp (point-at-eol) t))
+
+(defun org-mouse-end-headline ()
+ "Go to the end of current headline (ignoring tags)."
+ (interactive)
+ (end-of-line)
+ (skip-chars-backward "\t ")
+ (when (looking-back ":[A-Za-z]+:" (line-beginning-position))
+ (skip-chars-backward ":A-Za-z")
+ (skip-chars-backward "\t ")))
+
+(defvar-local org-mouse-context-menu-function nil
+ "Function to create the context menu.
+The value of this variable is the function invoked by
+`org-mouse-context-menu' as the context menu.")
+
+(defun org-mouse-show-context-menu (event prefix)
+ "Invoke the context menu.
+
+If the value of `org-mouse-context-menu-function' is a function, then
+this function is called. Otherwise, the current major mode menu is used."
+ (interactive "@e \nP")
+ (if (and (= (event-click-count event) 1)
+ (or (not mark-active)
+ (sit-for (/ double-click-time 1000.0))))
+ (progn
+ (select-window (posn-window (event-start event)))
+ (when (not (org-mouse-mark-active))
+ (goto-char (posn-point (event-start event)))
+ (when (not (eolp)) (save-excursion (run-hooks 'post-command-hook)))
+ (sit-for 0))
+ (if (functionp org-mouse-context-menu-function)
+ (funcall org-mouse-context-menu-function event)
+ (if (fboundp 'mouse-menu-major-mode-map)
+ (popup-menu (mouse-menu-major-mode-map) event prefix)
+ (with-no-warnings ; don't warn about fallback, obsolete since 23.1
+ (mouse-major-mode-menu event prefix)))))
+ (setq this-command 'mouse-save-then-kill)
+ (mouse-save-then-kill event)))
+
+(defun org-mouse-line-position ()
+ "Return `:beginning' or `:middle' or `:end', depending on the point position.
+
+If the point is at the end of the line, return `:end'.
+If the point is separated from the beginning of the line only by white
+space and *'s (`org-mouse-bolp'), return `:beginning'. Otherwise,
+return `:middle'."
+ (cond
+ ((eolp) :end)
+ ((org-mouse-bolp) :beginning)
+ (t :middle)))
+
+(defun org-mouse-empty-line ()
+ "Return non-nil iff the line contains only white space."
+ (save-excursion (beginning-of-line) (looking-at "[ \t]*$")))
+
+(defun org-mouse-next-heading ()
+ "Go to the next heading.
+If there is none, ensure that the point is at the beginning of an empty line."
+ (unless (outline-next-heading)
+ (beginning-of-line)
+ (unless (org-mouse-empty-line)
+ (end-of-line)
+ (newline))))
+
+(defun org-mouse-insert-heading ()
+ "Insert a new heading, as `org-insert-heading'.
+
+If the point is at the :beginning (`org-mouse-line-position') of the line,
+insert the new heading before the current line. Otherwise, insert it
+after the current heading."
+ (interactive)
+ (cl-case (org-mouse-line-position)
+ (:beginning (beginning-of-line)
+ (org-insert-heading))
+ (t (org-mouse-next-heading)
+ (org-insert-heading))))
+
+(defun org-mouse-timestamp-today (&optional shift units)
+ "Change the timestamp into SHIFT UNITS in the future.
+
+For the acceptable UNITS, see `org-timestamp-change'."
+ (interactive)
+ (org-time-stamp nil)
+ (when shift (org-timestamp-change shift units)))
+
+(defun org-mouse-keyword-menu (keywords function &optional selected itemformat)
+ "A helper function.
+
+Returns a menu fragment consisting of KEYWORDS. When a keyword
+is selected by the user, FUNCTION is called with the selected
+keyword as the only argument.
+
+If SELECTED is nil, then all items are normal menu items. If
+SELECTED is a function, then each item is a checkbox, which is
+enabled for a given keyword iff (funcall SELECTED keyword) return
+non-nil. If SELECTED is neither nil nor a function, then the
+items are radio buttons. A radio button is enabled for the
+keyword `equal' to SELECTED.
+
+ITEMFORMAT governs formatting of the elements of KEYWORDS. If it
+is a function, it is invoked with the keyword as the only
+argument. If it is a string, it is interpreted as the format
+string to (format ITEMFORMAT keyword). If it is neither a string
+nor a function, elements of KEYWORDS are used directly."
+ (mapcar
+ `(lambda (keyword)
+ (vector (cond
+ ((functionp ,itemformat) (funcall ,itemformat keyword))
+ ((stringp ,itemformat) (format ,itemformat keyword))
+ (t keyword))
+ (list 'funcall ,function keyword)
+ :style (cond
+ ((null ,selected) t)
+ ((functionp ,selected) 'toggle)
+ (t 'radio))
+ :selected (if (functionp ,selected)
+ (and (funcall ,selected keyword) t)
+ (equal ,selected keyword))))
+ keywords))
+
+(defun org-mouse-remove-match-and-spaces ()
+ "Remove the match, make just one space around the point."
+ (interactive)
+ (replace-match "")
+ (just-one-space))
+
+(defvar org-mouse-rest)
+(defun org-mouse-replace-match-and-surround
+ (_newtext &optional _fixedcase _literal _string subexp)
+ "The same as `replace-match', but surrounds the replacement with spaces."
+ (apply #'replace-match org-mouse-rest)
+ (save-excursion
+ (goto-char (match-beginning (or subexp 0)))
+ (just-one-space)
+ (goto-char (match-end (or subexp 0)))
+ (just-one-space)))
+
+(defun org-mouse-keyword-replace-menu (keywords &optional group itemformat
+ nosurround)
+ "A helper function.
+
+Returns a menu fragment consisting of KEYWORDS. When a keyword
+is selected, group GROUP of the current match is replaced by the
+keyword. The method ensures that both ends of the replacement
+are separated from the rest of the text in the buffer by
+individual spaces (unless NOSURROUND is non-nil).
+
+The final entry of the menu is always \"None\", which removes the
+match.
+
+ITEMFORMAT governs formatting of the elements of KEYWORDS. If it
+is a function, it is invoked with the keyword as the only
+argument. If it is a string, it is interpreted as the format
+string to (format ITEMFORMAT keyword). If it is neither a string
+nor a function, elements of KEYWORDS are used directly."
+ (setq group (or group 0))
+ (let ((replace (org-mouse-match-closure
+ (if nosurround 'replace-match
+ 'org-mouse-replace-match-and-surround))))
+ (append
+ (org-mouse-keyword-menu
+ keywords
+ `(lambda (keyword) (funcall ,replace keyword t t nil ,group))
+ (match-string group)
+ itemformat)
+ `(["None" org-mouse-remove-match-and-spaces
+ :style radio
+ :selected ,(not (member (match-string group) keywords))]))))
+
+(defun org-mouse-show-headlines ()
+ "Change the visibility of the current org buffer to only show headlines."
+ (interactive)
+ (let ((this-command 'org-cycle)
+ (last-command 'org-cycle)
+ (org-cycle-global-status nil))
+ (org-cycle '(4))
+ (org-cycle '(4))))
+
+(defun org-mouse-show-overview ()
+ "Change visibility of current org buffer to first-level headlines only."
+ (interactive)
+ (let ((org-cycle-global-status nil))
+ (org-cycle '(4))))
+
+(defun org-mouse-set-priority (priority)
+ "Set the priority of the current headline to PRIORITY."
+ (org-priority priority))
+
+(defvar org-mouse-priority-regexp "\\[#\\([A-Z]\\)\\]"
+ "Regular expression matching the priority indicator.
+Differs from `org-priority-regexp' in that it doesn't contain the
+leading `.*?'.")
+
+(defun org-mouse-get-priority (&optional default)
+ "Return the priority of the current headline.
+DEFAULT is returned if no priority is given in the headline."
+ (save-excursion
+ (if (org-mouse-re-search-line org-mouse-priority-regexp)
+ (match-string 1)
+ (when default (char-to-string org-default-priority)))))
+
+(defun org-mouse-delete-timestamp ()
+ "Deletes the current timestamp as well as the preceding keyword.
+SCHEDULED: or DEADLINE: or ANYTHINGLIKETHIS:"
+ (when (or (org-at-date-range-p) (org-at-timestamp-p))
+ (replace-match "") ; delete the timestamp
+ (skip-chars-backward " :A-Z")
+ (when (looking-at " *[A-Z][A-Z]+:")
+ (replace-match ""))))
+
+(defun org-mouse-looking-at (regexp skipchars &optional movechars)
+ (save-excursion
+ (let ((point (point)))
+ (if (looking-at regexp) t
+ (skip-chars-backward skipchars)
+ (forward-char (or movechars 0))
+ (when (looking-at regexp)
+ (> (match-end 0) point))))))
+
+(defun org-mouse-priority-list ()
+ (cl-loop for priority from ?A to org-lowest-priority
+ collect (char-to-string priority)))
+
+(defun org-mouse-todo-menu (state)
+ "Create the menu with TODO keywords."
+ (append
+ (let ((kwds org-todo-keywords-1))
+ (org-mouse-keyword-menu
+ kwds
+ `(lambda (kwd) (org-todo kwd))
+ (lambda (kwd) (equal state kwd))))))
+
+(defun org-mouse-tag-menu () ;todo
+ "Create the tags menu."
+ (append
+ (let ((tags (org-get-tags)))
+ (org-mouse-keyword-menu
+ (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
+ `(lambda (tag)
+ (org-mouse-set-tags
+ (sort (if (member tag (quote ,tags))
+ (delete tag (quote ,tags))
+ (cons tag (quote ,tags)))
+ 'string-lessp)))
+ `(lambda (tag) (member tag (quote ,tags)))
+ ))
+ '("--"
+ ["Align Tags Here" (org-set-tags nil t) t]
+ ["Align Tags in Buffer" (org-set-tags t t) t]
+ ["Set Tags ..." (org-set-tags) t])))
+
+(defun org-mouse-set-tags (tags)
+ (save-excursion
+ ;; remove existing tags first
+ (beginning-of-line)
+ (when (org-mouse-re-search-line ":\\(\\([A-Za-z_]+:\\)+\\)")
+ (replace-match ""))
+
+ ;; set new tags if any
+ (when tags
+ (end-of-line)
+ (insert " :" (mapconcat 'identity tags ":") ":")
+ (org-set-tags nil t))))
+
+(defun org-mouse-insert-checkbox ()
+ (interactive)
+ (and (org-at-item-p)
+ (goto-char (match-end 0))
+ (unless (org-at-item-checkbox-p)
+ (delete-horizontal-space)
+ (insert " [ ] "))))
+
+(defun org-mouse-agenda-type (type)
+ (pcase type
+ (`tags "Tags: ")
+ (`todo "TODO: ")
+ (`tags-tree "Tags tree: ")
+ (`todo-tree "TODO tree: ")
+ (`occur-tree "Occur tree: ")
+ (_ "Agenda command ???")))
+
+(defun org-mouse-list-options-menu (alloptions &optional function)
+ (let ((options (save-match-data
+ (split-string (match-string-no-properties 1)))))
+ (print options)
+ (cl-loop for name in alloptions
+ collect
+ (vector name
+ `(progn
+ (replace-match
+ (mapconcat 'identity
+ (sort (if (member ',name ',options)
+ (delete ',name ',options)
+ (cons ',name ',options))
+ 'string-lessp)
+ " ")
+ nil nil nil 1)
+ (when (functionp ',function) (funcall ',function)))
+ :style 'toggle
+ :selected (and (member name options) t)))))
+
+(defun org-mouse-clip-text (text maxlength)
+ (if (> (length text) maxlength)
+ (concat (substring text 0 (- maxlength 3)) "...")
+ text))
+
+(defun org-mouse-popup-global-menu ()
+ (popup-menu
+ `("Main Menu"
+ ["Show Overview" org-mouse-show-overview t]
+ ["Show Headlines" org-mouse-show-headlines t]
+ ["Show All" outline-show-all t]
+ ["Remove Highlights" org-remove-occur-highlights
+ :visible org-occur-highlights]
+ "--"
+ ["Check Deadlines"
+ (if (functionp 'org-check-deadlines-and-todos)
+ (org-check-deadlines-and-todos org-deadline-warning-days)
+ (org-check-deadlines org-deadline-warning-days)) t]
+ ["Check TODOs" org-show-todo-tree t]
+ ("Check Tags"
+ ,@(org-mouse-keyword-menu
+ (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
+ #'(lambda (tag) (org-tags-sparse-tree nil tag)))
+ "--"
+ ["Custom Tag ..." org-tags-sparse-tree t])
+ ["Check Phrase ..." org-occur]
+ "--"
+ ["Display Agenda" org-agenda-list t]
+ ["Display Timeline" org-timeline t]
+ ["Display TODO List" org-todo-list t]
+ ("Display Tags"
+ ,@(org-mouse-keyword-menu
+ (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp)
+ #'(lambda (tag) (org-tags-view nil tag)))
+ "--"
+ ["Custom Tag ..." org-tags-view t])
+ ["Display Calendar" org-goto-calendar t]
+ "--"
+ ,@(org-mouse-keyword-menu
+ (mapcar 'car org-agenda-custom-commands)
+ #'(lambda (key)
+ (eval `(org-agenda nil (string-to-char ,key))))
+ nil
+ #'(lambda (key)
+ (let ((entry (assoc key org-agenda-custom-commands)))
+ (org-mouse-clip-text
+ (cond
+ ((stringp (nth 1 entry)) (nth 1 entry))
+ ((stringp (nth 2 entry))
+ (concat (org-mouse-agenda-type (nth 1 entry))
+ (nth 2 entry)))
+ (t "Agenda Command `%s'"))
+ 30))))
+ "--"
+ ["Delete Blank Lines" delete-blank-lines
+ :visible (org-mouse-empty-line)]
+ ["Insert Checkbox" org-mouse-insert-checkbox
+ :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))]
+ ["Insert Checkboxes"
+ (org-mouse-for-each-item 'org-mouse-insert-checkbox)
+ :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))]
+ ["Plain List to Outline" org-mouse-transform-to-outline
+ :visible (org-at-item-p)])))
+
+(defun org-mouse-get-context (contextlist context)
+ (let ((contextdata (assq context contextlist)))
+ (when contextdata
+ (save-excursion
+ (goto-char (nth 1 contextdata))
+ (re-search-forward ".*" (nth 2 contextdata))))))
+
+(defun org-mouse-for-each-item (funct)
+ ;; Functions called by `org-apply-on-list' need an argument.
+ (let ((wrap-fun (lambda (_) (funcall funct))))
+ (when (ignore-errors (goto-char (org-in-item-p)))
+ (save-excursion (org-apply-on-list wrap-fun nil)))))
+
+(defun org-mouse-bolp ()
+ "Return true if there only spaces, tabs, and `*' before point.
+This means, between the beginning of line and the point."
+ (save-excursion
+ (skip-chars-backward " \t*") (bolp)))
+
+(defun org-mouse-insert-item (text)
+ (cl-case (org-mouse-line-position)
+ (:beginning ; insert before
+ (beginning-of-line)
+ (looking-at "[ \t]*")
+ (open-line 1)
+ (indent-to-column (- (match-end 0) (match-beginning 0)))
+ (insert "+ "))
+ (:middle ; insert after
+ (end-of-line)
+ (newline t)
+ (indent-relative)
+ (insert "+ "))
+ (:end ; insert text here
+ (skip-chars-backward " \t")
+ (kill-region (point) (point-at-eol))
+ (unless (looking-back org-mouse-punctuation (line-beginning-position))
+ (insert (concat org-mouse-punctuation " ")))))
+ (insert text)
+ (beginning-of-line))
+
+(defadvice dnd-insert-text (around org-mouse-dnd-insert-text activate)
+ (if (derived-mode-p 'org-mode)
+ (org-mouse-insert-item text)
+ ad-do-it))
+
+(defadvice dnd-open-file (around org-mouse-dnd-open-file activate)
+ (if (derived-mode-p 'org-mode)
+ (org-mouse-insert-item uri)
+ ad-do-it))
+
+(defun org-mouse-match-closure (function)
+ (let ((match (match-data t)))
+ `(lambda (&rest rest)
+ (save-match-data
+ (set-match-data ',match)
+ (apply ',function rest)))))
+
+(defun org-mouse-yank-link (click)
+ (interactive "e")
+ ;; Give temporary modes such as isearch a chance to turn off.
+ (run-hooks 'mouse-leave-buffer-hook)
+ (mouse-set-point click)
+ (setq mouse-selection-click-count 0)
+ (delete-horizontal-space)
+ (insert-for-yank (concat " [[" (current-kill 0) "]] ")))
+
+(defun org-mouse-context-menu (&optional event)
+ (let* ((stamp-prefixes (list org-deadline-string org-scheduled-string))
+ (contextlist (org-context))
+ (get-context (lambda (context) (org-mouse-get-context contextlist context))))
+ (cond
+ ((org-mouse-mark-active)
+ (let ((region-string (buffer-substring (region-beginning) (region-end))))
+ (popup-menu
+ `(nil
+ ["Sparse Tree" (org-occur ',region-string)]
+ ["Find in Buffer" (occur ',region-string)]
+ ["Grep in Current Dir"
+ (grep (format "grep -rnH -e '%s' *" ',region-string))]
+ ["Grep in Parent Dir"
+ (grep (format "grep -rnH -e '%s' ../*" ',region-string))]
+ "--"
+ ["Convert to Link"
+ (progn (save-excursion (goto-char (region-beginning)) (insert "[["))
+ (save-excursion (goto-char (region-end)) (insert "]]")))]
+ ["Insert Link Here" (org-mouse-yank-link ',event)]))))
+ ((save-excursion (beginning-of-line) (looking-at "[ \t]*#\\+STARTUP: \\(.*\\)"))
+ (popup-menu
+ `(nil
+ ,@(org-mouse-list-options-menu (mapcar 'car org-startup-options)
+ 'org-mode-restart))))
+ ((or (eolp)
+ (and (looking-at "\\( \\|\t\\)\\(+:[0-9a-zA-Z_:]+\\)?\\( \\|\t\\)+$")
+ (looking-back " \\|\t" (- (point) 2)
+ (line-beginning-position))))
+ (org-mouse-popup-global-menu))
+ ((funcall get-context :checkbox)
+ (popup-menu
+ '(nil
+ ["Toggle" org-toggle-checkbox t]
+ ["Remove" org-mouse-remove-match-and-spaces t]
+ ""
+ ["All Clear" (org-mouse-for-each-item
+ (lambda ()
+ (when (save-excursion (org-at-item-checkbox-p))
+ (replace-match "[ ] "))))]
+ ["All Set" (org-mouse-for-each-item
+ (lambda ()
+ (when (save-excursion (org-at-item-checkbox-p))
+ (replace-match "[X] "))))]
+ ["All Toggle" (org-mouse-for-each-item 'org-toggle-checkbox) t]
+ ["All Remove" (org-mouse-for-each-item
+ (lambda ()
+ (when (save-excursion (org-at-item-checkbox-p))
+ (org-mouse-remove-match-and-spaces))))]
+ )))
+ ((and (org-mouse-looking-at "\\b\\w+" "a-zA-Z0-9_")
+ (member (match-string 0) org-todo-keywords-1))
+ (popup-menu
+ `(nil
+ ,@(org-mouse-todo-menu (match-string 0))
+ "--"
+ ["Check TODOs" org-show-todo-tree t]
+ ["List all TODO keywords" org-todo-list t]
+ [,(format "List only %s" (match-string 0))
+ (org-todo-list (match-string 0)) t]
+ )))
+ ((and (org-mouse-looking-at "\\b[A-Z]+:" "A-Z")
+ (member (match-string 0) stamp-prefixes))
+ (popup-menu
+ `(nil
+ ,@(org-mouse-keyword-replace-menu stamp-prefixes)
+ "--"
+ ["Check Deadlines" org-check-deadlines t]
+ )))
+ ((org-mouse-looking-at org-mouse-priority-regexp "[]A-Z#") ; priority
+ (popup-menu `(nil ,@(org-mouse-keyword-replace-menu
+ (org-mouse-priority-list) 1 "Priority %s" t))))
+ ((funcall get-context :link)
+ (popup-menu
+ '(nil
+ ["Open" org-open-at-point t]
+ ["Open in Emacs" (org-open-at-point t) t]
+ "--"
+ ["Copy link" (org-kill-new (match-string 0))]
+ ["Cut link"
+ (progn
+ (kill-region (match-beginning 0) (match-end 0))
+ (just-one-space))]
+ "--"
+ ["Grep for TODOs"
+ (grep (format "grep -nH -i 'todo\\|fixme' %s*" (match-string 2)))]
+ ; ["Paste file link" ((insert "file:") (yank))]
+ )))
+ ((org-mouse-looking-at ":\\([A-Za-z0-9_]+\\):" "A-Za-z0-9_" -1) ;tags
+ (popup-menu
+ `(nil
+ [,(format-message "Display `%s'" (match-string 1))
+ (org-tags-view nil ,(match-string 1))]
+ [,(format-message "Sparse Tree `%s'" (match-string 1))
+ (org-tags-sparse-tree nil ,(match-string 1))]
+ "--"
+ ,@(org-mouse-tag-menu))))
+ ((org-at-timestamp-p)
+ (popup-menu
+ '(nil
+ ["Show Day" org-open-at-point t]
+ ["Change Timestamp" org-time-stamp t]
+ ["Delete Timestamp" (org-mouse-delete-timestamp) t]
+ ["Compute Time Range" org-evaluate-time-range (org-at-date-range-p)]
+ "--"
+ ["Set for Today" org-mouse-timestamp-today]
+ ["Set for Tomorrow" (org-mouse-timestamp-today 1 'day)]
+ ["Set in 1 Week" (org-mouse-timestamp-today 7 'day)]
+ ["Set in 2 Weeks" (org-mouse-timestamp-today 14 'day)]
+ ["Set in a Month" (org-mouse-timestamp-today 1 'month)]
+ "--"
+ ["+ 1 Day" (org-timestamp-change 1 'day)]
+ ["+ 1 Week" (org-timestamp-change 7 'day)]
+ ["+ 1 Month" (org-timestamp-change 1 'month)]
+ "--"
+ ["- 1 Day" (org-timestamp-change -1 'day)]
+ ["- 1 Week" (org-timestamp-change -7 'day)]
+ ["- 1 Month" (org-timestamp-change -1 'month)])))
+ ((funcall get-context :table-special)
+ (let ((mdata (match-data)))
+ (cl-incf (car mdata) 2)
+ (store-match-data mdata))
+ (message "match: %S" (match-string 0))
+ (popup-menu `(nil ,@(org-mouse-keyword-replace-menu
+ '(" " "!" "^" "_" "$" "#" "*" "'") 0
+ (lambda (mark)
+ (cl-case (string-to-char mark)
+ (? "( ) Nothing Special")
+ (?! "(!) Column Names")
+ (?^ "(^) Field Names Above")
+ (?_ "(^) Field Names Below")
+ (?$ "($) Formula Parameters")
+ (?# "(#) Recalculation: Auto")
+ (?* "(*) Recalculation: Manual")
+ (?' "(') Recalculation: None"))) t))))
+ ((assq :table contextlist)
+ (popup-menu
+ '(nil
+ ["Align Table" org-ctrl-c-ctrl-c]
+ ["Blank Field" org-table-blank-field]
+ ["Edit Field" org-table-edit-field]
+ "--"
+ ("Column"
+ ["Move Column Left" org-metaleft]
+ ["Move Column Right" org-metaright]
+ ["Delete Column" org-shiftmetaleft]
+ ["Insert Column" org-shiftmetaright]
+ "--"
+ ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :selected org-table-limit-column-width :style toggle])
+ ("Row"
+ ["Move Row Up" org-metaup]
+ ["Move Row Down" org-metadown]
+ ["Delete Row" org-shiftmetaup]
+ ["Insert Row" org-shiftmetadown]
+ ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
+ "--"
+ ["Insert Hline" org-table-insert-hline])
+ ("Rectangle"
+ ["Copy Rectangle" org-copy-special]
+ ["Cut Rectangle" org-cut-special]
+ ["Paste Rectangle" org-paste-special]
+ ["Fill Rectangle" org-table-wrap-region])
+ "--"
+ ["Set Column Formula" org-table-eval-formula]
+ ["Set Field Formula" (org-table-eval-formula '(4))]
+ ["Edit Formulas" org-table-edit-formulas]
+ "--"
+ ["Recalculate Line" org-table-recalculate]
+ ["Recalculate All" (org-table-recalculate '(4))]
+ ["Iterate All" (org-table-recalculate '(16))]
+ "--"
+ ["Toggle Recalculate Mark" org-table-rotate-recalc-marks]
+ ["Sum Column/Rectangle" org-table-sum
+ :active (or (org-at-table-p) (org-region-active-p))]
+ ["Field Info" org-table-field-info]
+ ["Debug Formulas"
+ (setq org-table-formula-debug (not org-table-formula-debug))
+ :style toggle :selected org-table-formula-debug]
+ )))
+ ((and (assq :headline contextlist) (not (eolp)))
+ (let ((priority (org-mouse-get-priority t)))
+ (popup-menu
+ `("Headline Menu"
+ ("Tags and Priorities"
+ ,@(org-mouse-keyword-menu
+ (org-mouse-priority-list)
+ #'(lambda (keyword)
+ (org-mouse-set-priority (string-to-char keyword)))
+ priority "Priority %s")
+ "--"
+ ,@(org-mouse-tag-menu))
+ ("TODO Status"
+ ,@(org-mouse-todo-menu (org-get-todo-state)))
+ ["Show Tags"
+ (with-current-buffer org-mouse-main-buffer (org-agenda-show-tags))
+ :visible (not org-mouse-direct)]
+ ["Show Priority"
+ (with-current-buffer org-mouse-main-buffer (org-agenda-show-priority))
+ :visible (not org-mouse-direct)]
+ ,@(if org-mouse-direct '("--") nil)
+ ["New Heading" org-mouse-insert-heading :visible org-mouse-direct]
+ ["Set Deadline"
+ (progn (org-mouse-end-headline) (insert " ") (org-deadline))
+ :active (not (save-excursion
+ (org-mouse-re-search-line org-deadline-regexp)))]
+ ["Schedule Task"
+ (progn (org-mouse-end-headline) (insert " ") (org-schedule))
+ :active (not (save-excursion
+ (org-mouse-re-search-line org-scheduled-regexp)))]
+ ["Insert Timestamp"
+ (progn (org-mouse-end-headline) (insert " ") (org-time-stamp nil)) t]
+ ; ["Timestamp (inactive)" org-time-stamp-inactive t]
+ "--"
+ ["Archive Subtree" org-archive-subtree]
+ ["Cut Subtree" org-cut-special]
+ ["Copy Subtree" org-copy-special]
+ ["Paste Subtree" org-paste-special :visible org-mouse-direct]
+ ("Sort Children"
+ ["Alphabetically" (org-sort-entries nil ?a)]
+ ["Numerically" (org-sort-entries nil ?n)]
+ ["By Time/Date" (org-sort-entries nil ?t)]
+ "--"
+ ["Reverse Alphabetically" (org-sort-entries nil ?A)]
+ ["Reverse Numerically" (org-sort-entries nil ?N)]
+ ["Reverse By Time/Date" (org-sort-entries nil ?T)])
+ "--"
+ ["Move Trees" org-mouse-move-tree :active nil]
+ ))))
+ (t
+ (org-mouse-popup-global-menu)))))
+
+(defun org-mouse-mark-active ()
+ (and mark-active transient-mark-mode))
+
+(defun org-mouse-in-region-p (pos)
+ (and (org-mouse-mark-active)
+ (>= pos (region-beginning))
+ (< pos (region-end))))
+
+(defun org-mouse-down-mouse (event)
+ (interactive "e")
+ (setq this-command last-command)
+ (unless (and (= 1 (event-click-count event))
+ (org-mouse-in-region-p (posn-point (event-start event))))
+ (mouse-drag-region event)))
+
+(add-hook 'org-mode-hook
+ #'(lambda ()
+ (setq org-mouse-context-menu-function 'org-mouse-context-menu)
+
+ (when (memq 'context-menu org-mouse-features)
+ (org-defkey org-mouse-map [mouse-3] nil)
+ (org-defkey org-mode-map [mouse-3] 'org-mouse-show-context-menu))
+ (org-defkey org-mode-map [down-mouse-1] 'org-mouse-down-mouse)
+ (when (memq 'context-menu org-mouse-features)
+ (org-defkey org-mouse-map [C-drag-mouse-1] 'org-mouse-move-tree)
+ (org-defkey org-mouse-map [C-down-mouse-1] 'org-mouse-move-tree-start))
+ (when (memq 'yank-link org-mouse-features)
+ (org-defkey org-mode-map [S-mouse-2] 'org-mouse-yank-link)
+ (org-defkey org-mode-map [drag-mouse-3] 'org-mouse-yank-link))
+ (when (memq 'move-tree org-mouse-features)
+ (org-defkey org-mouse-map [drag-mouse-3] 'org-mouse-move-tree)
+ (org-defkey org-mouse-map [down-mouse-3] 'org-mouse-move-tree-start))
+
+ (when (memq 'activate-stars org-mouse-features)
+ (font-lock-add-keywords
+ nil
+ `((,org-outline-regexp
+ 0 `(face org-link mouse-face highlight keymap ,org-mouse-map)
+ 'prepend))
+ t))
+
+ (when (memq 'activate-bullets org-mouse-features)
+ (font-lock-add-keywords
+ nil
+ `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +"
+ (1 `(face org-link keymap ,org-mouse-map mouse-face highlight)
+ 'prepend)))
+ t))
+
+ (when (memq 'activate-checkboxes org-mouse-features)
+ (font-lock-add-keywords
+ nil
+ `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
+ (2 `(face bold keymap ,org-mouse-map mouse-face highlight) t)))
+ t))
+
+ (defadvice org-open-at-point (around org-mouse-open-at-point activate)
+ (let ((context (org-context)))
+ (cond
+ ((assq :headline-stars context) (org-cycle))
+ ((assq :checkbox context) (org-toggle-checkbox))
+ ((assq :item-bullet context)
+ (let ((org-cycle-include-plain-lists t)) (org-cycle)))
+ ((org-footnote-at-reference-p) nil)
+ (t ad-do-it))))))
+
+(defun org-mouse-move-tree-start (_event)
+ (interactive "e")
+ (message "Same line: promote/demote, (***):move before, (text): make a child"))
+
+
+(defun org-mouse-make-marker (position)
+ (with-current-buffer (window-buffer (posn-window position))
+ (copy-marker (posn-point position))))
+
+(defun org-mouse-move-tree (event)
+ ;; todo: handle movements between different buffers
+ (interactive "e")
+ (save-excursion
+ (let* ((start (org-mouse-make-marker (event-start event)))
+ (end (org-mouse-make-marker (event-end event)))
+ (sbuf (marker-buffer start))
+ (ebuf (marker-buffer end)))
+
+ (when (and sbuf ebuf)
+ (set-buffer sbuf)
+ (goto-char start)
+ (org-back-to-heading)
+ (if (and (eq sbuf ebuf)
+ (equal
+ (point)
+ (save-excursion (goto-char end) (org-back-to-heading) (point))))
+ ;; if the same line then promote/demote
+ (if (>= end start) (org-demote-subtree) (org-promote-subtree))
+ ;; if different lines then move
+ (org-cut-subtree)
+
+ (set-buffer ebuf)
+ (goto-char end)
+ (org-back-to-heading)
+ (when (and (eq sbuf ebuf)
+ (equal
+ (point)
+ (save-excursion (goto-char start)
+ (org-back-to-heading) (point))))
+ (progn (org-end-of-subtree nil t)
+ (unless (eobp) (backward-char)))
+ (end-of-line)
+ (if (eobp) (newline) (forward-char)))
+
+ (when (looking-at org-outline-regexp)
+ (let ((level (- (match-end 0) (match-beginning 0))))
+ (when (> end (match-end 0))
+ (progn (org-end-of-subtree nil t)
+ (unless (eobp) (backward-char)))
+ (end-of-line)
+ (if (eobp) (newline) (forward-char))
+ (setq level (1+ level)))
+ (org-paste-subtree level)
+ (save-excursion
+ (progn (org-end-of-subtree nil t)
+ (unless (eobp) (backward-char)))
+ (when (bolp) (delete-char -1))))))))))
+
+
+(defun org-mouse-transform-to-outline ()
+ (interactive)
+ (org-back-to-heading)
+ (let ((minlevel 1000)
+ (replace-text (concat (match-string 0) "* ")))
+ (beginning-of-line 2)
+ (save-excursion
+ (while (not (or (eobp) (looking-at org-outline-regexp)))
+ (when (looking-at org-mouse-plain-list-regexp)
+ (setq minlevel (min minlevel (- (match-end 1) (match-beginning 1)))))
+ (forward-line)))
+ (while (not (or (eobp) (looking-at org-outline-regexp)))
+ (when (and (looking-at org-mouse-plain-list-regexp)
+ (eq minlevel (- (match-end 1) (match-beginning 1))))
+ (replace-match replace-text))
+ (forward-line))))
+
+(defvar org-mouse-cmd) ;dynamically scoped from `org-with-remote-undo'.
+
+(defun org-mouse-do-remotely (command)
+ ;; (org-agenda-check-no-diary)
+ (when (get-text-property (point) 'org-marker)
+ (let* ((anticol (- (point-at-eol) (point)))
+ (marker (get-text-property (point) 'org-marker))
+ (buffer (marker-buffer marker))
+ (pos (marker-position marker))
+ (hdmarker (get-text-property (point) 'org-hd-marker))
+ (buffer-read-only nil)
+ (newhead "--- removed ---")
+ (org-mouse-direct nil)
+ (org-mouse-main-buffer (current-buffer)))
+ (when (eq (with-current-buffer buffer major-mode) 'org-mode)
+ (let ((endmarker (with-current-buffer buffer
+ (org-end-of-subtree nil t)
+ (unless (eobp) (forward-char 1))
+ (point-marker))))
+ (org-with-remote-undo buffer
+ (with-current-buffer buffer
+ (widen)
+ (goto-char pos)
+ (org-show-hidden-entry)
+ (save-excursion
+ (and (outline-next-heading)
+ (org-flag-heading nil))) ; show the next heading
+ (org-back-to-heading)
+ (setq marker (point-marker))
+ (goto-char (max (point-at-bol) (- (point-at-eol) anticol)))
+ (funcall command)
+ (message "_cmd: %S" org-mouse-cmd)
+ (message "this-command: %S" this-command)
+ (unless (eq (marker-position marker) (marker-position endmarker))
+ (setq newhead (org-get-heading))))
+
+ (beginning-of-line 1)
+ (save-excursion
+ (org-agenda-change-all-lines newhead hdmarker 'fixface))))
+ t))))
+
+(defun org-mouse-agenda-context-menu (&optional _event)
+ (or (org-mouse-do-remotely 'org-mouse-context-menu)
+ (popup-menu
+ '("Agenda"
+ ("Agenda Files")
+ "--"
+ ["Undo" (progn (message "last command: %S" last-command) (setq this-command 'org-agenda-undo) (org-agenda-undo))
+ :visible (if (eq last-command 'org-agenda-undo)
+ org-agenda-pending-undo-list
+ org-agenda-undo-list)]
+ ["Rebuild Buffer" org-agenda-redo t]
+ ["New Diary Entry"
+ org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline) t]
+ "--"
+ ["Goto Today" org-agenda-goto-today
+ (org-agenda-check-type nil 'agenda 'timeline) t]
+ ["Display Calendar" org-agenda-goto-calendar
+ (org-agenda-check-type nil 'agenda 'timeline) t]
+ ("Calendar Commands"
+ ["Phases of the Moon" org-agenda-phases-of-moon
+ (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Sunrise/Sunset" org-agenda-sunrise-sunset
+ (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Holidays" org-agenda-holidays
+ (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Convert" org-agenda-convert-date
+ (org-agenda-check-type nil 'agenda 'timeline)]
+ "--"
+ ["Create iCalendar file" org-icalendar-combine-agenda-files t])
+ "--"
+ ["Day View" org-agenda-day-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'day)]
+ ["Week View" org-agenda-week-view
+ :active (org-agenda-check-type nil 'agenda)
+ :style radio :selected (eq org-agenda-current-span 'week)]
+ "--"
+ ["Show Logbook entries" org-agenda-log-mode
+ :style toggle :selected org-agenda-show-log
+ :active (org-agenda-check-type nil 'agenda 'timeline)]
+ ["Include Diary" org-agenda-toggle-diary
+ :style toggle :selected org-agenda-include-diary
+ :active (org-agenda-check-type nil 'agenda)]
+ ["Use Time Grid" org-agenda-toggle-time-grid
+ :style toggle :selected org-agenda-use-time-grid
+ :active (org-agenda-check-type nil 'agenda)]
+ ["Follow Mode" org-agenda-follow-mode
+ :style toggle :selected org-agenda-follow-mode]
+ "--"
+ ["Quit" org-agenda-quit t]
+ ["Exit and Release Buffers" org-agenda-exit t]
+ ))))
+
+(defun org-mouse-get-gesture (event)
+ (let ((startxy (posn-x-y (event-start event)))
+ (endxy (posn-x-y (event-end event))))
+ (if (< (car startxy) (car endxy)) :right :left)))
+
+
+ ; (setq org-agenda-mode-hook nil)
+(defvar org-agenda-mode-map)
+(add-hook 'org-agenda-mode-hook
+ (lambda ()
+ (setq org-mouse-context-menu-function 'org-mouse-agenda-context-menu)
+ (org-defkey org-agenda-mode-map [mouse-3] 'org-mouse-show-context-menu)
+ (org-defkey org-agenda-mode-map [down-mouse-3] 'org-mouse-move-tree-start)
+ (org-defkey org-agenda-mode-map [C-mouse-4] 'org-agenda-earlier)
+ (org-defkey org-agenda-mode-map [C-mouse-5] 'org-agenda-later)
+ (org-defkey org-agenda-mode-map [drag-mouse-3]
+ (lambda (event) (interactive "e")
+ (cl-case (org-mouse-get-gesture event)
+ (:left (org-agenda-earlier 1))
+ (:right (org-agenda-later 1)))))))
+
+(provide 'org-mouse)
+
+;;; org-mouse.el ends here
diff --git a/lisp/org-pcomplete.el b/lisp/org-pcomplete.el
new file mode 100644
index 0000000..61ec5fa
--- /dev/null
+++ b/lisp/org-pcomplete.el
@@ -0,0 +1,391 @@
+;;; org-pcomplete.el --- In-buffer Completion Code -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; John Wiegley <johnw at gnu dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Code:
+
+;;;; Require other packages
+
+(require 'org-macs)
+(require 'org-compat)
+(require 'pcomplete)
+
+(declare-function org-make-org-heading-search-string "org" (&optional string))
+(declare-function org-get-buffer-tags "org" ())
+(declare-function org-get-tags "org" ())
+(declare-function org-buffer-property-keys "org"
+ (&optional specials defaults columns ignore-malformed))
+(declare-function org-entry-properties "org" (&optional pom which))
+(declare-function org-tag-alist-to-string "org" (alist &optional skip-key))
+
+;;;; Customization variables
+
+(defgroup org-complete nil
+ "Outline-based notes management and organizer."
+ :tag "Org"
+ :group 'org)
+
+(defvar org-drawer-regexp)
+(defvar org-property-re)
+(defvar org-current-tag-alist)
+
+(defun org-thing-at-point ()
+ "Examine the thing at point and let the caller know what it is.
+The return value is a string naming the thing at point."
+ (let ((beg1 (save-excursion
+ (skip-chars-backward "[:alnum:]-_@")
+ (point)))
+ (beg (save-excursion
+ (skip-chars-backward "a-zA-Z0-9-_:$")
+ (point)))
+ (line-to-here (buffer-substring (point-at-bol) (point))))
+ (cond
+ ((string-match "\\`[ \t]*#\\+begin: clocktable[ \t]+" line-to-here)
+ (cons "block-option" "clocktable"))
+ ((string-match "\\`[ \t]*#\\+begin_src[ \t]+" line-to-here)
+ (cons "block-option" "src"))
+ ((save-excursion
+ (re-search-backward "^[ \t]*#\\+\\([A-Z_]+\\):.*"
+ (line-beginning-position) t))
+ (cons "file-option" (match-string-no-properties 1)))
+ ((string-match "\\`[ \t]*#\\+[a-zA-Z_]*\\'" line-to-here)
+ (cons "file-option" nil))
+ ((equal (char-before beg) ?\[)
+ (cons "link" nil))
+ ((equal (char-before beg) ?\\)
+ (cons "tex" nil))
+ ((string-match "\\`\\*+[ \t]+\\'"
+ (buffer-substring (point-at-bol) beg))
+ (cons "todo" nil))
+ ((equal (char-before beg) ?*)
+ (cons "searchhead" nil))
+ ((and (equal (char-before beg1) ?:)
+ (equal (char-after (point-at-bol)) ?*))
+ (cons "tag" nil))
+ ((and (equal (char-before beg1) ?:)
+ (not (equal (char-after (point-at-bol)) ?*))
+ (save-excursion
+ (move-beginning-of-line 1)
+ (skip-chars-backward "[ \t\n]")
+ ;; org-drawer-regexp matches a whole line but while
+ ;; looking-back, we just ignore trailing whitespaces
+ (or (looking-back (substring org-drawer-regexp 0 -1)
+ (line-beginning-position))
+ (looking-back org-property-re
+ (line-beginning-position)))))
+ (cons "prop" nil))
+ ((and (equal (char-before beg1) ?:)
+ (not (equal (char-after (point-at-bol)) ?*)))
+ (cons "drawer" nil))
+ (t nil))))
+
+(defun org-command-at-point ()
+ "Return the qualified name of the Org completion entity at point.
+When completing for #+STARTUP, for example, this function returns
+\"file-option/startup\"."
+ (let ((thing (org-thing-at-point)))
+ (cond
+ ((string= "file-option" (car thing))
+ (concat (car thing)
+ (and (cdr thing) (concat "/" (downcase (cdr thing))))))
+ ((string= "block-option" (car thing))
+ (concat (car thing) "/" (downcase (cdr thing))))
+ (t (car thing)))))
+
+(defun org-parse-arguments ()
+ "Parse whitespace separated arguments in the current region."
+ (let ((begin (line-beginning-position))
+ (end (line-end-position))
+ begins args)
+ (save-restriction
+ (narrow-to-region begin end)
+ (save-excursion
+ (goto-char (point-min))
+ (while (not (eobp))
+ (skip-chars-forward " \t\n[")
+ (setq begins (cons (point) begins))
+ (skip-chars-forward "^ \t\n[")
+ (setq args (cons (buffer-substring-no-properties
+ (car begins) (point))
+ args)))
+ (cons (reverse args) (reverse begins))))))
+
+(defun org-pcomplete-initial ()
+ "Calls the right completion function for first argument completions."
+ (ignore
+ (funcall (or (pcomplete-find-completion-function
+ (car (org-thing-at-point)))
+ pcomplete-default-completion-function))))
+
+(defvar org-options-keywords) ; From org.el
+(defvar org-element-affiliated-keywords) ; From org-element.el
+(declare-function org-get-export-keywords "org" ())
+(defun pcomplete/org-mode/file-option ()
+ "Complete against all valid file options."
+ (require 'org-element)
+ (pcomplete-here
+ (org-pcomplete-case-double
+ (append (mapcar (lambda (keyword) (concat keyword " "))
+ org-options-keywords)
+ (mapcar (lambda (keyword) (concat keyword ": "))
+ org-element-affiliated-keywords)
+ (let (block-names)
+ (dolist (name
+ '("CENTER" "COMMENT" "EXAMPLE" "EXPORT" "QUOTE" "SRC"
+ "VERSE")
+ block-names)
+ (push (format "END_%s" name) block-names)
+ (push (concat "BEGIN_"
+ name
+ ;; Since language is compulsory in
+ ;; export blocks source blocks, add
+ ;; a space.
+ (and (member name '("EXPORT" "SRC")) " "))
+ block-names)
+ (push (format "ATTR_%s: " name) block-names)))
+ (mapcar (lambda (keyword) (concat keyword ": "))
+ (org-get-export-keywords))))
+ (substring pcomplete-stub 2)))
+
+(defun pcomplete/org-mode/file-option/author ()
+ "Complete arguments for the #+AUTHOR file option."
+ (pcomplete-here (list user-full-name)))
+
+(defvar org-time-stamp-formats)
+(defun pcomplete/org-mode/file-option/date ()
+ "Complete arguments for the #+DATE file option."
+ (pcomplete-here (list (format-time-string (car org-time-stamp-formats)))))
+
+(defun pcomplete/org-mode/file-option/email ()
+ "Complete arguments for the #+EMAIL file option."
+ (pcomplete-here (list user-mail-address)))
+
+(defvar org-export-exclude-tags)
+(defun pcomplete/org-mode/file-option/exclude_tags ()
+ "Complete arguments for the #+EXCLUDE_TAGS file option."
+ (require 'ox)
+ (pcomplete-here
+ (and org-export-exclude-tags
+ (list (mapconcat 'identity org-export-exclude-tags " ")))))
+
+(defvar org-file-tags)
+(defun pcomplete/org-mode/file-option/filetags ()
+ "Complete arguments for the #+FILETAGS file option."
+ (pcomplete-here (and org-file-tags (mapconcat 'identity org-file-tags " "))))
+
+(defvar org-export-default-language)
+(defun pcomplete/org-mode/file-option/language ()
+ "Complete arguments for the #+LANGUAGE file option."
+ (require 'ox)
+ (pcomplete-here
+ (pcomplete-uniqify-list
+ (list org-export-default-language "en"))))
+
+(defvar org-default-priority)
+(defvar org-highest-priority)
+(defvar org-lowest-priority)
+(defun pcomplete/org-mode/file-option/priorities ()
+ "Complete arguments for the #+PRIORITIES file option."
+ (pcomplete-here (list (format "%c %c %c"
+ org-highest-priority
+ org-lowest-priority
+ org-default-priority))))
+
+(defvar org-export-select-tags)
+(defun pcomplete/org-mode/file-option/select_tags ()
+ "Complete arguments for the #+SELECT_TAGS file option."
+ (require 'ox)
+ (pcomplete-here
+ (and org-export-select-tags
+ (list (mapconcat 'identity org-export-select-tags " ")))))
+
+(defvar org-startup-options)
+(defun pcomplete/org-mode/file-option/startup ()
+ "Complete arguments for the #+STARTUP file option."
+ (while (pcomplete-here
+ (let ((opts (pcomplete-uniqify-list
+ (mapcar 'car org-startup-options))))
+ ;; Some options are mutually exclusive, and shouldn't be completed
+ ;; against if certain other options have already been seen.
+ (dolist (arg pcomplete-args)
+ (cond
+ ((string= arg "hidestars")
+ (setq opts (delete "showstars" opts)))))
+ opts))))
+
+(defun pcomplete/org-mode/file-option/tags ()
+ "Complete arguments for the #+TAGS file option."
+ (pcomplete-here
+ (list (org-tag-alist-to-string org-current-tag-alist))))
+
+(defun pcomplete/org-mode/file-option/title ()
+ "Complete arguments for the #+TITLE file option."
+ (pcomplete-here
+ (let ((visited-file (buffer-file-name (buffer-base-buffer))))
+ (list (or (and visited-file
+ (file-name-sans-extension
+ (file-name-nondirectory visited-file)))
+ (buffer-name (buffer-base-buffer)))))))
+
+
+(declare-function org-export-backend-options "ox" (cl-x) t)
+(defun pcomplete/org-mode/file-option/options ()
+ "Complete arguments for the #+OPTIONS file option."
+ (while (pcomplete-here
+ (pcomplete-uniqify-list
+ (append
+ ;; Hard-coded OPTION items always available.
+ '("H:" "\\n:" "num:" "timestamp:" "arch:" "author:" "c:"
+ "creator:" "date:" "d:" "email:" "*:" "e:" "::" "f:"
+ "inline:" "tex:" "p:" "pri:" "':" "-:" "stat:" "^:" "toc:"
+ "|:" "tags:" "tasks:" "<:" "todo:")
+ ;; OPTION items from registered back-ends.
+ (let (items)
+ (dolist (backend (bound-and-true-p
+ org-export-registered-backends))
+ (dolist (option (org-export-backend-options backend))
+ (let ((item (nth 2 option)))
+ (when item (push (concat item ":") items)))))
+ items))))))
+
+(defun pcomplete/org-mode/file-option/infojs_opt ()
+ "Complete arguments for the #+INFOJS_OPT file option."
+ (while (pcomplete-here
+ (pcomplete-uniqify-list
+ (mapcar (lambda (item) (format "%s:" (car item)))
+ (bound-and-true-p org-html-infojs-opts-table))))))
+
+(defun pcomplete/org-mode/file-option/bind ()
+ "Complete arguments for the #+BIND file option, which are variable names."
+ (let (vars)
+ (mapatoms
+ (lambda (a) (if (boundp a) (setq vars (cons (symbol-name a) vars)))))
+ (pcomplete-here vars)))
+
+(defvar org-link-abbrev-alist-local)
+(defvar org-link-abbrev-alist)
+(defun pcomplete/org-mode/link ()
+ "Complete against defined #+LINK patterns."
+ (pcomplete-here
+ (pcomplete-uniqify-list
+ (copy-sequence
+ (append (mapcar 'car org-link-abbrev-alist-local)
+ (mapcar 'car org-link-abbrev-alist))))))
+
+(defvar org-entities)
+(defun pcomplete/org-mode/tex ()
+ "Complete against TeX-style HTML entity names."
+ (require 'org-entities)
+ (while (pcomplete-here
+ (pcomplete-uniqify-list (remove nil (mapcar 'car-safe org-entities)))
+ (substring pcomplete-stub 1))))
+
+(defvar org-todo-keywords-1)
+(defun pcomplete/org-mode/todo ()
+ "Complete against known TODO keywords."
+ (pcomplete-here (pcomplete-uniqify-list (copy-sequence org-todo-keywords-1))))
+
+(defvar org-todo-line-regexp)
+(defun pcomplete/org-mode/searchhead ()
+ "Complete against all headings.
+This needs more work, to handle headings with lots of spaces in them."
+ (while
+ (pcomplete-here
+ (save-excursion
+ (goto-char (point-min))
+ (let (tbl)
+ (let ((case-fold-search nil))
+ (while (re-search-forward org-todo-line-regexp nil t)
+ (push (org-make-org-heading-search-string
+ (match-string-no-properties 3))
+ tbl)))
+ (pcomplete-uniqify-list tbl)))
+ (substring pcomplete-stub 1))))
+
+(defun pcomplete/org-mode/tag ()
+ "Complete a tag name. Omit tags already set."
+ (while (pcomplete-here
+ (mapcar (lambda (x) (concat x ":"))
+ (let ((lst (pcomplete-uniqify-list
+ (or (remq
+ nil
+ (mapcar (lambda (x) (org-string-nw-p (car x)))
+ org-current-tag-alist))
+ (mapcar #'car (org-get-buffer-tags))))))
+ (dolist (tag (org-get-tags))
+ (setq lst (delete tag lst)))
+ lst))
+ (and (string-match ".*:" pcomplete-stub)
+ (substring pcomplete-stub (match-end 0))))))
+
+(defun pcomplete/org-mode/prop ()
+ "Complete a property name. Omit properties already set."
+ (pcomplete-here
+ (mapcar (lambda (x)
+ (concat x ": "))
+ (let ((lst (pcomplete-uniqify-list
+ (copy-sequence
+ (org-buffer-property-keys nil t t t)))))
+ (dolist (prop (org-entry-properties))
+ (setq lst (delete (car prop) lst)))
+ lst))
+ (substring pcomplete-stub 1)))
+
+(defun pcomplete/org-mode/block-option/src ()
+ "Complete the arguments of a begin_src block.
+Complete a language in the first field, the header arguments and switches."
+ (pcomplete-here
+ (mapcar
+ (lambda(x) (symbol-name (nth 3 x)))
+ (cdr (car (cdr (memq :key-type (plist-get
+ (symbol-plist
+ 'org-babel-load-languages)
+ 'custom-type)))))))
+ (while (pcomplete-here
+ '("-n" "-r" "-l"
+ ":cache" ":colnames" ":comments" ":dir" ":eval" ":exports"
+ ":file" ":hlines" ":no-expand" ":noweb" ":results" ":rownames"
+ ":session" ":shebang" ":tangle" ":tangle-mode" ":var"))))
+
+(defun pcomplete/org-mode/block-option/clocktable ()
+ "Complete keywords in a clocktable line."
+ (while (pcomplete-here '(":maxlevel" ":scope" ":lang"
+ ":tstart" ":tend" ":block" ":step"
+ ":stepskip0" ":fileskip0"
+ ":emphasize" ":link" ":narrow" ":indent"
+ ":tcolumns" ":level" ":compact" ":timestamp"
+ ":formula" ":formatter" ":wstart" ":mstart"))))
+
+(defun org-pcomplete-case-double (list)
+ "Return list with both upcase and downcase version of all strings in LIST."
+ (let (e res)
+ (while (setq e (pop list))
+ (setq res (cons (downcase e) (cons (upcase e) res))))
+ (nreverse res)))
+
+;;;; Finish up
+
+(provide 'org-pcomplete)
+
+;;; org-pcomplete.el ends here
diff --git a/lisp/org-plot.el b/lisp/org-plot.el
new file mode 100644
index 0000000..449143a
--- /dev/null
+++ b/lisp/org-plot.el
@@ -0,0 +1,354 @@
+;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Author: Eric Schulte <schulte dot eric at gmail dot com>
+;; Keywords: tables, plotting
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; Borrows ideas and a couple of lines of code from org-exp.el.
+
+;; Thanks to the Org mailing list for testing and implementation and
+;; feature suggestions
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+(require 'org-table)
+
+(declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
+(declare-function gnuplot-mode "ext:gnuplot" ())
+(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())
+
+(defvar org-plot/gnuplot-default-options
+ '((:plot-type . 2d)
+ (:with . lines)
+ (:ind . 0))
+ "Default options to gnuplot used by `org-plot/gnuplot'.")
+
+(defvar org-plot-timestamp-fmt nil)
+
+(defun org-plot/add-options-to-plist (p options)
+ "Parse an OPTIONS line and set values in the property list P.
+Returns the resulting property list."
+ (when options
+ (let ((op '(("type" . :plot-type)
+ ("script" . :script)
+ ("line" . :line)
+ ("set" . :set)
+ ("title" . :title)
+ ("ind" . :ind)
+ ("deps" . :deps)
+ ("with" . :with)
+ ("file" . :file)
+ ("labels" . :labels)
+ ("map" . :map)
+ ("timeind" . :timeind)
+ ("timefmt" . :timefmt)))
+ (multiples '("set" "line"))
+ (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
+ (start 0))
+ (dolist (o op)
+ (if (member (car o) multiples) ;; keys with multiple values
+ (while (string-match
+ (concat (regexp-quote (car o)) regexp)
+ options start)
+ (setq start (match-end 0))
+ (setq p (plist-put p (cdr o)
+ (cons (car (read-from-string
+ (match-string 1 options)))
+ (plist-get p (cdr o)))))
+ p)
+ (if (string-match (concat (regexp-quote (car o)) regexp)
+ options)
+ (setq p (plist-put p (cdr o)
+ (car (read-from-string
+ (match-string 1 options))))))))))
+ p)
+
+(defun org-plot/goto-nearest-table ()
+ "Move the point forward to the beginning of nearest table.
+Return value is the point at the beginning of the table."
+ (interactive) (move-beginning-of-line 1)
+ (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
+ (goto-char (org-table-begin)))
+
+(defun org-plot/collect-options (&optional params)
+ "Collect options from an org-plot `#+Plot:' line.
+Accepts an optional property list PARAMS, to which the options
+will be added. Returns the resulting property list."
+ (interactive)
+ (let ((line (thing-at-point 'line)))
+ (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
+ (org-plot/add-options-to-plist params (match-string 1 line))
+ params)))
+
+(defun org-plot-quote-timestamp-field (s)
+ "Convert field S from timestamp to Unix time and export to gnuplot."
+ (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))
+
+(defun org-plot-quote-tsv-field (s)
+ "Quote field S for export to gnuplot."
+ (if (string-match org-table-number-regexp s) s
+ (if (string-match org-ts-regexp3 s)
+ (org-plot-quote-timestamp-field s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
+
+(defun org-plot/gnuplot-to-data (table data-file params)
+ "Export TABLE to DATA-FILE in a format readable by gnuplot.
+Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
+ (with-temp-file
+ data-file
+ (setq-local org-plot-timestamp-fmt (or
+ (plist-get params :timefmt)
+ "%Y-%m-%d-%H:%M:%S"))
+ (insert (orgtbl-to-generic
+ table
+ (org-combine-plists
+ '(:sep "\t" :fmt org-plot-quote-tsv-field)
+ params))))
+ nil)
+
+(defun org-plot/gnuplot-to-grid-data (table data-file params)
+ "Export the data in TABLE to DATA-FILE for gnuplot.
+This means in a format appropriate for grid plotting by gnuplot.
+PARAMS specifies which columns of TABLE should be plotted as independent
+and dependant variables."
+ (interactive)
+ (let* ((ind (- (plist-get params :ind) 1))
+ (deps (if (plist-member params :deps)
+ (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
+ (let (collector)
+ (dotimes (col (length (nth 0 table)))
+ (setf collector (cons col collector)))
+ collector)))
+ (counter 0)
+ row-vals)
+ (when (>= ind 0) ;; collect values of ind col
+ (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
+ (cons counter (nth ind row))) table)))
+ (when (or deps (>= ind 0)) ;; remove non-plotting columns
+ (setf deps (delq ind deps))
+ (setf table (mapcar (lambda (row)
+ (dotimes (col (length row))
+ (unless (memq col deps)
+ (setf (nth col row) nil)))
+ (delq nil row))
+ table)))
+ ;; write table to gnuplot grid datafile format
+ (with-temp-file data-file
+ (let ((num-rows (length table)) (num-cols (length (nth 0 table)))
+ (gnuplot-row (lambda (col row value)
+ (setf col (+ 1 col)) (setf row (+ 1 row))
+ (format "%f %f %f\n%f %f %f\n"
+ col (- row 0.5) value ;; lower edge
+ col (+ row 0.5) value))) ;; upper edge
+ front-edge back-edge)
+ (dotimes (col num-cols)
+ (dotimes (row num-rows)
+ (setf back-edge
+ (concat back-edge
+ (funcall gnuplot-row (- col 1) row
+ (string-to-number (nth col (nth row table))))))
+ (setf front-edge
+ (concat front-edge
+ (funcall gnuplot-row col row
+ (string-to-number (nth col (nth row table)))))))
+ ;; only insert once per row
+ (insert back-edge) (insert "\n") ;; back edge
+ (insert front-edge) (insert "\n") ;; front edge
+ (setf back-edge "") (setf front-edge ""))))
+ row-vals))
+
+(defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
+ "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
+NUM-COLS controls the number of columns plotted in a 2-d plot.
+Optional argument PREFACE returns only option parameters in a
+manner suitable for prepending to a user-specified script."
+ (let* ((type (plist-get params :plot-type))
+ (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
+ (sets (plist-get params :set))
+ (lines (plist-get params :line))
+ (map (plist-get params :map))
+ (title (plist-get params :title))
+ (file (plist-get params :file))
+ (ind (plist-get params :ind))
+ (time-ind (plist-get params :timeind))
+ (timefmt (plist-get params :timefmt))
+ (text-ind (plist-get params :textind))
+ (deps (if (plist-member params :deps) (plist-get params :deps)))
+ (col-labels (plist-get params :labels))
+ (x-labels (plist-get params :xlabels))
+ (y-labels (plist-get params :ylabels))
+ (plot-str "'%s' using %s%d%s with %s title '%s'")
+ (plot-cmd (pcase type
+ (`2d "plot")
+ (`3d "splot")
+ (`grid "splot")))
+ (script "reset")
+ ;; ats = add-to-script
+ (ats (lambda (line) (setf script (concat script "\n" line))))
+ plot-lines)
+ (when file ; output file
+ (funcall ats (format "set term %s" (file-name-extension file)))
+ (funcall ats (format "set output '%s'" file)))
+ (pcase type ; type
+ (`2d ())
+ (`3d (when map (funcall ats "set map")))
+ (`grid (funcall ats (if map "set pm3d map" "set pm3d"))))
+ (when title (funcall ats (format "set title '%s'" title))) ; title
+ (mapc ats lines) ; line
+ (dolist (el sets) (funcall ats (format "set %s" el))) ; set
+ ;; Unless specified otherwise, values are TAB separated.
+ (unless (string-match-p "^set datafile separator" script)
+ (funcall ats "set datafile separator \"\\t\""))
+ (when x-labels ; x labels (xtics)
+ (funcall ats
+ (format "set xtics (%s)"
+ (mapconcat (lambda (pair)
+ (format "\"%s\" %d" (cdr pair) (car pair)))
+ x-labels ", "))))
+ (when y-labels ; y labels (ytics)
+ (funcall ats
+ (format "set ytics (%s)"
+ (mapconcat (lambda (pair)
+ (format "\"%s\" %d" (cdr pair) (car pair)))
+ y-labels ", "))))
+ (when time-ind ; timestamp index
+ (funcall ats "set xdata time")
+ (funcall ats (concat "set timefmt \""
+ (or timefmt ; timefmt passed to gnuplot
+ "%Y-%m-%d-%H:%M:%S") "\"")))
+ (unless preface
+ (pcase type ; plot command
+ (`2d (dotimes (col num-cols)
+ (unless (and (eq type '2d)
+ (or (and ind (equal (1+ col) ind))
+ (and deps (not (member (1+ col) deps)))))
+ (setf plot-lines
+ (cons
+ (format plot-str data-file
+ (or (and ind (> ind 0)
+ (not text-ind)
+ (format "%d:" ind)) "")
+ (1+ col)
+ (if text-ind (format ":xticlabel(%d)" ind) "")
+ with
+ (or (nth col col-labels)
+ (format "%d" (1+ col))))
+ plot-lines)))))
+ (`3d
+ (setq plot-lines (list (format "'%s' matrix with %s title ''"
+ data-file with))))
+ (`grid
+ (setq plot-lines (list (format "'%s' with %s title ''"
+ data-file with)))))
+ (funcall ats
+ (concat plot-cmd " " (mapconcat #'identity
+ (reverse plot-lines)
+ ",\\\n "))))
+ script))
+
+;;-----------------------------------------------------------------------------
+;; facade functions
+;;;###autoload
+(defun org-plot/gnuplot (&optional params)
+ "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
+If not given options will be taken from the +PLOT
+line directly before or after the table."
+ (interactive)
+ (require 'gnuplot)
+ (save-window-excursion
+ (delete-other-windows)
+ (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
+ (with-current-buffer "*gnuplot*"
+ (goto-char (point-max))))
+ (org-plot/goto-nearest-table)
+ ;; Set default options.
+ (dolist (pair org-plot/gnuplot-default-options)
+ (unless (plist-member params (car pair))
+ (setf params (plist-put params (car pair) (cdr pair)))))
+ ;; collect table and table information
+ (let* ((data-file (make-temp-file "org-plot"))
+ (table (org-table-to-lisp))
+ (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
+ (nth 0 table)))))
+ (run-with-idle-timer 0.1 nil #'delete-file data-file)
+ (while (eq 'hline (car table)) (setf table (cdr table)))
+ (when (eq (cadr table) 'hline)
+ (setf params
+ (plist-put params :labels (nth 0 table))) ; headers to labels
+ (setf table (delq 'hline (cdr table)))) ; clean non-data from table
+ ;; Collect options.
+ (save-excursion (while (and (equal 0 (forward-line -1))
+ (looking-at "[[:space:]]*#\\+"))
+ (setf params (org-plot/collect-options params))))
+ ;; Dump table to datafile (very different for grid).
+ (pcase (plist-get params :plot-type)
+ (`2d (org-plot/gnuplot-to-data table data-file params))
+ (`3d (org-plot/gnuplot-to-data table data-file params))
+ (`grid (let ((y-labels (org-plot/gnuplot-to-grid-data
+ table data-file params)))
+ (when y-labels (plist-put params :ylabels y-labels)))))
+ ;; Check for timestamp ind column.
+ (let ((ind (1- (plist-get params :ind))))
+ (when (and (>= ind 0) (eq '2d (plist-get params :plot-type)))
+ (if (= (length
+ (delq 0 (mapcar
+ (lambda (el)
+ (if (string-match org-ts-regexp3 el) 0 1))
+ (mapcar (lambda (row) (nth ind row)) table))))
+ 0)
+ (plist-put params :timeind t)
+ ;; Check for text ind column.
+ (if (or (string= (plist-get params :with) "hist")
+ (> (length
+ (delq 0 (mapcar
+ (lambda (el)
+ (if (string-match org-table-number-regexp el)
+ 0 1))
+ (mapcar (lambda (row) (nth ind row)) table))))
+ 0))
+ (plist-put params :textind t)))))
+ ;; Write script.
+ (with-temp-buffer
+ (if (plist-get params :script) ; user script
+ (progn (insert
+ (org-plot/gnuplot-script data-file num-cols params t))
+ (insert "\n")
+ (insert-file-contents (plist-get params :script))
+ (goto-char (point-min))
+ (while (re-search-forward "$datafile" nil t)
+ (replace-match data-file nil nil)))
+ (insert (org-plot/gnuplot-script data-file num-cols params)))
+ ;; Graph table.
+ (gnuplot-mode)
+ (gnuplot-send-buffer-to-gnuplot))
+ ;; Cleanup.
+ (bury-buffer (get-buffer "*gnuplot*")))))
+
+(provide 'org-plot)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-plot.el ends here
diff --git a/lisp/org-protocol.el b/lisp/org-protocol.el
new file mode 100644
index 0000000..8254356
--- /dev/null
+++ b/lisp/org-protocol.el
@@ -0,0 +1,717 @@
+;;; org-protocol.el --- Intercept Calls from Emacsclient to Trigger Custom Actions -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+;;
+;; Authors: Bastien Guerry <bzg@gnu.org>
+;; Daniel M German <dmg AT uvic DOT org>
+;; Sebastian Rose <sebastian_rose AT gmx DOT de>
+;; Ross Patterson <me AT rpatterson DOT net>
+;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de>
+;; Keywords: org, emacsclient, wp
+
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Commentary:
+;;
+;; Intercept calls from emacsclient to trigger custom actions.
+;;
+;; This is done by advising `server-visit-files' to scan the list of filenames
+;; for `org-protocol-the-protocol' and sub-protocols defined in
+;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
+;;
+;; Any application that supports calling external programs with an URL
+;; as argument may be used with this functionality.
+;;
+;;
+;; Usage:
+;; ------
+;;
+;; 1.) Add this to your init file (.emacs probably):
+;;
+;; (add-to-list 'load-path "/path/to/org-protocol/")
+;; (require 'org-protocol)
+;;
+;; 3.) Ensure emacs-server is up and running.
+;; 4.) Try this from the command line (adjust the URL as needed):
+;;
+;; $ emacsclient \
+;; org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title
+;;
+;; 5.) Optionally add custom sub-protocols and handlers:
+;;
+;; (setq org-protocol-protocol-alist
+;; '(("my-protocol"
+;; :protocol "my-protocol"
+;; :function my-protocol-handler-function)))
+;;
+;; A "sub-protocol" will be found in URLs like this:
+;;
+;; org-protocol://sub-protocol?key=val&key2=val2
+;;
+;; If it works, you can now setup other applications for using this feature.
+;;
+;;
+;; As of March 2009 Firefox users follow the steps documented on
+;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
+;; http://www.opera.com/support/kb/view/535/
+;;
+;;
+;; Documentation
+;; -------------
+;;
+;; org-protocol.el comes with and installs handlers to open sources of published
+;; online content, store and insert the browser's URLs and cite online content
+;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
+;; applications:
+;;
+;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
+;; URLs to local filenames defined in `org-protocol-project-alist'.
+;;
+;; * `org-protocol-store-link' stores an Org link (if Org is present) and
+;; pushes the browsers URL to the `kill-ring' for yanking. This handler is
+;; triggered through the sub-protocol \"store-link\".
+;;
+;; * Call `org-protocol-capture' by using the sub-protocol \"capture\". If
+;; Org is loaded, Emacs will pop-up a capture buffer and fill the
+;; template with the data provided. I.e. the browser's URL is inserted as an
+;; Org-link of which the page title will be the description part. If text
+;; was select in the browser, that text will be the body of the entry.
+;;
+;; You may use the same bookmark URL for all those standard handlers and just
+;; adjust the sub-protocol used:
+;;
+;; location.href='org-protocol://sub-protocol?url='+
+;; encodeURIComponent(location.href)+'&title='+
+;; encodeURIComponent(document.title)+'&body='+
+;; encodeURIComponent(window.getSelection())
+;;
+;; The handler for the sub-protocol \"capture\" detects an optional template
+;; char that, if present, triggers the use of a special template.
+;; Example:
+;;
+;; location.href='org-protocol://capture?template=x'+ ...
+;;
+;; uses template ?x.
+;;
+;; Note that using double slashes is optional from org-protocol.el's point of
+;; view because emacsclient squashes the slashes to one.
+;;
+;;
+;; provides: 'org-protocol
+;;
+;;; Code:
+
+(require 'org)
+
+(declare-function org-publish-get-project-from-filename "ox-publish"
+ (filename &optional up))
+(declare-function server-edit "server" (&optional arg))
+
+(defvar org-capture-link-is-already-stored)
+
+(defgroup org-protocol nil
+ "Intercept calls from emacsclient to trigger custom actions.
+
+This is done by advising `server-visit-files' to scan the list of filenames
+for `org-protocol-the-protocol' and sub-protocols defined in
+`org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
+ :version "22.1"
+ :group 'convenience
+ :group 'org)
+
+
+;;; Variables:
+
+(defconst org-protocol-protocol-alist-default
+ '(("org-capture" :protocol "capture" :function org-protocol-capture :kill-client t)
+ ("org-store-link" :protocol "store-link" :function org-protocol-store-link)
+ ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
+ "Default protocols to use.
+See `org-protocol-protocol-alist' for a description of this variable.")
+
+(defconst org-protocol-the-protocol "org-protocol"
+ "This is the protocol to detect if org-protocol.el is loaded.
+`org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold
+the sub-protocols that trigger the required action. You will have to define
+just one protocol handler OS-wide (MS-Windows) or per application (Linux).
+That protocol handler should call emacsclient.")
+
+;;; User variables:
+
+(defcustom org-protocol-reverse-list-of-files t
+ "Non-nil means re-reverse the list of filenames passed on the command line.
+The filenames passed on the command line are passed to the emacs-server in
+reverse order. Set to t (default) to re-reverse the list, i.e. use the
+sequence on the command line. If nil, the sequence of the filenames is
+unchanged."
+ :group 'org-protocol
+ :type 'boolean)
+
+(defcustom org-protocol-project-alist nil
+ "Map URLs to local filenames for `org-protocol-open-source' (open-source).
+
+Each element of this list must be of the form:
+
+ (module-name :property value property: value ...)
+
+where module-name is an arbitrary name. All the values are strings.
+
+Possible properties are:
+
+ :online-suffix - the suffix to strip from the published URLs
+ :working-suffix - the replacement for online-suffix
+ :base-url - the base URL, e.g. http://www.example.com/project/
+ Last slash required.
+ :working-directory - the local working directory. This is, what base-url will
+ be replaced with.
+ :redirects - A list of cons cells, each of which maps a regular
+ expression to match to a path relative to :working-directory.
+
+Example:
+
+ (setq org-protocol-project-alist
+ \\='((\"http://orgmode.org/worg/\"
+ :online-suffix \".php\"
+ :working-suffix \".org\"
+ :base-url \"http://orgmode.org/worg/\"
+ :working-directory \"/home/user/org/Worg/\")
+ (\"http://localhost/org-notes/\"
+ :online-suffix \".html\"
+ :working-suffix \".org\"
+ :base-url \"http://localhost/org/\"
+ :working-directory \"/home/user/org/\"
+ :rewrites ((\"org/?$\" . \"index.php\")))))
+
+ The last line tells `org-protocol-open-source' to open
+ /home/user/org/index.php, if the URL cannot be mapped to an existing
+ file, and ends with either \"org\" or \"org/\".
+
+Consider using the interactive functions `org-protocol-create' and
+`org-protocol-create-for-org' to help you filling this variable with valid contents."
+ :group 'org-protocol
+ :type 'alist)
+
+(defcustom org-protocol-protocol-alist nil
+ "Register custom handlers for org-protocol.
+
+Each element of this list must be of the form:
+
+ (module-name :protocol protocol :function func :kill-client nil)
+
+protocol - protocol to detect in a filename without trailing
+ colon and slashes. See rfc1738 section 2.1 for more
+ on this. If you define a protocol \"my-protocol\",
+ `org-protocol-check-filename-for-protocol' will search
+ filenames for \"org-protocol:/my-protocol\" and
+ trigger your action for every match. `org-protocol'
+ is defined in `org-protocol-the-protocol'. Double and
+ triple slashes are compressed to one by emacsclient.
+
+function - function that handles requests with protocol and takes
+ one argument. If a new-style link (key=val&key2=val2)
+ is given, the argument will be a property list with
+ the values from the link. If an old-style link is
+ given (val1/val2), the argument will be the filename
+ with all protocols stripped.
+
+ If the function returns nil, emacsclient and -server
+ do nothing. Any non-nil return value is considered a
+ valid filename and thus passed to the server.
+
+ `org-protocol.el' provides some support for handling
+ old-style filenames, if you follow the conventions
+ used for the standard handlers in
+ `org-protocol-protocol-alist-default'. See
+ `org-protocol-parse-parameters'.
+
+kill-client - If t, kill the client immediately, once the sub-protocol is
+ detected. This is necessary for actions that can be interrupted by
+ `C-g' to avoid dangling emacsclients. Note that all other command
+ line arguments but the this one will be discarded. Greedy handlers
+ still receive the whole list of arguments though.
+
+Here is an example:
+
+ (setq org-protocol-protocol-alist
+ \\='((\"my-protocol\"
+ :protocol \"my-protocol\"
+ :function my-protocol-handler-function)
+ (\"your-protocol\"
+ :protocol \"your-protocol\"
+ :function your-protocol-handler-function)))"
+ :group 'org-protocol
+ :type '(alist))
+
+(defcustom org-protocol-default-template-key nil
+ "The default template key to use.
+This is usually a single character string but can also be a
+string with two characters."
+ :group 'org-protocol
+ :type '(choice (const nil) (string)))
+
+(defcustom org-protocol-data-separator "/+\\|\\?"
+ "The default data separator to use.
+This should be a single regexp string."
+ :group 'org-protocol
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+;;; Helper functions:
+
+(defun org-protocol-sanitize-uri (uri)
+ "Sanitize slashes to double-slashes in URI.
+Emacsclient compresses double and triple slashes."
+ (when (string-match "^\\([a-z]+\\):/" uri)
+ (let* ((splitparts (split-string uri "/+")))
+ (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/")))))
+ uri)
+
+(defun org-protocol-split-data (data &optional unhexify separator)
+ "Split the DATA argument for an org-protocol handler function.
+If UNHEXIFY is non-nil, hex-decode each split part. If UNHEXIFY
+is a function, use that function to decode each split part. The
+string is split at each occurrence of SEPARATOR (regexp). If no
+SEPARATOR is specified or SEPARATOR is nil, assume \"/+\". The
+results of that splitting are returned as a list."
+ (let* ((sep (or separator "/+\\|\\?"))
+ (split-parts (split-string data sep)))
+ (if unhexify
+ (if (fboundp unhexify)
+ (mapcar unhexify split-parts)
+ (mapcar 'org-link-unescape split-parts))
+ split-parts)))
+
+(defun org-protocol-flatten-greedy (param-list &optional strip-path replacement)
+ "Transform PARAM-LIST into a flat list for greedy handlers.
+
+Greedy handlers might receive a list like this from emacsclient:
+\((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
+where \"/dir/\" is the absolute path to emacsclient's working directory. This
+function transforms it into a flat list using `org-protocol-flatten' and
+transforms the elements of that list as follows:
+
+If STRIP-PATH is non-nil, remove the \"/dir/\" prefix from all members of
+param-list.
+
+If REPLACEMENT is string, replace the \"/dir/\" prefix with it.
+
+The first parameter, the one that contains the protocols, is always changed.
+Everything up to the end of the protocols is stripped.
+
+Note, that this function will always behave as if
+`org-protocol-reverse-list-of-files' was set to t and the returned list will
+reflect that. emacsclient's first parameter will be the first one in the
+returned list."
+ (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
+ param-list
+ (reverse param-list))))
+ (trigger (car l))
+ (len 0)
+ dir
+ ret)
+ (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-z0-9][-_a-zA-z0-9]*:/+\\)\\(.*\\)" trigger)
+ (setq dir (match-string 1 trigger))
+ (setq len (length dir))
+ (setcar l (concat dir (match-string 3 trigger))))
+ (if strip-path
+ (progn
+ (dolist (e l ret)
+ (setq ret
+ (append ret
+ (list
+ (if (stringp e)
+ (if (stringp replacement)
+ (setq e (concat replacement (substring e len)))
+ (setq e (substring e len)))
+ e)))))
+ ret)
+ l)))
+
+(defun org-protocol-flatten (list)
+ "Transform LIST into a flat list.
+
+Greedy handlers might receive a list like this from emacsclient:
+\((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
+where \"/dir/\" is the absolute path to emacsclients working directory.
+This function transforms it into a flat list."
+ (if (null list) ()
+ (if (listp list)
+ (append (org-protocol-flatten (car list)) (org-protocol-flatten (cdr list)))
+ (list list))))
+
+(defun org-protocol-parse-parameters (info &optional new-style default-order)
+ "Return a property list of parameters from INFO.
+If NEW-STYLE is non-nil, treat INFO as a query string (ex:
+url=URL&title=TITLE). If old-style links are used (ex:
+org-protocol://store-link/url/title), assign them to attributes
+following DEFAULT-ORDER.
+
+If no DEFAULT-ORDER is specified, return the list of values.
+
+If INFO is already a property list, return it unchanged."
+ (if (listp info)
+ info
+ (if new-style
+ (let ((data (org-protocol-convert-query-to-plist info))
+ result)
+ (while data
+ (setq result
+ (append
+ result
+ (list
+ (pop data)
+ (org-link-unescape (pop data))))))
+ result)
+ (let ((data (org-protocol-split-data info t org-protocol-data-separator)))
+ (if default-order
+ (org-protocol-assign-parameters data default-order)
+ data)))))
+
+(defun org-protocol-assign-parameters (data default-order)
+ "Return a property list of parameters from DATA.
+Key names are taken from DEFAULT-ORDER, which should be a list of
+symbols. If DEFAULT-ORDER is shorter than the number of values
+specified, the rest of the values are treated as :key value pairs."
+ (let (result)
+ (while default-order
+ (setq result
+ (append result
+ (list (pop default-order)
+ (pop data)))))
+ (while data
+ (setq result
+ (append result
+ (list (intern (concat ":" (pop data)))
+ (pop data)))))
+ result))
+
+;;; Standard protocol handlers:
+
+(defun org-protocol-store-link (fname)
+ "Process an org-protocol://store-link style url.
+Additionally store a browser URL as an org link. Also pushes the
+link's URL to the `kill-ring'.
+
+Parameters: url, title (optional), body (optional)
+
+Old-style links such as org-protocol://store-link://URL/TITLE are
+also recognized.
+
+The location for a browser's bookmark has to look like this:
+
+ javascript:location.href = \\
+ \\='org-protocol://store-link?url=\\=' + \\
+ encodeURIComponent(location.href) + \\='&title=\\=' + \\
+ encodeURIComponent(document.title);
+
+Don't use `escape()'! Use `encodeURIComponent()' instead. The
+title of the page could contain slashes and the location
+definitely will.
+
+The sub-protocol used to reach this function is set in
+`org-protocol-protocol-alist'.
+
+FNAME should be a property list. If not, an old-style link of the
+form URL/TITLE can also be used."
+ (let* ((splitparts (org-protocol-parse-parameters fname nil '(:url :title)))
+ (uri (org-protocol-sanitize-uri (plist-get splitparts :url)))
+ (title (plist-get splitparts :title)))
+ (when (boundp 'org-stored-links)
+ (push (list uri title) org-stored-links))
+ (kill-new uri)
+ (message "`%s' to insert new org-link, `%s' to insert `%s'"
+ (substitute-command-keys "`\\[org-insert-link]'")
+ (substitute-command-keys "`\\[yank]'")
+ uri))
+ nil)
+
+(defun org-protocol-capture (info)
+ "Process an org-protocol://capture style url with INFO.
+
+The sub-protocol used to reach this function is set in
+`org-protocol-protocol-alist'.
+
+This function detects an URL, title and optional text, separated
+by `/'. The location for a browser's bookmark looks like this:
+
+ javascript:location.href = \\='org-protocol://capture?url=\\='+ \\
+ encodeURIComponent(location.href) + \\='&title=\\=' \\
+ encodeURIComponent(document.title) + \\='&body=\\=' + \\
+ encodeURIComponent(window.getSelection())
+
+By default, it uses the character `org-protocol-default-template-key',
+which should be associated with a template in `org-capture-templates'.
+You may specify the template with a template= query parameter, like this:
+
+ javascript:location.href = \\='org-protocol://capture?template=b\\='+ ...
+
+Now template ?b will be used."
+ (if (and (boundp 'org-stored-links)
+ (org-protocol-do-capture info))
+ (message "Item captured."))
+ nil)
+
+(defun org-protocol-convert-query-to-plist (query)
+ "Convert QUERY key=value pairs in the URL to a property list."
+ (if query
+ (apply 'append (mapcar (lambda (x)
+ (let ((c (split-string x "=")))
+ (list (intern (concat ":" (car c))) (cadr c))))
+ (split-string query "&")))))
+
+(defun org-protocol-do-capture (info)
+ "Perform the actual capture based on INFO."
+ (let* ((temp-parts (org-protocol-parse-parameters info))
+ (parts
+ (cond
+ ((and (listp info) (symbolp (car info))) info)
+ ((= (length (car temp-parts)) 1) ;; First parameter is exactly one character long
+ (org-protocol-assign-parameters temp-parts '(:template :url :title :body)))
+ (t
+ (org-protocol-assign-parameters temp-parts '(:url :title :body)))))
+ (template (or (plist-get parts :template)
+ org-protocol-default-template-key))
+ (url (and (plist-get parts :url) (org-protocol-sanitize-uri (plist-get parts :url))))
+ (type (and url (if (string-match "^\\([a-z]+\\):" url)
+ (match-string 1 url))))
+ (title (or (plist-get parts :title) ""))
+ (region (or (plist-get parts :body) ""))
+ (orglink (if url
+ (org-make-link-string
+ url (if (string-match "[^[:space:]]" title) title url))
+ title))
+ (org-capture-link-is-already-stored t)) ;; avoid call to org-store-link
+ (setq org-stored-links
+ (cons (list url title) org-stored-links))
+ (org-store-link-props :type type
+ :link url
+ :description title
+ :annotation orglink
+ :initial region
+ :query parts)
+ (raise-frame)
+ (funcall 'org-capture nil template)))
+
+(defun org-protocol-open-source (fname)
+ "Process an org-protocol://open-source?url= style URL with FNAME.
+
+Change a filename by mapping URLs to local filenames as set
+in `org-protocol-project-alist'.
+
+The location for a browser's bookmark should look like this:
+
+ javascript:location.href = \\='org-protocol://open-source?url=\\=' + \\
+ encodeURIComponent(location.href)"
+ ;; As we enter this function for a match on our protocol, the return value
+ ;; defaults to nil.
+ (let ((result nil)
+ (f (plist-get (org-protocol-parse-parameters fname nil '(:url)) :url)))
+ (catch 'result
+ (dolist (prolist org-protocol-project-alist)
+ (let* ((base-url (plist-get (cdr prolist) :base-url))
+ (wsearch (regexp-quote base-url)))
+
+ (when (string-match wsearch f)
+ (let* ((wdir (plist-get (cdr prolist) :working-directory))
+ (strip-suffix (plist-get (cdr prolist) :online-suffix))
+ (add-suffix (plist-get (cdr prolist) :working-suffix))
+ ;; Strip "[?#].*$" if `f' is a redirect with another
+ ;; ending than strip-suffix here:
+ (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f)))
+ (start-pos (+ (string-match wsearch f1) (length base-url)))
+ (end-pos (string-match
+ (regexp-quote strip-suffix) f1))
+ ;; We have to compare redirects without suffix below:
+ (f2 (concat wdir (substring f1 start-pos end-pos)))
+ (the-file (concat f2 add-suffix)))
+
+ ;; Note: the-file may still contain `%C3' et al here because browsers
+ ;; tend to encode `&auml;' in URLs to `%25C3' - `%25' being `%'.
+ ;; So the results may vary.
+
+ ;; -- start redirects --
+ (unless (file-exists-p the-file)
+ (message "File %s does not exist.\nTesting for rewritten URLs." the-file)
+ (let ((rewrites (plist-get (cdr prolist) :rewrites)))
+ (when rewrites
+ (message "Rewrites found: %S" rewrites)
+ (dolist (rewrite rewrites)
+ ;; Try to match a rewritten URL and map it to
+ ;; a real file. Compare redirects without
+ ;; suffix.
+ (when (string-match-p (car rewrite) f2)
+ (throw 'result (concat wdir (cdr rewrite))))))))
+ ;; -- end of redirects --
+
+ (if (file-readable-p the-file)
+ (throw 'result the-file))
+ (if (file-exists-p the-file)
+ (message "%s: permission denied!" the-file)
+ (message "%s: no such file or directory." the-file))))))
+ result)))
+
+
+;;; Core functions:
+
+(defun org-protocol-check-filename-for-protocol (fname restoffiles _client)
+ "Check if `org-protocol-the-protocol' and a valid protocol are used in FNAME.
+Sub-protocols are registered in `org-protocol-protocol-alist' and
+`org-protocol-protocol-alist-default'. This is how the matching is done:
+
+ (string-match \"protocol:/+sub-protocol\\\\(://\\\\|\\\\?\\\\)\" ...)
+
+protocol and sub-protocol are regexp-quoted.
+
+Old-style links such as \"protocol://sub-protocol://param1/param2\" are
+also recognized.
+
+If a matching protocol is found, the protocol is stripped from
+fname and the result is passed to the protocol function as the
+first parameter. The second parameter will be non-nil if FNAME
+uses key=val&key2=val2-type arguments, or nil if FNAME uses
+val/val2-type arguments. If the function returns nil, the
+filename is removed from the list of filenames passed from
+emacsclient to the server. If the function returns a non-nil
+value, that value is passed to the server as filename.
+
+If the handler function is greedy, RESTOFFILES will also be passed to it.
+
+CLIENT is ignored."
+ (let ((sub-protocols (append org-protocol-protocol-alist
+ org-protocol-protocol-alist-default)))
+ (catch 'fname
+ (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol)
+ ":/+")))
+ (when (string-match the-protocol fname)
+ (dolist (prolist sub-protocols)
+ (let ((proto
+ (concat the-protocol
+ (regexp-quote (plist-get (cdr prolist) :protocol))
+ "\\(:/+\\|\\?\\)")))
+ (when (string-match proto fname)
+ (let* ((func (plist-get (cdr prolist) :function))
+ (greedy (plist-get (cdr prolist) :greedy))
+ (split (split-string fname proto))
+ (result (if greedy restoffiles (cadr split)))
+ (new-style (string= (match-string 1 fname) "?")))
+ (when (plist-get (cdr prolist) :kill-client)
+ (message "Greedy org-protocol handler. Killing client.")
+ (server-edit))
+ (when (fboundp func)
+ (unless greedy
+ (throw 'fname
+ (if new-style
+ (funcall func (org-protocol-parse-parameters
+ result new-style))
+ (warn "Please update your Org Protocol handler \
+to deal with new-style links.")
+ (funcall func result))))
+ ;; Greedy protocol handlers are responsible for
+ ;; parsing their own filenames.
+ (funcall func result)
+ (throw 'fname t))))))))
+ fname)))
+
+(defadvice server-visit-files (before org-protocol-detect-protocol-server activate)
+ "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
+ (let ((flist (if org-protocol-reverse-list-of-files
+ (reverse (ad-get-arg 0))
+ (ad-get-arg 0)))
+ (client (ad-get-arg 1)))
+ (catch 'greedy
+ (dolist (var flist)
+ ;; `\' to `/' on windows. FIXME: could this be done any better?
+ (let ((fname (expand-file-name (car var))))
+ (setq fname (org-protocol-check-filename-for-protocol
+ fname (member var flist) client))
+ (if (eq fname t) ;; greedy? We need the t return value.
+ (progn
+ (ad-set-arg 0 nil)
+ (throw 'greedy t))
+ (if (stringp fname) ;; probably filename
+ (setcar var fname)
+ (ad-set-arg 0 (delq var (ad-get-arg 0))))))))))
+
+;;; Org specific functions:
+
+(defun org-protocol-create-for-org ()
+ "Create a Org protocol project for the current file's project.
+The visited file needs to be part of a publishing project in
+`org-publish-project-alist' for this to work. The function
+delegates most of the work to `org-protocol-create'."
+ (interactive)
+ (require 'ox-publish)
+ (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
+ (if all (org-protocol-create (cdr all))
+ (message "%s"
+ (substitute-command-keys
+ "Not in an Org project. \
+Did you mean `\\[org-protocol-create]'?")))))
+
+(defun org-protocol-create (&optional project-plist)
+ "Create a new org-protocol project interactively.
+An org-protocol project is an entry in
+`org-protocol-project-alist' which is used by
+`org-protocol-open-source'. Optionally use PROJECT-PLIST to
+initialize the defaults for this project. If PROJECT-PLIST is
+the cdr of an element in `org-publish-project-alist', reuse
+:base-directory, :html-extension and :base-extension."
+ (interactive)
+ (let ((working-dir (expand-file-name
+ (or (plist-get project-plist :base-directory)
+ default-directory)))
+ (base-url "http://orgmode.org/worg/")
+ (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
+ (working-suffix (if (plist-get project-plist :base-extension)
+ (concat "." (plist-get project-plist :base-extension))
+ ".org"))
+ (insert-default-directory t)
+ (minibuffer-allow-text-properties nil))
+
+ (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
+ (or (string-suffix-p "/" base-url)
+ (setq base-url (concat base-url "/")))
+
+ (setq working-dir
+ (expand-file-name
+ (read-directory-name "Local working directory: " working-dir working-dir t)))
+ (or (string-suffix-p "/" working-dir)
+ (setq working-dir (concat working-dir "/")))
+
+ (setq strip-suffix
+ (read-string
+ (concat "Extension to strip from published URLs (" strip-suffix "): ")
+ strip-suffix nil strip-suffix t))
+
+ (setq working-suffix
+ (read-string
+ (concat "Extension of editable files (" working-suffix "): ")
+ working-suffix nil working-suffix t))
+
+ (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
+ (setq org-protocol-project-alist
+ (cons `(,base-url . (:base-url ,base-url
+ :working-directory ,working-dir
+ :online-suffix ,strip-suffix
+ :working-suffix ,working-suffix))
+ org-protocol-project-alist))
+ (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))))
+
+(provide 'org-protocol)
+
+;;; org-protocol.el ends here
diff --git a/lisp/org-rmail.el b/lisp/org-rmail.el
new file mode 100644
index 0000000..31c59a1
--- /dev/null
+++ b/lisp/org-rmail.el
@@ -0,0 +1,115 @@
+;;; org-rmail.el --- Support for Links to Rmail Messages -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements links to Rmail messages from within Org mode.
+;; Org mode loads this module by default - if this is not what you
+;; want, configure the variable `org-modules'.
+
+;;; Code:
+
+(require 'org)
+
+;; Declare external functions and variables
+(declare-function rmail-show-message "rmail" (&optional n no-summary))
+(declare-function rmail-what-message "rmail" (&optional pos))
+(declare-function rmail-toggle-header "rmail" (&optional arg))
+(declare-function rmail "rmail" (&optional file-name-arg))
+(declare-function rmail-widen "rmail" ())
+(defvar rmail-current-message) ; From rmail.el
+(defvar rmail-header-style) ; From rmail.el
+(defvar rmail-file-name) ; From rmail.el
+
+;; Install the link type
+(org-link-set-parameters "rmail" :follow #'org-rmail-open :store #'org-rmail-store-link)
+
+;; Implementation
+(defun org-rmail-store-link ()
+ "Store a link to an Rmail folder or message."
+ (when (or (eq major-mode 'rmail-mode)
+ (eq major-mode 'rmail-summary-mode))
+ (save-window-excursion
+ (save-restriction
+ (when (eq major-mode 'rmail-summary-mode)
+ (rmail-show-message rmail-current-message))
+ (when (fboundp 'rmail-narrow-to-non-pruned-header)
+ (rmail-narrow-to-non-pruned-header))
+ (when (eq rmail-header-style 'normal)
+ (rmail-toggle-header -1))
+ (let* ((folder buffer-file-name)
+ (message-id (mail-fetch-field "message-id"))
+ (from (mail-fetch-field "from"))
+ (to (mail-fetch-field "to"))
+ (subject (mail-fetch-field "subject"))
+ (date (mail-fetch-field "date"))
+ desc link)
+ (org-store-link-props
+ :type "rmail" :from from :to to :date date
+ :subject subject :message-id message-id)
+ (setq message-id (org-unbracket-string "<" ">" message-id))
+ (setq desc (org-email-link-description))
+ (setq link (concat "rmail:" folder "#" message-id))
+ (org-add-link-props :link link :description desc)
+ (rmail-show-message rmail-current-message)
+ link)))))
+
+(defun org-rmail-open (path)
+ "Follow an Rmail message link to the specified PATH."
+ (let (folder article)
+ (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
+ (error "Error in Rmail link"))
+ (setq folder (match-string 1 path)
+ article (match-string 3 path))
+ (org-rmail-follow-link folder article)))
+
+(defun org-rmail-follow-link (folder article)
+ "Follow an Rmail link to FOLDER and ARTICLE."
+ (require 'rmail)
+ (cond ((null article) (setq article ""))
+ ((stringp article)
+ (setq article (org-add-angle-brackets article)))
+ (t (user-error "Wrong RMAIL link format")))
+ (let (message-number)
+ (save-excursion
+ (save-window-excursion
+ (rmail (if (string= folder "RMAIL") rmail-file-name folder))
+ (setq message-number
+ (save-restriction
+ (rmail-widen)
+ (goto-char (point-max))
+ (if (re-search-backward
+ (concat "^Message-ID:\\s-+" (regexp-quote article))
+ nil t)
+ (rmail-what-message))))))
+ (if message-number
+ (progn
+ (rmail (if (string= folder "RMAIL") rmail-file-name folder))
+ (rmail-show-message message-number)
+ message-number)
+ (error "Message not found"))))
+
+(provide 'org-rmail)
+
+;;; org-rmail.el ends here
diff --git a/lisp/org-src.el b/lisp/org-src.el
new file mode 100644
index 0000000..0e04d4b
--- /dev/null
+++ b/lisp/org-src.el
@@ -0,0 +1,1104 @@
+;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
+;;
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Bastien Guerry <bzg@gnu.org>
+;; Dan Davison <davison at stats dot ox dot ac dot uk>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the code dealing with source code examples in
+;; Org mode.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-macs)
+(require 'org-compat)
+(require 'ob-keys)
+(require 'ob-comint)
+
+(declare-function org-base-buffer "org" (buffer))
+(declare-function org-do-remove-indentation "org" (&optional n))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-class "org-element" (datum &optional parent))
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-lineage "org-element"
+ (blob &optional types with-self))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-footnote-goto-definition "org-footnote"
+ (label &optional location))
+(declare-function org-get-indentation "org" (&optional line))
+(declare-function org-switch-to-buffer-other-window "org" (&rest args))
+(declare-function org-trim "org" (s &optional keep-lead))
+
+(defvar org-inhibit-startup)
+
+(defcustom org-edit-src-turn-on-auto-save nil
+ "Non-nil means turn `auto-save-mode' on when editing a source block.
+This will save the content of the source code editing buffer into
+a newly created file, not the base buffer for this source block.
+
+If you want to regularly save the base buffer instead of the source
+code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
+ :group 'org-edit-structure
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-edit-src-auto-save-idle-delay 0
+ "Delay before saving a source code buffer back into its base buffer.
+When a positive integer N, save after N seconds of idle time.
+When 0 (the default), don't auto-save.
+
+If you want to save the source code buffer itself, don't use this.
+Check `org-edit-src-turn-on-auto-save' instead."
+ :group 'org-edit-structure
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-coderef-label-format "(ref:%s)"
+ "The default coderef format.
+This format string will be used to search for coderef labels in literal
+examples (EXAMPLE and SRC blocks). The format can be overwritten in
+an individual literal example with the -l option, like
+
+#+BEGIN_SRC pascal +n -r -l \"((%s))\"
+...
+#+END_SRC
+
+If you want to use this for HTML export, make sure that the format does
+not introduce special font-locking, and avoid the HTML special
+characters `<', `>', and `&'. The reason for this restriction is that
+the labels are searched for only after htmlize has done its job."
+ :group 'org-edit-structure ; FIXME this is not in the right group
+ :type 'string)
+
+(defcustom org-edit-fixed-width-region-mode 'artist-mode
+ "The mode that should be used to edit fixed-width regions.
+These are the regions where each line starts with a colon."
+ :group 'org-edit-structure
+ :type '(choice
+ (const artist-mode)
+ (const picture-mode)
+ (const fundamental-mode)
+ (function :tag "Other (specify)")))
+
+(defcustom org-src-preserve-indentation nil
+ "If non-nil preserve leading whitespace characters on export.
+\\<org-mode-map>
+If non-nil leading whitespace characters in source code blocks
+are preserved on export, and when switching between the org
+buffer and the language mode edit buffer.
+
+When this variable is nil, after editing with `\\[org-edit-src-code]',
+the minimum (across-lines) number of leading whitespace characters
+are removed from all lines, and the code block is uniformly indented
+according to the value of `org-edit-src-content-indentation'."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-edit-src-content-indentation 2
+ "Indentation for the content of a source code block.
+
+This should be the number of spaces added to the indentation of the #+begin
+line in order to compute the indentation of the block content after
+editing it with `\\[org-edit-src-code]'.
+
+It has no effect if `org-src-preserve-indentation' is non-nil."
+ :group 'org-edit-structure
+ :type 'integer)
+
+(defcustom org-edit-src-persistent-message t
+ "Non-nil means show persistent exit help message while editing src examples.
+The message is shown in the header-line, which will be created in the
+first line of the window showing the editing buffer."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-src-ask-before-returning-to-edit-buffer t
+ "Non-nil means ask before switching to an existing edit buffer.
+If nil, when `org-edit-src-code' is used on a block that already
+has an active edit buffer, it will switch to that edit buffer
+immediately; otherwise it will ask whether you want to return to
+the existing edit buffer."
+ :group 'org-edit-structure
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-src-window-setup 'reorganize-frame
+ "How the source code edit buffer should be displayed.
+Possible values for this option are:
+
+current-window Show edit buffer in the current window, keeping all other
+ windows.
+other-window Use `switch-to-buffer-other-window' to display edit buffer.
+reorganize-frame Show only two windows on the current frame, the current
+ window and the edit buffer. When exiting the edit buffer,
+ return to one window.
+other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
+ Also, when exiting the edit buffer, kill that frame."
+ :group 'org-edit-structure
+ :type '(choice
+ (const current-window)
+ (const other-frame)
+ (const other-window)
+ (const reorganize-frame)))
+
+(defvar org-src-mode-hook nil
+ "Hook run after Org switched a source code snippet to its Emacs mode.
+\\<org-mode-map>
+This hook will run:
+- when editing a source code snippet with `\\[org-edit-special]'
+- when formatting a source code snippet for export with htmlize.
+
+You may want to use this hook for example to turn off `outline-minor-mode'
+or similar things which you want to have when editing a source code file,
+but which mess up the display of a snippet in Org exported files.")
+
+(defcustom org-src-lang-modes
+ '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
+ ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
+ ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
+ ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
+ "Alist mapping languages to their major mode.
+The key is the language name, the value is the string that should
+be inserted as the name of the major mode. For many languages this is
+simple, but for language where this is not the case, this variable
+provides a way to simplify things on the user side.
+For example, there is no ocaml-mode in Emacs, but the mode to use is
+`tuareg-mode'."
+ :group 'org-edit-structure
+ :type '(repeat
+ (cons
+ (string "Language name")
+ (symbol "Major mode"))))
+
+(defcustom org-src-block-faces nil
+ "Alist of faces to be used for source-block.
+Each element is a cell of the format
+
+ (\"language\" FACE)
+
+Where FACE is either a defined face or an anonymous face.
+
+For instance, the following value would color the background of
+emacs-lisp source blocks and python source blocks in purple and
+green, respectability.
+
+ \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
+ (\"python\" (:background \"#e5ffb8\")))"
+ :group 'org-edit-structure
+ :type '(repeat (list (string :tag "language")
+ (choice
+ (face :tag "Face")
+ (sexp :tag "Anonymous face"))))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defcustom org-src-tab-acts-natively nil
+ "If non-nil, the effect of TAB in a code block is as if it were
+issued in the language major mode buffer."
+ :type 'boolean
+ :version "24.1"
+ :group 'org-babel)
+
+
+
+;;; Internal functions and variables
+
+(defvar org-src--allow-write-back t)
+(defvar org-src--auto-save-timer nil)
+(defvar org-src--babel-info nil)
+(defvar org-src--beg-marker nil)
+(defvar org-src--block-indentation nil)
+(defvar org-src--end-marker nil)
+(defvar org-src--from-org-mode nil)
+(defvar org-src--overlay nil)
+(defvar org-src--preserve-indentation nil)
+(defvar org-src--remote nil)
+(defvar org-src--saved-temp-window-config nil)
+(defvar org-src--source-type nil
+ "Type of element being edited, as a symbol.")
+(defvar org-src--tab-width nil
+ "Contains `tab-width' value from Org source buffer.
+However, if `indent-tabs-mode' is nil in that buffer, its value
+is 0.")
+
+(defun org-src--construct-edit-buffer-name (org-buffer-name lang)
+ "Construct the buffer name for a source editing buffer."
+ (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
+
+(defun org-src--edit-buffer (beg end)
+ "Return buffer editing area between BEG and END.
+Return nil if there is no such buffer."
+ (catch 'exit
+ (dolist (b (buffer-list))
+ (with-current-buffer b
+ (and (org-src-edit-buffer-p)
+ (= beg org-src--beg-marker)
+ (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
+ (= end org-src--end-marker)
+ (eq (marker-buffer end) (marker-buffer org-src--end-marker))
+ (throw 'exit b))))))
+
+(defun org-src--source-buffer ()
+ "Return source buffer edited by current buffer."
+ (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
+ (or (marker-buffer org-src--beg-marker)
+ (error "No source buffer available for current editing session")))
+
+(defun org-src--get-lang-mode (lang)
+ "Return major mode that should be used for LANG.
+LANG is a string, and the returned major mode is a symbol."
+ (intern
+ (concat
+ (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
+ (if (symbolp l) (symbol-name l) l))
+ "-mode")))
+
+(defun org-src--coordinates (pos beg end)
+ "Return coordinates of POS relatively to BEG and END.
+POS, BEG and END are buffer positions. Return value is either
+a cons cell (LINE . COLUMN) or symbol `end'. See also
+`org-src--goto-coordinates'."
+ (if (>= pos end) 'end
+ (org-with-wide-buffer
+ (goto-char (max beg pos))
+ (cons (count-lines beg (line-beginning-position))
+ ;; Column is relative to the end of line to avoid problems of
+ ;; comma escaping or colons appended in front of the line.
+ (- (current-column)
+ (progn (end-of-line) (current-column)))))))
+
+(defun org-src--goto-coordinates (coord beg end)
+ "Move to coordinates COORD relatively to BEG and END.
+COORD are coordinates, as returned by `org-src--coordinates',
+which see. BEG and END are buffer positions."
+ (goto-char
+ (if (eq coord 'end) (max (1- end) beg)
+ ;; If BEG happens to be located outside of the narrowed part of
+ ;; the buffer, widen it first.
+ (org-with-wide-buffer
+ (goto-char beg)
+ (forward-line (car coord))
+ (end-of-line)
+ (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
+ (point)))))
+
+(defun org-src--contents-area (datum)
+ "Return contents boundaries of DATUM.
+DATUM is an element or object. Return a list (BEG END CONTENTS)
+where BEG and END are buffer positions and CONTENTS is a string."
+ (let ((type (org-element-type datum)))
+ (org-with-wide-buffer
+ (cond
+ ((eq type 'footnote-definition)
+ (let* ((beg (progn
+ (goto-char (org-element-property :post-affiliated datum))
+ (search-forward "]")))
+ (end (or (org-element-property :contents-end datum) beg)))
+ (list beg end (buffer-substring-no-properties beg end))))
+ ((eq type 'inline-src-block)
+ (let ((beg (progn (goto-char (org-element-property :begin datum))
+ (search-forward "{" (line-end-position) t)))
+ (end (progn (goto-char (org-element-property :end datum))
+ (search-backward "}" (line-beginning-position) t))))
+ (list beg end (buffer-substring-no-properties beg end))))
+ ((org-element-property :contents-begin datum)
+ (let ((beg (org-element-property :contents-begin datum))
+ (end (org-element-property :contents-end datum)))
+ (list beg end (buffer-substring-no-properties beg end))))
+ ((memq type '(example-block export-block src-block))
+ (list (progn (goto-char (org-element-property :post-affiliated datum))
+ (line-beginning-position 2))
+ (progn (goto-char (org-element-property :end datum))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 1))
+ (org-element-property :value datum)))
+ ((memq type '(fixed-width table))
+ (let ((beg (org-element-property :post-affiliated datum))
+ (end (progn (goto-char (org-element-property :end datum))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))))
+ (list beg
+ end
+ (if (eq type 'fixed-width) (org-element-property :value datum)
+ (buffer-substring-no-properties beg end)))))
+ (t (error "Unsupported element or object: %s" type))))))
+
+(defun org-src--make-source-overlay (beg end edit-buffer)
+ "Create overlay between BEG and END positions and return it.
+EDIT-BUFFER is the buffer currently editing area between BEG and
+END."
+ (let ((overlay (make-overlay beg end)))
+ (overlay-put overlay 'face 'secondary-selection)
+ (overlay-put overlay 'edit-buffer edit-buffer)
+ (overlay-put overlay 'help-echo
+ "Click with mouse-1 to switch to buffer editing this segment")
+ (overlay-put overlay 'face 'secondary-selection)
+ (overlay-put overlay 'keymap
+ (let ((map (make-sparse-keymap)))
+ (define-key map [mouse-1] 'org-edit-src-continue)
+ map))
+ (let ((read-only
+ (list
+ (lambda (&rest _)
+ (user-error
+ "Cannot modify an area being edited in a dedicated buffer")))))
+ (overlay-put overlay 'modification-hooks read-only)
+ (overlay-put overlay 'insert-in-front-hooks read-only)
+ (overlay-put overlay 'insert-behind-hooks read-only))
+ overlay))
+
+(defun org-src--remove-overlay ()
+ "Remove overlay from current source buffer."
+ (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
+
+(defun org-src--on-datum-p (datum)
+ "Non-nil when point is on DATUM.
+DATUM is an element or an object. Consider blank lines or white
+spaces after it as being outside."
+ (and (>= (point) (org-element-property :begin datum))
+ (<= (point)
+ (org-with-wide-buffer
+ (goto-char (org-element-property :end datum))
+ (skip-chars-backward " \r\t\n")
+ (if (eq (org-element-class datum) 'element)
+ (line-end-position)
+ (point))))))
+
+(defun org-src--contents-for-write-back ()
+ "Return buffer contents in a format appropriate for write back.
+Assume point is in the corresponding edit buffer."
+ (let ((indentation-offset
+ (if org-src--preserve-indentation 0
+ (+ (or org-src--block-indentation 0)
+ (if (memq org-src--source-type '(example-block src-block))
+ org-edit-src-content-indentation
+ 0))))
+ (use-tabs? (and (> org-src--tab-width 0) t))
+ (source-tab-width org-src--tab-width)
+ (contents (org-with-wide-buffer (buffer-string)))
+ (write-back org-src--allow-write-back))
+ (with-temp-buffer
+ ;; Reproduce indentation parameters from source buffer.
+ (setq-local indent-tabs-mode use-tabs?)
+ (when (> source-tab-width 0) (setq-local tab-width source-tab-width))
+ ;; Apply WRITE-BACK function on edit buffer contents.
+ (insert (org-no-properties contents))
+ (goto-char (point-min))
+ (when (functionp write-back) (save-excursion (funcall write-back)))
+ ;; Add INDENTATION-OFFSET to every non-empty line in buffer,
+ ;; unless indentation is meant to be preserved.
+ (when (> indentation-offset 0)
+ (while (not (eobp))
+ (skip-chars-forward " \t")
+ (unless (eolp) ;ignore blank lines
+ (let ((i (current-column)))
+ (delete-region (line-beginning-position) (point))
+ (indent-to (+ i indentation-offset))))
+ (forward-line)))
+ (buffer-string))))
+
+(defun org-src--edit-element
+ (datum name &optional major write-back contents remote)
+ "Edit DATUM contents in a dedicated buffer NAME.
+
+MAJOR is the major mode used in the edit buffer. A nil value is
+equivalent to `fundamental-mode'.
+
+When WRITE-BACK is non-nil, assume contents will replace original
+region. Moreover, if it is a function, apply it in the edit
+buffer, from point min, before returning the contents.
+
+When CONTENTS is non-nil, display them in the edit buffer.
+Otherwise, show DATUM contents as specified by
+`org-src--contents-area'.
+
+When REMOTE is non-nil, do not try to preserve point or mark when
+moving from the edit area to the source.
+
+Leave point in edit buffer."
+ (setq org-src--saved-temp-window-config (current-window-configuration))
+ (let* ((area (org-src--contents-area datum))
+ (beg (copy-marker (nth 0 area)))
+ (end (copy-marker (nth 1 area) t))
+ (old-edit-buffer (org-src--edit-buffer beg end))
+ (contents (or contents (nth 2 area))))
+ (if (and old-edit-buffer
+ (or (not org-src-ask-before-returning-to-edit-buffer)
+ (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
+ ;; Move to existing buffer.
+ (org-src-switch-to-buffer old-edit-buffer 'return)
+ ;; Discard old edit buffer.
+ (when old-edit-buffer
+ (with-current-buffer old-edit-buffer (org-src--remove-overlay))
+ (kill-buffer old-edit-buffer))
+ (let* ((org-mode-p (derived-mode-p 'org-mode))
+ (source-tab-width (if indent-tabs-mode tab-width 0))
+ (type (org-element-type datum))
+ (ind (org-with-wide-buffer
+ (goto-char (org-element-property :begin datum))
+ (org-get-indentation)))
+ (preserve-ind
+ (and (memq type '(example-block src-block))
+ (or (org-element-property :preserve-indent datum)
+ org-src-preserve-indentation)))
+ ;; Store relative positions of mark (if any) and point
+ ;; within the edited area.
+ (point-coordinates (and (not remote)
+ (org-src--coordinates (point) beg end)))
+ (mark-coordinates (and (not remote)
+ (org-region-active-p)
+ (let ((m (mark)))
+ (and (>= m beg) (>= end m)
+ (org-src--coordinates m beg end)))))
+ ;; Generate a new edit buffer.
+ (buffer (generate-new-buffer name))
+ ;; Add an overlay on top of source.
+ (overlay (org-src--make-source-overlay beg end buffer)))
+ ;; Switch to edit buffer.
+ (org-src-switch-to-buffer buffer 'edit)
+ ;; Insert contents.
+ (insert contents)
+ (remove-text-properties (point-min) (point-max)
+ '(display nil invisible nil intangible nil))
+ (unless preserve-ind (org-do-remove-indentation))
+ (set-buffer-modified-p nil)
+ (setq buffer-file-name nil)
+ ;; Start major mode.
+ (if (not major) (fundamental-mode)
+ (let ((org-inhibit-startup t))
+ (condition-case e (funcall major)
+ (error (message "Language mode `%s' fails with: %S"
+ major (nth 1 e))))))
+ ;; Transmit buffer-local variables for exit function. It must
+ ;; be done after initializing major mode, as this operation
+ ;; may reset them otherwise.
+ (setq-local org-src--tab-width source-tab-width)
+ (setq-local org-src--from-org-mode org-mode-p)
+ (setq-local org-src--beg-marker beg)
+ (setq-local org-src--end-marker end)
+ (setq-local org-src--remote remote)
+ (setq-local org-src--source-type type)
+ (setq-local org-src--block-indentation ind)
+ (setq-local org-src--preserve-indentation preserve-ind)
+ (setq-local org-src--overlay overlay)
+ (setq-local org-src--allow-write-back write-back)
+ ;; Start minor mode.
+ (org-src-mode)
+ ;; Move mark and point in edit buffer to the corresponding
+ ;; location.
+ (if remote
+ (progn
+ ;; Put point at first non read-only character after
+ ;; leading blank.
+ (goto-char
+ (or (text-property-any (point-min) (point-max) 'read-only nil)
+ (point-max)))
+ (skip-chars-forward " \r\t\n"))
+ ;; Set mark and point.
+ (when mark-coordinates
+ (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
+ (push-mark (point) 'no-message t)
+ (setq deactivate-mark nil))
+ (org-src--goto-coordinates
+ point-coordinates (point-min) (point-max)))))))
+
+
+
+;;; Fontification of source blocks
+
+(defun org-src-font-lock-fontify-block (lang start end)
+ "Fontify code block.
+This function is called by emacs automatic fontification, as long
+as `org-src-fontify-natively' is non-nil."
+ (let ((lang-mode (org-src--get-lang-mode lang)))
+ (when (fboundp lang-mode)
+ (let ((string (buffer-substring-no-properties start end))
+ (modified (buffer-modified-p))
+ (org-buffer (current-buffer)))
+ (remove-text-properties start end '(face nil))
+ (with-current-buffer
+ (get-buffer-create
+ (format " *org-src-fontification:%s*" lang-mode))
+ (let ((inhibit-modification-hooks nil))
+ (erase-buffer)
+ ;; Add string and a final space to ensure property change.
+ (insert string " "))
+ (unless (eq major-mode lang-mode) (funcall lang-mode))
+ (org-font-lock-ensure)
+ (let ((pos (point-min)) next)
+ (while (setq next (next-property-change pos))
+ ;; Handle additional properties from font-lock, so as to
+ ;; preserve, e.g., composition.
+ (dolist (prop (cons 'face font-lock-extra-managed-props))
+ (let ((new-prop (get-text-property pos prop)))
+ (put-text-property
+ (+ start (1- pos)) (1- (+ start next)) prop new-prop
+ org-buffer)))
+ (setq pos next))))
+ ;; Add Org faces.
+ (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
+ (when (or (facep src-face) (listp src-face))
+ (font-lock-append-text-property start end 'face src-face))
+ (font-lock-append-text-property start end 'face 'org-block))
+ (add-text-properties
+ start end
+ '(font-lock-fontified t fontified t font-lock-multiline t))
+ (set-buffer-modified-p modified)))))
+
+
+;;; Escape contents
+
+(defun org-escape-code-in-region (beg end)
+ "Escape lines between BEG and END.
+Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
+\",#+\" by appending a comma to it."
+ (interactive "r")
+ (save-excursion
+ (goto-char end)
+ (while (re-search-backward "^[ \t]*,?\\(\\*\\|#\\+\\)" beg t)
+ (save-excursion (replace-match ",\\1" nil nil nil 1)))))
+
+(defun org-escape-code-in-string (s)
+ "Escape lines in string S.
+Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
+\",#+\" by appending a comma to it."
+ (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
+
+(defun org-unescape-code-in-region (beg end)
+ "Un-escape lines between BEG and END.
+Un-escaping happens by removing the first comma on lines starting
+with \",*\", \",#+\", \",,*\" and \",,#+\"."
+ (interactive "r")
+ (save-excursion
+ (goto-char end)
+ (while (re-search-backward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
+ (save-excursion (replace-match "" nil nil nil 1)))))
+
+(defun org-unescape-code-in-string (s)
+ "Un-escape lines in string S.
+Un-escaping happens by removing the first comma on lines starting
+with \",*\", \",#+\", \",,*\" and \",,#+\"."
+ (replace-regexp-in-string
+ "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
+
+
+
+;;; Org src minor mode
+
+(defvar org-src-mode-map
+ (let ((map (make-sparse-keymap)))
+ (define-key map "\C-c'" 'org-edit-src-exit)
+ (define-key map "\C-c\C-k" 'org-edit-src-abort)
+ (define-key map "\C-x\C-s" 'org-edit-src-save)
+ map))
+
+(define-minor-mode org-src-mode
+ "Minor mode for language major mode buffers generated by Org.
+\\<org-mode-map>
+This minor mode is turned on in two situations:
+ - when editing a source code snippet with `\\[org-edit-special]'
+ - when formatting a source code snippet for export with htmlize.
+
+\\{org-src-mode-map}
+
+See also `org-src-mode-hook'."
+ nil " OrgSrc" nil
+ (when org-edit-src-persistent-message
+ (setq-local
+ header-line-format
+ (substitute-command-keys
+ (if org-src--allow-write-back
+ "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
+`\\[org-edit-src-abort]'"
+ "Exit with `\\[org-edit-src-exit]' or abort with \
+`\\[org-edit-src-abort]'"))))
+ ;; Possibly activate various auto-save features (for the edit buffer
+ ;; or the source buffer).
+ (when org-edit-src-turn-on-auto-save
+ (setq buffer-auto-save-file-name
+ (concat (make-temp-name "org-src-")
+ (format-time-string "-%Y-%d-%m")
+ ".txt")))
+ (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
+ (setq org-src--auto-save-timer
+ (run-with-idle-timer
+ org-edit-src-auto-save-idle-delay t
+ (lambda ()
+ (save-excursion
+ (let (edit-flag)
+ (dolist (b (buffer-list))
+ (with-current-buffer b
+ (when (org-src-edit-buffer-p)
+ (unless edit-flag (setq edit-flag t))
+ (when (buffer-modified-p) (org-edit-src-save)))))
+ (unless edit-flag
+ (cancel-timer org-src--auto-save-timer)
+ (setq org-src--auto-save-timer nil)))))))))
+
+(defun org-src-mode-configure-edit-buffer ()
+ (when (bound-and-true-p org-src--from-org-mode)
+ (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
+ (if (bound-and-true-p org-src--allow-write-back)
+ (progn
+ (setq buffer-offer-save t)
+ (setq buffer-file-name
+ (concat (buffer-file-name (marker-buffer org-src--beg-marker))
+ "[" (buffer-name) "]"))
+ (setq-local write-contents-functions '(org-edit-src-save)))
+ (setq buffer-read-only t))))
+
+(add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
+
+
+
+;;; Babel related functions
+
+(defun org-src-associate-babel-session (info)
+ "Associate edit buffer with comint session."
+ (interactive)
+ (let ((session (cdr (assq :session (nth 2 info)))))
+ (and session (not (string= session "none"))
+ (org-babel-comint-buffer-livep session)
+ (let ((f (intern (format "org-babel-%s-associate-session"
+ (nth 0 info)))))
+ (and (fboundp f) (funcall f session))))))
+
+(defun org-src-babel-configure-edit-buffer ()
+ (when org-src--babel-info
+ (org-src-associate-babel-session org-src--babel-info)))
+
+(add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
+
+
+;;; Public API
+
+(defmacro org-src-do-at-code-block (&rest body)
+ "Execute BODY from an edit buffer in the Org mode buffer."
+ (declare (debug (body)))
+ `(let ((beg-marker org-src--beg-marker))
+ (when beg-marker
+ (with-current-buffer (marker-buffer beg-marker)
+ (goto-char beg-marker)
+ ,@body))))
+
+(defun org-src-do-key-sequence-at-code-block (&optional key)
+ "Execute key sequence at code block in the source Org buffer.
+The command bound to KEY in the Org-babel key map is executed
+remotely with point temporarily at the start of the code block in
+the Org buffer.
+
+This command is not bound to a key by default, to avoid conflicts
+with language major mode bindings. To bind it to C-c @ in all
+language major modes, you could use
+
+ (add-hook \\='org-src-mode-hook
+ (lambda () (define-key org-src-mode-map \"\\C-c@\"
+ \\='org-src-do-key-sequence-at-code-block)))
+
+In that case, for example, C-c @ t issued in code edit buffers
+would tangle the current Org code block, C-c @ e would execute
+the block and C-c @ h would display the other available
+Org-babel commands."
+ (interactive "kOrg-babel key: ")
+ (if (equal key (kbd "C-g")) (keyboard-quit)
+ (org-edit-src-save)
+ (org-src-do-at-code-block
+ (call-interactively (lookup-key org-babel-map key)))))
+
+(defun org-src-edit-buffer-p (&optional buffer)
+ "Non-nil when current buffer is a source editing buffer.
+If BUFFER is non-nil, test it instead."
+ (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
+ (and (buffer-live-p buffer)
+ (local-variable-p 'org-src--beg-marker buffer)
+ (local-variable-p 'org-src--end-marker buffer))))
+
+(defun org-src-switch-to-buffer (buffer context)
+ (pcase org-src-window-setup
+ (`current-window (pop-to-buffer-same-window buffer))
+ (`other-window
+ (switch-to-buffer-other-window buffer))
+ (`other-frame
+ (pcase context
+ (`exit
+ (let ((frame (selected-frame)))
+ (switch-to-buffer-other-frame buffer)
+ (delete-frame frame)))
+ (`save
+ (kill-buffer (current-buffer))
+ (pop-to-buffer-same-window buffer))
+ (_ (switch-to-buffer-other-frame buffer))))
+ (`reorganize-frame
+ (when (eq context 'edit) (delete-other-windows))
+ (org-switch-to-buffer-other-window buffer)
+ (when (eq context 'exit) (delete-other-windows)))
+ (`switch-invisibly (set-buffer buffer))
+ (_
+ (message "Invalid value %s for `org-src-window-setup'"
+ org-src-window-setup)
+ (pop-to-buffer-same-window buffer))))
+
+(defun org-src-coderef-format (&optional element)
+ "Return format string for block at point.
+
+When optional argument ELEMENT is provided, use that block.
+Otherwise, assume point is either at a source block, at an
+example block.
+
+If point is in an edit buffer, retrieve format string associated
+to the remote source block."
+ (cond
+ ((and element (org-element-property :label-fmt element)))
+ ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
+ ((org-element-property :label-fmt (org-element-at-point)))
+ (t org-coderef-label-format)))
+
+(defun org-src-coderef-regexp (fmt &optional label)
+ "Return regexp matching a coderef format string FMT.
+
+When optional argument LABEL is non-nil, match coderef for that
+label only.
+
+Match group 1 contains the full coderef string with surrounding
+white spaces. Match group 2 contains the same string without any
+surrounding space. Match group 3 contains the label.
+
+A coderef format regexp can only match at the end of a line."
+ (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
+ (replace-regexp-in-string
+ "%s"
+ (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
+ (regexp-quote fmt)
+ nil t)))
+
+(defun org-edit-footnote-reference ()
+ "Edit definition of footnote reference at point."
+ (interactive)
+ (let* ((context (org-element-context))
+ (label (org-element-property :label context)))
+ (unless (and (eq (org-element-type context) 'footnote-reference)
+ (org-src--on-datum-p context))
+ (user-error "Not on a footnote reference"))
+ (unless label (user-error "Cannot edit remotely anonymous footnotes"))
+ (let* ((definition (org-with-wide-buffer
+ (org-footnote-goto-definition label)
+ (backward-char)
+ (org-element-context)))
+ (inline? (eq 'footnote-reference (org-element-type definition)))
+ (contents
+ (org-with-wide-buffer
+ (buffer-substring-no-properties
+ (or (org-element-property :post-affiliated definition)
+ (org-element-property :begin definition))
+ (cond
+ (inline? (1+ (org-element-property :contents-end definition)))
+ ((org-element-property :contents-end definition))
+ (t (goto-char (org-element-property :post-affiliated definition))
+ (line-end-position)))))))
+ (add-text-properties
+ 0
+ (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
+ (match-end 0))
+ '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
+ contents)
+ (when inline?
+ (let ((l (length contents)))
+ (add-text-properties
+ (1- l) l
+ '(read-only "Cannot edit past footnote reference"
+ front-sticky nil rear-nonsticky nil)
+ contents)))
+ (org-src--edit-element
+ definition
+ (format "*Edit footnote [%s]*" label)
+ #'org-mode
+ (lambda ()
+ (if (not inline?) (delete-region (point) (search-forward "]"))
+ (delete-region (point) (search-forward ":" nil t 2))
+ (delete-region (1- (point-max)) (point-max))
+ (when (re-search-forward "\n[ \t]*\n" nil t)
+ (user-error "Inline definitions cannot contain blank lines"))
+ ;; If footnote reference belongs to a table, make sure to
+ ;; remove any newline characters in order to preserve
+ ;; table's structure.
+ (when (org-element-lineage definition '(table-cell))
+ (while (search-forward "\n" nil t) (replace-match "")))))
+ contents
+ 'remote))
+ ;; Report success.
+ t))
+
+(defun org-edit-table.el ()
+ "Edit \"table.el\" table at point.
+\\<org-src-mode-map>
+A new buffer is created and the table is copied into it. Then
+the table is recognized with `table-recognize'. When done
+editing, exit with `\\[org-edit-src-exit]'. The edited text will \
+then replace
+the area in the Org mode buffer.
+
+Throw an error when not at such a table."
+ (interactive)
+ (let ((element (org-element-at-point)))
+ (unless (and (eq (org-element-type element) 'table)
+ (eq (org-element-property :type element) 'table.el)
+ (org-src--on-datum-p element))
+ (user-error "Not in a table.el table"))
+ (org-src--edit-element
+ element
+ (org-src--construct-edit-buffer-name (buffer-name) "Table")
+ #'text-mode t)
+ (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
+ (table-recognize)
+ t))
+
+(defun org-edit-export-block ()
+ "Edit export block at point.
+\\<org-src-mode-map>
+A new buffer is created and the block is copied into it, and the
+buffer is switched into an appropriate major mode. See also
+`org-src-lang-modes'.
+
+When done, exit with `\\[org-edit-src-exit]'. The edited text \
+will then replace
+the area in the Org mode buffer.
+
+Throw an error when not at an export block."
+ (interactive)
+ (let ((element (org-element-at-point)))
+ (unless (and (eq (org-element-type element) 'export-block)
+ (org-src--on-datum-p element))
+ (user-error "Not in an export block"))
+ (let* ((type (downcase (org-element-property :type element)))
+ (mode (org-src--get-lang-mode type)))
+ (unless (functionp mode) (error "No such language mode: %s" mode))
+ (org-src--edit-element
+ element
+ (org-src--construct-edit-buffer-name (buffer-name) type)
+ mode
+ (lambda () (org-escape-code-in-region (point-min) (point-max)))))
+ t))
+
+(defun org-edit-src-code (&optional code edit-buffer-name)
+ "Edit the source or example block at point.
+\\<org-src-mode-map>
+The code is copied to a separate buffer and the appropriate mode
+is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
+will remove the
+original code in the Org buffer, and replace it with the edited
+version. See `org-src-window-setup' to configure the display of
+windows containing the Org buffer and the code buffer.
+
+When optional argument CODE is a string, edit it in a dedicated
+buffer instead.
+
+When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
+name of the sub-editing buffer."
+ (interactive)
+ (let* ((element (org-element-at-point))
+ (type (org-element-type element)))
+ (unless (and (memq type '(example-block src-block))
+ (org-src--on-datum-p element))
+ (user-error "Not in a source or example block"))
+ (let* ((lang
+ (if (eq type 'src-block) (org-element-property :language element)
+ "example"))
+ (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
+ (babel-info (and (eq type 'src-block)
+ (org-babel-get-src-block-info 'light)))
+ deactivate-mark)
+ (when (and (eq type 'src-block) (not (functionp lang-f)))
+ (error "No such language mode: %s" lang-f))
+ (org-src--edit-element
+ element
+ (or edit-buffer-name
+ (org-src--construct-edit-buffer-name (buffer-name) lang))
+ lang-f
+ (and (null code)
+ (lambda () (org-escape-code-in-region (point-min) (point-max))))
+ (and code (org-unescape-code-in-string code)))
+ ;; Finalize buffer.
+ (setq-local org-coderef-label-format
+ (or (org-element-property :label-fmt element)
+ org-coderef-label-format))
+ (when (eq type 'src-block)
+ (setq-local org-src--babel-info babel-info)
+ (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
+ (when (fboundp edit-prep-func)
+ (funcall edit-prep-func babel-info))))
+ t)))
+
+(defun org-edit-inline-src-code ()
+ "Edit inline source code at point."
+ (interactive)
+ (let ((context (org-element-context)))
+ (unless (and (eq (org-element-type context) 'inline-src-block)
+ (org-src--on-datum-p context))
+ (user-error "Not on inline source code"))
+ (let* ((lang (org-element-property :language context))
+ (lang-f (org-src--get-lang-mode lang))
+ (babel-info (org-babel-get-src-block-info 'light))
+ deactivate-mark)
+ (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
+ (org-src--edit-element
+ context
+ (org-src--construct-edit-buffer-name (buffer-name) lang)
+ lang-f
+ (lambda ()
+ ;; Inline src blocks are limited to one line.
+ (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
+ ;; Trim contents.
+ (goto-char (point-min))
+ (skip-chars-forward " \t")
+ (delete-region (point-min) (point))
+ (goto-char (point-max))
+ (skip-chars-backward " \t")
+ (delete-region (point) (point-max))))
+ ;; Finalize buffer.
+ (setq-local org-src--babel-info babel-info)
+ (setq-local org-src--preserve-indentation t)
+ (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
+ (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
+ ;; Return success.
+ t)))
+
+(defun org-edit-fixed-width-region ()
+ "Edit the fixed-width ASCII drawing at point.
+\\<org-src-mode-map>
+This must be a region where each line starts with a colon
+followed by a space or a newline character.
+
+A new buffer is created and the fixed-width region is copied into
+it, and the buffer is switched into the major mode defined in
+`org-edit-fixed-width-region-mode', which see.
+
+When done, exit with `\\[org-edit-src-exit]'. The edited text \
+will then replace
+the area in the Org mode buffer."
+ (interactive)
+ (let ((element (org-element-at-point)))
+ (unless (and (eq (org-element-type element) 'fixed-width)
+ (org-src--on-datum-p element))
+ (user-error "Not in a fixed-width area"))
+ (org-src--edit-element
+ element
+ (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
+ org-edit-fixed-width-region-mode
+ (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
+ ;; Return success.
+ t))
+
+(defun org-edit-src-abort ()
+ "Abort editing of the src code and return to the Org buffer."
+ (interactive)
+ (let (org-src--allow-write-back) (org-edit-src-exit)))
+
+(defun org-edit-src-continue (e)
+ "Unconditionally return to buffer editing area under point.
+Throw an error if there is no such buffer."
+ (interactive "e")
+ (mouse-set-point e)
+ (let ((buf (get-char-property (point) 'edit-buffer)))
+ (if buf (org-src-switch-to-buffer buf 'continue)
+ (user-error "No sub-editing buffer for area at point"))))
+
+(defun org-edit-src-save ()
+ "Save parent buffer with current state source-code buffer."
+ (interactive)
+ (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
+ (set-buffer-modified-p nil)
+ (let ((edited-code (org-src--contents-for-write-back))
+ (beg org-src--beg-marker)
+ (end org-src--end-marker)
+ (overlay org-src--overlay))
+ (with-current-buffer (org-src--source-buffer)
+ (undo-boundary)
+ (goto-char beg)
+ ;; Temporarily disable read-only features of OVERLAY in order to
+ ;; insert new contents.
+ (delete-overlay overlay)
+ (delete-region beg end)
+ (let ((expecting-bol (bolp)))
+ (insert edited-code)
+ (when (and expecting-bol (not (bolp))) (insert "\n")))
+ (save-buffer)
+ (move-overlay overlay beg (point))))
+ ;; `write-contents-functions' requires the function to return
+ ;; a non-nil value so that other functions are not called.
+ t)
+
+(defun org-edit-src-exit ()
+ "Kill current sub-editing buffer and return to source buffer."
+ (interactive)
+ (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
+ (let* ((beg org-src--beg-marker)
+ (end org-src--end-marker)
+ (write-back org-src--allow-write-back)
+ (remote org-src--remote)
+ (coordinates (and (not remote)
+ (org-src--coordinates (point) 1 (point-max))))
+ (code (and write-back (org-src--contents-for-write-back))))
+ (set-buffer-modified-p nil)
+ ;; Switch to source buffer. Kill sub-editing buffer.
+ (let ((edit-buffer (current-buffer))
+ (source-buffer (marker-buffer beg)))
+ (unless source-buffer (error "Source buffer disappeared. Aborting"))
+ (org-src-switch-to-buffer source-buffer 'exit)
+ (kill-buffer edit-buffer))
+ ;; Insert modified code. Ensure it ends with a newline character.
+ (org-with-wide-buffer
+ (when (and write-back (not (equal (buffer-substring beg end) code)))
+ (undo-boundary)
+ (goto-char beg)
+ (delete-region beg end)
+ (let ((expecting-bol (bolp)))
+ (insert code)
+ (when (and expecting-bol (not (bolp))) (insert "\n")))))
+ ;; If we are to return to source buffer, put point at an
+ ;; appropriate location. In particular, if block is hidden, move
+ ;; to the beginning of the block opening line.
+ (unless remote
+ (goto-char beg)
+ (cond
+ ;; Block is hidden; move at start of block.
+ ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
+ (overlays-at (point)))
+ (beginning-of-line 0))
+ (write-back (org-src--goto-coordinates coordinates beg end))))
+ ;; Clean up left-over markers and restore window configuration.
+ (set-marker beg nil)
+ (set-marker end nil)
+ (when org-src--saved-temp-window-config
+ (set-window-configuration org-src--saved-temp-window-config)
+ (setq org-src--saved-temp-window-config nil))))
+
+
+(provide 'org-src)
+
+;;; org-src.el ends here
diff --git a/lisp/org-table.el b/lisp/org-table.el
new file mode 100644
index 0000000..40a715a
--- /dev/null
+++ b/lisp/org-table.el
@@ -0,0 +1,5505 @@
+;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file contains the table editor and spreadsheet for Org mode.
+
+;; Watch out: Here we are talking about two different kind of tables.
+;; Most of the code is for the tables created with the Org mode table editor.
+;; Sometimes, we talk about tables created and edited with the table.el
+;; Emacs package. We call the former org-type tables, and the latter
+;; table.el-type tables.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org)
+
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-contents "org-element" (element))
+(declare-function org-element-extract-element "org-element" (element))
+(declare-function org-element-interpret-data "org-element" (data))
+(declare-function org-element-lineage "org-element"
+ (blob &optional types with-self))
+(declare-function org-element-map "org-element"
+ (data types fun
+ &optional info first-match no-recursion with-affiliated))
+(declare-function org-element-parse-buffer "org-element"
+ (&optional granularity visible-only))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-type "org-element" (element))
+
+(declare-function org-export-create-backend "ox" (&rest rest) t)
+(declare-function org-export-data-with-backend "ox" (data backend info))
+(declare-function org-export-filter-apply-functions "ox"
+ (filters value info))
+(declare-function org-export-first-sibling-p "ox" (blob info))
+(declare-function org-export-get-backend "ox" (name))
+(declare-function org-export-get-environment "ox"
+ (&optional backend subtreep ext-plist))
+(declare-function org-export-install-filters "ox" (info))
+(declare-function org-export-table-has-special-column-p "ox" (table))
+(declare-function org-export-table-row-is-special-p "ox" (table-row info))
+
+(declare-function calc-eval "calc" (str &optional separator &rest args))
+
+(defvar orgtbl-mode) ; defined below
+(defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
+(defvar constants-unit-system)
+(defvar org-export-filters-alist)
+(defvar org-table-follow-field-mode)
+(defvar sort-fold-case)
+
+(defvar orgtbl-after-send-table-hook nil
+ "Hook for functions attaching to `C-c C-c', if the table is sent.
+This can be used to add additional functionality after the table is sent
+to the receiver position, otherwise, if table is not sent, the functions
+are not run.")
+
+(defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
+
+(defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
+ "Non-nil means use the optimized table editor version for `orgtbl-mode'.
+In the optimized version, the table editor takes over all simple keys that
+normally just insert a character. In tables, the characters are inserted
+in a way to minimize disturbing the table structure (i.e. in overwrite mode
+for empty fields). Outside tables, the correct binding of the keys is
+restored.
+
+The default for this option is t if the optimized version is also used in
+Org mode. See the variable `org-enable-table-editor' for details. Changing
+this variable requires a restart of Emacs to become effective."
+ :group 'org-table
+ :type 'boolean)
+
+(defcustom orgtbl-radio-table-templates
+ '((latex-mode "% BEGIN RECEIVE ORGTBL %n
+% END RECEIVE ORGTBL %n
+\\begin{comment}
+#+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
+| | |
+\\end{comment}\n")
+ (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
+@c END RECEIVE ORGTBL %n
+@ignore
+#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
+| | |
+@end ignore\n")
+ (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
+<!-- END RECEIVE ORGTBL %n -->
+<!--
+#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
+| | |
+-->\n")
+ (org-mode "#+ BEGIN RECEIVE ORGTBL %n
+#+ END RECEIVE ORGTBL %n
+
+#+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
+| | |
+"))
+ "Templates for radio tables in different major modes.
+Each template must define lines that will be treated as a comment and that
+must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
+lines where \"%n\" will be replaced with the name of the table during
+insertion of the template. The transformed table will later be inserted
+between these lines.
+
+The template should also contain a minimal table in a multiline comment.
+If multiline comments are not possible in the buffer language,
+you can pack it into a string that will not be used when the code
+is compiled or executed. Above the table will you need a line with
+the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
+convert the table into a data structure useful in the
+language of the buffer. Check the manual for the section on
+\"Translator functions\", and more generally check out
+http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
+
+All occurrences of %n in a template will be replaced with the name of the
+table, obtained by prompting the user."
+ :group 'org-table
+ :type '(repeat
+ (list (symbol :tag "Major mode")
+ (string :tag "Format"))))
+
+(defgroup org-table-settings nil
+ "Settings for tables in Org mode."
+ :tag "Org Table Settings"
+ :group 'org-table)
+
+(defcustom org-table-default-size "5x2"
+ "The default size for newly created tables, Columns x Rows."
+ :group 'org-table-settings
+ :type 'string)
+
+(defcustom org-table-number-regexp
+ "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
+ "Regular expression for recognizing numbers in table columns.
+If a table column contains mostly numbers, it will be aligned to the
+right. If not, it will be aligned to the left.
+
+The default value of this option is a regular expression which allows
+anything which looks remotely like a number as used in scientific
+context. For example, all of the following will be considered a
+number:
+ 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
+
+Other options offered by the customize interface are more restrictive."
+ :group 'org-table-settings
+ :type '(choice
+ (const :tag "Positive Integers"
+ "^[0-9]+$")
+ (const :tag "Integers"
+ "^[-+]?[0-9]+$")
+ (const :tag "Floating Point Numbers"
+ "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
+ (const :tag "Floating Point Number or Integer"
+ "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
+ (const :tag "Exponential, Floating point, Integer"
+ "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
+ (const :tag "Very General Number-Like, including hex and Calc radix"
+ "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
+ (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
+ "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
+ (string :tag "Regexp:")))
+
+(defcustom org-table-number-fraction 0.5
+ "Fraction of numbers in a column required to make the column align right.
+In a column all non-white fields are considered. If at least
+this fraction of fields is matched by `org-table-number-regexp',
+alignment to the right border applies."
+ :group 'org-table-settings
+ :type 'number)
+
+(defgroup org-table-editing nil
+ "Behavior of tables during editing in Org mode."
+ :tag "Org Table Editing"
+ :group 'org-table)
+
+(defcustom org-table-automatic-realign t
+ "Non-nil means automatically re-align table when pressing TAB or RETURN.
+When nil, aligning is only done with `\\[org-table-align]', or after column
+removal/insertion."
+ :group 'org-table-editing
+ :type 'boolean)
+
+(defcustom org-table-auto-blank-field t
+ "Non-nil means automatically blank table field when starting to type into it.
+This only happens when typing immediately after a field motion
+command (TAB, S-TAB or RET).
+Only relevant when `org-enable-table-editor' is equal to `optimized'."
+ :group 'org-table-editing
+ :type 'boolean)
+
+(defcustom org-table-exit-follow-field-mode-when-leaving-table t
+ "Non-nil means automatically exit the follow mode.
+When nil, the follow mode will stay on and be active in any table
+the cursor enters. Since the table follow filed mode messes with the
+window configuration, it is not recommended to set this variable to nil,
+except maybe locally in a special file that has mostly tables with long
+fields."
+ :group 'org-table
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-table-fix-formulas-confirm nil
+ "Whether the user should confirm when Org fixes formulas."
+ :group 'org-table-editing
+ :version "24.1"
+ :type '(choice
+ (const :tag "with yes-or-no" yes-or-no-p)
+ (const :tag "with y-or-n" y-or-n-p)
+ (const :tag "no confirmation" nil)))
+(put 'org-table-fix-formulas-confirm
+ 'safe-local-variable
+ #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
+
+(defcustom org-table-tab-jumps-over-hlines t
+ "Non-nil means tab in the last column of a table with jump over a hline.
+If a horizontal separator line is following the current line,
+`org-table-next-field' can either create a new row before that line, or jump
+over the line. When this option is nil, a new line will be created before
+this line."
+ :group 'org-table-editing
+ :type 'boolean)
+
+(defgroup org-table-calculation nil
+ "Options concerning tables in Org mode."
+ :tag "Org Table Calculation"
+ :group 'org-table)
+
+(defcustom org-table-use-standard-references 'from
+ "Non-nil means using table references like B3 instead of @3$2.
+Possible values are:
+nil never use them
+from accept as input, do not present for editing
+t accept as input and present for editing"
+ :group 'org-table-calculation
+ :type '(choice
+ (const :tag "Never, don't even check user input for them" nil)
+ (const :tag "Always, both as user input, and when editing" t)
+ (const :tag "Convert user input, don't offer during editing" from)))
+
+(defcustom org-table-copy-increment t
+ "Non-nil means increment when copying current field with \
+`\\[org-table-copy-down]'."
+ :group 'org-table-calculation
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "Use the difference between the current and the above fields" t)
+ (integer :tag "Use a number" 1)
+ (const :tag "Don't increment the value when copying a field" nil)))
+
+(defcustom org-calc-default-modes
+ '(calc-internal-prec 12
+ calc-float-format (float 8)
+ calc-angle-mode deg
+ calc-prefer-frac nil
+ calc-symbolic-mode nil
+ calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
+ calc-display-working-message t
+ )
+ "List with Calc mode settings for use in `calc-eval' for table formulas.
+The list must contain alternating symbols (Calc modes variables and values).
+Don't remove any of the default settings, just change the values. Org mode
+relies on the variables to be present in the list."
+ :group 'org-table-calculation
+ :type 'plist)
+
+(defcustom org-table-duration-custom-format 'hours
+ "Format for the output of calc computations like $1+$2;t.
+The default value is `hours', and will output the results as a
+number of hours. Other allowed values are `seconds', `minutes' and
+`days', and the output will be a fraction of seconds, minutes or
+days."
+ :group 'org-table-calculation
+ :version "24.1"
+ :type '(choice (symbol :tag "Seconds" 'seconds)
+ (symbol :tag "Minutes" 'minutes)
+ (symbol :tag "Hours " 'hours)
+ (symbol :tag "Days " 'days)))
+
+(defcustom org-table-formula-field-format "%s"
+ "Format for fields which contain the result of a formula.
+For example, using \"~%s~\" will display the result within tilde
+characters. Beware that modifying the display can prevent the
+field from being used in another formula."
+ :group 'org-table-settings
+ :version "24.1"
+ :type 'string)
+
+(defcustom org-table-formula-evaluate-inline t
+ "Non-nil means TAB and RET evaluate a formula in current table field.
+If the current field starts with an equal sign, it is assumed to be a formula
+which should be evaluated as described in the manual and in the documentation
+string of the command `org-table-eval-formula'. This feature requires the
+Emacs calc package.
+When this variable is nil, formula calculation is only available through
+the command `\\[org-table-eval-formula]'."
+ :group 'org-table-calculation
+ :type 'boolean)
+
+(defcustom org-table-formula-use-constants t
+ "Non-nil means interpret constants in formulas in tables.
+A constant looks like `$c' or `$Grav' and will be replaced before evaluation
+by the value given in `org-table-formula-constants', or by a value obtained
+from the `constants.el' package."
+ :group 'org-table-calculation
+ :type 'boolean)
+
+(defcustom org-table-formula-constants nil
+ "Alist with constant names and values, for use in table formulas.
+The car of each element is a name of a constant, without the `$' before it.
+The cdr is the value as a string. For example, if you'd like to use the
+speed of light in a formula, you would configure
+
+ (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
+
+and then use it in an equation like `$1*$c'.
+
+Constants can also be defined on a per-file basis using a line like
+
+#+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
+ :group 'org-table-calculation
+ :type '(repeat
+ (cons (string :tag "name")
+ (string :tag "value"))))
+
+(defcustom org-table-allow-automatic-line-recalculation t
+ "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
+\\<org-mode-map>\
+Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
+are pressed in the line."
+ :group 'org-table-calculation
+ :type 'boolean)
+
+(defcustom org-table-relative-ref-may-cross-hline t
+ "Non-nil means relative formula references may cross hlines.
+Here are the allowed values:
+
+nil Relative references may not cross hlines. They will reference the
+ field next to the hline instead. Coming from below, the reference
+ will be to the field below the hline. Coming from above, it will be
+ to the field above.
+t Relative references may cross hlines.
+error An attempt to cross a hline will throw an error.
+
+It is probably good to never set this variable to nil, for the sake of
+portability of tables."
+ :group 'org-table-calculation
+ :type '(choice
+ (const :tag "Allow to cross" t)
+ (const :tag "Stick to hline" nil)
+ (const :tag "Error on attempt to cross" error)))
+
+(defcustom org-table-formula-create-columns nil
+ "Non-nil means that evaluation of a field formula can add new
+columns if an out-of-bounds field is being set."
+ :group 'org-table-calculation
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
+ (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
+ (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
+ (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
+
+(defgroup org-table-import-export nil
+ "Options concerning table import and export in Org mode."
+ :tag "Org Table Import Export"
+ :group 'org-table)
+
+(defcustom org-table-export-default-format "orgtbl-to-tsv"
+ "Default export parameters for `org-table-export'.
+These can be overridden for a specific table by setting the
+TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
+radio tables for the different export transformations and
+available parameters."
+ :group 'org-table-import-export
+ :type 'string)
+
+(defcustom org-table-convert-region-max-lines 999
+ "Max lines that `org-table-convert-region' will attempt to process.
+
+The function can be slow on larger regions; this safety feature
+prevents it from hanging emacs."
+ :group 'org-table-import-export
+ :type 'integer
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+(defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
+ "Regexp matching a line marked for automatic recalculation.")
+
+(defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
+ "Regexp matching a line marked for recalculation.")
+
+(defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
+ "Regexp matching a line marked for calculation.")
+
+(defconst org-table-border-regexp "^[ \t]*[^| \t]"
+ "Regexp matching any line outside an Org table.")
+
+(defvar org-table-last-highlighted-reference nil)
+
+(defvar org-table-formula-history nil)
+
+(defvar org-table-column-names nil
+ "Alist with column names, derived from the `!' line.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-column-name-regexp nil
+ "Regular expression matching the current column names.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-local-parameters nil
+ "Alist with parameter names, derived from the `$' line.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-named-field-locations nil
+ "Alist with locations of named fields.
+Associations follow the pattern (NAME LINE COLUMN) where
+ NAME is the name of the field as a string,
+ LINE is the number of lines from the beginning of the table,
+ COLUMN is the column of the field, as an integer.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-current-line-types nil
+ "Table row types in current table.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-current-begin-pos nil
+ "Current table begin position, as a marker.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-current-ncol nil
+ "Number of columns in current table.
+This variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-dlines nil
+ "Vector of data line line numbers in the current table.
+Line numbers are counted from the beginning of the table. This
+variable is initialized with `org-table-analyze'.")
+
+(defvar org-table-hlines nil
+ "Vector of hline line numbers in the current table.
+Line numbers are counted from the beginning of the table. This
+variable is initialized with `org-table-analyze'.")
+
+(defconst org-table-range-regexp
+ "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
+ ;; 1 2 3 4 5
+ "Regular expression for matching ranges in formulas.")
+
+(defconst org-table-range-regexp2
+ (concat
+ "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
+ "\\.\\."
+ "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
+ "Match a range for reference display.")
+
+(defconst org-table-translate-regexp
+ (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
+ "Match a reference that needs translation, for reference display.")
+
+(defmacro org-table-save-field (&rest body)
+ "Save current field; execute BODY; restore field.
+Field is restored even in case of abnormal exit."
+ (declare (debug (body)))
+ (org-with-gensyms (line column)
+ `(let ((,line (copy-marker (line-beginning-position)))
+ (,column (org-table-current-column)))
+ (unwind-protect
+ (progn ,@body)
+ (goto-char ,line)
+ (org-table-goto-column ,column)
+ (set-marker ,line nil)))))
+
+;;;###autoload
+(defun org-table-create-with-table.el ()
+ "Use the table.el package to insert a new table.
+If there is already a table at point, convert between Org tables
+and table.el tables."
+ (interactive)
+ (require 'table)
+ (cond
+ ((org-at-table.el-p)
+ (if (y-or-n-p "Convert table to Org table? ")
+ (org-table-convert)))
+ ((org-at-table-p)
+ (when (y-or-n-p "Convert table to table.el table? ")
+ (org-table-align)
+ (org-table-convert)))
+ (t (call-interactively 'table-insert))))
+
+;;;###autoload
+(defun org-table-create-or-convert-from-region (arg)
+ "Convert region to table, or create an empty table.
+If there is an active region, convert it to a table, using the function
+`org-table-convert-region'. See the documentation of that function
+to learn how the prefix argument is interpreted to determine the field
+separator.
+If there is no such region, create an empty table with `org-table-create'."
+ (interactive "P")
+ (if (org-region-active-p)
+ (org-table-convert-region (region-beginning) (region-end) arg)
+ (org-table-create arg)))
+
+;;;###autoload
+(defun org-table-create (&optional size)
+ "Query for a size and insert a table skeleton.
+SIZE is a string Columns x Rows like for example \"3x2\"."
+ (interactive "P")
+ (unless size
+ (setq size (read-string
+ (concat "Table size Columns x Rows [e.g. "
+ org-table-default-size "]: ")
+ "" nil org-table-default-size)))
+
+ (let* ((pos (point))
+ (indent (make-string (current-column) ?\ ))
+ (split (org-split-string size " *x *"))
+ (rows (string-to-number (nth 1 split)))
+ (columns (string-to-number (car split)))
+ (line (concat (apply 'concat indent "|" (make-list columns " |"))
+ "\n")))
+ (if (string-match "^[ \t]*$" (buffer-substring-no-properties
+ (point-at-bol) (point)))
+ (beginning-of-line 1)
+ (newline))
+ ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
+ (dotimes (_ rows) (insert line))
+ (goto-char pos)
+ (if (> rows 1)
+ ;; Insert a hline after the first row.
+ (progn
+ (end-of-line 1)
+ (insert "\n|-")
+ (goto-char pos)))
+ (org-table-align)))
+
+;;;###autoload
+(defun org-table-convert-region (beg0 end0 &optional separator)
+ "Convert region to a table.
+
+The region goes from BEG0 to END0, but these borders will be moved
+slightly, to make sure a beginning of line in the first line is included.
+
+SEPARATOR specifies the field separator in the lines. It can have the
+following values:
+
+(4) Use the comma as a field separator
+(16) Use a TAB as field separator
+(64) Prompt for a regular expression as field separator
+integer When a number, use that many spaces, or a TAB, as field separator
+regexp When a regular expression, use it to match the separator
+nil When nil, the command tries to be smart and figure out the
+ separator in the following way:
+ - when each line contains a TAB, assume TAB-separated material
+ - when each line contains a comma, assume CSV material
+ - else, assume one or more SPACE characters as separator."
+ (interactive "r\nP")
+ (let* ((beg (min beg0 end0))
+ (end (max beg0 end0))
+ re)
+ (if (> (count-lines beg end) org-table-convert-region-max-lines)
+ (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
+ org-table-convert-region-max-lines)
+ (if (equal separator '(64))
+ (setq separator (read-regexp "Regexp for field separator")))
+ (goto-char beg)
+ (beginning-of-line 1)
+ (setq beg (point-marker))
+ (goto-char end)
+ (if (bolp) (backward-char 1) (end-of-line 1))
+ (setq end (point-marker))
+ ;; Get the right field separator
+ (unless separator
+ (goto-char beg)
+ (setq separator
+ (cond
+ ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
+ ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
+ (t 1))))
+ (goto-char beg)
+ (if (equal separator '(4))
+ (while (< (point) end)
+ ;; parse the csv stuff
+ (cond
+ ((looking-at "^") (insert "| "))
+ ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
+ ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
+ (replace-match "\\1")
+ (if (looking-at "\"") (insert "\"")))
+ ((looking-at "[^,\n]+") (goto-char (match-end 0)))
+ ((looking-at "[ \t]*,") (replace-match " | "))
+ (t (beginning-of-line 2))))
+ (setq re (cond
+ ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
+ ((equal separator '(16)) "^\\|\t")
+ ((integerp separator)
+ (if (< separator 1)
+ (user-error "Number of spaces in separator must be >= 1")
+ (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
+ ((stringp separator)
+ (format "^ *\\|%s" separator))
+ (t (error "This should not happen"))))
+ (while (re-search-forward re end t)
+ (replace-match "| " t t)))
+ (goto-char beg)
+ (org-table-align))))
+
+;;;###autoload
+(defun org-table-import (file arg)
+ "Import FILE as a table.
+The file is assumed to be tab-separated. Such files can be produced by most
+spreadsheet and database applications. If no tabs (at least one per line)
+are found, lines will be split on whitespace into fields."
+ (interactive "f\nP")
+ (or (bolp) (newline))
+ (let ((beg (point))
+ (pm (point-max)))
+ (insert-file-contents file)
+ (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
+
+
+;;;###autoload
+(defun org-table-export (&optional file format)
+ "Export table to a file, with configurable format.
+Such a file can be imported into usual spreadsheet programs.
+
+FILE can be the output file name. If not given, it will be taken
+from a TABLE_EXPORT_FILE property in the current entry or higher
+up in the hierarchy, or the user will be prompted for a file
+name. FORMAT can be an export format, of the same kind as it
+used when `orgtbl-mode' sends a table in a different format.
+
+The command suggests a format depending on TABLE_EXPORT_FORMAT,
+whether it is set locally or up in the hierarchy, then on the
+extension of the given file name, and finally on the variable
+`org-table-export-default-format'."
+ (interactive)
+ (unless (org-at-table-p) (user-error "No table at point"))
+ (org-table-align) ; Make sure we have everything we need.
+ (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
+ (unless file
+ (setq file (read-file-name "Export table to: "))
+ (unless (or (not (file-exists-p file))
+ (y-or-n-p (format "Overwrite file %s? " file)))
+ (user-error "File not written")))
+ (when (file-directory-p file)
+ (user-error "This is a directory path, not a file"))
+ (when (and (buffer-file-name (buffer-base-buffer))
+ (file-equal-p
+ (file-truename file)
+ (file-truename (buffer-file-name (buffer-base-buffer)))))
+ (user-error "Please specify a file name that is different from current"))
+ (let ((fileext (concat (file-name-extension file) "$"))
+ (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
+ (unless format
+ (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
+ "orgtbl-to-html" "orgtbl-to-generic"
+ "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
+ "orgtbl-to-unicode"))
+ (deffmt-readable
+ (replace-regexp-in-string
+ "\t" "\\t"
+ (replace-regexp-in-string
+ "\n" "\\n"
+ (or (car (delq nil
+ (mapcar
+ (lambda (f)
+ (and (string-match-p fileext f) f))
+ formats)))
+ org-table-export-default-format)
+ t t) t t)))
+ (setq format
+ (org-completing-read
+ "Format: " formats nil nil deffmt-readable))))
+ (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
+ (let ((transform (intern (match-string 1 format)))
+ (params (and (match-end 2)
+ (read (concat "(" (match-string 2 format) ")"))))
+ (table (org-table-to-lisp
+ (buffer-substring-no-properties
+ (org-table-begin) (org-table-end)))))
+ (unless (fboundp transform)
+ (user-error "No such transformation function %s" transform))
+ (let (buf)
+ (with-current-buffer (find-file-noselect file)
+ (setq buf (current-buffer))
+ (erase-buffer)
+ (fundamental-mode)
+ (insert (funcall transform table params) "\n")
+ (save-buffer))
+ (kill-buffer buf))
+ (message "Export done."))
+ (user-error "TABLE_EXPORT_FORMAT invalid")))))
+
+(defvar org-table-aligned-begin-marker (make-marker)
+ "Marker at the beginning of the table last aligned.
+Used to check if cursor still is in that table, to minimize realignment.")
+(defvar org-table-aligned-end-marker (make-marker)
+ "Marker at the end of the table last aligned.
+Used to check if cursor still is in that table, to minimize realignment.")
+(defvar org-table-last-alignment nil
+ "List of flags for flushright alignment, from the last re-alignment.
+This is being used to correctly align a single field after TAB or RET.")
+(defvar org-table-last-column-widths nil
+ "List of max width of fields in each column.
+This is being used to correctly align a single field after TAB or RET.")
+(defvar-local org-table-formula-debug nil
+ "Non-nil means debug table formulas.
+When nil, simply write \"#ERROR\" in corrupted fields.")
+(defvar-local org-table-overlay-coordinates nil
+ "Overlay coordinates after each align of a table.")
+
+(defvar org-last-recalc-line nil)
+(defvar org-table-do-narrow t) ; for dynamic scoping
+(defconst org-narrow-column-arrow "=>"
+ "Used as display property in narrowed table columns.")
+
+;;;###autoload
+(defun org-table-align ()
+ "Align the table at point by aligning all vertical bars."
+ (interactive)
+ (let* ((beg (org-table-begin))
+ (end (copy-marker (org-table-end))))
+ (org-table-save-field
+ ;; Make sure invisible characters in the table are at the right
+ ;; place since column widths take them into account.
+ (font-lock-fontify-region beg end)
+ (move-marker org-table-aligned-begin-marker beg)
+ (move-marker org-table-aligned-end-marker end)
+ (goto-char beg)
+ (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
+ ;; Table's rows. Separators are replaced by nil. Trailing
+ ;; spaces are also removed.
+ (lines (mapcar (lambda (l)
+ (and (not (string-match-p "\\`[ \t]*|-" l))
+ (let ((l (org-trim l)))
+ (remove-text-properties
+ 0 (length l) '(display t org-cwidth t) l)
+ l)))
+ (org-split-string (buffer-substring beg end) "\n")))
+ ;; Get the data fields by splitting the lines.
+ (fields (mapcar (lambda (l) (org-split-string l " *| *"))
+ (remq nil lines)))
+ ;; Compute number of fields in the longest line. If the
+ ;; table contains no field, create a default table.
+ (maxfields (if fields (apply #'max (mapcar #'length fields))
+ (kill-region beg end)
+ (org-table-create org-table-default-size)
+ (user-error "Empty table - created default table")))
+ ;; A list of empty strings to fill any short rows on output.
+ (emptycells (make-list maxfields ""))
+ lengths typenums)
+ ;; Check for special formatting.
+ (dotimes (i maxfields)
+ (let ((column (mapcar (lambda (x) (or (nth i x) "")) fields))
+ fmax falign)
+ ;; Look for an explicit width or alignment.
+ (when (save-excursion
+ (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t)
+ (and org-table-do-narrow
+ (re-search-forward
+ "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t))))
+ (catch :exit
+ (dolist (cell column)
+ (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell)
+ (when (match-end 1) (setq falign (match-string 1 cell)))
+ (when (and org-table-do-narrow (match-end 2))
+ (setq fmax (string-to-number (match-string 2 cell))))
+ (when (or falign fmax) (throw :exit nil)))))
+ ;; Find fields that are wider than FMAX, and shorten them.
+ (when fmax
+ (dolist (x column)
+ (when (> (org-string-width x) fmax)
+ (org-add-props x nil
+ 'help-echo
+ (concat
+ "Clipped table field, use `\\[org-table-edit-field]' to \
+edit. Full value is:\n"
+ (substring-no-properties x)))
+ (let ((l (length x))
+ (f1 (min fmax
+ (or (string-match org-bracket-link-regexp x)
+ fmax)))
+ (f2 1))
+ (unless (> f1 1)
+ (user-error
+ "Cannot narrow field starting with wide link \"%s\""
+ (match-string 0 x)))
+ (if (= (org-string-width x) l) (setq f2 f1)
+ (setq f2 1)
+ (while (< (org-string-width (substring x 0 f2)) f1)
+ (cl-incf f2)))
+ (add-text-properties f2 l (list 'org-cwidth t) x)
+ (add-text-properties
+ (if (>= (string-width (substring x (1- f2) f2)) 2) (1- f2)
+ (- f2 2))
+ f2
+ (list 'display org-narrow-column-arrow)
+ x))))))
+ ;; Get the maximum width for each column
+ (push (apply #'max (or fmax 1) 1 (mapcar #'org-string-width column))
+ lengths)
+ ;; Get the fraction of numbers among non-empty cells to
+ ;; decide about alignment of the column.
+ (if falign (push (equal (downcase falign) "r") typenums)
+ (let ((cnt 0)
+ (frac 0.0))
+ (dolist (x column)
+ (unless (equal x "")
+ (setq frac
+ (/ (+ (* frac cnt)
+ (if (string-match-p org-table-number-regexp x)
+ 1
+ 0))
+ (cl-incf cnt)))))
+ (push (>= frac org-table-number-fraction) typenums)))))
+ (setq lengths (nreverse lengths))
+ (setq typenums (nreverse typenums))
+ ;; Store alignment of this table, for later editing of single
+ ;; fields.
+ (setq org-table-last-alignment typenums)
+ (setq org-table-last-column-widths lengths)
+ ;; With invisible characters, `format' does not get the field
+ ;; width right So we need to make these fields wide by hand.
+ ;; Invisible characters may be introduced by fontified links,
+ ;; emphasis, macros or sub/superscripts.
+ (when (or (text-property-any beg end 'invisible 'org-link)
+ (text-property-any beg end 'invisible t))
+ (dotimes (i maxfields)
+ (let ((len (nth i lengths)))
+ (dotimes (j (length fields))
+ (let* ((c (nthcdr i (nth j fields)))
+ (cell (car c)))
+ (when (and
+ (stringp cell)
+ (let ((l (length cell)))
+ (or (text-property-any 0 l 'invisible 'org-link cell)
+ (text-property-any beg end 'invisible t)))
+ (< (org-string-width cell) len))
+ (let ((s (make-string (- len (org-string-width cell)) ?\s)))
+ (setcar c (if (nth i typenums) (concat s cell)
+ (concat cell s))))))))))
+
+ ;; Compute the formats needed for output of the table.
+ (let ((hfmt (concat indent "|"))
+ (rfmt (concat indent "|"))
+ (rfmt1 " %%%s%ds |")
+ (hfmt1 "-%s-+"))
+ (dolist (l lengths (setq hfmt (concat (substring hfmt 0 -1) "|")))
+ (let ((ty (if (pop typenums) "" "-"))) ; Flush numbers right.
+ (setq rfmt (concat rfmt (format rfmt1 ty l)))
+ (setq hfmt (concat hfmt (format hfmt1 (make-string l ?-))))))
+ ;; Replace modified lines only. Check not only contents, but
+ ;; also columns' width.
+ (dolist (l lines)
+ (let ((line
+ (if l (apply #'format rfmt (append (pop fields) emptycells))
+ hfmt))
+ (previous (buffer-substring (point) (line-end-position))))
+ (if (and (equal previous line)
+ (let ((a 0)
+ (b 0))
+ (while (and (progn
+ (setq a (next-single-property-change
+ a 'org-cwidth previous))
+ (setq b (next-single-property-change
+ b 'org-cwidth line)))
+ (eq a b)))
+ (eq a b)))
+ (forward-line)
+ (insert line "\n")
+ (delete-region (point) (line-beginning-position 2))))))
+ (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
+ (goto-char org-table-aligned-begin-marker)
+ (while (org-hide-wide-columns org-table-aligned-end-marker)))
+ (set-marker end nil)
+ (when org-table-overlay-coordinates (org-table-overlay-coordinates))
+ (setq org-table-may-need-update nil)))))
+
+;;;###autoload
+(defun org-table-begin (&optional table-type)
+ "Find the beginning of the table and return its position.
+With a non-nil optional argument TABLE-TYPE, return the beginning
+of a table.el-type table. This function assumes point is on
+a table."
+ (cond (table-type
+ (org-element-property :post-affiliated (org-element-at-point)))
+ ((save-excursion
+ (and (re-search-backward org-table-border-regexp nil t)
+ (line-beginning-position 2))))
+ (t (point-min))))
+
+;;;###autoload
+(defun org-table-end (&optional table-type)
+ "Find the end of the table and return its position.
+With a non-nil optional argument TABLE-TYPE, return the end of
+a table.el-type table. This function assumes point is on
+a table."
+ (save-excursion
+ (cond (table-type
+ (goto-char (org-element-property :end (org-element-at-point)))
+ (skip-chars-backward " \t\n")
+ (line-beginning-position 2))
+ ((re-search-forward org-table-border-regexp nil t)
+ (match-beginning 0))
+ ;; When the line right after the table is the last line in
+ ;; the buffer with trailing spaces but no final newline
+ ;; character, be sure to catch the correct ending at its
+ ;; beginning. In any other case, ending is expected to be
+ ;; at point max.
+ (t (goto-char (point-max))
+ (skip-chars-backward " \t")
+ (if (bolp) (point) (line-end-position))))))
+
+;;;###autoload
+(defun org-table-justify-field-maybe (&optional new)
+ "Justify the current field, text to left, number to right.
+Optional argument NEW may specify text to replace the current field content."
+ (cond
+ ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
+ ((org-at-table-hline-p))
+ ((and (not new)
+ (or (not (eq (marker-buffer org-table-aligned-begin-marker)
+ (current-buffer)))
+ (< (point) org-table-aligned-begin-marker)
+ (>= (point) org-table-aligned-end-marker)))
+ ;; This is not the same table, force a full re-align.
+ (setq org-table-may-need-update t))
+ (t
+ ;; Realign the current field, based on previous full realign.
+ (let ((pos (point))
+ (col (org-table-current-column)))
+ (when (> col 0)
+ (skip-chars-backward "^|")
+ (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
+ (setq org-table-may-need-update t)
+ (let* ((numbers? (nth (1- col) org-table-last-alignment))
+ (cell (match-string 0))
+ (field (match-string 1))
+ (len (max 1 (- (org-string-width cell) 3)))
+ (properly-closed? (/= (match-beginning 2) (match-end 2)))
+ (fmt (format (if numbers? " %%%ds %s" " %%-%ds %s")
+ len
+ (if properly-closed? "|"
+ (setq org-table-may-need-update t)
+ "")))
+ (new-cell
+ (cond ((not new) (format fmt field))
+ ((<= (org-string-width new) len) (format fmt new))
+ (t
+ (setq org-table-may-need-update t)
+ (format " %s |" new)))))
+ (unless (equal new-cell cell)
+ (let (org-table-may-need-update)
+ (replace-match new-cell t t)))
+ (goto-char pos))))))))
+
+;;;###autoload
+(defun org-table-next-field ()
+ "Go to the next field in the current table, creating new lines as needed.
+Before doing so, re-align the table if necessary."
+ (interactive)
+ (org-table-maybe-eval-formula)
+ (org-table-maybe-recalculate-line)
+ (if (and org-table-automatic-realign
+ org-table-may-need-update)
+ (org-table-align))
+ (let ((end (org-table-end)))
+ (if (org-at-table-hline-p)
+ (end-of-line 1))
+ (condition-case nil
+ (progn
+ (re-search-forward "|" end)
+ (if (looking-at "[ \t]*$")
+ (re-search-forward "|" end))
+ (if (and (looking-at "-")
+ org-table-tab-jumps-over-hlines
+ (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
+ (goto-char (match-beginning 1)))
+ (if (looking-at "-")
+ (progn
+ (beginning-of-line 0)
+ (org-table-insert-row 'below))
+ (if (looking-at " ") (forward-char 1))))
+ (error
+ (org-table-insert-row 'below)))))
+
+;;;###autoload
+(defun org-table-previous-field ()
+ "Go to the previous field in the table.
+Before doing so, re-align the table if necessary."
+ (interactive)
+ (org-table-justify-field-maybe)
+ (org-table-maybe-recalculate-line)
+ (if (and org-table-automatic-realign
+ org-table-may-need-update)
+ (org-table-align))
+ (if (org-at-table-hline-p)
+ (end-of-line 1))
+ (condition-case nil
+ (progn
+ (re-search-backward "|" (org-table-begin))
+ (re-search-backward "|" (org-table-begin)))
+ (error (user-error "Cannot move to previous table field")))
+ (while (looking-at "|\\(-\\|[ \t]*$\\)")
+ (re-search-backward "|" (org-table-begin)))
+ (if (looking-at "| ?")
+ (goto-char (match-end 0))))
+
+(defun org-table-beginning-of-field (&optional n)
+ "Move to the beginning of the current table field.
+If already at or before the beginning, move to the beginning of the
+previous field.
+With numeric argument N, move N-1 fields backward first."
+ (interactive "p")
+ (let ((pos (point)))
+ (while (> n 1)
+ (setq n (1- n))
+ (org-table-previous-field))
+ (if (not (re-search-backward "|" (point-at-bol 0) t))
+ (user-error "No more table fields before the current")
+ (goto-char (match-end 0))
+ (and (looking-at " ") (forward-char 1)))
+ (if (>= (point) pos) (org-table-beginning-of-field 2))))
+
+(defun org-table-end-of-field (&optional n)
+ "Move to the end of the current table field.
+If already at or after the end, move to the end of the next table field.
+With numeric argument N, move N-1 fields forward first."
+ (interactive "p")
+ (let ((pos (point)))
+ (while (> n 1)
+ (setq n (1- n))
+ (org-table-next-field))
+ (when (re-search-forward "|" (point-at-eol 1) t)
+ (backward-char 1)
+ (skip-chars-backward " ")
+ (if (and (equal (char-before (point)) ?|) (looking-at " "))
+ (forward-char 1)))
+ (if (<= (point) pos) (org-table-end-of-field 2))))
+
+;;;###autoload
+(defun org-table-next-row ()
+ "Go to the next row (same column) in the current table.
+Before doing so, re-align the table if necessary."
+ (interactive)
+ (org-table-maybe-eval-formula)
+ (org-table-maybe-recalculate-line)
+ (if (or (looking-at "[ \t]*$")
+ (save-excursion (skip-chars-backward " \t") (bolp)))
+ (newline)
+ (if (and org-table-automatic-realign
+ org-table-may-need-update)
+ (org-table-align))
+ (let ((col (org-table-current-column)))
+ (beginning-of-line 2)
+ (if (or (not (org-at-table-p))
+ (org-at-table-hline-p))
+ (progn
+ (beginning-of-line 0)
+ (org-table-insert-row 'below)))
+ (org-table-goto-column col)
+ (skip-chars-backward "^|\n\r")
+ (if (looking-at " ") (forward-char 1)))))
+
+;;;###autoload
+(defun org-table-copy-down (n)
+ "Copy the value of the current field one row below.
+
+If the field at the cursor is empty, copy the content of the
+nearest non-empty field above. With argument N, use the Nth
+non-empty field.
+
+If the current field is not empty, it is copied down to the next
+row, and the cursor is moved with it. Therefore, repeating this
+command causes the column to be filled row-by-row.
+
+If the variable `org-table-copy-increment' is non-nil and the
+field is an integer or a timestamp, it will be incremented while
+copying. By default, increment by the difference between the
+value in the current field and the one in the field above. To
+increment using a fixed integer, set `org-table-copy-increment'
+to a number. In the case of a timestamp, increment by days."
+ (interactive "p")
+ (let* ((colpos (org-table-current-column))
+ (col (current-column))
+ (field (save-excursion (org-table-get-field)))
+ (field-up (or (save-excursion
+ (org-table-get (1- (org-table-current-line))
+ (org-table-current-column))) ""))
+ (non-empty (string-match "[^ \t]" field))
+ (non-empty-up (string-match "[^ \t]" field-up))
+ (beg (org-table-begin))
+ (orig-n n)
+ txt txt-up inc)
+ (org-table-check-inside-data-field)
+ (if (not non-empty)
+ (save-excursion
+ (setq txt
+ (catch 'exit
+ (while (progn (beginning-of-line 1)
+ (re-search-backward org-table-dataline-regexp
+ beg t))
+ (org-table-goto-column colpos t)
+ (if (and (looking-at
+ "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
+ (<= (setq n (1- n)) 0))
+ (throw 'exit (match-string 1))))))
+ (setq field-up
+ (catch 'exit
+ (while (progn (beginning-of-line 1)
+ (re-search-backward org-table-dataline-regexp
+ beg t))
+ (org-table-goto-column colpos t)
+ (if (and (looking-at
+ "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
+ (<= (setq n (1- n)) 0))
+ (throw 'exit (match-string 1))))))
+ (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
+ ;; Above field was not empty, go down to the next row
+ (setq txt (org-trim field))
+ (org-table-next-row)
+ (org-table-blank-field))
+ (if non-empty-up (setq txt-up (org-trim field-up)))
+ (setq inc (cond
+ ((numberp org-table-copy-increment) org-table-copy-increment)
+ (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
+ (string-match org-ts-regexp3 txt))
+ (- (org-time-string-to-absolute txt)
+ (org-time-string-to-absolute txt-up)))
+ ((string-match org-ts-regexp3 txt) 1)
+ ((string-match "\\([-+]\\)?[0-9]+\\(?:\.[0-9]+\\)?" txt-up)
+ (- (string-to-number txt)
+ (string-to-number (match-string 0 txt-up))))
+ (t 1)))
+ (t 1)))
+ (if (not txt)
+ (user-error "No non-empty field found")
+ (if (and org-table-copy-increment
+ (not (equal orig-n 0))
+ (string-match-p "^[-+^/*0-9eE.]+$" txt)
+ (< (string-to-number txt) 100000000))
+ (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
+ (insert txt)
+ (org-move-to-column col)
+ (if (and org-table-copy-increment (org-at-timestamp-p t))
+ (org-timestamp-up-day inc)
+ (org-table-maybe-recalculate-line))
+ (org-table-align)
+ (org-move-to-column col))))
+
+(defun org-table-check-inside-data-field (&optional noerror)
+ "Is point inside a table data field?
+I.e. not on a hline or before the first or after the last column?
+This actually throws an error, so it aborts the current command."
+ (cond ((and (org-at-table-p)
+ (not (save-excursion (skip-chars-backward " \t") (bolp)))
+ (not (org-at-table-hline-p))
+ (not (looking-at "[ \t]*$"))))
+ (noerror nil)
+ (t (user-error "Not in table data field"))))
+
+(defvar org-table-clip nil
+ "Clipboard for table regions.")
+
+(defun org-table-get (line column)
+ "Get the field in table line LINE, column COLUMN.
+If LINE is larger than the number of data lines in the table, the function
+returns nil. However, if COLUMN is too large, we will simply return an
+empty string.
+If LINE is nil, use the current line.
+If COLUMN is nil, use the current column."
+ (setq column (or column (org-table-current-column)))
+ (save-excursion
+ (and (or (not line) (org-table-goto-line line))
+ (org-trim (org-table-get-field column)))))
+
+(defun org-table-put (line column value &optional align)
+ "Put VALUE into line LINE, column COLUMN.
+When ALIGN is set, also realign the table."
+ (setq column (or column (org-table-current-column)))
+ (prog1 (save-excursion
+ (and (or (not line) (org-table-goto-line line))
+ (progn (org-table-goto-column column nil 'force) t)
+ (org-table-get-field column value)))
+ (and align (org-table-align))))
+
+(defun org-table-current-line ()
+ "Return the index of the current data line."
+ (let ((pos (point)) (end (org-table-end)) (cnt 0))
+ (save-excursion
+ (goto-char (org-table-begin))
+ (while (and (re-search-forward org-table-dataline-regexp end t)
+ (setq cnt (1+ cnt))
+ (< (point-at-eol) pos))))
+ cnt))
+
+(defun org-table-goto-line (N)
+ "Go to the Nth data line in the current table.
+Return t when the line exists, nil if it does not exist."
+ (goto-char (org-table-begin))
+ (let ((end (org-table-end)) (cnt 0))
+ (while (and (re-search-forward org-table-dataline-regexp end t)
+ (< (setq cnt (1+ cnt)) N)))
+ (= cnt N)))
+
+;;;###autoload
+(defun org-table-blank-field ()
+ "Blank the current table field or active region."
+ (interactive)
+ (org-table-check-inside-data-field)
+ (if (and (called-interactively-p 'any) (org-region-active-p))
+ (let (org-table-clip)
+ (org-table-cut-region (region-beginning) (region-end)))
+ (skip-chars-backward "^|")
+ (backward-char 1)
+ (if (looking-at "|[^|\n]+")
+ (let* ((pos (match-beginning 0))
+ (match (match-string 0))
+ (len (org-string-width match)))
+ (replace-match (concat "|" (make-string (1- len) ?\ )))
+ (goto-char (+ 2 pos))
+ (substring match 1)))))
+
+(defun org-table-get-field (&optional n replace)
+ "Return the value of the field in column N of current row.
+N defaults to current column. If REPLACE is a string, replace
+field with this value. The return value is always the old
+value."
+ (when n (org-table-goto-column n))
+ (skip-chars-backward "^|\n")
+ (if (or (bolp) (looking-at-p "[ \t]*$"))
+ ;; Before first column or after last one.
+ ""
+ (looking-at "[^|\r\n]*")
+ (let* ((pos (match-beginning 0))
+ (val (buffer-substring pos (match-end 0))))
+ (when replace
+ (replace-match (if (equal replace "") " " replace) t t))
+ (goto-char (min (line-end-position) (1+ pos)))
+ val)))
+
+;;;###autoload
+(defun org-table-field-info (_arg)
+ "Show info about the current field, and highlight any reference at point."
+ (interactive "P")
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (org-table-analyze)
+ (save-excursion
+ (let* ((pos (point))
+ (col (org-table-current-column))
+ (cname (car (rassoc (int-to-string col) org-table-column-names)))
+ (name (car (rassoc (list (count-lines org-table-current-begin-pos
+ (line-beginning-position))
+ col)
+ org-table-named-field-locations)))
+ (eql (org-table-expand-lhs-ranges
+ (mapcar
+ (lambda (e)
+ (cons (org-table-formula-handle-first/last-rc (car e))
+ (cdr e)))
+ (org-table-get-stored-formulas))))
+ (dline (org-table-current-dline))
+ (ref (format "@%d$%d" dline col))
+ (ref1 (org-table-convert-refs-to-an ref))
+ ;; Prioritize field formulas over column formulas.
+ (fequation (or (assoc name eql) (assoc ref eql)))
+ (cequation (assoc (format "$%d" col) eql))
+ (eqn (or fequation cequation)))
+ (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
+ (when p (setq eqn p)))
+ (goto-char pos)
+ (ignore-errors (org-table-show-reference 'local))
+ (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
+ dline col
+ (if cname (concat " or $" cname) "")
+ dline col ref1
+ (if name (concat " or $" name) "")
+ ;; FIXME: formula info not correct if special table line
+ (if eqn
+ (concat ", formula: "
+ (org-table-formula-to-user
+ (concat
+ (if (or (string-prefix-p "$" (car eqn))
+ (string-prefix-p "@" (car eqn)))
+ ""
+ "$")
+ (car eqn) "=" (cdr eqn))))
+ "")))))
+
+(defun org-table-current-column ()
+ "Find out which column we are in."
+ (interactive)
+ (when (called-interactively-p 'any) (org-table-check-inside-data-field))
+ (save-excursion
+ (let ((column 0) (pos (point)))
+ (beginning-of-line)
+ (while (search-forward "|" pos t) (cl-incf column))
+ (when (called-interactively-p 'interactive)
+ (message "In table column %d" column))
+ column)))
+
+;;;###autoload
+(defun org-table-current-dline ()
+ "Find out what table data line we are in.
+Only data lines count for this."
+ (interactive)
+ (when (called-interactively-p 'any)
+ (org-table-check-inside-data-field))
+ (save-excursion
+ (let ((c 0)
+ (pos (point)))
+ (goto-char (org-table-begin))
+ (while (<= (point) pos)
+ (when (looking-at org-table-dataline-regexp) (cl-incf c))
+ (forward-line))
+ (when (called-interactively-p 'any)
+ (message "This is table line %d" c))
+ c)))
+
+;;;###autoload
+(defun org-table-goto-column (n &optional on-delim force)
+ "Move the cursor to the Nth column in the current table line.
+With optional argument ON-DELIM, stop with point before the left delimiter
+of the field.
+If there are less than N fields, just go to after the last delimiter.
+However, when FORCE is non-nil, create new columns if necessary."
+ (interactive "p")
+ (beginning-of-line 1)
+ (when (> n 0)
+ (while (and (> (setq n (1- n)) -1)
+ (or (search-forward "|" (point-at-eol) t)
+ (and force
+ (progn (end-of-line 1)
+ (skip-chars-backward "^|")
+ (insert " | ")
+ t)))))
+ (when (and force (not (looking-at ".*|")))
+ (save-excursion (end-of-line 1) (insert " | ")))
+ (if on-delim
+ (backward-char 1)
+ (if (looking-at " ") (forward-char 1)))))
+
+;;;###autoload
+(defun org-table-insert-column ()
+ "Insert a new column into the table."
+ (interactive)
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (org-table-find-dataline)
+ (let* ((col (max 1 (org-table-current-column)))
+ (beg (org-table-begin))
+ (end (copy-marker (org-table-end))))
+ (org-table-save-field
+ (goto-char beg)
+ (while (< (point) end)
+ (unless (org-at-table-hline-p)
+ (org-table-goto-column col t)
+ (insert "| "))
+ (forward-line)))
+ (set-marker end nil)
+ (org-table-align)
+ (when (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm "Fix formulas? "))
+ (org-table-fix-formulas "$" nil (1- col) 1)
+ (org-table-fix-formulas "$LR" nil (1- col) 1))))
+
+(defun org-table-find-dataline ()
+ "Find a data line in the current table, which is needed for column commands."
+ (if (and (org-at-table-p)
+ (not (org-at-table-hline-p)))
+ t
+ (let ((col (current-column))
+ (end (org-table-end)))
+ (org-move-to-column col)
+ (while (and (< (point) end)
+ (or (not (= (current-column) col))
+ (org-at-table-hline-p)))
+ (beginning-of-line 2)
+ (org-move-to-column col))
+ (if (and (org-at-table-p)
+ (not (org-at-table-hline-p)))
+ t
+ (user-error
+ "Please position cursor in a data line for column operations")))))
+
+(defun org-table-line-to-dline (line &optional above)
+ "Turn a buffer line number into a data line number.
+
+If there is no data line in this line, return nil.
+
+If there is no matching dline (most likely the reference was
+a hline), the first dline below it is used. When ABOVE is
+non-nil, the one above is used."
+ (let ((min 1)
+ (max (1- (length org-table-dlines))))
+ (cond ((or (> (aref org-table-dlines min) line)
+ (< (aref org-table-dlines max) line))
+ nil)
+ ((= (aref org-table-dlines max) line) max)
+ (t (catch 'exit
+ (while (> (- max min) 1)
+ (let* ((mean (/ (+ max min) 2))
+ (v (aref org-table-dlines mean)))
+ (cond ((= v line) (throw 'exit mean))
+ ((> v line) (setq max mean))
+ (t (setq min mean)))))
+ (if above min max))))))
+
+;;;###autoload
+(defun org-table-delete-column ()
+ "Delete a column from the table."
+ (interactive)
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (org-table-find-dataline)
+ (org-table-check-inside-data-field)
+ (let ((col (org-table-current-column))
+ (beg (org-table-begin))
+ (end (copy-marker (org-table-end))))
+ (org-table-save-field
+ (goto-char beg)
+ (while (< (point) end)
+ (if (org-at-table-hline-p)
+ nil
+ (org-table-goto-column col t)
+ (and (looking-at "|[^|\n]+|")
+ (replace-match "|")))
+ (forward-line)))
+ (set-marker end nil)
+ (org-table-goto-column (max 1 (1- col)))
+ (org-table-align)
+ (when (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm "Fix formulas? "))
+ (org-table-fix-formulas
+ "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
+ (org-table-fix-formulas
+ "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
+
+;;;###autoload
+(defun org-table-move-column-right ()
+ "Move column to the right."
+ (interactive)
+ (org-table-move-column nil))
+;;;###autoload
+(defun org-table-move-column-left ()
+ "Move column to the left."
+ (interactive)
+ (org-table-move-column 'left))
+
+;;;###autoload
+(defun org-table-move-column (&optional left)
+ "Move the current column to the right. With arg LEFT, move to the left."
+ (interactive "P")
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (org-table-find-dataline)
+ (org-table-check-inside-data-field)
+ (let* ((col (org-table-current-column))
+ (col1 (if left (1- col) col))
+ (colpos (if left (1- col) (1+ col)))
+ (beg (org-table-begin))
+ (end (copy-marker (org-table-end))))
+ (when (and left (= col 1))
+ (user-error "Cannot move column further left"))
+ (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
+ (user-error "Cannot move column further right"))
+ (org-table-save-field
+ (goto-char beg)
+ (while (< (point) end)
+ (unless (org-at-table-hline-p)
+ (org-table-goto-column col1 t)
+ (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
+ (transpose-regions
+ (match-beginning 1) (match-end 1)
+ (match-beginning 2) (match-end 2))))
+ (forward-line)))
+ (set-marker end nil)
+ (org-table-goto-column colpos)
+ (org-table-align)
+ (when (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm "Fix formulas? "))
+ (org-table-fix-formulas
+ "$" (list (cons (number-to-string col) (number-to-string colpos))
+ (cons (number-to-string colpos) (number-to-string col))))
+ (org-table-fix-formulas
+ "$LR" (list (cons (number-to-string col) (number-to-string colpos))
+ (cons (number-to-string colpos) (number-to-string col)))))))
+
+;;;###autoload
+(defun org-table-move-row-down ()
+ "Move table row down."
+ (interactive)
+ (org-table-move-row nil))
+;;;###autoload
+(defun org-table-move-row-up ()
+ "Move table row up."
+ (interactive)
+ (org-table-move-row 'up))
+
+;;;###autoload
+(defun org-table-move-row (&optional up)
+ "Move the current table line down. With arg UP, move it up."
+ (interactive "P")
+ (let* ((col (current-column))
+ (pos (point))
+ (hline1p (save-excursion (beginning-of-line 1)
+ (looking-at org-table-hline-regexp)))
+ (dline1 (org-table-current-dline))
+ (dline2 (+ dline1 (if up -1 1)))
+ (tonew (if up 0 2))
+ txt hline2p)
+ (beginning-of-line tonew)
+ (unless (org-at-table-p)
+ (goto-char pos)
+ (user-error "Cannot move row further"))
+ (setq hline2p (looking-at org-table-hline-regexp))
+ (goto-char pos)
+ (beginning-of-line 1)
+ (setq pos (point))
+ (setq txt (buffer-substring (point) (1+ (point-at-eol))))
+ (delete-region (point) (1+ (point-at-eol)))
+ (beginning-of-line tonew)
+ (insert txt)
+ (beginning-of-line 0)
+ (org-move-to-column col)
+ (unless (or hline1p hline2p
+ (not (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm
+ "Fix formulas? "))))
+ (org-table-fix-formulas
+ "@" (list (cons (number-to-string dline1) (number-to-string dline2))
+ (cons (number-to-string dline2) (number-to-string dline1)))))))
+
+;;;###autoload
+(defun org-table-insert-row (&optional arg)
+ "Insert a new row above the current line into the table.
+With prefix ARG, insert below the current line."
+ (interactive "P")
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
+ (new (org-table-clean-line line)))
+ ;; Fix the first field if necessary
+ (if (string-match "^[ \t]*| *[#$] *|" line)
+ (setq new (replace-match (match-string 0 line) t t new)))
+ (beginning-of-line (if arg 2 1))
+ ;; Buffer may not end of a newline character, so ensure
+ ;; (beginning-of-line 2) moves point to a new line.
+ (unless (bolp) (insert "\n"))
+ (let (org-table-may-need-update) (insert-before-markers new "\n"))
+ (beginning-of-line 0)
+ (re-search-forward "| ?" (line-end-position) t)
+ (when (or org-table-may-need-update org-table-overlay-coordinates)
+ (org-table-align))
+ (when (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm "Fix formulas? "))
+ (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
+
+;;;###autoload
+(defun org-table-insert-hline (&optional above)
+ "Insert a horizontal-line below the current line into the table.
+With prefix ABOVE, insert above the current line."
+ (interactive "P")
+ (if (not (org-at-table-p))
+ (user-error "Not at a table"))
+ (when (eobp) (insert "\n") (backward-char 1))
+ (if (not (string-match-p "|[ \t]*$" (org-current-line-string)))
+ (org-table-align))
+ (let ((line (org-table-clean-line
+ (buffer-substring (point-at-bol) (point-at-eol))))
+ (col (current-column)))
+ (while (string-match "|\\( +\\)|" line)
+ (setq line (replace-match
+ (concat "+" (make-string (- (match-end 1) (match-beginning 1))
+ ?-) "|") t t line)))
+ (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
+ (beginning-of-line (if above 1 2))
+ (insert line "\n")
+ (beginning-of-line (if above 1 -1))
+ (org-move-to-column col)
+ (and org-table-overlay-coordinates (org-table-align))))
+
+;;;###autoload
+(defun org-table-hline-and-move (&optional same-column)
+ "Insert a hline and move to the row below that line."
+ (interactive "P")
+ (let ((col (org-table-current-column)))
+ (org-table-maybe-eval-formula)
+ (org-table-maybe-recalculate-line)
+ (org-table-insert-hline)
+ (end-of-line 2)
+ (if (looking-at "\n[ \t]*|-")
+ (progn (insert "\n|") (org-table-align))
+ (org-table-next-field))
+ (if same-column (org-table-goto-column col))))
+
+(defun org-table-clean-line (s)
+ "Convert a table line S into a string with only \"|\" and space.
+In particular, this does handle wide and invisible characters."
+ (if (string-match "^[ \t]*|-" s)
+ ;; It's a hline, just map the characters
+ (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
+ (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
+ (setq s (replace-match
+ (concat "|" (make-string (org-string-width (match-string 1 s))
+ ?\ ) "|")
+ t t s)))
+ s))
+
+;;;###autoload
+(defun org-table-kill-row ()
+ "Delete the current row or horizontal line from the table."
+ (interactive)
+ (if (not (org-at-table-p))
+ (user-error "Not at a table"))
+ (let ((col (current-column))
+ (dline (org-table-current-dline)))
+ (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
+ (if (not (org-at-table-p)) (beginning-of-line 0))
+ (org-move-to-column col)
+ (when (or (not org-table-fix-formulas-confirm)
+ (funcall org-table-fix-formulas-confirm "Fix formulas? "))
+ (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
+ dline -1 dline))))
+
+;;;###autoload
+(defun org-table-sort-lines
+ (&optional with-case sorting-type getkey-func compare-func interactive?)
+ "Sort table lines according to the column at point.
+
+The position of point indicates the column to be used for
+sorting, and the range of lines is the range between the nearest
+horizontal separator lines, or the entire table of no such lines
+exist. If point is before the first column, you will be prompted
+for the sorting column. If there is an active region, the mark
+specifies the first line and the sorting column, while point
+should be in the last line to be included into the sorting.
+
+The command then prompts for the sorting type which can be
+alphabetically, numerically, or by time (as given in a time stamp
+in the field, or as a HH:MM value). Sorting in reverse order is
+also possible.
+
+With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
+
+If SORTING-TYPE is specified when this function is called from a Lisp
+program, no prompting will take place. SORTING-TYPE must be a character,
+any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
+sorting should be done in reverse order.
+
+If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
+a function to be called to extract the key. It must return a value
+that is compatible with COMPARE-FUNC, the function used to compare
+entries.
+
+A non-nil value for INTERACTIVE? is used to signal that this
+function is being called interactively."
+ (interactive (list current-prefix-arg nil nil nil t))
+ (when (org-region-active-p) (goto-char (region-beginning)))
+ ;; Point must be either within a field or before a data line.
+ (save-excursion
+ (skip-chars-backward " \t")
+ (when (bolp) (search-forward "|" (line-end-position) t))
+ (org-table-check-inside-data-field))
+ ;; Set appropriate case sensitivity and column used for sorting.
+ (let ((column (let ((c (org-table-current-column)))
+ (cond ((> c 0) c)
+ (interactive?
+ (read-number "Use column N for sorting: "))
+ (t 1))))
+ (sorting-type
+ (or sorting-type
+ (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
+\[t]ime, [f]unc. A/N/T/F means reversed: "))))
+ (save-restriction
+ ;; Narrow buffer to appropriate sorting area.
+ (if (org-region-active-p)
+ (progn (goto-char (region-beginning))
+ (narrow-to-region
+ (point)
+ (save-excursion (goto-char (region-end))
+ (line-beginning-position 2))))
+ (let ((start (org-table-begin))
+ (end (org-table-end)))
+ (narrow-to-region
+ (save-excursion
+ (if (re-search-backward org-table-hline-regexp start t)
+ (line-beginning-position 2)
+ start))
+ (if (save-excursion (re-search-forward org-table-hline-regexp end t))
+ (match-beginning 0)
+ end))))
+ ;; Determine arguments for `sort-subr'. Also record original
+ ;; position. `org-table-save-field' cannot help here since
+ ;; sorting is too much destructive.
+ (let* ((sort-fold-case (not with-case))
+ (coordinates
+ (cons (count-lines (point-min) (line-beginning-position))
+ (current-column)))
+ (extract-key-from-field
+ ;; Function to be called on the contents of the field
+ ;; used for sorting in the current row.
+ (cl-case sorting-type
+ ((?n ?N) #'string-to-number)
+ ((?a ?A) #'org-sort-remove-invisible)
+ ((?t ?T)
+ (lambda (f)
+ (cond ((string-match org-ts-regexp-both f)
+ (float-time
+ (org-time-string-to-time (match-string 0 f))))
+ ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" f)
+ (org-hh:mm-string-to-minutes f))
+ (t 0))))
+ ((?f ?F)
+ (or getkey-func
+ (and interactive?
+ (org-read-function "Function for extracting keys: "))
+ (error "Missing key extractor to sort rows")))
+ (t (user-error "Invalid sorting type `%c'" sorting-type))))
+ (predicate
+ (cl-case sorting-type
+ ((?n ?N ?t ?T) #'<)
+ ((?a ?A) #'string<)
+ ((?f ?F)
+ (or compare-func
+ (and interactive?
+ (org-read-function
+ (concat "Fuction for comparing keys "
+ "(empty for default `sort-subr' predicate): ")
+ 'allow-empty)))))))
+ (goto-char (point-min))
+ (sort-subr (memq sorting-type '(?A ?N ?T ?F))
+ (lambda ()
+ (forward-line)
+ (while (and (not (eobp))
+ (not (looking-at org-table-dataline-regexp)))
+ (forward-line)))
+ #'end-of-line
+ (lambda ()
+ (funcall extract-key-from-field
+ (org-trim (org-table-get-field column))))
+ nil
+ predicate)
+ ;; Move back to initial field.
+ (forward-line (car coordinates))
+ (move-to-column (cdr coordinates))))))
+
+;;;###autoload
+(defun org-table-cut-region (beg end)
+ "Copy region in table to the clipboard and blank all relevant fields.
+If there is no active region, use just the field at point."
+ (interactive (list
+ (if (org-region-active-p) (region-beginning) (point))
+ (if (org-region-active-p) (region-end) (point))))
+ (org-table-copy-region beg end 'cut))
+
+;;;###autoload
+(defun org-table-copy-region (beg end &optional cut)
+ "Copy rectangular region in table to clipboard.
+A special clipboard is used which can only be accessed
+with `org-table-paste-rectangle'."
+ (interactive (list
+ (if (org-region-active-p) (region-beginning) (point))
+ (if (org-region-active-p) (region-end) (point))
+ current-prefix-arg))
+ (goto-char (min beg end))
+ (org-table-check-inside-data-field)
+ (let ((beg (line-beginning-position))
+ (c01 (org-table-current-column))
+ region)
+ (goto-char (max beg end))
+ (org-table-check-inside-data-field)
+ (let* ((end (copy-marker (line-end-position)))
+ (c02 (org-table-current-column))
+ (column-start (min c01 c02))
+ (column-end (max c01 c02))
+ (column-number (1+ (- column-end column-start)))
+ (rpl (and cut " ")))
+ (goto-char beg)
+ (while (< (point) end)
+ (unless (org-at-table-hline-p)
+ ;; Collect every cell between COLUMN-START and COLUMN-END.
+ (let (cols)
+ (dotimes (c column-number)
+ (push (org-table-get-field (+ c column-start) rpl) cols))
+ (push (nreverse cols) region)))
+ (forward-line))
+ (set-marker end nil))
+ (when cut (org-table-align))
+ (setq org-table-clip (nreverse region))))
+
+;;;###autoload
+(defun org-table-paste-rectangle ()
+ "Paste a rectangular region into a table.
+The upper right corner ends up in the current field. All involved fields
+will be overwritten. If the rectangle does not fit into the present table,
+the table is enlarged as needed. The process ignores horizontal separator
+lines."
+ (interactive)
+ (unless (consp org-table-clip)
+ (user-error "First cut/copy a region to paste!"))
+ (org-table-check-inside-data-field)
+ (let* ((column (org-table-current-column))
+ (org-enable-table-editor t)
+ (org-table-automatic-realign nil))
+ (org-table-save-field
+ (dolist (row org-table-clip)
+ (while (org-at-table-hline-p) (forward-line))
+ ;; If we left the table, create a new row.
+ (when (and (bolp) (not (looking-at "[ \t]*|")))
+ (end-of-line 0)
+ (org-table-next-field))
+ (let ((c column))
+ (dolist (field row)
+ (org-table-goto-column c nil 'force)
+ (org-table-get-field nil field)
+ (cl-incf c)))
+ (forward-line)))
+ (org-table-align)))
+
+;;;###autoload
+(defun org-table-convert ()
+ "Convert from `org-mode' table to table.el and back.
+Obviously, this only works within limits. When an Org table is converted
+to table.el, all horizontal separator lines get lost, because table.el uses
+these as cell boundaries and has no notion of horizontal lines. A table.el
+table can be converted to an Org table only if it does not do row or column
+spanning. Multiline cells will become multiple cells. Beware, Org mode
+does not test if the table can be successfully converted - it blindly
+applies a recipe that works for simple tables."
+ (interactive)
+ (require 'table)
+ (if (org-at-table.el-p)
+ ;; convert to Org table
+ (let ((beg (copy-marker (org-table-begin t)))
+ (end (copy-marker (org-table-end t))))
+ (table-unrecognize-region beg end)
+ (goto-char beg)
+ (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
+ (replace-match ""))
+ (goto-char beg))
+ (if (org-at-table-p)
+ ;; convert to table.el table
+ (let ((beg (copy-marker (org-table-begin)))
+ (end (copy-marker (org-table-end))))
+ ;; first, get rid of all horizontal lines
+ (goto-char beg)
+ (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
+ (replace-match ""))
+ ;; insert a hline before first
+ (goto-char beg)
+ (org-table-insert-hline 'above)
+ (beginning-of-line -1)
+ ;; insert a hline after each line
+ (while (progn (beginning-of-line 3) (< (point) end))
+ (org-table-insert-hline))
+ (goto-char beg)
+ (setq end (move-marker end (org-table-end)))
+ ;; replace "+" at beginning and ending of hlines
+ (while (re-search-forward "^\\([ \t]*\\)|-" end t)
+ (replace-match "\\1+-"))
+ (goto-char beg)
+ (while (re-search-forward "-|[ \t]*$" end t)
+ (replace-match "-+"))
+ (goto-char beg)))))
+
+(defun org-table-transpose-table-at-point ()
+ "Transpose Org table at point and eliminate hlines.
+So a table like
+
+| 1 | 2 | 4 | 5 |
+|---+---+---+---|
+| a | b | c | d |
+| e | f | g | h |
+
+will be transposed as
+
+| 1 | a | e |
+| 2 | b | f |
+| 4 | c | g |
+| 5 | d | h |
+
+Note that horizontal lines disappear."
+ (interactive)
+ (let* ((table (delete 'hline (org-table-to-lisp)))
+ (dline_old (org-table-current-line))
+ (col_old (org-table-current-column))
+ (contents (mapcar (lambda (_)
+ (let ((tp table))
+ (mapcar
+ (lambda (_)
+ (prog1
+ (pop (car tp))
+ (setq tp (cdr tp))))
+ table)))
+ (car table))))
+ (goto-char (org-table-begin))
+ (re-search-forward "|")
+ (backward-char)
+ (delete-region (point) (org-table-end))
+ (insert (mapconcat
+ (lambda(x)
+ (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
+ contents ""))
+ (org-table-goto-line col_old)
+ (org-table-goto-column dline_old))
+ (org-table-align))
+
+;;;###autoload
+(defun org-table-wrap-region (arg)
+ "Wrap several fields in a column like a paragraph.
+This is useful if you'd like to spread the contents of a field over several
+lines, in order to keep the table compact.
+
+If there is an active region, and both point and mark are in the same column,
+the text in the column is wrapped to minimum width for the given number of
+lines. Generally, this makes the table more compact. A prefix ARG may be
+used to change the number of desired lines. For example, \
+`C-2 \\[org-table-wrap-region]'
+formats the selected text to two lines. If the region was longer than two
+lines, the remaining lines remain empty. A negative prefix argument reduces
+the current number of lines by that amount. The wrapped text is pasted back
+into the table. If you formatted it to more lines than it was before, fields
+further down in the table get overwritten - so you might need to make space in
+the table first.
+
+If there is no region, the current field is split at the cursor position and
+the text fragment to the right of the cursor is prepended to the field one
+line down.
+
+If there is no region, but you specify a prefix ARG, the current field gets
+blank, and the content is appended to the field above."
+ (interactive "P")
+ (org-table-check-inside-data-field)
+ (if (org-region-active-p)
+ ;; There is a region: fill as a paragraph.
+ (let ((start (region-beginning)))
+ (org-table-cut-region (region-beginning) (region-end))
+ (when (> (length (car org-table-clip)) 1)
+ (user-error "Region must be limited to single column"))
+ (let ((nlines (cond ((not arg) (length org-table-clip))
+ ((< arg 1) (+ (length org-table-clip) arg))
+ (t arg))))
+ (setq org-table-clip
+ (mapcar #'list
+ (org-wrap (mapconcat #'car org-table-clip " ")
+ nil
+ nlines))))
+ (goto-char start)
+ (org-table-paste-rectangle))
+ ;; No region, split the current field at point.
+ (unless (org-get-alist-option org-M-RET-may-split-line 'table)
+ (skip-chars-forward "^\r\n|"))
+ (cond
+ (arg ; Combine with field above.
+ (let ((s (org-table-blank-field))
+ (col (org-table-current-column)))
+ (forward-line -1)
+ (while (org-at-table-hline-p) (forward-line -1))
+ (org-table-goto-column col)
+ (skip-chars-forward "^|")
+ (skip-chars-backward " ")
+ (insert " " (org-trim s))
+ (org-table-align)))
+ ((looking-at "\\([^|]+\\)+|") ; Split field.
+ (let ((s (match-string 1)))
+ (replace-match " |")
+ (goto-char (match-beginning 0))
+ (org-table-next-row)
+ (insert (org-trim s) " ")
+ (org-table-align)))
+ (t (org-table-next-row)))))
+
+(defvar org-field-marker nil)
+
+;;;###autoload
+(defun org-table-edit-field (arg)
+ "Edit table field in a different window.
+This is mainly useful for fields that contain hidden parts. When called
+with a `\\[universal-argument]' prefix, just make the full field \
+visible so that it can be
+edited in place."
+ (interactive "P")
+ (cond
+ ((equal arg '(16))
+ (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
+ (arg
+ (let ((b (save-excursion (skip-chars-backward "^|") (point)))
+ (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
+ (remove-text-properties b e '(org-cwidth t invisible t
+ display t intangible t))
+ (if (and (boundp 'font-lock-mode) font-lock-mode)
+ (font-lock-fontify-block))))
+ (t
+ (let ((pos (point-marker))
+ (coord
+ (if (eq org-table-use-standard-references t)
+ (concat (org-number-to-letters (org-table-current-column))
+ (int-to-string (org-table-current-dline)))
+ (concat "@" (int-to-string (org-table-current-dline))
+ "$" (int-to-string (org-table-current-column)))))
+ (field (org-table-get-field))
+ (cw (current-window-configuration))
+ p)
+ (goto-char pos)
+ (org-switch-to-buffer-other-window "*Org Table Edit Field*")
+ (when (and (local-variable-p 'org-field-marker)
+ (markerp org-field-marker))
+ (move-marker org-field-marker nil))
+ (erase-buffer)
+ (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
+ (let ((org-inhibit-startup t)) (org-mode))
+ (auto-fill-mode -1)
+ (setq truncate-lines nil)
+ (setq word-wrap t)
+ (goto-char (setq p (point-max)))
+ (insert (org-trim field))
+ (remove-text-properties p (point-max)
+ '(invisible t org-cwidth t display t
+ intangible t))
+ (goto-char p)
+ (setq-local org-finish-function 'org-table-finish-edit-field)
+ (setq-local org-window-configuration cw)
+ (setq-local org-field-marker pos)
+ (message "Edit and finish with C-c C-c")))))
+
+(defun org-table-finish-edit-field ()
+ "Finish editing a table data field.
+Remove all newline characters, insert the result into the table, realign
+the table and kill the editing buffer."
+ (let ((pos org-field-marker)
+ (cw org-window-configuration)
+ (cb (current-buffer))
+ text)
+ (goto-char (point-min))
+ (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
+ (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
+ (replace-match " "))
+ (setq text (org-trim (buffer-string)))
+ (set-window-configuration cw)
+ (kill-buffer cb)
+ (select-window (get-buffer-window (marker-buffer pos)))
+ (goto-char pos)
+ (move-marker pos nil)
+ (org-table-check-inside-data-field)
+ (org-table-get-field nil text)
+ (org-table-align)
+ (message "New field value inserted")))
+
+(define-minor-mode org-table-follow-field-mode
+ "Minor mode to make the table field editor window follow the cursor.
+When this mode is active, the field editor window will always show the
+current field. The mode exits automatically when the cursor leaves the
+table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
+ nil " TblFollow" nil
+ (if org-table-follow-field-mode
+ (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
+ 'append 'local)
+ (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
+ (let* ((buf (get-buffer "*Org Table Edit Field*"))
+ (win (and buf (get-buffer-window buf))))
+ (when win (delete-window win))
+ (when buf
+ (with-current-buffer buf
+ (move-marker org-field-marker nil))
+ (kill-buffer buf)))))
+
+(defun org-table-follow-fields-with-editor ()
+ (if (and org-table-exit-follow-field-mode-when-leaving-table
+ (not (org-at-table-p)))
+ ;; We have left the table, exit the follow mode
+ (org-table-follow-field-mode -1)
+ (when (org-table-check-inside-data-field 'noerror)
+ (let ((win (selected-window)))
+ (org-table-edit-field nil)
+ (org-fit-window-to-buffer)
+ (select-window win)))))
+
+(defvar org-timecnt) ; dynamically scoped parameter
+
+;;;###autoload
+(defun org-table-sum (&optional beg end nlast)
+ "Sum numbers in region of current table column.
+The result will be displayed in the echo area, and will be available
+as kill to be inserted with \\[yank].
+
+If there is an active region, it is interpreted as a rectangle and all
+numbers in that rectangle will be summed. If there is no active
+region and point is located in a table column, sum all numbers in that
+column.
+
+If at least one number looks like a time HH:MM or HH:MM:SS, all other
+numbers are assumed to be times as well (in decimal hours) and the
+numbers are added as such.
+
+If NLAST is a number, only the NLAST fields will actually be summed."
+ (interactive)
+ (save-excursion
+ (let (col (org-timecnt 0) diff h m s org-table-clip)
+ (cond
+ ((and beg end)) ; beg and end given explicitly
+ ((org-region-active-p)
+ (setq beg (region-beginning) end (region-end)))
+ (t
+ (setq col (org-table-current-column))
+ (goto-char (org-table-begin))
+ (unless (re-search-forward "^[ \t]*|[^-]" nil t)
+ (user-error "No table data"))
+ (org-table-goto-column col)
+ (setq beg (point))
+ (goto-char (org-table-end))
+ (unless (re-search-backward "^[ \t]*|[^-]" nil t)
+ (user-error "No table data"))
+ (org-table-goto-column col)
+ (setq end (point))))
+ (let* ((items (apply 'append (org-table-copy-region beg end)))
+ (items1 (cond ((not nlast) items)
+ ((>= nlast (length items)) items)
+ (t (setq items (reverse items))
+ (setcdr (nthcdr (1- nlast) items) nil)
+ (nreverse items))))
+ (numbers (delq nil (mapcar 'org-table-get-number-for-summing
+ items1)))
+ (res (apply '+ numbers))
+ (sres (if (= org-timecnt 0)
+ (number-to-string res)
+ (setq diff (* 3600 res)
+ h (floor (/ diff 3600)) diff (mod diff 3600)
+ m (floor (/ diff 60)) diff (mod diff 60)
+ s diff)
+ (format "%.0f:%02.0f:%02.0f" h m s))))
+ (kill-new sres)
+ (when (called-interactively-p 'interactive)
+ (message "%s" (substitute-command-keys
+ (format "Sum of %d items: %-20s \
+\(\\[yank] will insert result into buffer)" (length numbers) sres))))
+ sres))))
+
+(defun org-table-get-number-for-summing (s)
+ (let (n)
+ (if (string-match "^ *|? *" s)
+ (setq s (replace-match "" nil nil s)))
+ (if (string-match " *|? *$" s)
+ (setq s (replace-match "" nil nil s)))
+ (setq n (string-to-number s))
+ (cond
+ ((and (string-match "0" s)
+ (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
+ ((string-match "\\`[ \t]+\\'" s) nil)
+ ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
+ (let ((h (string-to-number (or (match-string 1 s) "0")))
+ (m (string-to-number (or (match-string 2 s) "0")))
+ (s (string-to-number (or (match-string 4 s) "0"))))
+ (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
+ (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
+ ((equal n 0) nil)
+ (t n))))
+
+(defun org-table-current-field-formula (&optional key noerror)
+ "Return the formula active for the current field.
+
+Assumes that table is already analyzed. If KEY is given, return
+the key to this formula. Otherwise return the formula preceded
+with \"=\" or \":=\"."
+ (let* ((line (count-lines org-table-current-begin-pos
+ (line-beginning-position)))
+ (row (org-table-line-to-dline line)))
+ (cond
+ (row
+ (let* ((col (org-table-current-column))
+ (name (car (rassoc (list line col)
+ org-table-named-field-locations)))
+ (scol (format "$%d" col))
+ (ref (format "@%d$%d" (org-table-current-dline) col))
+ (stored-list (org-table-get-stored-formulas noerror))
+ (ass (or (assoc name stored-list)
+ (assoc ref stored-list)
+ (assoc scol stored-list))))
+ (cond (key (car ass))
+ (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
+ (cdr ass))))))
+ (noerror nil)
+ (t (error "No formula active for the current field")))))
+
+(defun org-table-get-formula (&optional equation named)
+ "Read a formula from the minibuffer, offer stored formula as default.
+When NAMED is non-nil, look for a named equation."
+ (let* ((stored-list (org-table-get-stored-formulas))
+ (name (car (rassoc (list (count-lines org-table-current-begin-pos
+ (line-beginning-position))
+ (org-table-current-column))
+ org-table-named-field-locations)))
+ (ref (format "@%d$%d"
+ (org-table-current-dline)
+ (org-table-current-column)))
+ (scol (cond
+ ((not named) (format "$%d" (org-table-current-column)))
+ ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name)
+ (t ref)))
+ (name (or name ref))
+ (org-table-may-need-update nil)
+ (stored (cdr (assoc scol stored-list)))
+ (eq (cond
+ ((and stored equation (string-match-p "^ *=? *$" equation))
+ stored)
+ ((stringp equation)
+ equation)
+ (t (org-table-formula-from-user
+ (read-string
+ (org-table-formula-to-user
+ (format "%s formula %s="
+ (if named "Field" "Column")
+ scol))
+ (if stored (org-table-formula-to-user stored) "")
+ 'org-table-formula-history
+ )))))
+ mustsave)
+ (when (not (string-match "\\S-" eq))
+ ;; remove formula
+ (setq stored-list (delq (assoc scol stored-list) stored-list))
+ (org-table-store-formulas stored-list)
+ (user-error "Formula removed"))
+ (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
+ (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
+ (if (and name (not named))
+ ;; We set the column equation, delete the named one.
+ (setq stored-list (delq (assoc name stored-list) stored-list)
+ mustsave t))
+ (if stored
+ (setcdr (assoc scol stored-list) eq)
+ (setq stored-list (cons (cons scol eq) stored-list)))
+ (if (or mustsave (not (equal stored eq)))
+ (org-table-store-formulas stored-list))
+ eq))
+
+(defun org-table-store-formulas (alist &optional location)
+ "Store the list of formulas below the current table.
+If optional argument LOCATION is a buffer position, insert it at
+LOCATION instead."
+ (save-excursion
+ (if location
+ (progn (goto-char location) (beginning-of-line))
+ (goto-char (org-table-end)))
+ (let ((case-fold-search t))
+ (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
+ (progn
+ ;; Don't overwrite TBLFM, we might use text properties to
+ ;; store stuff.
+ (goto-char (match-beginning 3))
+ (delete-region (match-beginning 3) (match-end 0)))
+ (org-indent-line)
+ (insert (or (match-string 2) "#+TBLFM:")))
+ (insert " "
+ (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
+ (sort alist #'org-table-formula-less-p)
+ "::")
+ "\n"))))
+
+(defsubst org-table-formula-make-cmp-string (a)
+ (when (string-match "\\`$[<>]" a)
+ (let ((arrow (string-to-char (substring a 1))))
+ ;; Fake a high number to make sure this is sorted at the end.
+ (setq a (org-table-formula-handle-first/last-rc a))
+ (setq a (format "$%d" (+ 10000
+ (if (= arrow ?<) -1000 0)
+ (string-to-number (substring a 1)))))))
+ (when (string-match
+ "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
+ a)
+ (concat
+ (if (match-end 2)
+ (format "@%05d" (string-to-number (match-string 2 a))) "")
+ (if (match-end 4)
+ (format "$%05d" (string-to-number (match-string 4 a))) "")
+ (if (match-end 5)
+ (concat "@@" (match-string 5 a))))))
+
+(defun org-table-formula-less-p (a b)
+ "Compare two formulas for sorting."
+ (let ((as (org-table-formula-make-cmp-string (car a)))
+ (bs (org-table-formula-make-cmp-string (car b))))
+ (and as bs (string< as bs))))
+
+;;;###autoload
+(defun org-table-get-stored-formulas (&optional noerror location)
+ "Return an alist with the stored formulas directly after current table.
+By default, only return active formulas, i.e., formulas located
+on the first line after the table. However, if optional argument
+LOCATION is a buffer position, consider the formulas there."
+ (save-excursion
+ (if location
+ (progn (goto-char location) (beginning-of-line))
+ (goto-char (org-table-end)))
+ (let ((case-fold-search t))
+ (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
+ (let ((strings (org-split-string (match-string-no-properties 2)
+ " *:: *"))
+ eq-alist seen)
+ (dolist (string strings (nreverse eq-alist))
+ (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
+[<>]+\\)\\) *= *\\(.*[^ \t]\\)"
+ string)
+ (let ((lhs
+ (let ((m (match-string 1 string)))
+ (cond
+ ((not (match-end 2)) m)
+ ;; Is it a column reference?
+ ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m)
+ ;; Since named columns are not possible in
+ ;; LHS, assume this is a named field.
+ (t (match-string 2 string)))))
+ (rhs (match-string 3 string)))
+ (push (cons lhs rhs) eq-alist)
+ (cond
+ ((not (member lhs seen)) (push lhs seen))
+ (noerror
+ (message
+ "Double definition `%s=' in TBLFM line, please fix by hand"
+ lhs)
+ (ding)
+ (sit-for 2))
+ (t
+ (user-error
+ "Double definition `%s=' in TBLFM line, please fix by hand"
+ lhs)))))))))))
+
+(defun org-table-fix-formulas (key replace &optional limit delta remove)
+ "Modify the equations after the table structure has been edited.
+KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
+For all numbers larger than LIMIT, shift them by DELTA."
+ (save-excursion
+ (goto-char (org-table-end))
+ (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
+ (let ((msg "The formulas in #+TBLFM have been updated")
+ (re (concat key "\\([0-9]+\\)"))
+ (re2
+ (when remove
+ (if (or (equal key "$") (equal key "$LR"))
+ (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
+ (regexp-quote key) remove)
+ (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
+ s n a)
+ (when remove
+ (while (re-search-forward re2 (point-at-eol) t)
+ (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
+ (if (equal (char-before (match-beginning 0)) ?.)
+ (user-error
+ "Change makes TBLFM term %s invalid, use undo to recover"
+ (match-string 0))
+ (replace-match "")))))
+ (while (re-search-forward re (point-at-eol) t)
+ (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
+ (setq s (match-string 1) n (string-to-number s))
+ (cond
+ ((setq a (assoc s replace))
+ (replace-match (concat key (cdr a)) t t)
+ (message msg))
+ ((and limit (> n limit))
+ (replace-match (concat key (int-to-string (+ n delta))) t t)
+ (message msg))))))
+ (forward-line))))
+
+;;;###autoload
+(defun org-table-maybe-eval-formula ()
+ "Check if the current field starts with \"=\" or \":=\".
+If yes, store the formula and apply it."
+ ;; We already know we are in a table. Get field will only return a formula
+ ;; when appropriate. It might return a separator line, but no problem.
+ (when org-table-formula-evaluate-inline
+ (let* ((field (org-trim (or (org-table-get-field) "")))
+ named eq)
+ (when (string-match "^:?=\\(.*[^=]\\)$" field)
+ (setq named (equal (string-to-char field) ?:)
+ eq (match-string 1 field))
+ (org-table-eval-formula (and named '(4))
+ (org-table-formula-from-user eq))))))
+
+(defvar org-recalc-commands nil
+ "List of commands triggering the recalculation of a line.
+Will be filled automatically during use.")
+
+(defvar org-recalc-marks
+ '((" " . "Unmarked: no special line, no automatic recalculation")
+ ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
+ ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
+ ("!" . "Column name definition line. Reference in formula as $name.")
+ ("$" . "Parameter definition line name=value. Reference in formula as $name.")
+ ("_" . "Names for values in row below this one.")
+ ("^" . "Names for values in row above this one.")))
+
+;;;###autoload
+(defun org-table-rotate-recalc-marks (&optional newchar)
+ "Rotate the recalculation mark in the first column.
+If in any row, the first field is not consistent with a mark,
+insert a new column for the markers.
+When there is an active region, change all the lines in the region,
+after prompting for the marking character.
+After each change, a message will be displayed indicating the meaning
+of the new mark."
+ (interactive)
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (let* ((region (org-region-active-p))
+ (l1 (and region
+ (save-excursion (goto-char (region-beginning))
+ (copy-marker (line-beginning-position)))))
+ (l2 (and region
+ (save-excursion (goto-char (region-end))
+ (copy-marker (line-beginning-position)))))
+ (l (copy-marker (line-beginning-position)))
+ (col (org-table-current-column))
+ (newchar (if region
+ (char-to-string
+ (read-char-exclusive
+ "Change region to what mark? Type # * ! $ or SPC: "))
+ newchar))
+ (no-special-column
+ (save-excursion
+ (goto-char (org-table-begin))
+ (re-search-forward
+ "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
+ (when (and newchar (not (assoc newchar org-recalc-marks)))
+ (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
+ newchar))
+ (when l1 (goto-char l1))
+ (save-excursion
+ (beginning-of-line)
+ (unless (looking-at org-table-dataline-regexp)
+ (user-error "Not at a table data line")))
+ (when no-special-column
+ (org-table-goto-column 1)
+ (org-table-insert-column))
+ (let ((previous-line-end (line-end-position))
+ (newchar
+ (save-excursion
+ (beginning-of-line)
+ (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
+ (newchar)
+ (t (cadr (member (match-string 1)
+ (append (mapcar #'car org-recalc-marks)
+ '(" ")))))))))
+ ;; Rotate mark in first row.
+ (org-table-get-field 1 (format " %s " newchar))
+ ;; Rotate marks in additional rows if a region is active.
+ (when region
+ (save-excursion
+ (forward-line)
+ (while (<= (point) l2)
+ (when (looking-at org-table-dataline-regexp)
+ (org-table-get-field 1 (format " %s " newchar)))
+ (forward-line))))
+ ;; Only align if rotation actually changed lines' length.
+ (when (/= previous-line-end (line-end-position)) (org-table-align)))
+ (goto-char l)
+ (org-table-goto-column (if no-special-column (1+ col) col))
+ (when l1 (set-marker l1 nil))
+ (when l2 (set-marker l2 nil))
+ (set-marker l nil)
+ (when (called-interactively-p 'interactive)
+ (message "%s" (cdr (assoc newchar org-recalc-marks))))))
+
+;;;###autoload
+(defun org-table-analyze ()
+ "Analyze table at point and store results.
+
+This function sets up the following dynamically scoped variables:
+
+ `org-table-column-name-regexp',
+ `org-table-column-names',
+ `org-table-current-begin-pos',
+ `org-table-current-line-types',
+ `org-table-current-ncol',
+ `org-table-dlines',
+ `org-table-hlines',
+ `org-table-local-parameters',
+ `org-table-named-field-locations'."
+ (let ((beg (org-table-begin))
+ (end (org-table-end)))
+ (save-excursion
+ (goto-char beg)
+ ;; Extract column names.
+ (setq org-table-column-names nil)
+ (when (save-excursion
+ (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
+ (let ((c 1))
+ (dolist (name (org-split-string (match-string 1) " *| *"))
+ (cl-incf c)
+ (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
+ (push (cons name (int-to-string c)) org-table-column-names)))))
+ (setq org-table-column-names (nreverse org-table-column-names))
+ (setq org-table-column-name-regexp
+ (format "\\$\\(%s\\)\\>"
+ (regexp-opt (mapcar #'car org-table-column-names) t)))
+ ;; Extract local parameters.
+ (setq org-table-local-parameters nil)
+ (save-excursion
+ (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
+ (dolist (field (org-split-string (match-string 1) " *| *"))
+ (when (string-match
+ "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
+ (push (cons (match-string 1 field) (match-string 2 field))
+ org-table-local-parameters)))))
+ ;; Update named fields locations. We minimize `count-lines'
+ ;; processing by storing last known number of lines in LAST.
+ (setq org-table-named-field-locations nil)
+ (save-excursion
+ (let ((last (cons (point) 0)))
+ (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
+ (let ((c (match-string 1))
+ (fields (org-split-string (match-string 2) " *| *")))
+ (save-excursion
+ (forward-line (if (equal c "_") 1 -1))
+ (let ((fields1
+ (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
+ (org-split-string (match-string 1) " *| *")))
+ (line (cl-incf (cdr last) (count-lines (car last) (point))))
+ (col 1))
+ (setcar last (point)) ; Update last known position.
+ (while (and fields fields1)
+ (let ((field (pop fields))
+ (v (pop fields1)))
+ (cl-incf col)
+ (when (and (stringp field)
+ (stringp v)
+ (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
+ field))
+ (push (cons field v) org-table-local-parameters)
+ (push (list field line col)
+ org-table-named-field-locations))))))))))
+ ;; Re-use existing markers when possible.
+ (if (markerp org-table-current-begin-pos)
+ (move-marker org-table-current-begin-pos (point))
+ (setq org-table-current-begin-pos (point-marker)))
+ ;; Analyze the line types.
+ (let ((l 0) hlines dlines types)
+ (while (looking-at "[ \t]*|\\(-\\)?")
+ (push (if (match-end 1) 'hline 'dline) types)
+ (if (match-end 1) (push l hlines) (push l dlines))
+ (forward-line)
+ (cl-incf l))
+ (push 'hline types) ; Add an imaginary extra hline to the end.
+ (setq org-table-current-line-types (apply #'vector (nreverse types)))
+ (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
+ (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
+ ;; Get the number of columns from the first data line in table.
+ (goto-char beg)
+ (forward-line (aref org-table-dlines 1))
+ (let* ((fields
+ (org-split-string
+ (buffer-substring (line-beginning-position) (line-end-position))
+ "[ \t]*|[ \t]*"))
+ (nfields (length fields))
+ al al2)
+ (setq org-table-current-ncol nfields)
+ (let ((last-dline
+ (aref org-table-dlines (1- (length org-table-dlines)))))
+ (dotimes (i nfields)
+ (let ((column (1+ i)))
+ (push (list (format "LR%d" column) last-dline column) al)
+ (push (cons (format "LR%d" column) (nth i fields)) al2))))
+ (setq org-table-named-field-locations
+ (append org-table-named-field-locations al))
+ (setq org-table-local-parameters
+ (append org-table-local-parameters al2))))))
+
+(defun org-table-goto-field (ref &optional create-column-p)
+ "Move point to a specific field in the current table.
+
+REF is either the name of a field its absolute reference, as
+a string. No column is created unless CREATE-COLUMN-P is
+non-nil. If it is a function, it is called with the column
+number as its argument as is used as a predicate to know if the
+column can be created.
+
+This function assumes the table is already analyzed (i.e., using
+`org-table-analyze')."
+ (let* ((coordinates
+ (cond
+ ((cdr (assoc ref org-table-named-field-locations)))
+ ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
+ (list (condition-case nil
+ (aref org-table-dlines
+ (string-to-number (match-string 1 ref)))
+ (error (user-error "Invalid row number in %s" ref)))
+ (string-to-number (match-string 2 ref))))
+ (t (user-error "Unknown field: %s" ref))))
+ (line (car coordinates))
+ (column (nth 1 coordinates))
+ (create-new-column (if (functionp create-column-p)
+ (funcall create-column-p column)
+ create-column-p)))
+ (when coordinates
+ (goto-char org-table-current-begin-pos)
+ (forward-line line)
+ (org-table-goto-column column nil create-new-column))))
+
+;;;###autoload
+(defun org-table-maybe-recalculate-line ()
+ "Recompute the current line if marked for it, and if we haven't just done it."
+ (interactive)
+ (and org-table-allow-automatic-line-recalculation
+ (not (and (memq last-command org-recalc-commands)
+ (eq org-last-recalc-line (line-beginning-position))))
+ (save-excursion (beginning-of-line 1)
+ (looking-at org-table-auto-recalculate-regexp))
+ (org-table-recalculate) t))
+
+(defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
+(defsubst org-set-calc-mode (var &optional value)
+ (if (stringp var)
+ (setq var (assoc var '(("D" calc-angle-mode deg)
+ ("R" calc-angle-mode rad)
+ ("F" calc-prefer-frac t)
+ ("S" calc-symbolic-mode t)))
+ value (nth 2 var) var (nth 1 var)))
+ (if (memq var org-tbl-calc-modes)
+ (setcar (cdr (memq var org-tbl-calc-modes)) value)
+ (cons var (cons value org-tbl-calc-modes)))
+ org-tbl-calc-modes)
+
+;;;###autoload
+(defun org-table-eval-formula (&optional arg equation
+ suppress-align suppress-const
+ suppress-store suppress-analysis)
+ "Replace the table field value at the cursor by the result of a calculation.
+
+In a table, this command replaces the value in the current field with the
+result of a formula. It also installs the formula as the \"current\" column
+formula, by storing it in a special line below the table. When called
+with a `\\[universal-argument]' prefix the formula is installed as a \
+field formula.
+
+When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
+insert the active equation for the field
+back into the current field, so that it can be edited there. This is \
+useful
+in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
+check the referenced fields.
+
+When called, the command first prompts for a formula, which is read in
+the minibuffer. Previously entered formulas are available through the
+history list, and the last used formula is offered as a default.
+These stored formulas are adapted correctly when moving, inserting, or
+deleting columns with the corresponding commands.
+
+The formula can be any algebraic expression understood by the Calc package.
+For details, see the Org mode manual.
+
+This function can also be called from Lisp programs and offers
+additional arguments: EQUATION can be the formula to apply. If this
+argument is given, the user will not be prompted. SUPPRESS-ALIGN is
+used to speed-up recursive calls by by-passing unnecessary aligns.
+SUPPRESS-CONST suppresses the interpretation of constants in the
+formula, assuming that this has been done already outside the function.
+SUPPRESS-STORE means the formula should not be stored, either because
+it is already stored, or because it is a modified equation that should
+not overwrite the stored one. SUPPRESS-ANALYSIS prevents any call to
+`org-table-analyze'."
+ (interactive "P")
+ (org-table-check-inside-data-field)
+ (or suppress-analysis (org-table-analyze))
+ (if (equal arg '(16))
+ (let ((eq (org-table-current-field-formula)))
+ (org-table-get-field nil eq)
+ (org-table-align)
+ (setq org-table-may-need-update t))
+ (let* (fields
+ (ndown (if (integerp arg) arg 1))
+ (org-table-automatic-realign nil)
+ (case-fold-search nil)
+ (down (> ndown 1))
+ (formula (if (and equation suppress-store)
+ equation
+ (org-table-get-formula equation (equal arg '(4)))))
+ (n0 (org-table-current-column))
+ (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
+ (numbers nil) ; was a variable, now fixed default
+ (keep-empty nil)
+ n form form0 formrpl formrg bw fmt x ev orig c lispp literal
+ duration duration-output-format)
+ ;; Parse the format string. Since we have a lot of modes, this is
+ ;; a lot of work. However, I think calc still uses most of the time.
+ (if (string-match ";" formula)
+ (let ((tmp (org-split-string formula ";")))
+ (setq formula (car tmp)
+ fmt (concat (cdr (assoc "%" org-table-local-parameters))
+ (nth 1 tmp)))
+ (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
+ (setq c (string-to-char (match-string 1 fmt))
+ n (string-to-number (match-string 2 fmt)))
+ (if (= c ?p)
+ (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
+ (setq org-tbl-calc-modes
+ (org-set-calc-mode
+ 'calc-float-format
+ (list (cdr (assoc c '((?n . float) (?f . fix)
+ (?s . sci) (?e . eng))))
+ n))))
+ (setq fmt (replace-match "" t t fmt)))
+ (if (string-match "T" fmt)
+ (setq duration t numbers t
+ duration-output-format nil
+ fmt (replace-match "" t t fmt)))
+ (if (string-match "t" fmt)
+ (setq duration t
+ duration-output-format org-table-duration-custom-format
+ numbers t
+ fmt (replace-match "" t t fmt)))
+ (if (string-match "N" fmt)
+ (setq numbers t
+ fmt (replace-match "" t t fmt)))
+ (if (string-match "L" fmt)
+ (setq literal t
+ fmt (replace-match "" t t fmt)))
+ (if (string-match "E" fmt)
+ (setq keep-empty t
+ fmt (replace-match "" t t fmt)))
+ (while (string-match "[DRFS]" fmt)
+ (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
+ (setq fmt (replace-match "" t t fmt)))
+ (unless (string-match "\\S-" fmt)
+ (setq fmt nil))))
+ (when (and (not suppress-const) org-table-formula-use-constants)
+ (setq formula (org-table-formula-substitute-names formula)))
+ (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
+ (setq formula (org-table-formula-handle-first/last-rc formula))
+ (while (> ndown 0)
+ (setq fields (org-split-string
+ (org-trim
+ (buffer-substring-no-properties
+ (line-beginning-position) (line-end-position)))
+ " *| *"))
+ ;; replace fields with duration values if relevant
+ (if duration
+ (setq fields
+ (mapcar (lambda (x) (org-table-time-string-to-seconds x))
+ fields)))
+ (if (eq numbers t)
+ (setq fields (mapcar
+ (lambda (x)
+ (if (string-match "\\S-" x)
+ (number-to-string (string-to-number x))
+ x))
+ fields)))
+ (setq ndown (1- ndown))
+ (setq form (copy-sequence formula)
+ lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
+ (if (and lispp literal) (setq lispp 'literal))
+
+ ;; Insert row and column number of formula result field
+ (while (string-match "[@$]#" form)
+ (setq form
+ (replace-match
+ (format "%d"
+ (save-match-data
+ (if (equal (substring form (match-beginning 0)
+ (1+ (match-beginning 0)))
+ "@")
+ (org-table-current-dline)
+ (org-table-current-column))))
+ t t form)))
+
+ ;; Check for old vertical references
+ (org-table--error-on-old-row-references form)
+ ;; Insert remote references
+ (setq form (org-table-remote-reference-indirection form))
+ (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
+ (setq form
+ (replace-match
+ (save-match-data
+ (org-table-make-reference
+ (let ((rmtrng (org-table-get-remote-range
+ (match-string 1 form) (match-string 2 form))))
+ (if duration
+ (if (listp rmtrng)
+ (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
+ (org-table-time-string-to-seconds rmtrng))
+ rmtrng))
+ keep-empty numbers lispp))
+ t t form)))
+ ;; Insert complex ranges
+ (while (and (string-match org-table-range-regexp form)
+ (> (length (match-string 0 form)) 1))
+ (setq formrg
+ (save-match-data
+ (org-table-get-range
+ (match-string 0 form) org-table-current-begin-pos n0)))
+ (setq formrpl
+ (save-match-data
+ (org-table-make-reference
+ ;; possibly handle durations
+ (if duration
+ (if (listp formrg)
+ (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
+ (org-table-time-string-to-seconds formrg))
+ formrg)
+ keep-empty numbers lispp)))
+ (if (not (save-match-data
+ (string-match (regexp-quote form) formrpl)))
+ (setq form (replace-match formrpl t t form))
+ (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
+ ;; Insert simple ranges, i.e. included in the current row.
+ (while (string-match
+ "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
+ form)
+ (setq form
+ (replace-match
+ (save-match-data
+ (org-table-make-reference
+ (cl-subseq fields
+ (+ (if (match-end 2) n0 0)
+ (string-to-number (match-string 1 form))
+ -1)
+ (+ (if (match-end 4) n0 0)
+ (string-to-number (match-string 3 form))))
+ keep-empty numbers lispp))
+ t t form)))
+ (setq form0 form)
+ ;; Insert the references to fields in same row
+ (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
+ (setq n (+ (string-to-number (match-string 1 form))
+ (if (match-end 2) n0 0))
+ x (nth (1- (if (= n 0) n0 (max n 1))) fields)
+ formrpl (save-match-data
+ (org-table-make-reference
+ x keep-empty numbers lispp)))
+ (when (or (not x)
+ (save-match-data
+ (string-match (regexp-quote formula) formrpl)))
+ (user-error "Invalid field specifier \"%s\""
+ (match-string 0 form)))
+ (setq form (replace-match formrpl t t form)))
+
+ (if lispp
+ (setq ev (condition-case nil
+ (eval (eval (read form)))
+ (error "#ERROR"))
+ ev (if (numberp ev) (number-to-string ev) ev)
+ ev (if duration (org-table-time-seconds-to-string
+ (string-to-number ev)
+ duration-output-format) ev))
+
+ ;; Use <...> time-stamps so that Calc can handle them.
+ (setq form
+ (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
+ ;; Internationalize local time-stamps by setting locale to
+ ;; "C".
+ (setq form
+ (replace-regexp-in-string
+ org-ts-regexp
+ (lambda (ts)
+ (let ((system-time-locale "C"))
+ (format-time-string
+ (org-time-stamp-format
+ (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
+ (apply #'encode-time
+ (save-match-data (org-parse-time-string ts))))))
+ form t t))
+
+ (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
+ form
+ (calc-eval (cons form org-tbl-calc-modes)
+ (when (and (not keep-empty) numbers) 'num)))
+ ev (if duration (org-table-time-seconds-to-string
+ (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
+ (string-to-number (org-table-time-string-to-seconds ev))
+ (string-to-number ev))
+ duration-output-format)
+ ev)))
+
+ (when org-table-formula-debug
+ (with-output-to-temp-buffer "*Substitution History*"
+ (princ (format "Substitution history of formula
+Orig: %s
+$xyz-> %s
+@r$c-> %s
+$1-> %s\n" orig formula form0 form))
+ (if (consp ev)
+ (princ (format " %s^\nError: %s"
+ (make-string (car ev) ?\-) (nth 1 ev)))
+ (princ (format "Result: %s\nFormat: %s\nFinal: %s"
+ ev (or fmt "NONE")
+ (if fmt (format fmt (string-to-number ev)) ev)))))
+ (setq bw (get-buffer-window "*Substitution History*"))
+ (org-fit-window-to-buffer bw)
+ (unless (and (called-interactively-p 'any) (not ndown))
+ (unless (let (inhibit-redisplay)
+ (y-or-n-p "Debugging Formula. Continue to next? "))
+ (org-table-align)
+ (user-error "Abort"))
+ (delete-window bw)
+ (message "")))
+ (when (consp ev) (setq fmt nil ev "#ERROR"))
+ (org-table-justify-field-maybe
+ (format org-table-formula-field-format
+ (if fmt (format fmt (string-to-number ev)) ev)))
+ (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
+ (call-interactively 'org-return)
+ (setq ndown 0)))
+ (and down (org-table-maybe-recalculate-line))
+ (or suppress-align (and org-table-may-need-update
+ (org-table-align))))))
+
+(defun org-table-put-field-property (prop value)
+ (save-excursion
+ (put-text-property (progn (skip-chars-backward "^|") (point))
+ (progn (skip-chars-forward "^|") (point))
+ prop value)))
+
+(defun org-table-get-range (desc &optional tbeg col highlight corners-only)
+ "Get a calc vector from a column, according to descriptor DESC.
+
+Optional arguments TBEG and COL can give the beginning of the table and
+the current column, to avoid unnecessary parsing.
+
+HIGHLIGHT means just highlight the range.
+
+When CORNERS-ONLY is set, only return the corners of the range as
+a list (line1 column1 line2 column2) where line1 and line2 are
+line numbers relative to beginning of table, or TBEG, and column1
+and column2 are table column numbers."
+ (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
+ (replace-regexp-in-string "\\$" "@0$" desc)
+ desc))
+ (col (or col (org-table-current-column)))
+ (tbeg (or tbeg (org-table-begin)))
+ (thisline (count-lines tbeg (line-beginning-position))))
+ (unless (string-match org-table-range-regexp desc)
+ (user-error "Invalid table range specifier `%s'" desc))
+ (let ((rangep (match-end 3))
+ (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
+ (or (save-match-data
+ (and (org-string-nw-p r)
+ (org-table--descriptor-line r thisline)))
+ thisline)))
+ (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
+ (or (save-match-data
+ (and (org-string-nw-p r)
+ (org-table--descriptor-line r thisline)))
+ thisline)))
+ (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
+ (if (or (not c) (= (string-to-number c) 0)) col
+ (+ (string-to-number c)
+ (if (memq (string-to-char c) '(?- ?+)) col 0)))))
+ (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
+ (if (or (not c) (= (string-to-number c) 0)) col
+ (+ (string-to-number c)
+ (if (memq (string-to-char c) '(?- ?+)) col 0))))))
+ (save-excursion
+ (if (and (not corners-only)
+ (or (not rangep) (and (= r1 r2) (= c1 c2))))
+ ;; Just one field.
+ (progn
+ (forward-line (- r1 thisline))
+ (while (not (looking-at org-table-dataline-regexp))
+ (forward-line))
+ (prog1 (org-trim (org-table-get-field c1))
+ (when highlight (org-table-highlight-rectangle))))
+ ;; A range, return a vector. First sort the numbers to get
+ ;; a regular rectangle.
+ (let ((first-row (min r1 r2))
+ (last-row (max r1 r2))
+ (first-column (min c1 c2))
+ (last-column (max c1 c2)))
+ (if corners-only (list first-row first-column last-row last-column)
+ ;; Copy the range values into a list.
+ (forward-line (- first-row thisline))
+ (while (not (looking-at org-table-dataline-regexp))
+ (forward-line)
+ (cl-incf first-row))
+ (org-table-goto-column first-column)
+ (let ((beg (point)))
+ (forward-line (- last-row first-row))
+ (while (not (looking-at org-table-dataline-regexp))
+ (forward-line -1))
+ (org-table-goto-column last-column)
+ (let ((end (point)))
+ (when highlight
+ (org-table-highlight-rectangle
+ beg (progn (skip-chars-forward "^|\n") (point))))
+ ;; Return string representation of calc vector.
+ (mapcar #'org-trim
+ (apply #'append
+ (org-table-copy-region beg end))))))))))))
+
+(defun org-table--descriptor-line (desc cline)
+ "Return relative line number corresponding to descriptor DESC.
+The cursor is currently in relative line number CLINE."
+ (if (string-match "\\`[0-9]+\\'" desc)
+ (aref org-table-dlines (string-to-number desc))
+ (when (or (not (string-match
+ "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
+ ;; 1 2 3 4 5 6
+ desc))
+ (and (not (match-end 3)) (not (match-end 6)))
+ (and (match-end 3) (match-end 6) (not (match-end 5))))
+ (user-error "Invalid row descriptor `%s'" desc))
+ (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
+ (hdir (match-string 2 desc))
+ (odir (match-string 5 desc))
+ (on (and (match-end 6) (string-to-number (match-string 6 desc))))
+ (rel (and (match-end 6)
+ (or (and (match-end 1) (not (match-end 3)))
+ (match-end 5)))))
+ (when (and hn (not hdir))
+ (setq cline 0)
+ (setq hdir "+")
+ (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
+ (when (and (not hn) on (not odir)) (user-error "Should never happen"))
+ (when hn
+ (setq cline
+ (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
+ (when on
+ (setq cline
+ (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
+ cline)))
+
+(defun org-table--row-type (type n i backwards relative desc)
+ "Return relative line of Nth row with type TYPE.
+Search starts from relative line I. When BACKWARDS in non-nil,
+look before I. When RELATIVE is non-nil, the reference is
+relative. DESC is the original descriptor that started the
+search, as a string."
+ (let ((l (length org-table-current-line-types)))
+ (catch :exit
+ (dotimes (_ n)
+ (while (and (cl-incf i (if backwards -1 1))
+ (>= i 0)
+ (< i l)
+ (not (eq (aref org-table-current-line-types i) type))
+ ;; We are going to cross a hline. Check if this is
+ ;; an authorized move.
+ (cond
+ ((not relative))
+ ((not (eq (aref org-table-current-line-types i) 'hline)))
+ ((eq org-table-relative-ref-may-cross-hline t))
+ ((eq org-table-relative-ref-may-cross-hline 'error)
+ (user-error "Row descriptor %s crosses hline" desc))
+ (t (cl-decf i (if backwards -1 1)) ; Step back.
+ (throw :exit nil)))))))
+ (cond ((or (< i 0) (>= i l))
+ (user-error "Row descriptor %s leads outside table" desc))
+ ;; The last hline doesn't exist. Instead, point to last row
+ ;; in table.
+ ((= i (1- l)) (1- i))
+ (t i))))
+
+(defun org-table--error-on-old-row-references (s)
+ (when (string-match "&[-+0-9I]" s)
+ (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
+
+(defun org-table-make-reference (elements keep-empty numbers lispp)
+ "Convert list ELEMENTS to something appropriate to insert into formula.
+KEEP-EMPTY indicated to keep empty fields, default is to skip them.
+NUMBERS indicates that everything should be converted to numbers.
+LISPP non-nil means to return something appropriate for a Lisp
+list, `literal' is for the format specifier L."
+ ;; Calc nan (not a number) is used for the conversion of the empty
+ ;; field to a reference for several reasons: (i) It is accepted in a
+ ;; Calc formula (e. g. "" or "()" would result in a Calc error).
+ ;; (ii) In a single field (not in range) it can be distinguished
+ ;; from "(nan)" which is the reference made from a single field
+ ;; containing "nan".
+ (if (stringp elements)
+ ;; field reference
+ (if lispp
+ (if (eq lispp 'literal)
+ elements
+ (if (and (eq elements "") (not keep-empty))
+ ""
+ (prin1-to-string
+ (if numbers (string-to-number elements) elements))))
+ (if (string-match "\\S-" elements)
+ (progn
+ (when numbers (setq elements (number-to-string
+ (string-to-number elements))))
+ (concat "(" elements ")"))
+ (if (or (not keep-empty) numbers) "(0)" "nan")))
+ ;; range reference
+ (unless keep-empty
+ (setq elements
+ (delq nil
+ (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
+ elements))))
+ (setq elements (or elements '())) ; if delq returns nil then we need '()
+ (if lispp
+ (mapconcat
+ (lambda (x)
+ (if (eq lispp 'literal)
+ x
+ (prin1-to-string (if numbers (string-to-number x) x))))
+ elements " ")
+ (concat "[" (mapconcat
+ (lambda (x)
+ (if (string-match "\\S-" x)
+ (if numbers
+ (number-to-string (string-to-number x))
+ x)
+ (if (or (not keep-empty) numbers) "0" "nan")))
+ elements
+ ",") "]"))))
+
+(defun org-table-message-once-per-second (t1 &rest args)
+ "If there has been more than one second since T1, display message.
+ARGS are passed as arguments to the `message' function. Returns
+current time if a message is printed, otherwise returns T1. If
+T1 is nil, always messages."
+ (let ((curtime (current-time)))
+ (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
+ (progn (apply 'message args)
+ curtime)
+ t1)))
+
+;;;###autoload
+(defun org-table-recalculate (&optional all noalign)
+ "Recalculate the current table line by applying all stored formulas.
+
+With prefix arg ALL, do this for all lines in the table.
+
+When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
+if ALL is the symbol `iterate',
+recompute the table until it no longer changes.
+
+If NOALIGN is not nil, do not re-align the table after the computations
+are done. This is typically used internally to save time, if it is
+known that the table will be realigned a little later anyway."
+ (interactive "P")
+ (unless (memq this-command org-recalc-commands)
+ (push this-command org-recalc-commands))
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ (if (or (eq all 'iterate) (equal all '(16)))
+ (org-table-iterate)
+ (org-table-analyze)
+ (let* ((eqlist (sort (org-table-get-stored-formulas)
+ (lambda (a b) (string< (car a) (car b)))))
+ (inhibit-redisplay (not debug-on-error))
+ (line-re org-table-dataline-regexp)
+ (log-first-time (current-time))
+ (log-last-time log-first-time)
+ (cnt 0)
+ beg end eqlcol eqlfield)
+ ;; Insert constants in all formulas.
+ (when eqlist
+ (org-table-save-field
+ ;; Expand equations, then split the equation list between
+ ;; column formulas and field formulas.
+ (dolist (eq eqlist)
+ (let* ((rhs (org-table-formula-substitute-names
+ (org-table-formula-handle-first/last-rc (cdr eq))))
+ (old-lhs (car eq))
+ (lhs
+ (org-table-formula-handle-first/last-rc
+ (cond
+ ((string-match "\\`@-?I+" old-lhs)
+ (user-error "Can't assign to hline relative reference"))
+ ((string-match "\\`$[<>]" old-lhs)
+ (let ((new (org-table-formula-handle-first/last-rc
+ old-lhs)))
+ (when (assoc new eqlist)
+ (user-error "\"%s=\" formula tries to overwrite \
+existing formula for column %s"
+ old-lhs
+ new))
+ new))
+ (t old-lhs)))))
+ (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
+ (push (cons lhs rhs) eqlcol)
+ (push (cons lhs rhs) eqlfield))))
+ (setq eqlcol (nreverse eqlcol))
+ ;; Expand ranges in lhs of formulas
+ (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
+ ;; Get the correct line range to process.
+ (if all
+ (progn
+ (setq end (copy-marker (org-table-end)))
+ (goto-char (setq beg org-table-current-begin-pos))
+ (cond
+ ((re-search-forward org-table-calculate-mark-regexp end t)
+ ;; This is a table with marked lines, compute selected
+ ;; lines.
+ (setq line-re org-table-recalculate-regexp))
+ ;; Move forward to the first non-header line.
+ ((and (re-search-forward org-table-dataline-regexp end t)
+ (re-search-forward org-table-hline-regexp end t)
+ (re-search-forward org-table-dataline-regexp end t))
+ (setq beg (match-beginning 0)))
+ ;; Just leave BEG at the start of the table.
+ (t nil)))
+ (setq beg (line-beginning-position)
+ end (copy-marker (line-beginning-position 2))))
+ (goto-char beg)
+ ;; Mark named fields untouchable. Also check if several
+ ;; field/range formulas try to set the same field.
+ (remove-text-properties beg end '(org-untouchable t))
+ (let ((current-line (count-lines org-table-current-begin-pos
+ (line-beginning-position)))
+ seen-fields)
+ (dolist (eq eqlfield)
+ (let* ((name (car eq))
+ (location (assoc name org-table-named-field-locations))
+ (eq-line (or (nth 1 location)
+ (and (string-match "\\`@\\([0-9]+\\)" name)
+ (aref org-table-dlines
+ (string-to-number
+ (match-string 1 name))))))
+ (reference
+ (if location
+ ;; Turn field coordinates associated to NAME
+ ;; into an absolute reference.
+ (format "@%d$%d"
+ (org-table-line-to-dline eq-line)
+ (nth 2 location))
+ name)))
+ (when (member reference seen-fields)
+ (user-error "Several field/range formulas try to set %s"
+ reference))
+ (push reference seen-fields)
+ (when (or all (eq eq-line current-line))
+ (org-table-goto-field name)
+ (org-table-put-field-property :org-untouchable t)))))
+ ;; Evaluate the column formulas, but skip fields covered by
+ ;; field formulas.
+ (goto-char beg)
+ (while (re-search-forward line-re end t)
+ (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
+ ;; Unprotected line, recalculate.
+ (cl-incf cnt)
+ (when all
+ (setq log-last-time
+ (org-table-message-once-per-second
+ log-last-time
+ "Re-applying formulas to full table...(line %d)" cnt)))
+ (if (markerp org-last-recalc-line)
+ (move-marker org-last-recalc-line (line-beginning-position))
+ (setq org-last-recalc-line
+ (copy-marker (line-beginning-position))))
+ (dolist (entry eqlcol)
+ (goto-char org-last-recalc-line)
+ (org-table-goto-column
+ (string-to-number (substring (car entry) 1)) nil 'force)
+ (unless (get-text-property (point) :org-untouchable)
+ (org-table-eval-formula
+ nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
+ ;; Evaluate the field formulas.
+ (dolist (eq eqlfield)
+ (let ((reference (car eq))
+ (formula (cdr eq)))
+ (setq log-last-time
+ (org-table-message-once-per-second
+ (and all log-last-time)
+ "Re-applying formula to field: %s" (car eq)))
+ (org-table-goto-field
+ reference
+ ;; Possibly create a new column, as long as
+ ;; `org-table-formula-create-columns' allows it.
+ (let ((column-count (progn (end-of-line)
+ (1- (org-table-current-column)))))
+ (lambda (column)
+ (when (> column 1000)
+ (user-error "Formula column target too large"))
+ (and (> column column-count)
+ (or (eq org-table-formula-create-columns t)
+ (and (eq org-table-formula-create-columns 'warn)
+ (progn
+ (org-display-warning
+ "Out-of-bounds formula added columns")
+ t))
+ (and (eq org-table-formula-create-columns 'prompt)
+ (yes-or-no-p
+ "Out-of-bounds formula. Add columns? ")))))))
+ (org-table-eval-formula nil formula t t t t))))
+ ;; Clean up markers and internal text property.
+ (remove-text-properties (point-min) (point-max) '(org-untouchable t))
+ (set-marker end nil)
+ (unless noalign
+ (when org-table-may-need-update (org-table-align))
+ (when all
+ (org-table-message-once-per-second
+ log-first-time "Re-applying formulas to %d lines... done" cnt)))
+ (org-table-message-once-per-second
+ (and all log-first-time) "Re-applying formulas... done")))))
+
+;;;###autoload
+(defun org-table-iterate (&optional arg)
+ "Recalculate the table until it does not change anymore.
+The maximum number of iterations is 10, but you can choose a different value
+with the prefix ARG."
+ (interactive "P")
+ (let ((imax (if arg (prefix-numeric-value arg) 10))
+ (i 0)
+ (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
+ thistbl)
+ (catch 'exit
+ (while (< i imax)
+ (setq i (1+ i))
+ (org-table-recalculate 'all)
+ (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
+ (if (not (string= lasttbl thistbl))
+ (setq lasttbl thistbl)
+ (if (> i 1)
+ (message "Convergence after %d iterations" i)
+ (message "Table was already stable"))
+ (throw 'exit t)))
+ (user-error "No convergence after %d iterations" i))))
+
+;;;###autoload
+(defun org-table-recalculate-buffer-tables ()
+ "Recalculate all tables in the current buffer."
+ (interactive)
+ (org-with-wide-buffer
+ (org-table-map-tables
+ (lambda ()
+ ;; Reason for separate `org-table-align': When repeating
+ ;; (org-table-recalculate t) `org-table-may-need-update' gets in
+ ;; the way.
+ (org-table-recalculate t t)
+ (org-table-align))
+ t)))
+
+;;;###autoload
+(defun org-table-iterate-buffer-tables ()
+ "Iterate all tables in the buffer, to converge inter-table dependencies."
+ (interactive)
+ (let* ((imax 10)
+ (i imax)
+ (checksum (md5 (buffer-string)))
+ c1)
+ (org-with-wide-buffer
+ (catch 'exit
+ (while (> i 0)
+ (setq i (1- i))
+ (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
+ (if (equal checksum (setq c1 (md5 (buffer-string))))
+ (progn
+ (org-table-map-tables #'org-table-align t)
+ (message "Convergence after %d iterations" (- imax i))
+ (throw 'exit t))
+ (setq checksum c1)))
+ (org-table-map-tables #'org-table-align t)
+ (user-error "No convergence after %d iterations" imax)))))
+
+(defun org-table-calc-current-TBLFM (&optional arg)
+ "Apply the #+TBLFM in the line at point to the table."
+ (interactive "P")
+ (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
+ (let ((formula (buffer-substring
+ (line-beginning-position)
+ (line-end-position))))
+ (save-excursion
+ ;; Insert a temporary formula at right after the table
+ (goto-char (org-table-TBLFM-begin))
+ (let ((s (point-marker)))
+ (insert formula "\n")
+ (let ((e (point-marker)))
+ ;; Recalculate the table.
+ (beginning-of-line 0) ; move to the inserted line
+ (skip-chars-backward " \r\n\t")
+ (unwind-protect
+ (org-call-with-arg #'org-table-recalculate (or arg t))
+ ;; Delete the formula inserted temporarily.
+ (delete-region s e)
+ (set-marker s nil)
+ (set-marker e nil)))))))
+
+(defun org-table-TBLFM-begin ()
+ "Find the beginning of the TBLFM lines and return its position.
+Return nil when the beginning of TBLFM line was not found."
+ (save-excursion
+ (when (progn (forward-line 1)
+ (re-search-backward org-table-TBLFM-begin-regexp nil t))
+ (line-beginning-position 2))))
+
+(defun org-table-expand-lhs-ranges (equations)
+ "Expand list of formulas.
+If some of the RHS in the formulas are ranges or a row reference,
+expand them to individual field equations for each field. This
+function assumes the table is already analyzed (i.e., using
+`org-table-analyze')."
+ (let (res)
+ (dolist (e equations (nreverse res))
+ (let ((lhs (car e))
+ (rhs (cdr e)))
+ (cond
+ ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
+ ;; This just refers to one fixed field.
+ (push e res))
+ ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
+ ;; This just refers to one fixed named field.
+ (push e res))
+ ((string-match-p "\\`\\$[0-9]+\\'" lhs)
+ ;; Column formulas are treated specially and are not
+ ;; expanded.
+ (push e res))
+ ((string-match "\\`@[0-9]+\\'" lhs)
+ (dotimes (ic org-table-current-ncol)
+ (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
+ rhs)
+ res)))
+ (t
+ (let* ((range (org-table-get-range
+ lhs org-table-current-begin-pos 1 nil 'corners))
+ (r1 (org-table-line-to-dline (nth 0 range)))
+ (c1 (nth 1 range))
+ (r2 (org-table-line-to-dline (nth 2 range) 'above))
+ (c2 (nth 3 range)))
+ (cl-loop for ir from r1 to r2 do
+ (cl-loop for ic from c1 to c2 do
+ (push (cons (propertize
+ (format "@%d$%d" ir ic) :orig-eqn e)
+ rhs)
+ res))))))))))
+
+(defun org-table-formula-handle-first/last-rc (s)
+ "Replace @<, @>, $<, $> with first/last row/column of the table.
+So @< and $< will always be replaced with @1 and $1, respectively.
+The advantage of these special markers are that structure editing of
+the table will not change them, while @1 and $1 will be modified
+when a line/row is swapped out of that privileged position. So for
+formulas that use a range of rows or columns, it may often be better
+to anchor the formula with \"I\" row markers, or to offset from the
+borders of the table using the @< @> $< $> makers."
+ (let (n nmax len char (start 0))
+ (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
+ s start)
+ (if (match-end 3)
+ (setq start (match-end 3))
+ (setq nmax (if (equal (match-string 1 s) "@")
+ (1- (length org-table-dlines))
+ org-table-current-ncol)
+ len (- (match-end 2) (match-beginning 2))
+ char (string-to-char (match-string 2 s))
+ n (if (= char ?<)
+ len
+ (- nmax len -1)))
+ (if (or (< n 1) (> n nmax))
+ (user-error "Reference \"%s\" in expression \"%s\" points outside table"
+ (match-string 0 s) s))
+ (setq start (match-beginning 0))
+ (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
+ s)
+
+(defun org-table-formula-substitute-names (f)
+ "Replace $const with values in string F."
+ (let ((start 0)
+ (pp (/= (string-to-char f) ?'))
+ (duration (string-match-p ";.*[Tt].*\\'" f))
+ (new (replace-regexp-in-string ; Check for column names.
+ org-table-column-name-regexp
+ (lambda (m)
+ (concat "$" (cdr (assoc (match-string 1 m)
+ org-table-column-names))))
+ f t t)))
+ ;; Parameters and constants.
+ (while (setq start
+ (string-match
+ "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
+ new start))
+ (if (match-end 2) (setq start (match-end 2))
+ (cl-incf start)
+ ;; When a duration is expected, convert value on the fly.
+ (let ((value
+ (save-match-data
+ (let ((v (org-table-get-constant (match-string 1 new))))
+ (if (and (org-string-nw-p v) duration)
+ (org-table-time-string-to-seconds v)
+ v)))))
+ (when value
+ (setq new (replace-match
+ (concat (and pp "(") value (and pp ")")) t t new))))))
+ (if org-table-formula-debug (propertize new :orig-formula f) new)))
+
+(defun org-table-get-constant (const)
+ "Find the value for a parameter or constant in a formula.
+Parameters get priority."
+ (or (cdr (assoc const org-table-local-parameters))
+ (cdr (assoc const org-table-formula-constants-local))
+ (cdr (assoc const org-table-formula-constants))
+ (and (fboundp 'constants-get) (constants-get const))
+ (and (string= (substring const 0 (min 5 (length const))) "PROP_")
+ (org-entry-get nil (substring const 5) 'inherit))
+ "#UNDEFINED_NAME"))
+
+(defvar org-table-fedit-map
+ (let ((map (make-sparse-keymap)))
+ (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
+ (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
+ (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
+ (org-defkey map "\C-c'" 'org-table-fedit-finish)
+ (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
+ (org-defkey map "\C-c?" 'org-table-show-reference)
+ (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
+ (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
+ (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
+ (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
+ (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
+ (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
+ (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
+ (org-defkey map [(meta down)] 'org-table-fedit-scroll)
+ (org-defkey map [(meta tab)] 'lisp-complete-symbol)
+ (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
+ (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
+ (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
+ (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
+ (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
+ map))
+
+(easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
+ '("Edit-Formulas"
+ ["Finish and Install" org-table-fedit-finish t]
+ ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
+ ["Abort" org-table-fedit-abort t]
+ "--"
+ ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
+ ["Complete Lisp Symbol" lisp-complete-symbol t]
+ "--"
+ "Shift Reference at Point"
+ ["Up" org-table-fedit-ref-up t]
+ ["Down" org-table-fedit-ref-down t]
+ ["Left" org-table-fedit-ref-left t]
+ ["Right" org-table-fedit-ref-right t]
+ "-"
+ "Change Test Row for Column Formulas"
+ ["Up" org-table-fedit-line-up t]
+ ["Down" org-table-fedit-line-down t]
+ "--"
+ ["Scroll Table Window" org-table-fedit-scroll t]
+ ["Scroll Table Window down" org-table-fedit-scroll-down t]
+ ["Show Table Grid" org-table-fedit-toggle-coordinates
+ :style toggle :selected (with-current-buffer (marker-buffer org-pos)
+ org-table-overlay-coordinates)]
+ "--"
+ ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
+ :style toggle :selected org-table-buffer-is-an]))
+
+(defvar org-pos)
+(defvar org-table--fedit-source nil
+ "Position of the TBLFM line being edited.")
+
+;;;###autoload
+(defun org-table-edit-formulas ()
+ "Edit the formulas of the current table in a separate buffer."
+ (interactive)
+ (let ((at-tblfm (org-at-TBLFM-p)))
+ (unless (or at-tblfm (org-at-table-p))
+ (user-error "Not at a table"))
+ (save-excursion
+ ;; Move point within the table before analyzing it.
+ (when at-tblfm (re-search-backward "^[ \t]*|"))
+ (org-table-analyze))
+ (let ((key (org-table-current-field-formula 'key 'noerror))
+ (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
+ #'org-table-formula-less-p))
+ (pos (point-marker))
+ (source (copy-marker (line-beginning-position)))
+ (startline 1)
+ (wc (current-window-configuration))
+ (sel-win (selected-window))
+ (titles '((column . "# Column Formulas\n")
+ (field . "# Field and Range Formulas\n")
+ (named . "# Named Field Formulas\n"))))
+ (org-switch-to-buffer-other-window "*Edit Formulas*")
+ (erase-buffer)
+ ;; Keep global-font-lock-mode from turning on font-lock-mode
+ (let ((font-lock-global-modes '(not fundamental-mode)))
+ (fundamental-mode))
+ (setq-local font-lock-global-modes (list 'not major-mode))
+ (setq-local org-pos pos)
+ (setq-local org-table--fedit-source source)
+ (setq-local org-window-configuration wc)
+ (setq-local org-selected-window sel-win)
+ (use-local-map org-table-fedit-map)
+ (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
+ (easy-menu-add org-table-fedit-menu)
+ (setq startline (org-current-line))
+ (dolist (entry eql)
+ (let* ((type (cond
+ ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry))
+ 'column)
+ ((equal (string-to-char (car entry)) ?@) 'field)
+ (t 'named)))
+ (title (assq type titles)))
+ (when title
+ (unless (bobp) (insert "\n"))
+ (insert
+ (org-add-props (cdr title) nil 'face font-lock-comment-face))
+ (setq titles (remove title titles)))
+ (when (equal key (car entry)) (setq startline (org-current-line)))
+ (let ((s (concat
+ (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
+ (car entry) " = " (cdr entry) "\n")))
+ (remove-text-properties 0 (length s) '(face nil) s)
+ (insert s))))
+ (when (eq org-table-use-standard-references t)
+ (org-table-fedit-toggle-ref-type))
+ (org-goto-line startline)
+ (message "%s" (substitute-command-keys "\\<org-mode-map>\
+Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
+See menu for more commands.")))))
+
+(defun org-table-fedit-post-command ()
+ (when (not (memq this-command '(lisp-complete-symbol)))
+ (let ((win (selected-window)))
+ (save-excursion
+ (ignore-errors (org-table-show-reference))
+ (select-window win)))))
+
+(defun org-table-formula-to-user (s)
+ "Convert a formula from internal to user representation."
+ (if (eq org-table-use-standard-references t)
+ (org-table-convert-refs-to-an s)
+ s))
+
+(defun org-table-formula-from-user (s)
+ "Convert a formula from user to internal representation."
+ (if org-table-use-standard-references
+ (org-table-convert-refs-to-rc s)
+ s))
+
+(defun org-table-convert-refs-to-rc (s)
+ "Convert spreadsheet references from A7 to @7$28.
+Works for single references, but also for entire formulas and even the
+full TBLFM line."
+ (let ((start 0))
+ (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
+ (cond
+ ((match-end 3)
+ ;; format match, just advance
+ (setq start (match-end 0)))
+ ((and (> (match-beginning 0) 0)
+ (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
+ (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
+ ;; 3.e5 or something like this.
+ (setq start (match-end 0)))
+ ((or (> (- (match-end 1) (match-beginning 1)) 2)
+ ;; (member (match-string 1 s)
+ ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
+ )
+ ;; function name, just advance
+ (setq start (match-end 0)))
+ (t
+ (setq start (match-beginning 0)
+ s (replace-match
+ (if (equal (match-string 2 s) "&")
+ (format "$%d" (org-letters-to-number (match-string 1 s)))
+ (format "@%d$%d"
+ (string-to-number (match-string 2 s))
+ (org-letters-to-number (match-string 1 s))))
+ t t s)))))
+ s))
+
+(defun org-table-convert-refs-to-an (s)
+ "Convert spreadsheet references from to @7$28 to AB7.
+Works for single references, but also for entire formulas and even the
+full TBLFM line."
+ (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
+ (setq s (replace-match
+ (format "%s%d"
+ (org-number-to-letters
+ (string-to-number (match-string 2 s)))
+ (string-to-number (match-string 1 s)))
+ t t s)))
+ (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
+ (setq s (replace-match (concat "\\1"
+ (org-number-to-letters
+ (string-to-number (match-string 2 s))) "&")
+ t nil s)))
+ s)
+
+(defun org-letters-to-number (s)
+ "Convert a base 26 number represented by letters into an integer.
+For example: AB -> 28."
+ (let ((n 0))
+ (setq s (upcase s))
+ (while (> (length s) 0)
+ (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
+ s (substring s 1)))
+ n))
+
+(defun org-number-to-letters (n)
+ "Convert an integer into a base 26 number represented by letters.
+For example: 28 -> AB."
+ (let ((s ""))
+ (while (> n 0)
+ (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
+ n (/ (1- n) 26)))
+ s))
+
+(defun org-table-time-string-to-seconds (s)
+ "Convert a time string into numerical duration in seconds.
+S can be a string matching either -?HH:MM:SS or -?HH:MM.
+If S is a string representing a number, keep this number."
+ (if (equal s "")
+ s
+ (let (hour minus min sec res)
+ (cond
+ ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
+ (setq minus (< 0 (length (match-string 1 s)))
+ hour (string-to-number (match-string 2 s))
+ min (string-to-number (match-string 3 s))
+ sec (string-to-number (match-string 4 s)))
+ (if minus
+ (setq res (- (+ (* hour 3600) (* min 60) sec)))
+ (setq res (+ (* hour 3600) (* min 60) sec))))
+ ((and (not (string-match org-ts-regexp-both s))
+ (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
+ (setq minus (< 0 (length (match-string 1 s)))
+ hour (string-to-number (match-string 2 s))
+ min (string-to-number (match-string 3 s)))
+ (if minus
+ (setq res (- (+ (* hour 3600) (* min 60))))
+ (setq res (+ (* hour 3600) (* min 60)))))
+ (t (setq res (string-to-number s))))
+ (number-to-string res))))
+
+(defun org-table-time-seconds-to-string (secs &optional output-format)
+ "Convert a number of seconds to a time string.
+If OUTPUT-FORMAT is non-nil, return a number of days, hours,
+minutes or seconds."
+ (let* ((secs0 (abs secs))
+ (res
+ (cond ((eq output-format 'days)
+ (format "%.3f" (/ (float secs0) 86400)))
+ ((eq output-format 'hours)
+ (format "%.2f" (/ (float secs0) 3600)))
+ ((eq output-format 'minutes)
+ (format "%.1f" (/ (float secs0) 60)))
+ ((eq output-format 'seconds)
+ (format "%d" secs0))
+ (t (format-seconds "%.2h:%.2m:%.2s" secs0)))))
+ (if (< secs 0) (concat "-" res) res)))
+
+(defun org-table-fedit-convert-buffer (function)
+ "Convert all references in this buffer, using FUNCTION."
+ (let ((origin (copy-marker (line-beginning-position))))
+ (goto-char (point-min))
+ (while (not (eobp))
+ (insert (funcall function (buffer-substring (point) (line-end-position))))
+ (delete-region (point) (line-end-position))
+ (forward-line))
+ (goto-char origin)
+ (set-marker origin nil)))
+
+(defun org-table-fedit-toggle-ref-type ()
+ "Convert all references in the buffer from B3 to @3$2 and back."
+ (interactive)
+ (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
+ (org-table-fedit-convert-buffer
+ (if org-table-buffer-is-an
+ 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
+ (message "Reference type switched to %s"
+ (if org-table-buffer-is-an "A1 etc" "@row$column")))
+
+(defun org-table-fedit-ref-up ()
+ "Shift the reference at point one row/hline up."
+ (interactive)
+ (org-table-fedit-shift-reference 'up))
+(defun org-table-fedit-ref-down ()
+ "Shift the reference at point one row/hline down."
+ (interactive)
+ (org-table-fedit-shift-reference 'down))
+(defun org-table-fedit-ref-left ()
+ "Shift the reference at point one field to the left."
+ (interactive)
+ (org-table-fedit-shift-reference 'left))
+(defun org-table-fedit-ref-right ()
+ "Shift the reference at point one field to the right."
+ (interactive)
+ (org-table-fedit-shift-reference 'right))
+
+(defun org-table-fedit-shift-reference (dir)
+ (cond
+ ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
+ (if (memq dir '(left right))
+ (org-rematch-and-replace 1 (eq dir 'left))
+ (user-error "Cannot shift reference in this direction")))
+ ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
+ ;; A B3-like reference
+ (if (memq dir '(up down))
+ (org-rematch-and-replace 2 (eq dir 'up))
+ (org-rematch-and-replace 1 (eq dir 'left))))
+ ((org-in-regexp
+ "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
+ ;; An internal reference
+ (if (memq dir '(up down))
+ (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
+ (org-rematch-and-replace 5 (eq dir 'left))))))
+
+(defun org-rematch-and-replace (n &optional decr hline)
+ "Re-match the group N, and replace it with the shifted reference."
+ (or (match-end n) (user-error "Cannot shift reference in this direction"))
+ (goto-char (match-beginning n))
+ (and (looking-at (regexp-quote (match-string n)))
+ (replace-match (org-table-shift-refpart (match-string 0) decr hline)
+ t t)))
+
+(defun org-table-shift-refpart (ref &optional decr hline)
+ "Shift a reference part REF.
+If DECR is set, decrease the references row/column, else increase.
+If HLINE is set, this may be a hline reference, it certainly is not
+a translation reference."
+ (save-match-data
+ (let* ((sign (string-match "^[-+]" ref)) n)
+
+ (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
+ (cond
+ ((and hline (string-match "^I+" ref))
+ (setq n (string-to-number (concat sign (number-to-string (length ref)))))
+ (setq n (+ n (if decr -1 1)))
+ (if (= n 0) (setq n (+ n (if decr -1 1))))
+ (if sign
+ (setq sign (if (< n 0) "-" "+") n (abs n))
+ (setq n (max 1 n)))
+ (concat sign (make-string n ?I)))
+
+ ((string-match "^[0-9]+" ref)
+ (setq n (string-to-number (concat sign ref)))
+ (setq n (+ n (if decr -1 1)))
+ (if sign
+ (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
+ (number-to-string (max 1 n))))
+
+ ((string-match "^[a-zA-Z]+" ref)
+ (org-number-to-letters
+ (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
+
+ (t (user-error "Cannot shift reference"))))))
+
+(defun org-table-fedit-toggle-coordinates ()
+ "Toggle the display of coordinates in the referenced table."
+ (interactive)
+ (let ((pos (marker-position org-pos)))
+ (with-current-buffer (marker-buffer org-pos)
+ (save-excursion
+ (goto-char pos)
+ (org-table-toggle-coordinate-overlays)))))
+
+(defun org-table-fedit-finish (&optional arg)
+ "Parse the buffer for formula definitions and install them.
+With prefix ARG, apply the new formulas to the table."
+ (interactive "P")
+ (org-table-remove-rectangle-highlight)
+ (when org-table-use-standard-references
+ (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
+ (setq org-table-buffer-is-an nil))
+ (let ((pos org-pos)
+ (sel-win org-selected-window)
+ (source org-table--fedit-source)
+ eql)
+ (goto-char (point-min))
+ (while (re-search-forward
+ "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
+ nil t)
+ (let ((var (match-string 1))
+ (form (org-trim (match-string 3))))
+ (unless (equal form "")
+ (while (string-match "[ \t]*\n[ \t]*" form)
+ (setq form (replace-match " " t t form)))
+ (when (assoc var eql)
+ (user-error "Double formulas for %s" var))
+ (push (cons var form) eql))))
+ (set-window-configuration org-window-configuration)
+ (select-window sel-win)
+ (goto-char source)
+ (org-table-store-formulas eql)
+ (set-marker pos nil)
+ (set-marker source nil)
+ (kill-buffer "*Edit Formulas*")
+ (if arg
+ (org-table-recalculate 'all)
+ (message "New formulas installed - press C-u C-c C-c to apply."))))
+
+(defun org-table-fedit-abort ()
+ "Abort editing formulas, without installing the changes."
+ (interactive)
+ (org-table-remove-rectangle-highlight)
+ (let ((pos org-pos) (sel-win org-selected-window))
+ (set-window-configuration org-window-configuration)
+ (select-window sel-win)
+ (goto-char pos)
+ (move-marker pos nil)
+ (message "Formula editing aborted without installing changes")))
+
+(defun org-table-fedit-lisp-indent ()
+ "Pretty-print and re-indent Lisp expressions in the Formula Editor."
+ (interactive)
+ (let ((pos (point)) beg end ind)
+ (beginning-of-line 1)
+ (cond
+ ((looking-at "[ \t]")
+ (goto-char pos)
+ (call-interactively 'lisp-indent-line))
+ ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
+ ((not (fboundp 'pp-buffer))
+ (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
+ ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
+ (goto-char (- (match-end 0) 2))
+ (setq beg (point))
+ (setq ind (make-string (current-column) ?\ ))
+ (condition-case nil (forward-sexp 1)
+ (error
+ (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
+ (setq end (point))
+ (save-restriction
+ (narrow-to-region beg end)
+ (if (eq last-command this-command)
+ (progn
+ (goto-char (point-min))
+ (setq this-command nil)
+ (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
+ (replace-match " ")))
+ (pp-buffer)
+ (untabify (point-min) (point-max))
+ (goto-char (1+ (point-min)))
+ (while (re-search-forward "^." nil t)
+ (beginning-of-line 1)
+ (insert ind))
+ (goto-char (point-max))
+ (org-delete-backward-char 1)))
+ (goto-char beg))
+ (t nil))))
+
+(defvar org-show-positions nil)
+
+(defun org-table-show-reference (&optional local)
+ "Show the location/value of the $ expression at point.
+When LOCAL is non-nil, show references for the table at point."
+ (interactive)
+ (org-table-remove-rectangle-highlight)
+ (when local (org-table-analyze))
+ (catch 'exit
+ (let ((pos (if local (point) org-pos))
+ (face2 'highlight)
+ (org-inhibit-highlight-removal t)
+ (win (selected-window))
+ (org-show-positions nil)
+ var name e what match dest)
+ (setq what (cond
+ ((org-in-regexp "^@[0-9]+[ \t=]")
+ (setq match (concat (substring (match-string 0) 0 -1)
+ "$1.."
+ (substring (match-string 0) 0 -1)
+ "$100"))
+ 'range)
+ ((or (org-in-regexp org-table-range-regexp2)
+ (org-in-regexp org-table-translate-regexp)
+ (org-in-regexp org-table-range-regexp))
+ (setq match
+ (save-match-data
+ (org-table-convert-refs-to-rc (match-string 0))))
+ 'range)
+ ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
+ ((org-in-regexp "\\$[0-9]+") 'column)
+ ((not local) nil)
+ (t (user-error "No reference at point")))
+ match (and what (or match (match-string 0))))
+ (when (and match (not (equal (match-beginning 0) (point-at-bol))))
+ (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
+ 'secondary-selection))
+ (add-hook 'before-change-functions
+ #'org-table-remove-rectangle-highlight)
+ (when (eq what 'name) (setq var (substring match 1)))
+ (when (eq what 'range)
+ (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
+ (setq match (org-table-formula-substitute-names match)))
+ (unless local
+ (save-excursion
+ (end-of-line)
+ (re-search-backward "^\\S-" nil t)
+ (beginning-of-line)
+ (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
+\\([0-9]+\\|&\\)\\) *=")
+ (setq dest
+ (save-match-data
+ (org-table-convert-refs-to-rc (match-string 1))))
+ (org-table-add-rectangle-overlay
+ (match-beginning 1) (match-end 1) face2))))
+ (if (and (markerp pos) (marker-buffer pos))
+ (if (get-buffer-window (marker-buffer pos))
+ (select-window (get-buffer-window (marker-buffer pos)))
+ (org-switch-to-buffer-other-window (get-buffer-window
+ (marker-buffer pos)))))
+ (goto-char pos)
+ (org-table-force-dataline)
+ (let ((table-start
+ (if local org-table-current-begin-pos (org-table-begin))))
+ (when dest
+ (setq name (substring dest 1))
+ (cond
+ ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
+ (org-table-goto-field dest))
+ ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
+ dest)
+ (org-table-goto-field dest))
+ (t (org-table-goto-column (string-to-number name))))
+ (move-marker pos (point))
+ (org-table-highlight-rectangle nil nil face2))
+ (cond
+ ((equal dest match))
+ ((not match))
+ ((eq what 'range)
+ (ignore-errors (org-table-get-range match table-start nil 'highlight)))
+ ((setq e (assoc var org-table-named-field-locations))
+ (org-table-goto-field var)
+ (org-table-highlight-rectangle)
+ (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
+ ((setq e (assoc var org-table-column-names))
+ (org-table-goto-column (string-to-number (cdr e)))
+ (org-table-highlight-rectangle)
+ (goto-char table-start)
+ (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
+ (org-table-end) t)
+ (progn
+ (goto-char (match-beginning 1))
+ (org-table-highlight-rectangle)
+ (message "Named column (column %s)" (cdr e)))
+ (user-error "Column name not found")))
+ ((eq what 'column)
+ ;; Column number.
+ (org-table-goto-column (string-to-number (substring match 1)))
+ (org-table-highlight-rectangle)
+ (message "Column %s" (substring match 1)))
+ ((setq e (assoc var org-table-local-parameters))
+ (goto-char table-start)
+ (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
+ (progn
+ (goto-char (match-beginning 1))
+ (org-table-highlight-rectangle)
+ (message "Local parameter."))
+ (user-error "Parameter not found")))
+ ((not var) (user-error "No reference at point"))
+ ((setq e (assoc var org-table-formula-constants-local))
+ (message "Local Constant: $%s=%s in #+CONSTANTS line."
+ var (cdr e)))
+ ((setq e (assoc var org-table-formula-constants))
+ (message "Constant: $%s=%s in `org-table-formula-constants'."
+ var (cdr e)))
+ ((setq e (and (fboundp 'constants-get) (constants-get var)))
+ (message "Constant: $%s=%s, from `constants.el'%s."
+ var e (format " (%s units)" constants-unit-system)))
+ (t (user-error "Undefined name $%s" var)))
+ (goto-char pos)
+ (when (and org-show-positions
+ (not (memq this-command '(org-table-fedit-scroll
+ org-table-fedit-scroll-down))))
+ (push pos org-show-positions)
+ (push table-start org-show-positions)
+ (let ((min (apply 'min org-show-positions))
+ (max (apply 'max org-show-positions)))
+ (set-window-start (selected-window) min)
+ (goto-char max)
+ (or (pos-visible-in-window-p max)
+ (set-window-start (selected-window) max)))))
+ (select-window win))))
+
+(defun org-table-force-dataline ()
+ "Make sure the cursor is in a dataline in a table."
+ (unless (save-excursion
+ (beginning-of-line 1)
+ (looking-at org-table-dataline-regexp))
+ (let* ((re org-table-dataline-regexp)
+ (p1 (save-excursion (re-search-forward re nil 'move)))
+ (p2 (save-excursion (re-search-backward re nil 'move))))
+ (cond ((and p1 p2)
+ (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
+ p1 p2)))
+ ((or p1 p2) (goto-char (or p1 p2)))
+ (t (user-error "No table dataline around here"))))))
+
+(defun org-table-fedit-line-up ()
+ "Move cursor one line up in the window showing the table."
+ (interactive)
+ (org-table-fedit-move 'previous-line))
+
+(defun org-table-fedit-line-down ()
+ "Move cursor one line down in the window showing the table."
+ (interactive)
+ (org-table-fedit-move 'next-line))
+
+(defun org-table-fedit-move (command)
+ "Move the cursor in the window showing the table.
+Use COMMAND to do the motion, repeat if necessary to end up in a data line."
+ (let ((org-table-allow-automatic-line-recalculation nil)
+ (pos org-pos) (win (selected-window)) p)
+ (select-window (get-buffer-window (marker-buffer org-pos)))
+ (setq p (point))
+ (call-interactively command)
+ (while (and (org-at-table-p)
+ (org-at-table-hline-p))
+ (call-interactively command))
+ (or (org-at-table-p) (goto-char p))
+ (move-marker pos (point))
+ (select-window win)))
+
+(defun org-table-fedit-scroll (N)
+ (interactive "p")
+ (let ((other-window-scroll-buffer (marker-buffer org-pos)))
+ (scroll-other-window N)))
+
+(defun org-table-fedit-scroll-down (N)
+ (interactive "p")
+ (org-table-fedit-scroll (- N)))
+
+(defvar org-table-rectangle-overlays nil)
+
+(defun org-table-add-rectangle-overlay (beg end &optional face)
+ "Add a new overlay."
+ (let ((ov (make-overlay beg end)))
+ (overlay-put ov 'face (or face 'secondary-selection))
+ (push ov org-table-rectangle-overlays)))
+
+(defun org-table-highlight-rectangle (&optional beg end face)
+ "Highlight rectangular region in a table.
+When buffer positions BEG and END are provided, use them to
+delimit the region to highlight. Otherwise, refer to point. Use
+FACE, when non-nil, for the highlight."
+ (let* ((beg (or beg (point)))
+ (end (or end (point)))
+ (b (min beg end))
+ (e (max beg end))
+ (start-coordinates
+ (save-excursion
+ (goto-char b)
+ (cons (line-beginning-position) (org-table-current-column))))
+ (end-coordinates
+ (save-excursion
+ (goto-char e)
+ (cons (line-beginning-position) (org-table-current-column)))))
+ (when (boundp 'org-show-positions)
+ (setq org-show-positions (cons b (cons e org-show-positions))))
+ (goto-char (car start-coordinates))
+ (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
+ (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
+ (last-row (car end-coordinates)))
+ (while (<= (point) last-row)
+ (when (looking-at org-table-dataline-regexp)
+ (org-table-goto-column column-start)
+ (skip-chars-backward "^|\n")
+ (let ((p (point)))
+ (org-table-goto-column column-end)
+ (skip-chars-forward "^|\n")
+ (org-table-add-rectangle-overlay p (point) face)))
+ (forward-line)))
+ (goto-char (car start-coordinates)))
+ (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
+
+(defun org-table-remove-rectangle-highlight (&rest _ignore)
+ "Remove the rectangle overlays."
+ (unless org-inhibit-highlight-removal
+ (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
+ (mapc 'delete-overlay org-table-rectangle-overlays)
+ (setq org-table-rectangle-overlays nil)))
+
+(defvar-local org-table-coordinate-overlays nil
+ "Collects the coordinate grid overlays, so that they can be removed.")
+
+(defun org-table-overlay-coordinates ()
+ "Add overlays to the table at point, to show row/column coordinates."
+ (interactive)
+ (mapc 'delete-overlay org-table-coordinate-overlays)
+ (setq org-table-coordinate-overlays nil)
+ (save-excursion
+ (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
+ (goto-char (org-table-begin))
+ (while (org-at-table-p)
+ (setq eol (point-at-eol))
+ (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
+ (push ov org-table-coordinate-overlays)
+ (setq hline (looking-at org-table-hline-regexp))
+ (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
+ (format "%4d" (setq id (1+ id)))))
+ (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
+ (when hline
+ (setq ic 0)
+ (while (re-search-forward "[+|]\\(-+\\)" eol t)
+ (setq beg (1+ (match-beginning 0))
+ ic (1+ ic)
+ s1 (concat "$" (int-to-string ic))
+ s2 (org-number-to-letters ic)
+ str (if (eq org-table-use-standard-references t) s2 s1))
+ (setq ov (make-overlay beg (+ beg (length str))))
+ (push ov org-table-coordinate-overlays)
+ (org-overlay-display ov str 'org-special-keyword 'evaporate)))
+ (beginning-of-line 2)))))
+
+;;;###autoload
+(defun org-table-toggle-coordinate-overlays ()
+ "Toggle the display of Row/Column numbers in tables."
+ (interactive)
+ (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
+ (message "Tables Row/Column numbers display turned %s"
+ (if org-table-overlay-coordinates "on" "off"))
+ (if (and (org-at-table-p) org-table-overlay-coordinates)
+ (org-table-align))
+ (unless org-table-overlay-coordinates
+ (mapc 'delete-overlay org-table-coordinate-overlays)
+ (setq org-table-coordinate-overlays nil)))
+
+;;;###autoload
+(defun org-table-toggle-formula-debugger ()
+ "Toggle the formula debugger in tables."
+ (interactive)
+ (setq org-table-formula-debug (not org-table-formula-debug))
+ (message "Formula debugging has been turned %s"
+ (if org-table-formula-debug "on" "off")))
+
+;;; The orgtbl minor mode
+
+;; Define a minor mode which can be used in other modes in order to
+;; integrate the Org table editor.
+
+;; This is really a hack, because the Org table editor uses several
+;; keys which normally belong to the major mode, for example the TAB
+;; and RET keys. Here is how it works: The minor mode defines all the
+;; keys necessary to operate the table editor, but wraps the commands
+;; into a function which tests if the cursor is currently inside
+;; a table. If that is the case, the table editor command is
+;; executed. However, when any of those keys is used outside a table,
+;; the function uses `key-binding' to look up if the key has an
+;; associated command in another currently active keymap (minor modes,
+;; major mode, global), and executes that command. There might be
+;; problems if any of the keys used by the table editor is otherwise
+;; used as a prefix key.
+
+;; Another challenge is that the key binding for TAB can be tab or \C-i,
+;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
+;; addresses this by checking explicitly for both bindings.
+
+;; The optimized version (see variable `orgtbl-optimized') takes over
+;; all keys which are bound to `self-insert-command' in the *global map*.
+;; Some modes bind other commands to simple characters, for example
+;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
+;; active, this binding is ignored inside tables and replaced with a
+;; modified self-insert.
+
+
+(defvar orgtbl-mode-map (make-keymap)
+ "Keymap for `orgtbl-mode'.")
+
+(defvar org-old-auto-fill-inhibit-regexp nil
+ "Local variable used by `orgtbl-mode'.")
+
+(defconst orgtbl-line-start-regexp
+ "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
+ "Matches a line belonging to an orgtbl.")
+
+(defconst orgtbl-extra-font-lock-keywords
+ (list (list (concat "^" orgtbl-line-start-regexp ".*")
+ 0 (quote 'org-table) 'prepend))
+ "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
+
+;; Install it as a minor mode.
+(put 'orgtbl-mode :included t)
+(put 'orgtbl-mode :menu-tag "Org Table Mode")
+
+;;;###autoload
+(define-minor-mode orgtbl-mode
+ "The `org-mode' table editor as a minor mode for use in other modes."
+ :lighter " OrgTbl" :keymap orgtbl-mode-map
+ (org-load-modules-maybe)
+ (cond
+ ((derived-mode-p 'org-mode)
+ ;; Exit without error, in case some hook functions calls this
+ ;; by accident in org-mode.
+ (message "Orgtbl-mode is not useful in org-mode, command ignored"))
+ (orgtbl-mode
+ (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
+ ;; Make sure we are first in minor-mode-map-alist
+ (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
+ ;; FIXME: maybe it should use emulation-mode-map-alists?
+ (and c (setq minor-mode-map-alist
+ (cons c (delq c minor-mode-map-alist)))))
+ (setq-local org-table-may-need-update t)
+ (add-hook 'before-change-functions 'org-before-change-function
+ nil 'local)
+ (setq-local org-old-auto-fill-inhibit-regexp
+ auto-fill-inhibit-regexp)
+ (setq-local auto-fill-inhibit-regexp
+ (if auto-fill-inhibit-regexp
+ (concat orgtbl-line-start-regexp "\\|"
+ auto-fill-inhibit-regexp)
+ orgtbl-line-start-regexp))
+ (add-to-invisibility-spec '(org-cwidth))
+ (when (fboundp 'font-lock-add-keywords)
+ (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
+ (org-restart-font-lock))
+ (easy-menu-add orgtbl-mode-menu))
+ (t
+ (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
+ (org-table-cleanup-narrow-column-properties)
+ (org-remove-from-invisibility-spec '(org-cwidth))
+ (remove-hook 'before-change-functions 'org-before-change-function t)
+ (when (fboundp 'font-lock-remove-keywords)
+ (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
+ (org-restart-font-lock))
+ (easy-menu-remove orgtbl-mode-menu)
+ (force-mode-line-update 'all))))
+
+(defun org-table-cleanup-narrow-column-properties ()
+ "Remove all properties related to narrow-column invisibility."
+ (let ((s (point-min)))
+ (while (setq s (text-property-any s (point-max)
+ 'display org-narrow-column-arrow))
+ (remove-text-properties s (1+ s) '(display t)))
+ (setq s (point-min))
+ (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
+ (remove-text-properties s (1+ s) '(org-cwidth t)))
+ (setq s (point-min))
+ (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
+ (remove-text-properties s (1+ s) '(invisible t)))))
+
+(defun orgtbl-make-binding (fun n &rest keys)
+ "Create a function for binding in the table minor mode.
+FUN is the command to call inside a table. N is used to create a unique
+command name. KEYS are keys that should be checked in for a command
+to execute outside of tables."
+ (eval
+ (list 'defun
+ (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
+ '(arg)
+ (concat "In tables, run `" (symbol-name fun) "'.\n"
+ "Outside of tables, run the binding of `"
+ (mapconcat #'key-description keys "' or `")
+ "'.")
+ '(interactive "p")
+ (list 'if
+ '(org-at-table-p)
+ (list 'call-interactively (list 'quote fun))
+ (list 'let '(orgtbl-mode)
+ (list 'call-interactively
+ (append '(or)
+ (mapcar (lambda (k)
+ (list 'key-binding k))
+ keys)
+ '('orgtbl-error))))))))
+
+(defun orgtbl-error ()
+ "Error when there is no default binding for a table key."
+ (interactive)
+ (user-error "This key has no function outside tables"))
+
+(defun orgtbl-setup ()
+ "Setup orgtbl keymaps."
+ (let ((nfunc 0)
+ (bindings
+ '(([(meta shift left)] org-table-delete-column)
+ ([(meta left)] org-table-move-column-left)
+ ([(meta right)] org-table-move-column-right)
+ ([(meta shift right)] org-table-insert-column)
+ ([(meta shift up)] org-table-kill-row)
+ ([(meta shift down)] org-table-insert-row)
+ ([(meta up)] org-table-move-row-up)
+ ([(meta down)] org-table-move-row-down)
+ ("\C-c\C-w" org-table-cut-region)
+ ("\C-c\M-w" org-table-copy-region)
+ ("\C-c\C-y" org-table-paste-rectangle)
+ ("\C-c\C-w" org-table-wrap-region)
+ ("\C-c-" org-table-insert-hline)
+ ("\C-c}" org-table-toggle-coordinate-overlays)
+ ("\C-c{" org-table-toggle-formula-debugger)
+ ("\C-m" org-table-next-row)
+ ([(shift return)] org-table-copy-down)
+ ("\C-c?" org-table-field-info)
+ ("\C-c " org-table-blank-field)
+ ("\C-c+" org-table-sum)
+ ("\C-c=" org-table-eval-formula)
+ ("\C-c'" org-table-edit-formulas)
+ ("\C-c`" org-table-edit-field)
+ ("\C-c*" org-table-recalculate)
+ ("\C-c^" org-table-sort-lines)
+ ("\M-a" org-table-beginning-of-field)
+ ("\M-e" org-table-end-of-field)
+ ([(control ?#)] org-table-rotate-recalc-marks)))
+ elt key fun cmd)
+ (while (setq elt (pop bindings))
+ (setq nfunc (1+ nfunc))
+ (setq key (org-key (car elt))
+ fun (nth 1 elt)
+ cmd (orgtbl-make-binding fun nfunc key))
+ (org-defkey orgtbl-mode-map key cmd))
+
+ ;; Special treatment needed for TAB, RET and DEL
+ (org-defkey orgtbl-mode-map [(return)]
+ (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
+ (org-defkey orgtbl-mode-map "\C-m"
+ (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
+ (org-defkey orgtbl-mode-map [(tab)]
+ (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
+ (org-defkey orgtbl-mode-map "\C-i"
+ (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
+ (org-defkey orgtbl-mode-map [(shift tab)]
+ (orgtbl-make-binding 'org-table-previous-field 104
+ [(shift tab)] [(tab)] "\C-i"))
+ (org-defkey orgtbl-mode-map [backspace]
+ (orgtbl-make-binding 'org-delete-backward-char 109
+ [backspace] (kbd "DEL")))
+
+ (org-defkey orgtbl-mode-map [S-iso-lefttab]
+ (orgtbl-make-binding 'org-table-previous-field 107
+ [S-iso-lefttab] [backtab] [(shift tab)]
+ [(tab)] "\C-i"))
+
+ (org-defkey orgtbl-mode-map [backtab]
+ (orgtbl-make-binding 'org-table-previous-field 108
+ [backtab] [S-iso-lefttab] [(shift tab)]
+ [(tab)] "\C-i"))
+
+ (org-defkey orgtbl-mode-map "\M-\C-m"
+ (orgtbl-make-binding 'org-table-wrap-region 105
+ "\M-\C-m" [(meta return)]))
+ (org-defkey orgtbl-mode-map [(meta return)]
+ (orgtbl-make-binding 'org-table-wrap-region 106
+ [(meta return)] "\M-\C-m"))
+
+ (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
+ (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
+
+ (when orgtbl-optimized
+ ;; If the user wants maximum table support, we need to hijack
+ ;; some standard editing functions
+ (org-remap orgtbl-mode-map
+ 'self-insert-command 'orgtbl-self-insert-command
+ 'delete-char 'org-delete-char
+ 'delete-backward-char 'org-delete-backward-char)
+ (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
+ (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
+ '("OrgTbl"
+ ["Create or convert" org-table-create-or-convert-from-region
+ :active (not (org-at-table-p)) :keys "C-c |" ]
+ "--"
+ ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
+ ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
+ ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
+ ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
+ "--"
+ ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
+ ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
+ ["Copy Field from Above"
+ org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
+ "--"
+ ("Column"
+ ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
+ ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
+ ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
+ ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
+ ("Row"
+ ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
+ ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
+ ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
+ ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
+ ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
+ "--"
+ ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
+ ("Rectangle"
+ ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
+ ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
+ ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
+ ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
+ "--"
+ ("Radio tables"
+ ["Insert table template" orgtbl-insert-radio-table
+ (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
+ ["Comment/uncomment table" orgtbl-toggle-comment t])
+ "--"
+ ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
+ ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
+ ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
+ ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
+ ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
+ ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
+ ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
+ ["Sum Column/Rectangle" org-table-sum
+ :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
+ ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
+ ["Debug Formulas"
+ org-table-toggle-formula-debugger :active (org-at-table-p)
+ :keys "C-c {"
+ :style toggle :selected org-table-formula-debug]
+ ["Show Col/Row Numbers"
+ org-table-toggle-coordinate-overlays :active (org-at-table-p)
+ :keys "C-c }"
+ :style toggle :selected org-table-overlay-coordinates]
+ "--"
+ ("Plot"
+ ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
+ ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
+ t))
+
+(defun orgtbl-ctrl-c-ctrl-c (arg)
+ "If the cursor is inside a table, realign the table.
+If it is a table to be sent away to a receiver, do it.
+With prefix arg, also recompute table."
+ (interactive "P")
+ (let ((case-fold-search t) (pos (point)) action)
+ (save-excursion
+ (beginning-of-line 1)
+ (setq action (cond
+ ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
+ ((looking-at "[ \t]*|") pos)
+ ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
+ (cond
+ ((integerp action)
+ (goto-char action)
+ (org-table-maybe-eval-formula)
+ (if arg
+ (call-interactively 'org-table-recalculate)
+ (org-table-maybe-recalculate-line))
+ (call-interactively 'org-table-align)
+ (when (orgtbl-send-table 'maybe)
+ (run-hooks 'orgtbl-after-send-table-hook)))
+ ((eq action 'recalc)
+ (save-excursion
+ (beginning-of-line 1)
+ (skip-chars-backward " \r\n\t")
+ (if (org-at-table-p)
+ (org-call-with-arg 'org-table-recalculate t))))
+ (t (let (orgtbl-mode)
+ (call-interactively (key-binding "\C-c\C-c")))))))
+
+(defun orgtbl-create-or-convert-from-region (_arg)
+ "Create table or convert region to table, if no conflicting binding.
+This installs the table binding `C-c |', but only if there is no
+conflicting binding to this key outside orgtbl-mode."
+ (interactive "P")
+ (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
+ (if cmd
+ (call-interactively cmd)
+ (call-interactively 'org-table-create-or-convert-from-region))))
+
+(defun orgtbl-tab (arg)
+ "Justification and field motion for `orgtbl-mode'."
+ (interactive "P")
+ (if arg (org-table-edit-field t)
+ (org-table-justify-field-maybe)
+ (org-table-next-field)))
+
+(defun orgtbl-ret ()
+ "Justification and field motion for `orgtbl-mode'."
+ (interactive)
+ (if (bobp)
+ (newline)
+ (org-table-justify-field-maybe)
+ (org-table-next-row)))
+
+(defun orgtbl-self-insert-command (N)
+ "Like `self-insert-command', use overwrite-mode for whitespace in tables.
+If the cursor is in a table looking at whitespace, the whitespace is
+overwritten, and the table is not marked as requiring realignment."
+ (interactive "p")
+ (if (and (org-at-table-p)
+ (or
+ (and org-table-auto-blank-field
+ (member last-command
+ '(orgtbl-hijacker-command-100
+ orgtbl-hijacker-command-101
+ orgtbl-hijacker-command-102
+ orgtbl-hijacker-command-103
+ orgtbl-hijacker-command-104
+ orgtbl-hijacker-command-105
+ yas/expand))
+ (org-table-blank-field))
+ t)
+ (eq N 1)
+ (looking-at "[^|\n]* \\( \\)|"))
+ (let (org-table-may-need-update)
+ (delete-region (match-beginning 1) (match-end 1))
+ (self-insert-command N))
+ (setq org-table-may-need-update t)
+ (let* (orgtbl-mode
+ a
+ (cmd (or (key-binding
+ (or (and (listp function-key-map)
+ (setq a (assoc last-input-event function-key-map))
+ (cdr a))
+ (vector last-input-event)))
+ 'self-insert-command)))
+ (call-interactively cmd)
+ (if (and org-self-insert-cluster-for-undo
+ (eq cmd 'self-insert-command))
+ (if (not (eq last-command 'orgtbl-self-insert-command))
+ (setq org-self-insert-command-undo-counter 1)
+ (if (>= org-self-insert-command-undo-counter 20)
+ (setq org-self-insert-command-undo-counter 1)
+ (and (> org-self-insert-command-undo-counter 0)
+ buffer-undo-list
+ (not (cadr buffer-undo-list)) ; remove nil entry
+ (setcdr buffer-undo-list (cddr buffer-undo-list)))
+ (setq org-self-insert-command-undo-counter
+ (1+ org-self-insert-command-undo-counter))))))))
+
+;;;###autoload
+(defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
+ "Regular expression matching exponentials as produced by calc.")
+
+(defun orgtbl-gather-send-defs ()
+ "Gather a plist of :name, :transform, :params for each destination before
+a radio table."
+ (save-excursion
+ (goto-char (org-table-begin))
+ (let (rtn)
+ (beginning-of-line 0)
+ (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
+ (let ((name (org-no-properties (match-string 1)))
+ (transform (intern (match-string 2)))
+ (params (if (match-end 3)
+ (read (concat "(" (match-string 3) ")")))))
+ (push (list :name name :transform transform :params params)
+ rtn)
+ (beginning-of-line 0)))
+ rtn)))
+
+(defun orgtbl-send-replace-tbl (name text)
+ "Find and replace table NAME with TEXT."
+ (save-excursion
+ (goto-char (point-min))
+ (let* ((location-flag nil)
+ (name (regexp-quote name))
+ (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
+ (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
+ (while (re-search-forward begin-re nil t)
+ (unless location-flag (setq location-flag t))
+ (let ((beg (line-beginning-position 2)))
+ (unless (re-search-forward end-re nil t)
+ (user-error "Cannot find end of receiver location at %d" beg))
+ (beginning-of-line)
+ (delete-region beg (point))
+ (insert text "\n")))
+ (unless location-flag
+ (user-error "No valid receiver location found in the buffer")))))
+
+;;;###autoload
+(defun org-table-to-lisp (&optional txt)
+ "Convert the table at point to a Lisp structure.
+The structure will be a list. Each item is either the symbol `hline'
+for a horizontal separator line, or a list of field values as strings.
+The table is taken from the parameter TXT, or from the buffer at point."
+ (unless (or txt (org-at-table-p)) (user-error "No table at point"))
+ (let ((txt (or txt
+ (buffer-substring-no-properties (org-table-begin)
+ (org-table-end)))))
+ (mapcar (lambda (x)
+ (if (string-match org-table-hline-regexp x) 'hline
+ (org-split-string (org-trim x) "\\s-*|\\s-*")))
+ (org-split-string txt "[ \t]*\n[ \t]*"))))
+
+(defun orgtbl-send-table (&optional maybe)
+ "Send a transformed version of table at point to the receiver position.
+With argument MAYBE, fail quietly if no transformation is defined
+for this table."
+ (interactive)
+ (catch 'exit
+ (unless (org-at-table-p) (user-error "Not at a table"))
+ ;; when non-interactive, we assume align has just happened.
+ (when (called-interactively-p 'any) (org-table-align))
+ (let ((dests (orgtbl-gather-send-defs))
+ (table (org-table-to-lisp
+ (buffer-substring-no-properties (org-table-begin)
+ (org-table-end))))
+ (ntbl 0))
+ (unless dests
+ (if maybe (throw 'exit nil)
+ (user-error "Don't know how to transform this table")))
+ (dolist (dest dests)
+ (let ((name (plist-get dest :name))
+ (transform (plist-get dest :transform))
+ (params (plist-get dest :params)))
+ (unless (fboundp transform)
+ (user-error "No such transformation function %s" transform))
+ (orgtbl-send-replace-tbl name (funcall transform table params)))
+ (cl-incf ntbl))
+ (message "Table converted and installed at %d receiver location%s"
+ ntbl (if (> ntbl 1) "s" ""))
+ (and (> ntbl 0) ntbl))))
+
+(defun org-remove-by-index (list indices &optional i0)
+ "Remove the elements in LIST with indices in INDICES.
+First element has index 0, or I0 if given."
+ (if (not indices)
+ list
+ (if (integerp indices) (setq indices (list indices)))
+ (setq i0 (1- (or i0 0)))
+ (delq :rm (mapcar (lambda (x)
+ (setq i0 (1+ i0))
+ (if (memq i0 indices) :rm x))
+ list))))
+
+(defun orgtbl-toggle-comment ()
+ "Comment or uncomment the orgtbl at point."
+ (interactive)
+ (let* ((case-fold-search t)
+ (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
+ (re2 (concat "^" orgtbl-line-start-regexp))
+ (commented (save-excursion (beginning-of-line 1)
+ (cond ((looking-at re1) t)
+ ((looking-at re2) nil)
+ (t (user-error "Not at an org table")))))
+ (re (if commented re1 re2))
+ beg end)
+ (save-excursion
+ (beginning-of-line 1)
+ (while (looking-at re) (beginning-of-line 0))
+ (beginning-of-line 2)
+ (setq beg (point))
+ (while (looking-at re) (beginning-of-line 2))
+ (setq end (point)))
+ (comment-region beg end (if commented '(4) nil))))
+
+(defun orgtbl-insert-radio-table ()
+ "Insert a radio table template appropriate for this major mode."
+ (interactive)
+ (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
+ (txt (nth 1 e))
+ name pos)
+ (unless e (user-error "No radio table setup defined for %s" major-mode))
+ (setq name (read-string "Table name: "))
+ (while (string-match "%n" txt)
+ (setq txt (replace-match name t t txt)))
+ (or (bolp) (insert "\n"))
+ (setq pos (point))
+ (insert txt)
+ (goto-char pos)))
+
+;;;###autoload
+(defun orgtbl-to-generic (table params)
+ "Convert the orgtbl-mode TABLE to some other format.
+
+This generic routine can be used for many standard cases.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that
+line. PARAMS is a property list of parameters that can
+influence the conversion.
+
+Valid parameters are:
+
+:backend, :raw
+
+ Export back-end used as a basis to transcode elements of the
+ table, when no specific parameter applies to it. It is also
+ used to translate cells contents. You can prevent this by
+ setting :raw property to a non-nil value.
+
+:splice
+
+ When non-nil, only convert rows, not the table itself. This is
+ equivalent to setting to the empty string both :tstart
+ and :tend, which see.
+
+:skip
+
+ When set to an integer N, skip the first N lines of the table.
+ Horizontal separation lines do count for this parameter!
+
+:skipcols
+
+ List of columns that should be skipped. If the table has
+ a column with calculation marks, that column is automatically
+ discarded beforehand.
+
+:hline
+
+ String to be inserted on horizontal separation lines. May be
+ nil to ignore these lines altogether.
+
+:sep
+
+ Separator between two fields, as a string.
+
+Each in the following group may be either a string or a function
+of no arguments returning a string:
+
+:tstart, :tend
+
+ Strings to start and end the table. Ignored when :splice is t.
+
+:lstart, :lend
+
+ Strings to start and end a new table line.
+
+:llstart, :llend
+
+ Strings to start and end the last table line. Default,
+ respectively, to :lstart and :lend.
+
+Each in the following group may be a string or a function of one
+argument (either the cells in the current row, as a list of
+strings, or the current cell) returning a string:
+
+:lfmt
+
+ Format string for an entire row, with enough %s to capture all
+ fields. When non-nil, :lstart, :lend, and :sep are ignored.
+
+:llfmt
+
+ Format for the entire last line, defaults to :lfmt.
+
+:fmt
+
+ A format to be used to wrap the field, should contain %s for
+ the original field value. For example, to wrap everything in
+ dollars, you could use :fmt \"$%s$\". This may also be
+ a property list with column numbers and format strings, or
+ functions, e.g.,
+
+ (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
+
+:hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
+
+ Same as above, specific for the header lines in the table.
+ All lines before the first hline are treated as header. If
+ any of these is not present, the data line value is used.
+
+This may be either a string or a function of two arguments:
+
+:efmt
+
+ Use this format to print numbers with exponential. The format
+ should have %s twice for inserting mantissa and exponent, for
+ example \"%s\\\\times10^{%s}\". This may also be a property
+ list with column numbers and format strings or functions.
+ :fmt will still be applied after :efmt."
+ ;; Make sure `org-export-create-backend' is available.
+ (require 'ox)
+ (let* ((backend (plist-get params :backend))
+ (custom-backend
+ ;; Build a custom back-end according to PARAMS. Before
+ ;; defining a translator, check if there is anything to do.
+ ;; When there isn't, let BACKEND handle the element.
+ (org-export-create-backend
+ :parent (or backend 'org)
+ :transcoders
+ `((table . ,(org-table--to-generic-table params))
+ (table-row . ,(org-table--to-generic-row params))
+ (table-cell . ,(org-table--to-generic-cell params))
+ ;; Macros are not going to be expanded. However, no
+ ;; regular back-end has a transcoder for them. We
+ ;; provide one so they are not ignored, but displayed
+ ;; as-is instead.
+ (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
+ data info)
+ ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
+ ;; Initialize communication channel in INFO.
+ (with-temp-buffer
+ (let ((org-inhibit-startup t)) (org-mode))
+ (let ((standard-output (current-buffer)))
+ (dolist (e table)
+ (cond ((eq e 'hline) (princ "|--\n"))
+ ((consp e)
+ (princ "| ") (dolist (c e) (princ c) (princ " |"))
+ (princ "\n")))))
+ ;; Add back-end specific filters, but not user-defined ones. In
+ ;; particular, make sure to call parse-tree filters on the
+ ;; table.
+ (setq info
+ (let ((org-export-filters-alist nil))
+ (org-export-install-filters
+ (org-combine-plists
+ (org-export-get-environment backend nil params)
+ `(:back-end ,(org-export-get-backend backend))))))
+ (setq data
+ (org-export-filter-apply-functions
+ (plist-get info :filter-parse-tree)
+ (org-element-map (org-element-parse-buffer) 'table
+ #'identity nil t)
+ info)))
+ (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
+ (user-error "Unknown :backend value"))
+ (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
+ ;; Handle :skip parameter.
+ (let ((skip (plist-get info :skip)))
+ (when skip
+ (unless (wholenump skip) (user-error "Wrong :skip value"))
+ (let ((n 0))
+ (org-element-map data 'table-row
+ (lambda (row)
+ (if (>= n skip) t
+ (org-element-extract-element row)
+ (cl-incf n)
+ nil))
+ nil t))))
+ ;; Handle :skipcols parameter.
+ (let ((skipcols (plist-get info :skipcols)))
+ (when skipcols
+ (unless (consp skipcols) (user-error "Wrong :skipcols value"))
+ (org-element-map data 'table
+ (lambda (table)
+ (let ((specialp (org-export-table-has-special-column-p table)))
+ (dolist (row (org-element-contents table))
+ (when (eq (org-element-property :type row) 'standard)
+ (let ((c 1))
+ (dolist (cell (nthcdr (if specialp 1 0)
+ (org-element-contents row)))
+ (when (memq c skipcols)
+ (org-element-extract-element cell))
+ (cl-incf c))))))))))
+ ;; Since we are going to export using a low-level mechanism,
+ ;; ignore special column and special rows manually.
+ (let ((special? (org-export-table-has-special-column-p data))
+ ignore)
+ (org-element-map data (if special? '(table-cell table-row) 'table-row)
+ (lambda (datum)
+ (when (if (eq (org-element-type datum) 'table-row)
+ (org-export-table-row-is-special-p datum nil)
+ (org-export-first-sibling-p datum nil))
+ (push datum ignore))))
+ (setq info (plist-put info :ignore-list ignore)))
+ ;; We use a low-level mechanism to export DATA so as to skip all
+ ;; usual pre-processing and post-processing, i.e., hooks, Babel
+ ;; code evaluation, include keywords and macro expansion. Only
+ ;; back-end specific filters are retained.
+ (let ((output (org-export-data-with-backend data custom-backend info)))
+ ;; Remove final newline.
+ (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
+
+(defun org-table--generic-apply (value name &optional with-cons &rest args)
+ (cond ((null value) nil)
+ ((functionp value) `(funcall ',value ,@args))
+ ((stringp value)
+ (cond ((consp (car args)) `(apply #'format ,value ,@args))
+ (args `(format ,value ,@args))
+ (t value)))
+ ((and with-cons (consp value))
+ `(let ((val (cadr (memq column ',value))))
+ (cond ((null val) contents)
+ ((stringp val) (format val ,@args))
+ ((functionp val) (funcall val ,@args))
+ (t (user-error "Wrong %s value" ,name)))))
+ (t (user-error "Wrong %s value" name))))
+
+(defun org-table--to-generic-table (params)
+ "Return custom table transcoder according to PARAMS.
+PARAMS is a plist. See `orgtbl-to-generic' for more
+information."
+ (let ((backend (plist-get params :backend))
+ (splice (plist-get params :splice))
+ (tstart (plist-get params :tstart))
+ (tend (plist-get params :tend)))
+ `(lambda (table contents info)
+ (concat
+ ,(and tstart (not splice)
+ `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
+ ,(if (or (not backend) tstart tend splice) 'contents
+ `(org-export-with-backend ',backend table contents info))
+ ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
+
+(defun org-table--to-generic-row (params)
+ "Return custom table row transcoder according to PARAMS.
+PARAMS is a plist. See `orgtbl-to-generic' for more
+information."
+ (let* ((backend (plist-get params :backend))
+ (lstart (plist-get params :lstart))
+ (llstart (plist-get params :llstart))
+ (hlstart (plist-get params :hlstart))
+ (hllstart (plist-get params :hllstart))
+ (lend (plist-get params :lend))
+ (llend (plist-get params :llend))
+ (hlend (plist-get params :hlend))
+ (hllend (plist-get params :hllend))
+ (lfmt (plist-get params :lfmt))
+ (llfmt (plist-get params :llfmt))
+ (hlfmt (plist-get params :hlfmt))
+ (hllfmt (plist-get params :hllfmt)))
+ `(lambda (row contents info)
+ (if (eq (org-element-property :type row) 'rule)
+ ,(cond
+ ((plist-member params :hline)
+ (org-table--generic-apply (plist-get params :hline) ":hline"))
+ (backend `(org-export-with-backend ',backend row nil info)))
+ (let ((headerp (org-export-table-row-in-header-p row info))
+ (lastp (not (org-export-get-next-element row info)))
+ (last-header-p (org-export-table-row-ends-header-p row info)))
+ (when contents
+ ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
+ ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
+ ;; `:lstart', `:lend' and their relatives.
+ ,(let ((cells
+ '(org-element-map row 'table-cell
+ (lambda (cell)
+ ;; Export all cells, without separators.
+ ;;
+ ;; Use `org-export-data-with-backend'
+ ;; instead of `org-export-data' to eschew
+ ;; cached values, which
+ ;; ignore :orgtbl-ignore-sep parameter.
+ (org-export-data-with-backend
+ cell
+ (plist-get info :back-end)
+ (org-combine-plists info '(:orgtbl-ignore-sep t))))
+ info)))
+ `(cond
+ ,(and hllfmt
+ `(last-header-p ,(org-table--generic-apply
+ hllfmt ":hllfmt" nil cells)))
+ ,(and hlfmt
+ `(headerp ,(org-table--generic-apply
+ hlfmt ":hlfmt" nil cells)))
+ ,(and llfmt
+ `(lastp ,(org-table--generic-apply
+ llfmt ":llfmt" nil cells)))
+ (t
+ ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
+ `(concat
+ (cond
+ ,(and
+ (or hllstart hllend)
+ `(last-header-p
+ (concat
+ ,(org-table--generic-apply hllstart ":hllstart")
+ contents
+ ,(org-table--generic-apply hllend ":hllend"))))
+ ,(and
+ (or hlstart hlend)
+ `(headerp
+ (concat
+ ,(org-table--generic-apply hlstart ":hlstart")
+ contents
+ ,(org-table--generic-apply hlend ":hlend"))))
+ ,(and
+ (or llstart llend)
+ `(lastp
+ (concat
+ ,(org-table--generic-apply llstart ":llstart")
+ contents
+ ,(org-table--generic-apply llend ":llend"))))
+ (t
+ ,(cond
+ ((or lstart lend)
+ `(concat
+ ,(org-table--generic-apply lstart ":lstart")
+ contents
+ ,(org-table--generic-apply lend ":lend")))
+ (backend
+ `(org-export-with-backend
+ ',backend row contents info))
+ (t 'contents)))))))))))))))
+
+(defun org-table--to-generic-cell (params)
+ "Return custom table cell transcoder according to PARAMS.
+PARAMS is a plist. See `orgtbl-to-generic' for more
+information."
+ (let* ((backend (plist-get params :backend))
+ (efmt (plist-get params :efmt))
+ (fmt (plist-get params :fmt))
+ (hfmt (plist-get params :hfmt))
+ (sep (plist-get params :sep))
+ (hsep (plist-get params :hsep)))
+ `(lambda (cell contents info)
+ (let ((headerp (org-export-table-row-in-header-p
+ (org-export-get-parent-element cell) info))
+ (column (1+ (cdr (org-export-table-cell-address cell info)))))
+ ;; Make sure that contents are exported as Org data when :raw
+ ;; parameter is non-nil.
+ ,(when (and backend (plist-get params :raw))
+ `(setq contents
+ ;; Since we don't know what are the pseudo object
+ ;; types defined in backend, we cannot pass them to
+ ;; `org-element-interpret-data'. As a consequence,
+ ;; they will be treated as pseudo elements, and
+ ;; will have newlines appended instead of spaces.
+ ;; Therefore, we must make sure :post-blank value
+ ;; is really turned into spaces.
+ (replace-regexp-in-string
+ "\n" " "
+ (org-trim
+ (org-element-interpret-data
+ (org-element-contents cell))))))
+ (when contents
+ ;; Check if we can apply `:efmt' on CONTENTS.
+ ,(when efmt
+ `(when (string-match orgtbl-exp-regexp contents)
+ (let ((mantissa (match-string 1 contents))
+ (exponent (match-string 2 contents)))
+ (setq contents ,(org-table--generic-apply
+ efmt ":efmt" t 'mantissa 'exponent)))))
+ ;; Check if we can apply FMT (or HFMT) on CONTENTS.
+ (cond
+ ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
+ hfmt ":hfmt" t 'contents))))
+ ,(and fmt `(t (setq contents ,(org-table--generic-apply
+ fmt ":fmt" t 'contents))))))
+ ;; If a separator is provided, use it instead of BACKEND's.
+ ;; Separators are ignored when LFMT (or equivalent) is
+ ;; provided.
+ ,(cond
+ ((or hsep sep)
+ `(if (or ,(and (not sep) '(not headerp))
+ (plist-get info :orgtbl-ignore-sep)
+ (not (org-export-get-next-element cell info)))
+ ,(if (not backend) 'contents
+ `(org-export-with-backend ',backend cell contents info))
+ (concat contents
+ ,(if (and sep hsep) `(if headerp ,hsep ,sep)
+ (or hsep sep)))))
+ (backend `(org-export-with-backend ',backend cell contents info))
+ (t 'contents))))))
+
+;;;###autoload
+(defun orgtbl-to-tsv (table params)
+ "Convert the orgtbl-mode table to TAB separated material."
+ (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
+
+;;;###autoload
+(defun orgtbl-to-csv (table params)
+ "Convert the orgtbl-mode table to CSV material.
+This does take care of the proper quoting of fields with comma or quotes."
+ (orgtbl-to-generic table
+ (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
+ params)))
+
+;;;###autoload
+(defun orgtbl-to-latex (table params)
+ "Convert the orgtbl-mode TABLE to LaTeX.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following ones:
+
+:booktabs
+
+ When non-nil, use formal \"booktabs\" style.
+
+:environment
+
+ Specify environment to use, as a string. If you use
+ \"longtable\", you may also want to specify :language property,
+ as a string, to get proper continuation strings."
+ (require 'ox-latex)
+ (orgtbl-to-generic
+ table
+ (org-combine-plists
+ ;; Provide sane default values.
+ (list :backend 'latex
+ :latex-default-table-mode 'table
+ :latex-tables-centered nil
+ :latex-tables-booktabs (plist-get params :booktabs)
+ :latex-table-scientific-notation nil
+ :latex-default-table-environment
+ (or (plist-get params :environment) "tabular"))
+ params)))
+
+;;;###autoload
+(defun orgtbl-to-html (table params)
+ "Convert the orgtbl-mode TABLE to HTML.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following one:
+
+:attributes
+
+ Attributes and values, as a plist, which will be used in
+ <table> tag."
+ (require 'ox-html)
+ (orgtbl-to-generic
+ table
+ (org-combine-plists
+ ;; Provide sane default values.
+ (list :backend 'html
+ :html-table-data-tags '("<td%s>" . "</td>")
+ :html-table-use-header-tags-for-first-column nil
+ :html-table-align-individual-fields t
+ :html-table-row-tags '("<tr>" . "</tr>")
+ :html-table-attributes
+ (if (plist-member params :attributes)
+ (plist-get params :attributes)
+ '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
+ :frame "hsides")))
+ params)))
+
+;;;###autoload
+(defun orgtbl-to-texinfo (table params)
+ "Convert the orgtbl-mode TABLE to Texinfo.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following one:
+
+:columns
+
+ Column widths, as a string. When providing column fractions,
+ \"@columnfractions\" command can be omitted."
+ (require 'ox-texinfo)
+ (let ((output
+ (orgtbl-to-generic
+ table
+ (org-combine-plists
+ (list :backend 'texinfo
+ :texinfo-tables-verbatim nil
+ :texinfo-table-scientific-notation nil)
+ params)))
+ (columns (let ((w (plist-get params :columns)))
+ (cond ((not w) nil)
+ ((string-match-p "{\\|@columnfractions " w) w)
+ (t (concat "@columnfractions " w))))))
+ (if (not columns) output
+ (replace-regexp-in-string
+ "@multitable \\(.*\\)" columns output t nil 1))))
+
+;;;###autoload
+(defun orgtbl-to-orgtbl (table params)
+ "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported.
+
+Useful when slicing one table into many. The :hline, :sep,
+:lstart, and :lend provide orgtbl framing. :tstart and :tend can
+be set to provide ORGTBL directives for the generated table."
+ (require 'ox-org)
+ (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
+
+(defun orgtbl-to-table.el (table params)
+ "Convert the orgtbl-mode TABLE into a table.el table.
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported."
+ (with-temp-buffer
+ (insert (orgtbl-to-orgtbl table params))
+ (org-table-align)
+ (replace-regexp-in-string
+ "-|" "-+"
+ (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
+
+(defun orgtbl-to-unicode (table params)
+ "Convert the orgtbl-mode TABLE into a table with unicode characters.
+
+TABLE is a list, each entry either the symbol `hline' for
+a horizontal separator line, or a list of fields for that line.
+PARAMS is a property list of parameters that can influence the
+conversion. All parameters from `orgtbl-to-generic' are
+supported. It is also possible to use the following ones:
+
+:ascii-art
+
+ When non-nil, use \"ascii-art-to-unicode\" package to translate
+ the table. You can download it here:
+ http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
+
+:narrow
+
+ When non-nil, narrow columns width than provided width cookie,
+ using \"=>\" as an ellipsis, just like in an Org mode buffer."
+ (require 'ox-ascii)
+ (orgtbl-to-generic
+ table
+ (org-combine-plists
+ (list :backend 'ascii
+ :ascii-charset 'utf-8
+ :ascii-table-widen-columns (not (plist-get params :narrow))
+ :ascii-table-use-ascii-art (plist-get params :ascii-art))
+ params)))
+
+;; Put the cursor in a column containing numerical values
+;; of an Org table,
+;; type C-c " a
+;; A new column is added with a bar plot.
+;; When the table is refreshed (C-u C-c *),
+;; the plot is updated to reflect the new values.
+
+(defun orgtbl-ascii-draw (value min max &optional width characters)
+ "Draw an ascii bar in a table.
+VALUE is the value to plot, it determines the width of the bar to draw.
+MIN is the value that will be displayed as empty (zero width bar).
+MAX is the value that will draw a bar filling all the WIDTH.
+WIDTH is the span in characters from MIN to MAX.
+CHARACTERS is a string that will compose the bar, with shades of grey
+from pure white to pure black. It defaults to a 10 characters string
+of regular ascii characters."
+ (let* ((width (ceiling (or width 12)))
+ (characters (or characters " .:;c!lhVHW"))
+ (len (1- (length characters)))
+ (value (float (if (numberp value)
+ value (string-to-number value))))
+ (relative (/ (- value min) (- max min)))
+ (steps (round (* relative width len))))
+ (cond ((< steps 0) "too small")
+ ((> steps (* width len)) "too large")
+ (t (let* ((int-division (/ steps len))
+ (remainder (- steps (* int-division len))))
+ (concat (make-string int-division (elt characters len))
+ (string (elt characters remainder))))))))
+
+;;;###autoload
+(defun orgtbl-ascii-plot (&optional ask)
+ "Draw an ASCII bar plot in a column.
+
+With cursor in a column containing numerical values, this function
+will draw a plot in a new column.
+
+ASK, if given, is a numeric prefix to override the default 12
+characters width of the plot. ASK may also be the `\\[universal-argument]' \
+prefix,
+which will prompt for the width."
+ (interactive "P")
+ (let ((col (org-table-current-column))
+ (min 1e999) ; 1e999 will be converted to infinity
+ (max -1e999) ; which is the desired result
+ (table (org-table-to-lisp))
+ (length
+ (cond ((consp ask)
+ (read-number "Length of column " 12))
+ ((numberp ask) ask)
+ (t 12))))
+ ;; Skip any hline a the top of table.
+ (while (eq (car table) 'hline) (setq table (cdr table)))
+ ;; Skip table header if any.
+ (dolist (x (or (cdr (memq 'hline table)) table))
+ (when (consp x)
+ (setq x (nth (1- col) x))
+ (when (string-match
+ "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
+ x)
+ (setq x (string-to-number x))
+ (when (> min x) (setq min x))
+ (when (< max x) (setq max x)))))
+ (org-table-insert-column)
+ (org-table-move-column-right)
+ (org-table-store-formulas
+ (cons
+ (cons
+ (concat "$" (number-to-string (1+ col)))
+ (format "'(%s $%s %s %s %s)"
+ "orgtbl-ascii-draw" col min max length))
+ (org-table-get-stored-formulas)))
+ (org-table-recalculate t)))
+
+;; Example of extension: unicode characters
+;; Here are two examples of different styles.
+
+;; Unicode block characters are used to give a smooth effect.
+;; See http://en.wikipedia.org/wiki/Block_Elements
+;; Use one of those drawing functions
+;; - orgtbl-ascii-draw (the default ascii)
+;; - orgtbl-uc-draw-grid (unicode with a grid effect)
+;; - orgtbl-uc-draw-cont (smooth unicode)
+
+;; This is best viewed with the "DejaVu Sans Mono" font
+;; (use M-x set-default-font).
+
+(defun orgtbl-uc-draw-grid (value min max &optional width)
+ "Draw a bar in a table using block unicode characters.
+It is a variant of orgtbl-ascii-draw with Unicode block
+characters, for a smooth display. Bars appear as grids (to the
+extent the font allows)."
+ ;; http://en.wikipedia.org/wiki/Block_Elements
+ ;; best viewed with the "DejaVu Sans Mono" font.
+ (orgtbl-ascii-draw value min max width
+ " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
+
+(defun orgtbl-uc-draw-cont (value min max &optional width)
+ "Draw a bar in a table using block unicode characters.
+It is a variant of orgtbl-ascii-draw with Unicode block
+characters, for a smooth display. Bars are solid (to the extent
+the font allows)."
+ (orgtbl-ascii-draw value min max width
+ " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
+
+(defun org-table-get-remote-range (name-or-id form)
+ "Get a field value or a list of values in a range from table at ID.
+
+NAME-OR-ID may be the name of a table in the current file as set
+by a \"#+NAME:\" directive. The first table following this line
+will then be used. Alternatively, it may be an ID referring to
+any entry, also in a different file. In this case, the first
+table in that entry will be referenced.
+FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
+\"@I$2..@II$2\". All the references must be absolute, not relative.
+
+The return value is either a single string for a single field, or a
+list of the fields in the rectangle."
+ (save-match-data
+ (let ((case-fold-search t) (id-loc nil)
+ ;; Protect a bunch of variables from being overwritten by
+ ;; the context of the remote table.
+ org-table-column-names org-table-column-name-regexp
+ org-table-local-parameters org-table-named-field-locations
+ org-table-current-line-types
+ org-table-current-begin-pos org-table-dlines
+ org-table-current-ncol
+ org-table-hlines org-table-last-alignment
+ org-table-last-column-widths org-table-last-alignment
+ org-table-last-column-widths
+ buffer loc)
+ (setq form (org-table-convert-refs-to-rc form))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (if (re-search-forward
+ (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
+ (regexp-quote name-or-id) "[ \t]*$")
+ nil t)
+ (setq buffer (current-buffer) loc (match-beginning 0))
+ (setq id-loc (org-id-find name-or-id 'marker))
+ (unless (and id-loc (markerp id-loc))
+ (user-error "Can't find remote table \"%s\"" name-or-id))
+ (setq buffer (marker-buffer id-loc)
+ loc (marker-position id-loc))
+ (move-marker id-loc nil))
+ (with-current-buffer buffer
+ (org-with-wide-buffer
+ (goto-char loc)
+ (forward-char 1)
+ (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
+ (not (match-beginning 1)))
+ (user-error "Cannot find a table at NAME or ID %s" name-or-id))
+ (org-table-analyze)
+ (setq form (org-table-formula-substitute-names
+ (org-table-formula-handle-first/last-rc form)))
+ (if (and (string-match org-table-range-regexp form)
+ (> (length (match-string 0 form)) 1))
+ (org-table-get-range
+ (match-string 0 form) org-table-current-begin-pos 1)
+ form)))))))
+
+(defun org-table-remote-reference-indirection (form)
+ "Return formula with table remote references substituted by indirection.
+For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
+This indirection works only with the format @ROW$COLUMN. The
+format \"B3\" is not supported because it can not be
+distinguished from a plain table name or ID."
+ (let ((regexp
+ ;; Same as in `org-table-eval-formula'.
+ (concat "\\<remote([ \t]*\\("
+ ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
+ "[@$][^ \t,]+"
+ "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
+ (replace-regexp-in-string
+ regexp
+ (lambda (m)
+ (save-match-data
+ (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
+ (org-table-get-range
+ (if (string-match-p "\\`\\$[0-9]+\\'" eq)
+ (concat "@0" eq)
+ eq)))))
+ form t t 1)))
+
+(defmacro org-define-lookup-function (mode)
+ (let ((mode-str (symbol-name mode))
+ (first-p (eq mode 'first))
+ (all-p (eq mode 'all)))
+ (let ((plural-str (if all-p "s" "")))
+ `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
+ ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
+If R-LIST is nil, return matching element%s of S-LIST.
+If PREDICATE is not nil, use it instead of `equal' to match VAL.
+Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
+This function is generated by a call to the macro `org-define-lookup-function'."
+ mode-str plural-str plural-str plural-str)
+ (let ,(let ((lvars '((p (or predicate 'equal))
+ (sl s-list)
+ (rl (or r-list s-list))
+ (ret nil))))
+ (if first-p (cons '(match-p nil) lvars) lvars))
+ (while ,(if first-p '(and (not match-p) sl) 'sl)
+ (when (funcall p val (car sl))
+ ,(when first-p '(setq match-p t))
+ (let ((rval (car rl)))
+ (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
+ (setq sl (cdr sl) rl (cdr rl)))
+ ret)))))
+
+(org-define-lookup-function first)
+(org-define-lookup-function last)
+(org-define-lookup-function all)
+
+(provide 'org-table)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-table.el ends here
diff --git a/lisp/org-timer.el b/lisp/org-timer.el
new file mode 100644
index 0000000..146775b
--- /dev/null
+++ b/lisp/org-timer.el
@@ -0,0 +1,509 @@
+;;; org-timer.el --- Timer code for Org mode -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements two types of timers for Org buffers:
+;;
+;; - A relative timer that counts up (from 0 or a specified offset)
+;; - A countdown timer that counts down from a specified time
+;;
+;; The relative and countdown timers differ in their entry points.
+;; Use `org-timer' or `org-timer-start' to start the relative timer,
+;; and `org-timer-set-timer' to start the countdown timer.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'org-clock)
+
+(declare-function org-agenda-error "org-agenda" ())
+
+(defvar org-timer-start-time nil
+ "t=0 for the running timer.")
+
+(defvar org-timer-pause-time nil
+ "Time when the timer was paused.")
+
+(defvar org-timer-countdown-timer nil
+ "Current countdown timer.
+This is a timer object if there is an active countdown timer,
+`paused' if there is a paused countdown timer, and nil
+otherwise.")
+
+(defvar org-timer-countdown-timer-title nil
+ "Title for notification displayed when a countdown finishes.")
+
+(defconst org-timer-re "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)"
+ "Regular expression used to match timer stamps.")
+
+(defcustom org-timer-format "%s "
+ "The format to insert the time of the timer.
+This format must contain one instance of \"%s\" which will be replaced by
+the value of the timer."
+ :group 'org-time
+ :type 'string)
+
+(defcustom org-timer-default-timer "0"
+ "The default timer when a timer is set, in minutes or hh:mm:ss format.
+When 0, the user is prompted for a value."
+ :group 'org-time
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'string)
+
+(defcustom org-timer-display 'mode-line
+ "Define where running timer is displayed, if at all.
+When a timer is running, Org can display it in the mode line
+and/or frame title. Allowed values are:
+
+both displays in both mode line and frame title
+mode-line displays only in mode line (default)
+frame-title displays only in frame title
+nil current timer is not displayed"
+ :group 'org-time
+ :type '(choice
+ (const :tag "Mode line" mode-line)
+ (const :tag "Frame title" frame-title)
+ (const :tag "Both" both)
+ (const :tag "None" nil)))
+
+(defvar org-timer-start-hook nil
+ "Hook run after relative timer is started.")
+
+(defvar org-timer-stop-hook nil
+ "Hook run before relative or countdown timer is stopped.")
+
+(defvar org-timer-pause-hook nil
+ "Hook run before relative or countdown timer is paused.")
+
+(defvar org-timer-continue-hook nil
+ "Hook run after relative or countdown timer is continued.")
+
+(defvar org-timer-set-hook nil
+ "Hook run after countdown timer is set.")
+
+(defvar org-timer-done-hook nil
+ "Hook run after countdown timer reaches zero.")
+
+;;;###autoload
+(defun org-timer-start (&optional offset)
+ "Set the starting time for the relative timer to now.
+When called with prefix argument OFFSET, prompt the user for an offset time,
+with the default taken from a timer stamp at point, if any.
+If OFFSET is a string or an integer, it is directly taken to be the offset
+without user interaction.
+When called with a double prefix arg, all timer strings in the active
+region will be shifted by a specific amount. You will be prompted for
+the amount, with the default to make the first timer string in
+the region 0:00:00."
+ (interactive "P")
+ (cond
+ ((equal offset '(16))
+ (call-interactively 'org-timer-change-times-in-region))
+ (org-timer-countdown-timer
+ (user-error "Countdown timer is running. Cancel first"))
+ (t
+ (let (delta def s)
+ (if (not offset)
+ (setq org-timer-start-time (current-time))
+ (cond
+ ((integerp offset) (setq delta offset))
+ ((stringp offset) (setq delta (org-timer-hms-to-secs offset)))
+ (t
+ (setq def (if (org-in-regexp org-timer-re)
+ (match-string 0)
+ "0:00:00")
+ s (read-string
+ (format "Restart timer with offset [%s]: " def)))
+ (unless (string-match "\\S-" s) (setq s def))
+ (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete s)))))
+ (setq org-timer-start-time
+ (seconds-to-time
+ ;; Pass `current-time' result to `float-time' (instead
+ ;; of calling without arguments) so that only
+ ;; `current-time' has to be overriden in tests.
+ (- (float-time (current-time)) delta))))
+ (setq org-timer-pause-time nil)
+ (org-timer-set-mode-line 'on)
+ (message "Timer start time set to %s, current value is %s"
+ (format-time-string "%T" org-timer-start-time)
+ (org-timer-secs-to-hms (or delta 0)))
+ (run-hooks 'org-timer-start-hook)))))
+
+(defun org-timer-pause-or-continue (&optional stop)
+ "Pause or continue the relative or countdown timer.
+With prefix arg STOP, stop it entirely."
+ (interactive "P")
+ (cond
+ (stop (org-timer-stop))
+ ((not org-timer-start-time) (error "No timer is running"))
+ (org-timer-pause-time
+ (let ((start-secs (float-time org-timer-start-time))
+ (pause-secs (float-time org-timer-pause-time)))
+ (if org-timer-countdown-timer
+ (let ((new-secs (- start-secs pause-secs)))
+ (setq org-timer-countdown-timer
+ (org-timer--run-countdown-timer
+ new-secs org-timer-countdown-timer-title))
+ (setq org-timer-start-time
+ (time-add (current-time) (seconds-to-time new-secs))))
+ (setq org-timer-start-time
+ ;; Pass `current-time' result to `float-time' (instead
+ ;; of calling without arguments) so that only
+ ;; `current-time' has to be overriden in tests.
+ (seconds-to-time (- (float-time (current-time))
+ (- pause-secs start-secs)))))
+ (setq org-timer-pause-time nil)
+ (org-timer-set-mode-line 'on)
+ (run-hooks 'org-timer-continue-hook)
+ (message "Timer continues at %s" (org-timer-value-string))))
+ (t
+ ;; pause timer
+ (when org-timer-countdown-timer
+ (cancel-timer org-timer-countdown-timer)
+ (setq org-timer-countdown-timer 'paused))
+ (run-hooks 'org-timer-pause-hook)
+ (setq org-timer-pause-time (current-time))
+ (org-timer-set-mode-line 'paused)
+ (message "Timer paused at %s" (org-timer-value-string)))))
+
+(defun org-timer-stop ()
+ "Stop the relative or countdown timer."
+ (interactive)
+ (unless org-timer-start-time
+ (user-error "No timer running"))
+ (when (timerp org-timer-countdown-timer)
+ (cancel-timer org-timer-countdown-timer))
+ (run-hooks 'org-timer-stop-hook)
+ (setq org-timer-start-time nil
+ org-timer-pause-time nil
+ org-timer-countdown-timer nil)
+ (org-timer-set-mode-line 'off)
+ (message "Timer stopped"))
+
+;;;###autoload
+(defun org-timer (&optional restart no-insert)
+ "Insert a H:MM:SS string from the timer into the buffer.
+The first time this command is used, the timer is started.
+
+When used with a `\\[universal-argument]' prefix, force restarting the timer.
+
+When used with a `\\[universal-argument] \\[universal-argument]' \
+prefix, change all the timer strings
+in the region by a fixed amount. This can be used to re-calibrate
+a timer that was not started at the correct moment.
+
+If NO-INSERT is non-nil, return the string instead of inserting
+it in the buffer."
+ (interactive "P")
+ (if (equal restart '(16))
+ (org-timer-start restart)
+ (when (or (equal restart '(4)) (not org-timer-start-time))
+ (org-timer-start))
+ (if no-insert
+ (org-timer-value-string)
+ (insert (org-timer-value-string)))))
+
+(defun org-timer-value-string ()
+ "Set the timer string."
+ (format org-timer-format
+ (org-timer-secs-to-hms
+ (abs (floor (org-timer-seconds))))))
+
+(defun org-timer-seconds ()
+ ;; Pass `current-time' result to `float-time' (instead of calling
+ ;; without arguments) so that only `current-time' has to be
+ ;; overriden in tests.
+ (if org-timer-countdown-timer
+ (- (float-time org-timer-start-time)
+ (float-time (or org-timer-pause-time (current-time))))
+ (- (float-time (or org-timer-pause-time (current-time)))
+ (float-time org-timer-start-time))))
+
+;;;###autoload
+(defun org-timer-change-times-in-region (beg end delta)
+ "Change all h:mm:ss time in region by a DELTA."
+ (interactive
+ "r\nsEnter time difference like \"-1:08:26\". Default is first time to zero: ")
+ (let ((re "[-+]?[0-9]+:[0-9]\\{2\\}:[0-9]\\{2\\}") p)
+ (unless (string-match "\\S-" delta)
+ (save-excursion
+ (goto-char beg)
+ (when (re-search-forward re end t)
+ (setq delta (match-string 0))
+ (if (equal (string-to-char delta) ?-)
+ (setq delta (substring delta 1))
+ (setq delta (concat "-" delta))))))
+ (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete delta)))
+ (when (= delta 0) (error "No change"))
+ (save-excursion
+ (goto-char end)
+ (while (re-search-backward re beg t)
+ (setq p (point))
+ (replace-match
+ (save-match-data
+ (org-timer-secs-to-hms (+ (org-timer-hms-to-secs (match-string 0)) delta)))
+ t t)
+ (goto-char p)))))
+
+;;;###autoload
+(defun org-timer-item (&optional arg)
+ "Insert a description-type item with the current timer value."
+ (interactive "P")
+ (let ((itemp (org-in-item-p)) (pos (point)))
+ (cond
+ ;; In a timer list, insert with `org-list-insert-item',
+ ;; then fix the list.
+ ((and itemp (goto-char itemp) (org-at-item-timer-p))
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (s (concat (org-timer (when arg '(4)) t) ":: ")))
+ (setq struct (org-list-insert-item pos struct prevs nil s))
+ (org-list-write-struct struct (org-list-parents-alist struct))
+ (looking-at org-list-full-item-re)
+ (goto-char (match-end 0))))
+ ;; In a list of another type, don't break anything: throw an error.
+ (itemp (goto-char pos) (error "This is not a timer list"))
+ ;; Else, start a new list.
+ (t
+ (beginning-of-line)
+ (org-indent-line)
+ (insert "- ")
+ (org-timer (when arg '(4)))
+ (insert ":: ")))))
+
+(defun org-timer-fix-incomplete (hms)
+ "If hms is a H:MM:SS string with missing hour or hour and minute, fix it."
+ (if (string-match "\\(?:\\([0-9]+:\\)?\\([0-9]+:\\)\\)?\\([0-9]+\\)" hms)
+ (replace-match
+ (format "%d:%02d:%02d"
+ (if (match-end 1) (string-to-number (match-string 1 hms)) 0)
+ (if (match-end 2) (string-to-number (match-string 2 hms)) 0)
+ (string-to-number (match-string 3 hms)))
+ t t hms)
+ (error "Cannot parse HMS string \"%s\"" hms)))
+
+(defun org-timer-hms-to-secs (hms)
+ "Convert h:mm:ss string to an integer time.
+If the string starts with a minus sign, the integer will be negative."
+ (if (not (string-match
+ "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)"
+ hms))
+ 0
+ (let* ((h (string-to-number (match-string 1 hms)))
+ (m (string-to-number (match-string 2 hms)))
+ (s (string-to-number (match-string 3 hms)))
+ (sign (equal (substring (match-string 1 hms) 0 1) "-")))
+ (setq h (abs h))
+ (* (if sign -1 1) (+ s (* 60 (+ m (* 60 h))))))))
+
+(defun org-timer-secs-to-hms (s)
+ "Convert integer S into h:mm:ss.
+If the integer is negative, the string will start with \"-\"."
+ (let (sign m h)
+ (setq sign (if (< s 0) "-" "")
+ s (abs s)
+ m (/ s 60) s (- s (* 60 m))
+ h (/ m 60) m (- m (* 60 h)))
+ (format "%s%d:%02d:%02d" sign h m s)))
+
+(defvar org-timer-mode-line-timer nil)
+(defvar org-timer-mode-line-string nil)
+
+(defun org-timer-set-mode-line (value)
+ "Set the mode-line display for relative or countdown timer.
+VALUE can be `on', `off', or `paused'."
+ (when (or (eq org-timer-display 'mode-line)
+ (eq org-timer-display 'both))
+ (or global-mode-string (setq global-mode-string '("")))
+ (or (memq 'org-timer-mode-line-string global-mode-string)
+ (setq global-mode-string
+ (append global-mode-string '(org-timer-mode-line-string)))))
+ (when (or (eq org-timer-display 'frame-title)
+ (eq org-timer-display 'both))
+ (or (memq 'org-timer-mode-line-string frame-title-format)
+ (setq frame-title-format
+ (append frame-title-format '(org-timer-mode-line-string)))))
+ (cl-case value
+ (off
+ (when org-timer-mode-line-timer
+ (cancel-timer org-timer-mode-line-timer)
+ (setq org-timer-mode-line-timer nil))
+ (when (or (eq org-timer-display 'mode-line)
+ (eq org-timer-display 'both))
+ (setq global-mode-string
+ (delq 'org-timer-mode-line-string global-mode-string)))
+ (when (or (eq org-timer-display 'frame-title)
+ (eq org-timer-display 'both))
+ (setq frame-title-format
+ (delq 'org-timer-mode-line-string frame-title-format)))
+ (force-mode-line-update))
+ (paused
+ (when org-timer-mode-line-timer
+ (cancel-timer org-timer-mode-line-timer)
+ (setq org-timer-mode-line-timer nil)))
+ (on
+ (when (or (eq org-timer-display 'mode-line)
+ (eq org-timer-display 'both))
+ (or global-mode-string (setq global-mode-string '("")))
+ (or (memq 'org-timer-mode-line-string global-mode-string)
+ (setq global-mode-string
+ (append global-mode-string '(org-timer-mode-line-string)))))
+ (when (or (eq org-timer-display 'frame-title)
+ (eq org-timer-display 'both))
+ (or (memq 'org-timer-mode-line-string frame-title-format)
+ (setq frame-title-format
+ (append frame-title-format '(org-timer-mode-line-string)))))
+ (org-timer-update-mode-line)
+ (when org-timer-mode-line-timer
+ (cancel-timer org-timer-mode-line-timer)
+ (setq org-timer-mode-line-timer nil))
+ (when org-timer-display
+ (setq org-timer-mode-line-timer
+ (run-with-timer 1 1 'org-timer-update-mode-line))))))
+
+(defun org-timer-update-mode-line ()
+ "Update the timer time in the mode line."
+ (if org-timer-pause-time
+ nil
+ (setq org-timer-mode-line-string
+ (concat " <" (substring (org-timer-value-string) 0 -1) ">"))
+ (force-mode-line-update)))
+
+(defun org-timer-show-remaining-time ()
+ "Display the remaining time before the timer ends."
+ (interactive)
+ (require 'time)
+ (if (not org-timer-countdown-timer)
+ (message "No timer set")
+ (let* ((rtime (decode-time
+ (time-subtract (timer--time org-timer-countdown-timer)
+ (current-time))))
+ (rsecs (nth 0 rtime))
+ (rmins (nth 1 rtime)))
+ (message "%d minute(s) %d seconds left before next time out"
+ rmins rsecs))))
+
+;;;###autoload
+(defun org-timer-set-timer (&optional opt)
+ "Prompt for a duration in minutes or hh:mm:ss and set a timer.
+
+If `org-timer-default-timer' is not \"0\", suggest this value as
+the default duration for the timer. If a timer is already set,
+prompt the user if she wants to replace it.
+
+Called with a numeric prefix argument, use this numeric value as
+the duration of the timer in minutes.
+
+Called with a `C-u' prefix arguments, use `org-timer-default-timer'
+without prompting the user for a duration.
+
+With two `C-u' prefix arguments, use `org-timer-default-timer'
+without prompting the user for a duration and automatically
+replace any running timer.
+
+By default, the timer duration will be set to the number of
+minutes in the Effort property, if any. You can ignore this by
+using three `C-u' prefix arguments."
+ (interactive "P")
+ (when (and org-timer-start-time
+ (not org-timer-countdown-timer))
+ (user-error "Relative timer is running. Stop first"))
+ (let* ((default-timer
+ ;; `org-timer-default-timer' used to be a number, don't choke:
+ (if (numberp org-timer-default-timer)
+ (number-to-string org-timer-default-timer)
+ org-timer-default-timer))
+ (effort-minutes (ignore-errors (org-get-at-eol 'effort-minutes 1)))
+ (minutes (or (and (numberp opt) (number-to-string opt))
+ (and (not (equal opt '(64)))
+ effort-minutes
+ (number-to-string effort-minutes))
+ (and (consp opt) default-timer)
+ (and (stringp opt) opt)
+ (read-from-minibuffer
+ "How much time left? (minutes or h:mm:ss) "
+ (and (not (string-equal default-timer "0")) default-timer)))))
+ (when (string-match "\\`[0-9]+\\'" minutes)
+ (setq minutes (concat minutes ":00")))
+ (if (not (string-match "[0-9]+" minutes))
+ (org-timer-show-remaining-time)
+ (let ((secs (org-timer-hms-to-secs (org-timer-fix-incomplete minutes))))
+ (if (and org-timer-countdown-timer
+ (not (or (equal opt '(16))
+ (y-or-n-p "Replace current timer? "))))
+ (message "No timer set")
+ (when (timerp org-timer-countdown-timer)
+ (cancel-timer org-timer-countdown-timer))
+ (setq org-timer-countdown-timer-title
+ (org-timer--get-timer-title))
+ (setq org-timer-countdown-timer
+ (org-timer--run-countdown-timer
+ secs org-timer-countdown-timer-title))
+ (run-hooks 'org-timer-set-hook)
+ (setq org-timer-start-time
+ (time-add (current-time) (seconds-to-time secs)))
+ (setq org-timer-pause-time nil)
+ (org-timer-set-mode-line 'on))))))
+
+(defun org-timer--run-countdown-timer (secs title)
+ "Start countdown timer that will last SECS.
+TITLE will be appended to the notification message displayed when
+time is up."
+ (let ((msg (format "%s: time out" title)))
+ (run-with-timer
+ secs nil `(lambda ()
+ (setq org-timer-countdown-timer nil
+ org-timer-start-time nil)
+ (org-notify ,msg ,org-clock-sound)
+ (org-timer-set-mode-line 'off)
+ (run-hooks 'org-timer-done-hook)))))
+
+(defun org-timer--get-timer-title ()
+ "Construct timer title from heading or file name of Org buffer."
+ (cond
+ ((derived-mode-p 'org-agenda-mode)
+ (let* ((marker (or (get-text-property (point) 'org-marker)
+ (org-agenda-error)))
+ (hdmarker (or (get-text-property (point) 'org-hd-marker)
+ marker)))
+ (with-current-buffer (marker-buffer marker)
+ (org-with-wide-buffer
+ (goto-char hdmarker)
+ (org-show-entry)
+ (or (ignore-errors (org-get-heading))
+ (buffer-name (buffer-base-buffer)))))))
+ ((derived-mode-p 'org-mode)
+ (or (ignore-errors (org-get-heading))
+ (buffer-name (buffer-base-buffer))))
+ (t (error "Not in an Org buffer"))))
+
+(provide 'org-timer)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; org-timer.el ends here
diff --git a/lisp/org-version.el b/lisp/org-version.el
new file mode 100644
index 0000000..c083a83
--- /dev/null
+++ b/lisp/org-version.el
@@ -0,0 +1,27 @@
+;;; org-version.el --- autogenerated file, do not edit
+;;
+;;; Code:
+;;;###autoload
+(defun org-release ()
+ "The release version of Org.
+Inserted by installing Org mode or when a release is made."
+ (let ((org-release "9.0.9"))
+ org-release))
+;;;###autoload
+(defun org-git-version ()
+ "The Git version of org-mode.
+Inserted by installing Org or when a release is made."
+ (let ((org-git-version "9.0.9-dist"))
+ org-git-version))
+;;;###autoload
+(defvar org-odt-data-dir "/usr/share/emacs/etc/org"
+ "The location of ODT styles.")
+
+(provide 'org-version)
+
+;; Local Variables:
+;; version-control: never
+;; no-byte-compile: t
+;; coding: utf-8
+;; End:
+;;; org-version.el ends here
diff --git a/lisp/org-w3m.el b/lisp/org-w3m.el
new file mode 100644
index 0000000..e9bbeff
--- /dev/null
+++ b/lisp/org-w3m.el
@@ -0,0 +1,183 @@
+;;; org-w3m.el --- Support from Copy and Paste From w3m -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
+
+;; Author: Andy Stewart <lazycat dot manatee at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; This program is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+;; This file implements copying HTML content from a w3m buffer and
+;; transforming the text on the fly so that it can be pasted into an
+;; Org buffer with hot links. It will also work for regions in gnus
+;; buffers that have been washed with w3m.
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Acknowledgments:
+
+;; Richard Riley <rileyrgdev at googlemail dot com>
+;;
+;; The idea of transforming the HTML content with Org syntax is
+;; proposed by Richard, I'm just coding it.
+;;
+
+;;; Code:
+
+(require 'org)
+
+(defvar w3m-current-url)
+(defvar w3m-current-title)
+
+(org-link-set-parameters "w3m" :store #'org-w3m-store-link)
+(defun org-w3m-store-link ()
+ "Store a link to a w3m buffer."
+ (when (eq major-mode 'w3m-mode)
+ (org-store-link-props
+ :type "w3m"
+ :link w3m-current-url
+ :url (url-view-url t)
+ :description (or w3m-current-title w3m-current-url))))
+
+(defun org-w3m-copy-for-org-mode ()
+ "Copy current buffer content or active region with `org-mode' style links.
+This will encode `link-title' and `link-location' with
+`org-make-link-string', and insert the transformed test into the kill ring,
+so that it can be yanked into an Org buffer with links working correctly."
+ (interactive)
+ (let* ((regionp (org-region-active-p))
+ (transform-start (point-min))
+ (transform-end (point-max))
+ return-content
+ link-location link-title
+ temp-position out-bound)
+ (when regionp
+ (setq transform-start (region-beginning))
+ (setq transform-end (region-end))
+ ;; Deactivate mark if current mark is activate.
+ (if (fboundp 'deactivate-mark) (deactivate-mark)))
+ (message "Transforming links...")
+ (save-excursion
+ (goto-char transform-start)
+ (while (and (not out-bound) ; still inside region to copy
+ (not (org-w3m-no-next-link-p))) ; no next link current buffer
+ ;; store current point before jump next anchor
+ (setq temp-position (point))
+ ;; move to next anchor when current point is not at anchor
+ (or (get-text-property (point) 'w3m-href-anchor) (org-w3m-get-next-link-start))
+ (if (<= (point) transform-end) ; if point is inside transform bound
+ (progn
+ ;; get content between two links.
+ (if (> (point) temp-position)
+ (setq return-content (concat return-content
+ (buffer-substring
+ temp-position (point)))))
+ ;; get link location at current point.
+ (setq link-location (get-text-property (point) 'w3m-href-anchor))
+ ;; get link title at current point.
+ (setq link-title (buffer-substring (point)
+ (org-w3m-get-anchor-end)))
+ ;; concat `org-mode' style url to `return-content'.
+ (setq return-content (concat return-content
+ (org-make-link-string
+ link-location link-title))))
+ (goto-char temp-position) ; reset point before jump next anchor
+ (setq out-bound t) ; for break out `while' loop
+ ))
+ ;; add the rest until end of the region to be copied
+ (if (< (point) transform-end)
+ (setq return-content
+ (concat return-content
+ (buffer-substring (point) transform-end))))
+ (org-kill-new return-content)
+ (message "Transforming links...done, use C-y to insert text into Org file")
+ (message "Copy with link transformation complete."))))
+
+(defun org-w3m-get-anchor-start ()
+ "Move cursor to the start of current anchor. Return point."
+ ;; get start position of anchor or current point
+ (goto-char (or (previous-single-property-change (point) 'w3m-anchor-sequence)
+ (point))))
+
+(defun org-w3m-get-anchor-end ()
+ "Move cursor to the end of current anchor. Return point."
+ ;; get end position of anchor or point
+ (goto-char (or (next-single-property-change (point) 'w3m-anchor-sequence)
+ (point))))
+
+(defun org-w3m-get-next-link-start ()
+ "Move cursor to the start of next link. Return point."
+ (catch 'reach
+ (while (next-single-property-change (point) 'w3m-anchor-sequence)
+ ;; jump to next anchor
+ (goto-char (next-single-property-change (point) 'w3m-anchor-sequence))
+ (when (get-text-property (point) 'w3m-href-anchor)
+ ;; return point when current is valid link
+ (throw 'reach nil))))
+ (point))
+
+(defun org-w3m-get-prev-link-start ()
+ "Move cursor to the start of previous link. Return point."
+ (catch 'reach
+ (while (previous-single-property-change (point) 'w3m-anchor-sequence)
+ ;; jump to previous anchor
+ (goto-char (previous-single-property-change (point) 'w3m-anchor-sequence))
+ (when (get-text-property (point) 'w3m-href-anchor)
+ ;; return point when current is valid link
+ (throw 'reach nil))))
+ (point))
+
+(defun org-w3m-no-next-link-p ()
+ "Whether there is no next link after the cursor.
+Return t if there is no next link; otherwise, return nil."
+ (save-excursion
+ (equal (point) (org-w3m-get-next-link-start))))
+
+(defun org-w3m-no-prev-link-p ()
+ "Whether there is no previous link after the cursor.
+Return t if there is no previous link; otherwise, return nil."
+ (save-excursion
+ (equal (point) (org-w3m-get-prev-link-start))))
+
+;; Install keys into the w3m keymap
+(defvar w3m-mode-map)
+(defvar w3m-minor-mode-map)
+(when (and (boundp 'w3m-mode-map)
+ (keymapp w3m-mode-map))
+ (define-key w3m-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode)
+ (define-key w3m-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode))
+(when (and (boundp 'w3m-minor-mode-map)
+ (keymapp w3m-minor-mode-map))
+ (define-key w3m-minor-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode)
+ (define-key w3m-minor-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode))
+(add-hook
+ 'w3m-mode-hook
+ (lambda ()
+ (define-key w3m-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode)
+ (define-key w3m-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode)))
+(add-hook
+ 'w3m-minor-mode-hook
+ (lambda ()
+ (define-key w3m-minor-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode)
+ (define-key w3m-minor-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode)))
+
+(provide 'org-w3m)
+
+;;; org-w3m.el ends here
diff --git a/lisp/org.el b/lisp/org.el
new file mode 100644
index 0000000..22b7dbf
--- /dev/null
+++ b/lisp/org.el
@@ -0,0 +1,25144 @@
+;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
+
+;; Carstens outline-mode for keeping track of everything.
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+;;
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+;;
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+;;
+;;; Commentary:
+;;
+;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
+;; project planning with a fast and effective plain-text system.
+;;
+;; Org mode develops organizational tasks around NOTES files that
+;; contain information about projects as plain text. Org mode is
+;; implemented on top of outline-mode, which makes it possible to keep
+;; the content of large files well structured. Visibility cycling and
+;; structure editing help to work with the tree. Tables are easily
+;; created with a built-in table editor. Org mode supports ToDo
+;; items, deadlines, time stamps, and scheduling. It dynamically
+;; compiles entries into an agenda that utilizes and smoothly
+;; integrates much of the Emacs calendar and diary. Plain text
+;; URL-like links connect to websites, emails, Usenet messages, BBDB
+;; entries, and any files related to the projects. For printing and
+;; sharing of notes, an Org file can be exported as a structured ASCII
+;; file, as HTML, or (todo and agenda items only) as an iCalendar
+;; file. It can also serve as a publishing tool for a set of linked
+;; webpages.
+;;
+;; Installation and Activation
+;; ---------------------------
+;; See the corresponding sections in the manual at
+;;
+;; http://orgmode.org/org.html#Installation
+;;
+;; Documentation
+;; -------------
+;; The documentation of Org mode can be found in the TeXInfo file. The
+;; distribution also contains a PDF version of it. At the homepage of
+;; Org mode, you can read the same text online as HTML. There is also an
+;; excellent reference card made by Philip Rooke. This card can be found
+;; in the doc/ directory.
+;;
+;; A list of recent changes can be found at
+;; http://orgmode.org/Changes.html
+;;
+;;; Code:
+
+(defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
+(defvar-local org-table-formula-constants-local nil
+ "Local version of `org-table-formula-constants'.")
+
+;;;; Require other packages
+
+(require 'cl-lib)
+
+(eval-when-compile (require 'gnus-sum))
+
+(require 'calendar)
+(require 'find-func)
+(require 'format-spec)
+
+(or (eq this-command 'eval-buffer)
+ (condition-case nil
+ (load (concat (file-name-directory load-file-name)
+ "org-loaddefs.el")
+ nil t t t)
+ (error
+ (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
+ (sit-for 3)
+ (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
+ (sit-for 3))))
+
+(require 'org-macs)
+(require 'org-compat)
+
+;; `org-outline-regexp' ought to be a defconst but is let-bound in
+;; some places -- e.g. see the macro `org-with-limited-levels'.
+;;
+;; In Org buffers, the value of `outline-regexp' is that of
+;; `org-outline-regexp'. The only function still directly relying on
+;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
+;; job when `orgstruct-mode' is active.
+(defvar org-outline-regexp "\\*+ "
+ "Regexp to match Org headlines.")
+
+(defvar org-outline-regexp-bol "^\\*+ "
+ "Regexp to match Org headlines.
+This is similar to `org-outline-regexp' but additionally makes
+sure that we are at the beginning of the line.")
+
+(defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
+ "Matches a headline, putting stars and text into groups.
+Stars are put in group 1 and the trimmed body in group 2.")
+
+(declare-function calendar-check-holidays "holidays" (date))
+(declare-function cdlatex-environment "ext:cdlatex" (environment item))
+(declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
+(declare-function org-add-archive-files "org-archive" (files))
+(declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
+(declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
+(declare-function org-agenda-redo "org-agenda" (&optional all))
+(declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
+(declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
+(declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
+(declare-function org-clock-get-last-clock-out-time "org-clock" ())
+(declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
+(declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
+(declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
+(declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
+(declare-function org-clock-timestamps-down "org-clock" (&optional n))
+(declare-function org-clock-timestamps-up "org-clock" (&optional n))
+(declare-function org-clock-update-time-maybe "org-clock" ())
+(declare-function org-clocktable-shift "org-clock" (dir n))
+(declare-function org-element-at-point "org-element" ())
+(declare-function org-element-cache-refresh "org-element" (pos))
+(declare-function org-element-cache-reset "org-element" (&optional all))
+(declare-function org-element-contents "org-element" (element))
+(declare-function org-element-context "org-element" (&optional element))
+(declare-function org-element-copy "org-element" (datum))
+(declare-function org-element-interpret-data "org-element" (data))
+(declare-function org-element-lineage "org-element" (blob &optional types with-self))
+(declare-function org-element-link-parser "org-element" ())
+(declare-function org-element-nested-p "org-element" (elem-a elem-b))
+(declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
+(declare-function org-element-property "org-element" (property element))
+(declare-function org-element-put-property "org-element" (element property value))
+(declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
+(declare-function org-element-type "org-element" (element))
+(declare-function org-element-update-syntax "org-element" ())
+(declare-function org-id-find-id-file "org-id" (id))
+(declare-function org-id-get-create "org-id" (&optional force))
+(declare-function org-inlinetask-at-task-p "org-inlinetask" ())
+(declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
+(declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
+(declare-function org-plot/gnuplot "org-plot" (&optional params))
+(declare-function org-table-align "org-table" ())
+(declare-function org-table-begin "org-table" (&optional table-type))
+(declare-function org-table-beginning-of-field "org-table" (&optional n))
+(declare-function org-table-blank-field "org-table" ())
+(declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
+(declare-function org-table-copy-region "org-table" (beg end &optional cut))
+(declare-function org-table-cut-region "org-table" (beg end))
+(declare-function org-table-edit-field "org-table" (arg))
+(declare-function org-table-end "org-table" (&optional table-type))
+(declare-function org-table-end-of-field "org-table" (&optional n))
+(declare-function org-table-insert-row "org-table" (&optional arg))
+(declare-function org-table-justify-field-maybe "org-table" (&optional new))
+(declare-function org-table-maybe-eval-formula "org-table" ())
+(declare-function org-table-maybe-recalculate-line "org-table" ())
+(declare-function org-table-next-row "org-table" ())
+(declare-function org-table-paste-rectangle "org-table" ())
+(declare-function org-table-recalculate "org-table" (&optional all noalign))
+(declare-function org-table-wrap-region "org-table" (arg))
+(declare-function org-tags-view "org-agenda" (&optional todo-only match))
+(declare-function orgtbl-ascii-plot "org-table" (&optional ask))
+(declare-function orgtbl-mode "org-table" (&optional arg))
+(declare-function org-export-get-backend "ox" (name))
+(declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
+(declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
+
+(defsubst org-uniquify (list)
+ "Non-destructively remove duplicate elements from LIST."
+ (let ((res (copy-sequence list))) (delete-dups res)))
+
+(defsubst org-get-at-bol (property)
+ "Get text property PROPERTY at the beginning of line."
+ (get-text-property (point-at-bol) property))
+
+(defsubst org-trim (s &optional keep-lead)
+ "Remove whitespace at the beginning and the end of string S.
+When optional argument KEEP-LEAD is non-nil, removing blank lines
+at the beginning of the string does not affect leading indentation."
+ (replace-regexp-in-string
+ (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
+ (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
+
+;; load languages based on value of `org-babel-load-languages'
+(defvar org-babel-load-languages)
+
+;;;###autoload
+(defun org-babel-do-load-languages (sym value)
+ "Load the languages defined in `org-babel-load-languages'."
+ (set-default sym value)
+ (dolist (pair org-babel-load-languages)
+ (let ((active (cdr pair)) (lang (symbol-name (car pair))))
+ (if active
+ (require (intern (concat "ob-" lang)))
+ (funcall 'fmakunbound
+ (intern (concat "org-babel-execute:" lang)))
+ (funcall 'fmakunbound
+ (intern (concat "org-babel-expand-body:" lang)))))))
+
+(declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
+;;;###autoload
+(defun org-babel-load-file (file &optional compile)
+ "Load Emacs Lisp source code blocks in the Org FILE.
+This function exports the source code using `org-babel-tangle'
+and then loads the resulting file using `load-file'. With prefix
+arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
+file to byte-code before it is loaded."
+ (interactive "fFile to load: \nP")
+ (let* ((age (lambda (file)
+ (float-time
+ (time-subtract (current-time)
+ (nth 5 (or (file-attributes (file-truename file))
+ (file-attributes file)))))))
+ (base-name (file-name-sans-extension file))
+ (exported-file (concat base-name ".el")))
+ ;; tangle if the Org file is newer than the elisp file
+ (unless (and (file-exists-p exported-file)
+ (> (funcall age file) (funcall age exported-file)))
+ ;; Tangle-file traversal returns reversed list of tangled files
+ ;; and we want to evaluate the first target.
+ (setq exported-file
+ (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
+ (message "%s %s"
+ (if compile
+ (progn (byte-compile-file exported-file 'load)
+ "Compiled and loaded")
+ (progn (load-file exported-file) "Loaded"))
+ exported-file)))
+
+(defcustom org-babel-load-languages '((emacs-lisp . t))
+ "Languages which can be evaluated in Org buffers.
+This list can be used to load support for any of the languages
+below, note that each language will depend on a different set of
+system executables and/or Emacs modes. When a language is
+\"loaded\", then code blocks in that language can be evaluated
+with `org-babel-execute-src-block' bound by default to C-c
+C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
+be set to remove code block evaluation from the C-c C-c
+keybinding. By default only Emacs Lisp (which has no
+requirements) is loaded."
+ :group 'org-babel
+ :set 'org-babel-do-load-languages
+ :version "24.1"
+ :type '(alist :tag "Babel Languages"
+ :key-type
+ (choice
+ (const :tag "Awk" awk)
+ (const :tag "C" C)
+ (const :tag "R" R)
+ (const :tag "Asymptote" asymptote)
+ (const :tag "Calc" calc)
+ (const :tag "Clojure" clojure)
+ (const :tag "CSS" css)
+ (const :tag "Ditaa" ditaa)
+ (const :tag "Dot" dot)
+ (const :tag "Emacs Lisp" emacs-lisp)
+ (const :tag "Forth" forth)
+ (const :tag "Fortran" fortran)
+ (const :tag "Gnuplot" gnuplot)
+ (const :tag "Haskell" haskell)
+ (const :tag "IO" io)
+ (const :tag "J" J)
+ (const :tag "Java" java)
+ (const :tag "Javascript" js)
+ (const :tag "LaTeX" latex)
+ (const :tag "Ledger" ledger)
+ (const :tag "Lilypond" lilypond)
+ (const :tag "Lisp" lisp)
+ (const :tag "Makefile" makefile)
+ (const :tag "Maxima" maxima)
+ (const :tag "Matlab" matlab)
+ (const :tag "Mscgen" mscgen)
+ (const :tag "Ocaml" ocaml)
+ (const :tag "Octave" octave)
+ (const :tag "Org" org)
+ (const :tag "Perl" perl)
+ (const :tag "Pico Lisp" picolisp)
+ (const :tag "PlantUML" plantuml)
+ (const :tag "Python" python)
+ (const :tag "Ruby" ruby)
+ (const :tag "Sass" sass)
+ (const :tag "Scala" scala)
+ (const :tag "Scheme" scheme)
+ (const :tag "Screen" screen)
+ (const :tag "Shell Script" shell)
+ (const :tag "Shen" shen)
+ (const :tag "Sql" sql)
+ (const :tag "Sqlite" sqlite)
+ (const :tag "Stan" stan)
+ (const :tag "ebnf2ps" ebnf2ps))
+ :value-type (boolean :tag "Activate" :value t)))
+
+;;;; Customization variables
+(defcustom org-clone-delete-id nil
+ "Remove ID property of clones of a subtree.
+When non-nil, clones of a subtree don't inherit the ID property.
+Otherwise they inherit the ID property with a new unique
+identifier."
+ :type 'boolean
+ :version "24.1"
+ :group 'org-id)
+
+;;; Version
+(org-check-version)
+
+;;;###autoload
+(defun org-version (&optional here full message)
+ "Show the Org version.
+Interactively, or when MESSAGE is non-nil, show it in echo area.
+With prefix argument, or when HERE is non-nil, insert it at point.
+In non-interactive uses, a reduced version string is output unless
+FULL is given."
+ (interactive (list current-prefix-arg t (not current-prefix-arg)))
+ (let ((org-dir (ignore-errors (org-find-library-dir "org")))
+ (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
+ (load-suffixes (list ".el"))
+ (org-install-dir
+ (ignore-errors (org-find-library-dir "org-loaddefs"))))
+ (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
+ (org-load-noerror-mustsuffix (concat org-dir "org-version")))
+ (let* ((load-suffixes save-load-suffixes)
+ (release (org-release))
+ (git-version (org-git-version))
+ (version (format "Org mode version %s (%s @ %s)"
+ release
+ git-version
+ (if org-install-dir
+ (if (string= org-dir org-install-dir)
+ org-install-dir
+ (concat "mixed installation! "
+ org-install-dir
+ " and "
+ org-dir))
+ "org-loaddefs.el can not be found!")))
+ (version1 (if full version release)))
+ (when here (insert version1))
+ (when message (message "%s" version1))
+ version1)))
+
+(defconst org-version (org-version))
+
+
+;;; Syntax Constants
+
+;;;; Block
+
+(defconst org-block-regexp
+ "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
+ "Regular expression for hiding blocks.")
+
+(defconst org-dblock-start-re
+ "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
+ "Matches the start line of a dynamic block, with parameters.")
+
+(defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
+ "Matches the end of a dynamic block.")
+
+;;;; Clock and Planning
+
+(defconst org-clock-string "CLOCK:"
+ "String used as prefix for timestamps clocking work hours on an item.")
+
+(defvar org-closed-string "CLOSED:"
+ "String used as the prefix for timestamps logging closing a TODO entry.")
+
+(defvar org-deadline-string "DEADLINE:"
+ "String to mark deadline entries.
+\\<org-mode-map>
+A deadline is this string, followed by a time stamp. It must be
+a word, terminated by a colon. You can insert a schedule keyword
+and a timestamp with `\\[org-deadline]'.")
+
+(defvar org-scheduled-string "SCHEDULED:"
+ "String to mark scheduled TODO entries.
+\\<org-mode-map>
+A schedule is this string, followed by a time stamp. It must be
+a word, terminated by a colon. You can insert a schedule keyword
+and a timestamp with `\\[org-schedule]'.")
+
+(defconst org-ds-keyword-length
+ (+ 2
+ (apply #'max
+ (mapcar #'length
+ (list org-deadline-string org-scheduled-string
+ org-clock-string org-closed-string))))
+ "Maximum length of the DEADLINE and SCHEDULED keywords.")
+
+(defconst org-planning-line-re
+ (concat "^[ \t]*"
+ (regexp-opt
+ (list org-closed-string org-deadline-string org-scheduled-string)
+ t))
+ "Matches a line with planning info.
+Matched keyword is in group 1.")
+
+(defconst org-clock-line-re
+ (concat "^[ \t]*" org-clock-string)
+ "Matches a line with clock info.")
+
+(defconst org-deadline-regexp (concat "\\<" org-deadline-string)
+ "Matches the DEADLINE keyword.")
+
+(defconst org-deadline-time-regexp
+ (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
+ "Matches the DEADLINE keyword together with a time stamp.")
+
+(defconst org-deadline-time-hour-regexp
+ (concat "\\<" org-deadline-string
+ " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
+ "Matches the DEADLINE keyword together with a time-and-hour stamp.")
+
+(defconst org-deadline-line-regexp
+ (concat "\\<\\(" org-deadline-string "\\).*")
+ "Matches the DEADLINE keyword and the rest of the line.")
+
+(defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
+ "Matches the SCHEDULED keyword.")
+
+(defconst org-scheduled-time-regexp
+ (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
+ "Matches the SCHEDULED keyword together with a time stamp.")
+
+(defconst org-scheduled-time-hour-regexp
+ (concat "\\<" org-scheduled-string
+ " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
+ "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
+
+(defconst org-closed-time-regexp
+ (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
+ "Matches the CLOSED keyword together with a time stamp.")
+
+(defconst org-keyword-time-regexp
+ (concat "\\<"
+ (regexp-opt
+ (list org-scheduled-string org-deadline-string org-closed-string
+ org-clock-string)
+ t)
+ " *[[<]\\([^]>]+\\)[]>]")
+ "Matches any of the 4 keywords, together with the time stamp.")
+
+(defconst org-keyword-time-not-clock-regexp
+ (concat
+ "\\<"
+ (regexp-opt
+ (list org-scheduled-string org-deadline-string org-closed-string) t)
+ " *[[<]\\([^]>]+\\)[]>]")
+ "Matches any of the 3 keywords, together with the time stamp.")
+
+(defconst org-maybe-keyword-time-regexp
+ (concat "\\(\\<"
+ (regexp-opt
+ (list org-scheduled-string org-deadline-string org-closed-string
+ org-clock-string)
+ t)
+ "\\)?"
+ " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
+ "\\|"
+ "<%%([^\r\n>]*>\\)")
+ "Matches a timestamp, possibly preceded by a keyword.")
+
+(defconst org-all-time-keywords
+ (mapcar (lambda (w) (substring w 0 -1))
+ (list org-scheduled-string org-deadline-string
+ org-clock-string org-closed-string))
+ "List of time keywords.")
+
+;;;; Drawer
+
+(defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
+ "Matches first or last line of a hidden block.
+Group 1 contains drawer's name or \"END\".")
+
+(defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
+ "Regular expression matching the first line of a property drawer.")
+
+(defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
+ "Regular expression matching the last line of a property drawer.")
+
+(defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
+ "Regular expression matching the first line of a clock drawer.")
+
+(defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
+ "Regular expression matching the last line of a clock drawer.")
+
+(defconst org-property-drawer-re
+ (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
+ "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
+ "[ \t]*:END:[ \t]*$")
+ "Matches an entire property drawer.")
+
+(defconst org-clock-drawer-re
+ (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
+ org-clock-drawer-end-re "\\)\n?")
+ "Matches an entire clock drawer.")
+
+;;;; Headline
+
+(defconst org-heading-keyword-regexp-format
+ "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
+ "Printf format for a regexp matching a headline with some keyword.
+This regexp will match the headline of any node which has the
+exact keyword that is put into the format. The keyword isn't in
+any group by default, but the stars and the body are.")
+
+(defconst org-heading-keyword-maybe-regexp-format
+ "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
+ "Printf format for a regexp matching a headline, possibly with some keyword.
+This regexp can match any headline with the specified keyword, or
+without a keyword. The keyword isn't in any group by default,
+but the stars and the body are.")
+
+(defconst org-archive-tag "ARCHIVE"
+ "The tag that marks a subtree as archived.
+An archived subtree does not open during visibility cycling, and does
+not contribute to the agenda listings.")
+
+(defconst org-comment-string "COMMENT"
+ "Entries starting with this keyword will never be exported.
+\\<org-mode-map>
+An entry can be toggled between COMMENT and normal with
+`\\[org-toggle-comment]'.")
+
+
+;;;; LaTeX Environments and Fragments
+
+(defconst org-latex-regexps
+ '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
+ ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
+ ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
+ ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
+ ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
+ ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
+ ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
+ ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
+ "Regular expressions for matching embedded LaTeX.")
+
+;;;; Node Property
+
+(defconst org-effort-property "Effort"
+ "The property that is being used to keep track of effort estimates.
+Effort estimates given in this property need to have the format H:MM.")
+
+;;;; Table
+
+(defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
+ "Detect an org-type or table-type table.")
+
+(defconst org-table-line-regexp "^[ \t]*|"
+ "Detect an org-type table line.")
+
+(defconst org-table-dataline-regexp "^[ \t]*|[^-]"
+ "Detect an org-type table line.")
+
+(defconst org-table-hline-regexp "^[ \t]*|-"
+ "Detect an org-type table hline.")
+
+(defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
+ "Detect a table-type table hline.")
+
+(defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
+ "Detect the first line outside a table when searching from within it.
+This works for both table types.")
+
+(defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
+ "Detect a #+TBLFM line.")
+
+;;;; Timestamp
+
+(defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
+ "Regular expression for fast time stamp matching.")
+
+(defconst org-ts-regexp-inactive
+ "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
+ "Regular expression for fast inactive time stamp matching.")
+
+(defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
+ "Regular expression for fast time stamp matching.")
+
+(defconst org-ts-regexp0
+ "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
+ "Regular expression matching time strings for analysis.
+This one does not require the space after the date, so it can be used
+on a string that terminates immediately after the date.")
+
+(defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
+ "Regular expression matching time strings for analysis.")
+
+(defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
+ "Regular expression matching time stamps, with groups.")
+
+(defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
+ "Regular expression matching time stamps (also [..]), with groups.")
+
+(defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
+ "Regular expression matching a time stamp range.")
+
+(defconst org-tr-regexp-both
+ (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
+ "Regular expression matching a time stamp range.")
+
+(defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
+ org-ts-regexp "\\)?")
+ "Regular expression matching a time stamp or time stamp range.")
+
+(defconst org-tsr-regexp-both
+ (concat org-ts-regexp-both "\\(--?-?"
+ org-ts-regexp-both "\\)?")
+ "Regular expression matching a time stamp or time stamp range.
+The time stamps may be either active or inactive.")
+
+(defconst org-repeat-re
+ "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
+ "Regular expression for specifying repeated events.
+After a match, group 1 contains the repeat expression.")
+
+(defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
+ "Formats for `format-time-string' which are used for time stamps.")
+
+
+;;; The custom variables
+
+(defgroup org nil
+ "Outline-based notes management and organizer."
+ :tag "Org"
+ :group 'outlines
+ :group 'calendar)
+
+(defcustom org-mode-hook nil
+ "Mode hook for Org mode, run after the mode was turned on."
+ :group 'org
+ :type 'hook)
+
+(defcustom org-load-hook nil
+ "Hook that is run after org.el has been loaded."
+ :group 'org
+ :type 'hook)
+
+(defcustom org-log-buffer-setup-hook nil
+ "Hook that is run after an Org log buffer is created."
+ :group 'org
+ :version "24.1"
+ :type 'hook)
+
+(defvar org-modules) ; defined below
+(defvar org-modules-loaded nil
+ "Have the modules been loaded already?")
+
+(defun org-load-modules-maybe (&optional force)
+ "Load all extensions listed in `org-modules'."
+ (when (or force (not org-modules-loaded))
+ (dolist (ext org-modules)
+ (condition-case nil (require ext)
+ (error (message "Problems while trying to load feature `%s'" ext))))
+ (setq org-modules-loaded t)))
+
+(defun org-set-modules (var value)
+ "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
+ (set var value)
+ (when (featurep 'org)
+ (org-load-modules-maybe 'force)
+ (org-element-cache-reset 'all)))
+
+(defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
+ "Modules that should always be loaded together with org.el.
+
+If a description starts with <C>, the file is not part of Emacs
+and loading it will require that you have downloaded and properly
+installed the Org mode distribution.
+
+You can also use this system to load external packages (i.e. neither Org
+core modules, nor modules from the CONTRIB directory). Just add symbols
+to the end of the list. If the package is called org-xyz.el, then you need
+to add the symbol `xyz', and the package must have a call to:
+
+ (provide \\='org-xyz)
+
+For export specific modules, see also `org-export-backends'."
+ :group 'org
+ :set 'org-set-modules
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type
+ '(set :greedy t
+ (const :tag " bbdb: Links to BBDB entries" org-bbdb)
+ (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
+ (const :tag " crypt: Encryption of subtrees" org-crypt)
+ (const :tag " ctags: Access to Emacs tags with links" org-ctags)
+ (const :tag " docview: Links to doc-view buffers" org-docview)
+ (const :tag " eww: Store link to url of eww" org-eww)
+ (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
+ (const :tag " habit: Track your consistency with habits" org-habit)
+ (const :tag " id: Global IDs for identifying entries" org-id)
+ (const :tag " info: Links to Info nodes" org-info)
+ (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
+ (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
+ (const :tag " mhe: Links to MHE folders/messages" org-mhe)
+ (const :tag " mouse: Additional mouse support" org-mouse)
+ (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
+ (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
+ (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
+
+ (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
+ (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
+ (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
+ (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
+ (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
+ (const :tag "C collector: Collect properties into tables" org-collector)
+ (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
+ (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
+ (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
+ (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
+ (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
+ (const :tag "C eval: Include command output as text" org-eval)
+ (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
+ (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
+ (const :tag "C git-link: Provide org links to specific file version" org-git-link)
+ (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
+ (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
+ (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
+ (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
+ (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
+ (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
+ (const :tag "C man: Support for links to manpages in Org mode" org-man)
+ (const :tag "C mew: Links to Mew folders/messages" org-mew)
+ (const :tag "C mtags: Support for muse-like tags" org-mtags)
+ (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
+ (const :tag "C panel: Simple routines for us with bad memory" org-panel)
+ (const :tag "C registry: A registry for Org links" org-registry)
+ (const :tag "C screen: Visit screen sessions through Org links" org-screen)
+ (const :tag "C secretary: Team management with org-mode" org-secretary)
+ (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
+ (const :tag "C toc: Table of contents for Org buffer" org-toc)
+ (const :tag "C track: Keep up with Org mode development" org-track)
+ (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
+ (const :tag "C vm: Links to VM folders/messages" org-vm)
+ (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
+ (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
+ (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
+
+(defvar org-export-registered-backends) ; From ox.el.
+(declare-function org-export-derived-backend-p "ox" (backend &rest backends))
+(declare-function org-export-backend-name "ox" (backend) t)
+(defcustom org-export-backends '(ascii html icalendar latex odt)
+ "List of export back-ends that should be always available.
+
+If a description starts with <C>, the file is not part of Emacs
+and loading it will require that you have downloaded and properly
+installed the Org mode distribution.
+
+Unlike to `org-modules', libraries in this list will not be
+loaded along with Org, but only once the export framework is
+needed.
+
+This variable needs to be set before org.el is loaded. If you
+need to make a change while Emacs is running, use the customize
+interface or run the following code, where VAL stands for the new
+value of the variable, after updating it:
+
+ (progn
+ (setq org-export-registered-backends
+ (cl-remove-if-not
+ (lambda (backend)
+ (let ((name (org-export-backend-name backend)))
+ (or (memq name val)
+ (catch \\='parentp
+ (dolist (b val)
+ (and (org-export-derived-backend-p b name)
+ (throw \\='parentp t)))))))
+ org-export-registered-backends))
+ (let ((new-list (mapcar #\\='org-export-backend-name
+ org-export-registered-backends)))
+ (dolist (backend val)
+ (cond
+ ((not (load (format \"ox-%s\" backend) t t))
+ (message \"Problems while trying to load export back-end \\=`%s\\='\"
+ backend))
+ ((not (memq backend new-list)) (push backend new-list))))
+ (set-default \\='org-export-backends new-list)))
+
+Adding a back-end to this list will also pull the back-end it
+depends on, if any."
+ :group 'org
+ :group 'org-export
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :initialize 'custom-initialize-set
+ :set (lambda (var val)
+ (if (not (featurep 'ox)) (set-default var val)
+ ;; Any back-end not required anymore (not present in VAL and not
+ ;; a parent of any back-end in the new value) is removed from the
+ ;; list of registered back-ends.
+ (setq org-export-registered-backends
+ (cl-remove-if-not
+ (lambda (backend)
+ (let ((name (org-export-backend-name backend)))
+ (or (memq name val)
+ (catch 'parentp
+ (dolist (b val)
+ (and (org-export-derived-backend-p b name)
+ (throw 'parentp t)))))))
+ org-export-registered-backends))
+ ;; Now build NEW-LIST of both new back-ends and required
+ ;; parents.
+ (let ((new-list (mapcar #'org-export-backend-name
+ org-export-registered-backends)))
+ (dolist (backend val)
+ (cond
+ ((not (load (format "ox-%s" backend) t t))
+ (message "Problems while trying to load export back-end `%s'"
+ backend))
+ ((not (memq backend new-list)) (push backend new-list))))
+ ;; Set VAR to that list with fixed dependencies.
+ (set-default var new-list))))
+ :type '(set :greedy t
+ (const :tag " ascii Export buffer to ASCII format" ascii)
+ (const :tag " beamer Export buffer to Beamer presentation" beamer)
+ (const :tag " html Export buffer to HTML format" html)
+ (const :tag " icalendar Export buffer to iCalendar format" icalendar)
+ (const :tag " latex Export buffer to LaTeX format" latex)
+ (const :tag " man Export buffer to MAN format" man)
+ (const :tag " md Export buffer to Markdown format" md)
+ (const :tag " odt Export buffer to ODT format" odt)
+ (const :tag " org Export buffer to Org format" org)
+ (const :tag " texinfo Export buffer to Texinfo format" texinfo)
+ (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
+ (const :tag "C deck Export buffer to deck.js presentations" deck)
+ (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
+ (const :tag "C groff Export buffer to Groff format" groff)
+ (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
+ (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
+ (const :tag "C s5 Export buffer to s5 presentations" s5)
+ (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
+
+(eval-after-load 'ox
+ '(dolist (backend org-export-backends)
+ (condition-case nil (require (intern (format "ox-%s" backend)))
+ (error (message "Problems while trying to load export back-end `%s'"
+ backend)))))
+
+(defcustom org-support-shift-select nil
+ "Non-nil means make shift-cursor commands select text when possible.
+\\<org-mode-map>\
+
+In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
+start selecting a region, or enlarge regions started in this way.
+In Org mode, in special contexts, these same keys are used for
+other purposes, important enough to compete with shift selection.
+Org tries to balance these needs by supporting `shift-select-mode'
+outside these special contexts, under control of this variable.
+
+The default of this variable is nil, to avoid confusing behavior. Shifted
+cursor keys will then execute Org commands in the following contexts:
+- on a headline, changing TODO state (left/right) and priority (up/down)
+- on a time stamp, changing the time
+- in a plain list item, changing the bullet type
+- in a property definition line, switching between allowed values
+- in the BEGIN line of a clock table (changing the time block).
+Outside these contexts, the commands will throw an error.
+
+When this variable is t and the cursor is not in a special
+context, Org mode will support shift-selection for making and
+enlarging regions. To make this more effective, the bullet
+cycling will no longer happen anywhere in an item line, but only
+if the cursor is exactly on the bullet.
+
+If you set this variable to the symbol `always', then the keys
+will not be special in headlines, property lines, and item lines,
+to make shift selection work there as well. If this is what you
+want, you can use the following alternative commands:
+`\\[org-todo]' and `\\[org-priority]' \
+to change TODO state and priority,
+`\\[universal-argument] \\[universal-argument] \\[org-todo]' \
+can be used to switch TODO sets,
+`\\[org-ctrl-c-minus]' to cycle item bullet types,
+and properties can be edited by hand or in column view.
+
+However, when the cursor is on a timestamp, shift-cursor commands
+will still edit the time stamp - this is just too good to give up."
+ :group 'org
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "When outside special context" t)
+ (const :tag "Everywhere except timestamps" always)))
+
+(defcustom org-loop-over-headlines-in-active-region nil
+ "Shall some commands act upon headlines in the active region?
+
+When set to t, some commands will be performed in all headlines
+within the active region.
+
+When set to `start-level', some commands will be performed in all
+headlines within the active region, provided that these headlines
+are of the same level than the first one.
+
+When set to a string, those commands will be performed on the
+matching headlines within the active region. Such string must be
+a tags/property/todo match as it is used in the agenda tags view.
+
+The list of commands is: `org-schedule', `org-deadline',
+`org-todo', `org-archive-subtree', `org-archive-set-tag' and
+`org-archive-to-archive-sibling'. The archiving commands skip
+already archived entries."
+ :type '(choice (const :tag "Don't loop" nil)
+ (const :tag "All headlines in active region" t)
+ (const :tag "In active region, headlines at the same level than the first one" start-level)
+ (string :tag "Tags/Property/Todo matcher"))
+ :version "24.1"
+ :group 'org-todo
+ :group 'org-archive)
+
+(defgroup org-startup nil
+ "Options concerning startup of Org mode."
+ :tag "Org Startup"
+ :group 'org)
+
+(defcustom org-startup-folded t
+ "Non-nil means entering Org mode will switch to OVERVIEW.
+
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+
+ #+STARTUP: fold (or `overview', this is equivalent)
+ #+STARTUP: nofold (or `showall', this is equivalent)
+ #+STARTUP: content
+ #+STARTUP: showeverything
+
+Set `org-agenda-inhibit-startup' to a non-nil value if you want
+to ignore this option when Org opens agenda files for the first
+time."
+ :group 'org-startup
+ :type '(choice
+ (const :tag "nofold: show all" nil)
+ (const :tag "fold: overview" t)
+ (const :tag "content: all headlines" content)
+ (const :tag "show everything, even drawers" showeverything)))
+
+(defcustom org-startup-truncated t
+ "Non-nil means entering Org mode will set `truncate-lines'.
+This is useful since some lines containing links can be very long and
+uninteresting. Also tables look terrible when wrapped.
+
+The variable `org-startup-truncated' allows to configure
+truncation for Org mode different to the other modes that use the
+variable `truncate-lines' and as a shortcut instead of putting
+the variable `truncate-lines' into the `org-mode-hook'. If one
+wants to configure truncation for Org mode not statically but
+dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
+the variable `truncate-lines' has to be used because in such a
+case it is too late to set the variable `org-startup-truncated'."
+ :group 'org-startup
+ :type 'boolean)
+
+(defcustom org-startup-indented nil
+ "Non-nil means turn on `org-indent-mode' on startup.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+
+ #+STARTUP: indent
+ #+STARTUP: noindent"
+ :group 'org-structure
+ :type '(choice
+ (const :tag "Not" nil)
+ (const :tag "Globally (slow on startup in large files)" t)))
+
+(defcustom org-use-sub-superscripts t
+ "Non-nil means interpret \"_\" and \"^\" for display.
+
+If you want to control how Org exports those characters, see
+`org-export-with-sub-superscripts'. `org-use-sub-superscripts'
+used to be an alias for `org-export-with-sub-superscripts' in
+Org <8.0, it is not anymore.
+
+When this option is turned on, you can use TeX-like syntax for
+sub- and superscripts within the buffer. Several characters after
+\"_\" or \"^\" will be considered as a single item - so grouping
+with {} is normally not needed. For example, the following things
+will be parsed as single sub- or superscripts:
+
+ 10^24 or 10^tau several digits will be considered 1 item.
+ 10^-12 or 10^-tau a leading sign with digits or a word
+ x^2-y^3 will be read as x^2 - y^3, because items are
+ terminated by almost any nonword/nondigit char.
+ x_{i^2} or x^(2-i) braces or parenthesis do grouping.
+
+Still, ambiguity is possible. So when in doubt, use {} to enclose
+the sub/superscript. If you set this variable to the symbol `{}',
+the braces are *required* in order to trigger interpretations as
+sub/superscript. This can be helpful in documents that need \"_\"
+frequently in plain text."
+ :group 'org-startup
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Always interpret" t)
+ (const :tag "Only with braces" {})
+ (const :tag "Never interpret" nil)))
+
+(defcustom org-startup-with-beamer-mode nil
+ "Non-nil means turn on `org-beamer-mode' on startup.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+
+ #+STARTUP: beamer"
+ :group 'org-startup
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-startup-align-all-tables nil
+ "Non-nil means align all tables when visiting a file.
+This is useful when the column width in tables is forced with <N> cookies
+in table fields. Such tables will look correct only after the first re-align.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+ #+STARTUP: align
+ #+STARTUP: noalign"
+ :group 'org-startup
+ :type 'boolean)
+
+(defcustom org-startup-with-inline-images nil
+ "Non-nil means show inline images when loading a new Org file.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+ #+STARTUP: inlineimages
+ #+STARTUP: noinlineimages"
+ :group 'org-startup
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-startup-with-latex-preview nil
+ "Non-nil means preview LaTeX fragments when loading a new Org file.
+
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+ #+STARTUP: latexpreview
+ #+STARTUP: nolatexpreview"
+ :group 'org-startup
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-insert-mode-line-in-empty-file nil
+ "Non-nil means insert the first line setting Org mode in empty files.
+When the function `org-mode' is called interactively in an empty file, this
+normally means that the file name does not automatically trigger Org mode.
+To ensure that the file will always be in Org mode in the future, a
+line enforcing Org mode will be inserted into the buffer, if this option
+has been set."
+ :group 'org-startup
+ :type 'boolean)
+
+(defcustom org-replace-disputed-keys nil
+ "Non-nil means use alternative key bindings for some keys.
+Org mode uses S-<cursor> keys for changing timestamps and priorities.
+These keys are also used by other packages like shift-selection-mode'
+\(built into Emacs 23), `CUA-mode' or `windmove.el'.
+If you want to use Org mode together with one of these other modes,
+or more generally if you would like to move some Org mode commands to
+other keys, set this variable and configure the keys with the variable
+`org-disputed-keys'.
+
+This option is only relevant at load-time of Org mode, and must be set
+*before* org.el is loaded. Changing it requires a restart of Emacs to
+become effective."
+ :group 'org-startup
+ :type 'boolean)
+
+(defcustom org-use-extra-keys nil
+ "Non-nil means use extra key sequence definitions for certain commands.
+This happens automatically if `window-system' is nil. This
+variable lets you do the same manually. You must set it before
+loading Org."
+ :group 'org-startup
+ :type 'boolean)
+
+(defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
+
+(defcustom org-disputed-keys
+ '(([(shift up)] . [(meta p)])
+ ([(shift down)] . [(meta n)])
+ ([(shift left)] . [(meta -)])
+ ([(shift right)] . [(meta +)])
+ ([(control shift right)] . [(meta shift +)])
+ ([(control shift left)] . [(meta shift -)]))
+ "Keys for which Org mode and other modes compete.
+This is an alist, cars are the default keys, second element specifies
+the alternative to use when `org-replace-disputed-keys' is t.
+
+Keys can be specified in any syntax supported by `define-key'.
+The value of this option takes effect only at Org mode startup,
+therefore you'll have to restart Emacs to apply it after changing."
+ :group 'org-startup
+ :type 'alist)
+
+(defun org-key (key)
+ "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
+Or return the original if not disputed."
+ (when org-replace-disputed-keys
+ (let* ((nkey (key-description key))
+ (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
+ org-disputed-keys)))
+ (setq key (if x (cdr x) key))))
+ key)
+
+(defun org-defkey (keymap key def)
+ "Define a key, possibly translated, as returned by `org-key'."
+ (define-key keymap (org-key key) def))
+
+(defcustom org-ellipsis nil
+ "The ellipsis to use in the Org mode outline.
+
+When nil, just use the standard three dots.
+When a string, use that string instead.
+
+The change affects only Org mode (which will then use its own display table).
+Changing this requires executing `\\[org-mode]' in a buffer to become
+effective."
+ :group 'org-startup
+ :type '(choice (const :tag "Default" nil)
+ (string :tag "String" :value "...#"))
+ :safe #'string-or-null-p)
+
+(defvar org-display-table nil
+ "The display table for org-mode, in case `org-ellipsis' is non-nil.")
+
+(defgroup org-keywords nil
+ "Keywords in Org mode."
+ :tag "Org Keywords"
+ :group 'org)
+
+(defcustom org-closed-keep-when-no-todo nil
+ "Remove CLOSED: time-stamp when switching back to a non-todo state?"
+ :group 'org-todo
+ :group 'org-keywords
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defgroup org-structure nil
+ "Options concerning the general structure of Org files."
+ :tag "Org Structure"
+ :group 'org)
+
+(defgroup org-reveal-location nil
+ "Options about how to make context of a location visible."
+ :tag "Org Reveal Location"
+ :group 'org-structure)
+
+(defcustom org-show-context-detail '((agenda . local)
+ (bookmark-jump . lineage)
+ (isearch . lineage)
+ (default . ancestors))
+ "Alist between context and visibility span when revealing a location.
+
+\\<org-mode-map>Some actions may move point into invisible
+locations. As a consequence, Org always expose a neighborhood
+around point. How much is shown depends on the initial action,
+or context. Valid contexts are
+
+ agenda when exposing an entry from the agenda
+ org-goto when using the command `org-goto' (`\\[org-goto]')
+ occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
+ tags-tree when constructing a sparse tree based on tags matches
+ link-search when exposing search matches associated with a link
+ mark-goto when exposing the jump goal of a mark
+ bookmark-jump when exposing a bookmark location
+ isearch when exiting from an incremental search
+ default default for all contexts not set explicitly
+
+Allowed visibility spans are
+
+ minimal show current headline; if point is not on headline,
+ also show entry
+
+ local show current headline, entry and next headline
+
+ ancestors show current headline and its direct ancestors; if
+ point is not on headline, also show entry
+
+ lineage show current headline, its direct ancestors and all
+ their children; if point is not on headline, also show
+ entry and first child
+
+ tree show current headline, its direct ancestors and all
+ their children; if point is not on headline, also show
+ entry and all children
+
+ canonical show current headline, its direct ancestors along with
+ their entries and children; if point is not located on
+ the headline, also show current entry and all children
+
+As special cases, a nil or t value means show all contexts in
+`minimal' or `canonical' view, respectively.
+
+Some views can make displayed information very compact, but also
+make it harder to edit the location of the match. In such
+a case, use the command `org-reveal' (`\\[org-reveal]') to show
+more context."
+ :group 'org-reveal-location
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type '(choice
+ (const :tag "Canonical" t)
+ (const :tag "Minimal" nil)
+ (repeat :greedy t :tag "Individual contexts"
+ (cons
+ (choice :tag "Context"
+ (const agenda)
+ (const org-goto)
+ (const occur-tree)
+ (const tags-tree)
+ (const link-search)
+ (const mark-goto)
+ (const bookmark-jump)
+ (const isearch)
+ (const default))
+ (choice :tag "Detail level"
+ (const minimal)
+ (const local)
+ (const ancestors)
+ (const lineage)
+ (const tree)
+ (const canonical))))))
+
+(defcustom org-indirect-buffer-display 'other-window
+ "How should indirect tree buffers be displayed?
+
+This applies to indirect buffers created with the commands
+`org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
+
+Valid values are:
+current-window Display in the current window
+other-window Just display in another window.
+dedicated-frame Create one new frame, and re-use it each time.
+new-frame Make a new frame each time. Note that in this case
+ previously-made indirect buffers are kept, and you need to
+ kill these buffers yourself."
+ :group 'org-structure
+ :group 'org-agenda-windows
+ :type '(choice
+ (const :tag "In current window" current-window)
+ (const :tag "In current frame, other window" other-window)
+ (const :tag "Each time a new frame" new-frame)
+ (const :tag "One dedicated frame" dedicated-frame)))
+
+(defcustom org-use-speed-commands nil
+ "Non-nil means activate single letter commands at beginning of a headline.
+This may also be a function to test for appropriate locations where speed
+commands should be active.
+
+For example, to activate speed commands when the point is on any
+star at the beginning of the headline, you can do this:
+
+ (setq org-use-speed-commands
+ (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
+ :group 'org-structure
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "At beginning of headline stars" t)
+ (function)))
+
+(defcustom org-speed-commands-user nil
+ "Alist of additional speed commands.
+This list will be checked before `org-speed-commands-default'
+when the variable `org-use-speed-commands' is non-nil
+and when the cursor is at the beginning of a headline.
+The car if each entry is a string with a single letter, which must
+be assigned to `self-insert-command' in the global map.
+The cdr is either a command to be called interactively, a function
+to be called, or a form to be evaluated.
+An entry that is just a list with a single string will be interpreted
+as a descriptive headline that will be added when listing the speed
+commands in the Help buffer using the `?' speed command."
+ :group 'org-structure
+ :type '(repeat :value ("k" . ignore)
+ (choice :value ("k" . ignore)
+ (list :tag "Descriptive Headline" (string :tag "Headline"))
+ (cons :tag "Letter and Command"
+ (string :tag "Command letter")
+ (choice
+ (function)
+ (sexp))))))
+
+(defcustom org-bookmark-names-plist
+ '(:last-capture "org-capture-last-stored"
+ :last-refile "org-refile-last-stored"
+ :last-capture-marker "org-capture-last-stored-marker")
+ "Names for bookmarks automatically set by some Org commands.
+This can provide strings as names for a number of bookmarks Org sets
+automatically. The following keys are currently implemented:
+ :last-capture
+ :last-capture-marker
+ :last-refile
+When a key does not show up in the property list, the corresponding bookmark
+is not set."
+ :group 'org-structure
+ :type 'plist)
+
+(defgroup org-cycle nil
+ "Options concerning visibility cycling in Org mode."
+ :tag "Org Cycle"
+ :group 'org-structure)
+
+(defcustom org-cycle-skip-children-state-if-no-children t
+ "Non-nil means skip CHILDREN state in entries that don't have any."
+ :group 'org-cycle
+ :type 'boolean)
+
+(defcustom org-cycle-max-level nil
+ "Maximum level which should still be subject to visibility cycling.
+Levels higher than this will, for cycling, be treated as text, not a headline.
+When `org-odd-levels-only' is set, a value of N in this variable actually
+means 2N-1 stars as the limiting headline.
+When nil, cycle all levels.
+Note that the limiting level of cycling is also influenced by
+`org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
+`org-inlinetask-min-level' is, cycling will be limited to levels one less
+than its value."
+ :group 'org-cycle
+ :type '(choice
+ (const :tag "No limit" nil)
+ (integer :tag "Maximum level")))
+
+(defcustom org-hide-block-startup nil
+ "Non-nil means entering Org mode will fold all blocks.
+This can also be set in on a per-file basis with
+
+#+STARTUP: hideblocks
+#+STARTUP: showblocks"
+ :group 'org-startup
+ :group 'org-cycle
+ :type 'boolean)
+
+(defcustom org-cycle-global-at-bob nil
+ "Cycle globally if cursor is at beginning of buffer and not at a headline.
+
+This makes it possible to do global cycling without having to use `S-TAB'
+or `\\[universal-argument] TAB'. For this special case to work, the first \
+line of the buffer
+must not be a headline -- it may be empty or some other text.
+
+When used in this way, `org-cycle-hook' is disabled temporarily to make
+sure the cursor stays at the beginning of the buffer.
+
+When this option is nil, don't do anything special at the beginning of
+the buffer."
+ :group 'org-cycle
+ :type 'boolean)
+
+(defcustom org-cycle-level-after-item/entry-creation t
+ "Non-nil means cycle entry level or item indentation in new empty entries.
+
+When the cursor is at the end of an empty headline, i.e., with only stars
+and maybe a TODO keyword, TAB will then switch the entry to become a child,
+and then all possible ancestor states, before returning to the original state.
+This makes data entry extremely fast: M-RET to create a new headline,
+on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
+
+When the cursor is at the end of an empty plain list item, one TAB will
+make it a subitem, two or more tabs will back up to make this an item
+higher up in the item hierarchy."
+ :group 'org-cycle
+ :type 'boolean)
+
+(defcustom org-cycle-emulate-tab t
+ "Where should `org-cycle' emulate TAB.
+nil Never
+white Only in completely white lines
+whitestart Only at the beginning of lines, before the first non-white char
+t Everywhere except in headlines
+exc-hl-bol Everywhere except at the start of a headline
+If TAB is used in a place where it does not emulate TAB, the current subtree
+visibility is cycled."
+ :group 'org-cycle
+ :type '(choice (const :tag "Never" nil)
+ (const :tag "Only in completely white lines" white)
+ (const :tag "Before first char in a line" whitestart)
+ (const :tag "Everywhere except in headlines" t)
+ (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
+
+(defcustom org-cycle-separator-lines 2
+ "Number of empty lines needed to keep an empty line between collapsed trees.
+If you leave an empty line between the end of a subtree and the following
+headline, this empty line is hidden when the subtree is folded.
+Org mode will leave (exactly) one empty line visible if the number of
+empty lines is equal or larger to the number given in this variable.
+So the default 2 means at least 2 empty lines after the end of a subtree
+are needed to produce free space between a collapsed subtree and the
+following headline.
+
+If the number is negative, and the number of empty lines is at least -N,
+all empty lines are shown.
+
+Special case: when 0, never leave empty lines in collapsed view."
+ :group 'org-cycle
+ :type 'integer)
+(put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
+
+(defcustom org-pre-cycle-hook nil
+ "Hook that is run before visibility cycling is happening.
+The function(s) in this hook must accept a single argument which indicates
+the new state that will be set right after running this hook. The
+argument is a symbol. Before a global state change, it can have the values
+`overview', `content', or `all'. Before a local state change, it can have
+the values `folded', `children', or `subtree'."
+ :group 'org-cycle
+ :type 'hook)
+
+(defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
+ org-cycle-hide-drawers
+ org-cycle-show-empty-lines
+ org-optimize-window-after-visibility-change)
+ "Hook that is run after `org-cycle' has changed the buffer visibility.
+The function(s) in this hook must accept a single argument which indicates
+the new state that was set by the most recent `org-cycle' command. The
+argument is a symbol. After a global state change, it can have the values
+`overview', `contents', or `all'. After a local state change, it can have
+the values `folded', `children', or `subtree'."
+ :group 'org-cycle
+ :type 'hook
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+(defgroup org-edit-structure nil
+ "Options concerning structure editing in Org mode."
+ :tag "Org Edit Structure"
+ :group 'org-structure)
+
+(defcustom org-odd-levels-only nil
+ "Non-nil means skip even levels and only use odd levels for the outline.
+This has the effect that two stars are being added/taken away in
+promotion/demotion commands. It also influences how levels are
+handled by the exporters.
+Changing it requires restart of `font-lock-mode' to become effective
+for fontification also in regions already fontified.
+You may also set this on a per-file basis by adding one of the following
+lines to the buffer:
+
+ #+STARTUP: odd
+ #+STARTUP: oddeven"
+ :group 'org-edit-structure
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-adapt-indentation t
+ "Non-nil means adapt indentation to outline node level.
+
+When this variable is set, Org assumes that you write outlines by
+indenting text in each node to align with the headline (after the
+stars). The following issues are influenced by this variable:
+
+- The indentation is increased by one space in a demotion
+ command, and decreased by one in a promotion command. However,
+ in the latter case, if shifting some line in the entry body
+ would alter document structure (e.g., insert a new headline),
+ indentation is not changed at all.
+
+- Property drawers and planning information is inserted indented
+ when this variable is set. When nil, they will not be indented.
+
+- TAB indents a line relative to current level. The lines below
+ a headline will be indented when this variable is set.
+
+Note that this is all about true indentation, by adding and
+removing space characters. See also `org-indent.el' which does
+level-dependent indentation in a virtual way, i.e. at display
+time in Emacs."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-special-ctrl-a/e nil
+ "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
+
+When t, `C-a' will bring back the cursor to the beginning of the
+headline text, i.e. after the stars and after a possible TODO
+keyword. In an item, this will be the position after bullet and
+check-box, if any. When the cursor is already at that position,
+another `C-a' will bring it to the beginning of the line.
+
+`C-e' will jump to the end of the headline, ignoring the presence
+of tags in the headline. A second `C-e' will then jump to the
+true end of the line, after any tags. This also means that, when
+this variable is non-nil, `C-e' also will never jump beyond the
+end of the heading of a folded section, i.e. not after the
+ellipses.
+
+When set to the symbol `reversed', the first `C-a' or `C-e' works
+normally, going to the true line boundary first. Only a directly
+following, identical keypress will bring the cursor to the
+special positions.
+
+This may also be a cons cell where the behavior for `C-a' and
+`C-e' is set separately."
+ :group 'org-edit-structure
+ :type '(choice
+ (const :tag "off" nil)
+ (const :tag "on: after stars/bullet and before tags first" t)
+ (const :tag "reversed: true line boundary first" reversed)
+ (cons :tag "Set C-a and C-e separately"
+ (choice :tag "Special C-a"
+ (const :tag "off" nil)
+ (const :tag "on: after stars/bullet first" t)
+ (const :tag "reversed: before stars/bullet first" reversed))
+ (choice :tag "Special C-e"
+ (const :tag "off" nil)
+ (const :tag "on: before tags first" t)
+ (const :tag "reversed: after tags first" reversed)))))
+(defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
+
+(defcustom org-special-ctrl-k nil
+ "Non-nil means `C-k' will behave specially in headlines.
+When nil, `C-k' will call the default `kill-line' command.
+When t, the following will happen while the cursor is in the headline:
+
+- When the cursor is at the beginning of a headline, kill the entire
+ line and possible the folded subtree below the line.
+- When in the middle of the headline text, kill the headline up to the tags.
+- When after the headline text, kill the tags."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-ctrl-k-protect-subtree nil
+ "Non-nil means, do not delete a hidden subtree with C-k.
+When set to the symbol `error', simply throw an error when C-k is
+used to kill (part-of) a headline that has hidden text behind it.
+Any other non-nil value will result in a query to the user, if it is
+OK to kill that hidden subtree. When nil, kill without remorse."
+ :group 'org-edit-structure
+ :version "24.1"
+ :type '(choice
+ (const :tag "Do not protect hidden subtrees" nil)
+ (const :tag "Protect hidden subtrees with a security query" t)
+ (const :tag "Never kill a hidden subtree with C-k" error)))
+
+(defcustom org-special-ctrl-o t
+ "Non-nil means, make `C-o' insert a row in tables."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-catch-invisible-edits nil
+ "Check if in invisible region before inserting or deleting a character.
+Valid values are:
+
+nil Do not check, so just do invisible edits.
+error Throw an error and do nothing.
+show Make point visible, and do the requested edit.
+show-and-error Make point visible, then throw an error and abort the edit.
+smart Make point visible, and do insertion/deletion if it is
+ adjacent to visible text and the change feels predictable.
+ Never delete a previously invisible character or add in the
+ middle or right after an invisible region. Basically, this
+ allows insertion and backward-delete right before ellipses.
+ FIXME: maybe in this case we should not even show?"
+ :group 'org-edit-structure
+ :version "24.1"
+ :type '(choice
+ (const :tag "Do not check" nil)
+ (const :tag "Throw error when trying to edit" error)
+ (const :tag "Unhide, but do not do the edit" show-and-error)
+ (const :tag "Show invisible part and do the edit" show)
+ (const :tag "Be smart and do the right thing" smart)))
+
+(defcustom org-yank-folded-subtrees t
+ "Non-nil means when yanking subtrees, fold them.
+If the kill is a single subtree, or a sequence of subtrees, i.e. if
+it starts with a heading and all other headings in it are either children
+or siblings, then fold all the subtrees. However, do this only if no
+text after the yank would be swallowed into a folded tree by this action."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-yank-adjusted-subtrees nil
+ "Non-nil means when yanking subtrees, adjust the level.
+With this setting, `org-paste-subtree' is used to insert the subtree, see
+this function for details."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-M-RET-may-split-line '((default . t))
+ "Non-nil means M-RET will split the line at the cursor position.
+When nil, it will go to the end of the line before making a
+new line.
+You may also set this option in a different way for different
+contexts. Valid contexts are:
+
+headline when creating a new headline
+item when creating a new item
+table in a table field
+default the value to be used for all contexts not explicitly
+ customized"
+ :group 'org-structure
+ :group 'org-table
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (repeat :greedy t :tag "Individual contexts"
+ (cons
+ (choice :tag "Context"
+ (const headline)
+ (const item)
+ (const table)
+ (const default))
+ (boolean)))))
+
+
+(defcustom org-insert-heading-respect-content nil
+ "Non-nil means insert new headings after the current subtree.
+\\<org-mode-map>
+When nil, the new heading is created directly after the current line.
+The commands `\\[org-insert-heading-respect-content]' and \
+`\\[org-insert-todo-heading-respect-content]' turn this variable on
+for the duration of the command."
+ :group 'org-structure
+ :type 'boolean)
+
+(defcustom org-blank-before-new-entry '((heading . auto)
+ (plain-list-item . auto))
+ "Should `org-insert-heading' leave a blank line before new heading/item?
+The value is an alist, with `heading' and `plain-list-item' as CAR,
+and a boolean flag as CDR. The cdr may also be the symbol `auto', in
+which case Org will look at the surrounding headings/items and try to
+make an intelligent decision whether to insert a blank line or not."
+ :group 'org-edit-structure
+ :type '(list
+ (cons (const heading)
+ (choice (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (const :tag "Auto" auto)))
+ (cons (const plain-list-item)
+ (choice (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (const :tag "Auto" auto)))))
+
+(defcustom org-insert-heading-hook nil
+ "Hook being run after inserting a new heading."
+ :group 'org-edit-structure
+ :type 'hook)
+
+(defcustom org-enable-fixed-width-editor t
+ "Non-nil means lines starting with \":\" are treated as fixed-width.
+This currently only means they are never auto-wrapped.
+When nil, such lines will be treated like ordinary lines."
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defcustom org-goto-auto-isearch t
+ "Non-nil means typing characters in `org-goto' starts incremental search.
+When nil, you can use these keybindings to navigate the buffer:
+
+ q Quit the org-goto interface
+ n Go to the next visible heading
+ p Go to the previous visible heading
+ f Go one heading forward on same level
+ b Go one heading backward on same level
+ u Go one heading up"
+ :group 'org-edit-structure
+ :type 'boolean)
+
+(defgroup org-sparse-trees nil
+ "Options concerning sparse trees in Org mode."
+ :tag "Org Sparse Trees"
+ :group 'org-structure)
+
+(defcustom org-highlight-sparse-tree-matches t
+ "Non-nil means highlight all matches that define a sparse tree.
+The highlights will automatically disappear the next time the buffer is
+changed by an edit command."
+ :group 'org-sparse-trees
+ :type 'boolean)
+
+(defcustom org-remove-highlights-with-change t
+ "Non-nil means any change to the buffer will remove temporary highlights.
+\\<org-mode-map>\
+Such highlights are created by `org-occur' and `org-clock-display'.
+When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
+to get rid of the highlights.
+The highlights created by `org-toggle-latex-fragment' always need
+`\\[org-toggle-latex-fragment]' to be removed."
+ :group 'org-sparse-trees
+ :group 'org-time
+ :type 'boolean)
+
+(defcustom org-occur-case-fold-search t
+ "Non-nil means `org-occur' should be case-insensitive.
+If set to `smart' the search will be case-insensitive only if it
+doesn't specify any upper case character."
+ :group 'org-sparse-trees
+ :version "26.1"
+ :type '(choice
+ (const :tag "Case-sensitive" nil)
+ (const :tag "Case-insensitive" t)
+ (const :tag "Case-insensitive for lower case searches only" 'smart)))
+
+(defcustom org-occur-hook '(org-first-headline-recenter)
+ "Hook that is run after `org-occur' has constructed a sparse tree.
+This can be used to recenter the window to show as much of the structure
+as possible."
+ :group 'org-sparse-trees
+ :type 'hook)
+
+(defgroup org-imenu-and-speedbar nil
+ "Options concerning imenu and speedbar in Org mode."
+ :tag "Org Imenu and Speedbar"
+ :group 'org-structure)
+
+(defcustom org-imenu-depth 2
+ "The maximum level for Imenu access to Org headlines.
+This also applied for speedbar access."
+ :group 'org-imenu-and-speedbar
+ :type 'integer)
+
+(defgroup org-table nil
+ "Options concerning tables in Org mode."
+ :tag "Org Table"
+ :group 'org)
+
+(defcustom org-enable-table-editor 'optimized
+ "Non-nil means lines starting with \"|\" are handled by the table editor.
+When nil, such lines will be treated like ordinary lines.
+
+When equal to the symbol `optimized', the table editor will be optimized to
+do the following:
+- Automatic overwrite mode in front of whitespace in table fields.
+ This makes the structure of the table stay in tact as long as the edited
+ field does not exceed the column width.
+- Minimize the number of realigns. Normally, the table is aligned each time
+ TAB or RET are pressed to move to another field. With optimization this
+ happens only if changes to a field might have changed the column width.
+Optimization requires replacing the functions `self-insert-command',
+`delete-char', and `backward-delete-char' in Org buffers, with a
+slight (in fact: unnoticeable) speed impact for normal typing. Org is very
+good at guessing when a re-align will be necessary, but you can always
+force one with `\\[org-ctrl-c-ctrl-c]'.
+
+If you would like to use the optimized version in Org mode, but the
+un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
+
+This variable can be used to turn on and off the table editor during a session,
+but in order to toggle optimization, a restart is required.
+
+See also the variable `org-table-auto-blank-field'."
+ :group 'org-table
+ :type '(choice
+ (const :tag "off" nil)
+ (const :tag "on" t)
+ (const :tag "on, optimized" optimized)))
+
+(defcustom org-self-insert-cluster-for-undo nil
+ "Non-nil means cluster self-insert commands for undo when possible.
+If this is set, then, like in the Emacs command loop, 20 consecutive
+characters will be undone together.
+This is configurable, because there is some impact on typing performance."
+ :group 'org-table
+ :type 'boolean)
+
+(defcustom org-table-tab-recognizes-table.el t
+ "Non-nil means TAB will automatically notice a table.el table.
+When it sees such a table, it moves point into it and - if necessary -
+calls `table-recognize-table'."
+ :group 'org-table-editing
+ :type 'boolean)
+
+(defgroup org-link nil
+ "Options concerning links in Org mode."
+ :tag "Org Link"
+ :group 'org)
+
+(defvar-local org-link-abbrev-alist-local nil
+ "Buffer-local version of `org-link-abbrev-alist', which see.
+The value of this is taken from the #+LINK lines.")
+
+(defcustom org-link-parameters
+ '(("doi" :follow org--open-doi-link)
+ ("elisp" :follow org--open-elisp-link)
+ ("file" :complete org-file-complete-link)
+ ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
+ ("help" :follow org--open-help-link)
+ ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
+ ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
+ ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
+ ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
+ ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
+ ("shell" :follow org--open-shell-link))
+ "An alist of properties that defines all the links in Org mode.
+The key in each association is a string of the link type.
+Subsequent optional elements make up a p-list of link properties.
+
+:follow - A function that takes the link path as an argument.
+
+:export - A function that takes the link path, description and
+export-backend as arguments.
+
+:store - A function responsible for storing the link. See the
+function `org-store-link-functions'.
+
+:complete - A function that inserts a link with completion. The
+function takes one optional prefix arg.
+
+:face - A face for the link, or a function that returns a face.
+The function takes one argument which is the link path. The
+default face is `org-link'.
+
+:mouse-face - The mouse-face. The default is `highlight'.
+
+:display - `full' will not fold the link in descriptive
+display. Default is `org-link'.
+
+:help-echo - A string or function that takes (window object position)
+as arguments and returns a string.
+
+:keymap - A keymap that is active on the link. The default is
+`org-mouse-map'.
+
+:htmlize-link - A function for the htmlize-link. Defaults
+to (list :uri \"type:path\")
+
+:activate-func - A function to run at the end of font-lock
+activation. The function must accept (link-start link-end path bracketp)
+as arguments."
+ :group 'org-link
+ :type '(alist :tag "Link display parameters"
+ :value-type plist))
+
+(defun org-link-get-parameter (type key)
+ "Get TYPE link property for KEY.
+TYPE is a string and KEY is a plist keyword."
+ (plist-get
+ (cdr (assoc type org-link-parameters))
+ key))
+
+(defun org-link-set-parameters (type &rest parameters)
+ "Set link TYPE properties to PARAMETERS.
+ PARAMETERS should be :key val pairs."
+ (let ((data (assoc type org-link-parameters)))
+ (if data (setcdr data (org-combine-plists (cdr data) parameters))
+ (push (cons type parameters) org-link-parameters)
+ (org-make-link-regexps)
+ (org-element-update-syntax))))
+
+(defun org-link-types ()
+ "Return a list of known link types."
+ (mapcar #'car org-link-parameters))
+
+(defcustom org-link-abbrev-alist nil
+ "Alist of link abbreviations.
+The car of each element is a string, to be replaced at the start of a link.
+The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
+links in Org buffers can have an optional tag after a double colon, e.g.,
+
+ [[linkkey:tag][description]]
+
+The `linkkey' must be a single word, starting with a letter, followed
+by letters, numbers, `-' or `_'.
+
+If REPLACE is a string, the tag will simply be appended to create the link.
+If the string contains \"%s\", the tag will be inserted there. If the string
+contains \"%h\", it will cause a url-encoded version of the tag to be inserted
+at that point (see the function `url-hexify-string'). If the string contains
+the specifier \"%(my-function)\", then the custom function `my-function' will
+be invoked: this function takes the tag as its only argument and must return
+a string.
+
+REPLACE may also be a function that will be called with the tag as the
+only argument to create the link, which should be returned as a string.
+
+See the manual for examples."
+ :group 'org-link
+ :type '(repeat
+ (cons
+ (string :tag "Protocol")
+ (choice
+ (string :tag "Format")
+ (function)))))
+
+(defcustom org-descriptive-links t
+ "Non-nil means Org will display descriptive links.
+E.g. [[http://orgmode.org][Org website]] will be displayed as
+\"Org Website\", hiding the link itself and just displaying its
+description. When set to nil, Org will display the full links
+literally.
+
+You can interactively set the value of this variable by calling
+`org-toggle-link-display' or from the menu Org>Hyperlinks menu."
+ :group 'org-link
+ :type 'boolean)
+
+(defcustom org-link-file-path-type 'adaptive
+ "How the path name in file links should be stored.
+Valid values are:
+
+relative Relative to the current directory, i.e. the directory of the file
+ into which the link is being inserted.
+absolute Absolute path, if possible with ~ for home directory.
+noabbrev Absolute path, no abbreviation of home directory.
+adaptive Use relative path for files in the current directory and sub-
+ directories of it. For other files, use an absolute path."
+ :group 'org-link
+ :type '(choice
+ (const relative)
+ (const absolute)
+ (const noabbrev)
+ (const adaptive)))
+
+(defvaralias 'org-activate-links 'org-highlight-links)
+(defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
+ "Types of links that should be highlighted in Org files.
+
+This is a list of symbols, each one of them leading to the
+highlighting of a certain link type.
+
+You can still open links that are not highlighted.
+
+In principle, it does not hurt to turn on highlighting for all
+link types. There may be a small gain when turning off unused
+link types. The types are:
+
+bracket The recommended [[link][description]] or [[link]] links with hiding.
+angle Links in angular brackets that may contain whitespace like
+ <bbdb:Carsten Dominik>.
+plain Plain links in normal text, no whitespace, like http://google.com.
+radio Text that is matched by a radio target, see manual for details.
+tag Tag settings in a headline (link to tag search).
+date Time stamps (link to calendar).
+footnote Footnote labels.
+
+If you set this variable during an Emacs session, use `org-mode-restart'
+in the Org buffer so that the change takes effect."
+ :group 'org-link
+ :group 'org-appearance
+ :type '(set :greedy t
+ (const :tag "Double bracket links" bracket)
+ (const :tag "Angular bracket links" angle)
+ (const :tag "Plain text links" plain)
+ (const :tag "Radio target matches" radio)
+ (const :tag "Tags" tag)
+ (const :tag "Timestamps" date)
+ (const :tag "Footnotes" footnote)))
+
+(defcustom org-make-link-description-function nil
+ "Function to use for generating link descriptions from links.
+When nil, the link location will be used. This function must take
+two parameters: the first one is the link, the second one is the
+description generated by `org-insert-link'. The function should
+return the description to use."
+ :group 'org-link
+ :type '(choice (const nil) (function)))
+
+(defgroup org-link-store nil
+ "Options concerning storing links in Org mode."
+ :tag "Org Store Link"
+ :group 'org-link)
+
+(defcustom org-url-hexify-p t
+ "When non-nil, hexify URL when creating a link."
+ :type 'boolean
+ :version "24.3"
+ :group 'org-link-store)
+
+(defcustom org-email-link-description-format "Email %c: %.30s"
+ "Format of the description part of a link to an email or usenet message.
+The following %-escapes will be replaced by corresponding information:
+
+%F full \"From\" field
+%f name, taken from \"From\" field, address if no name
+%T full \"To\" field
+%t first name in \"To\" field, address if no name
+%c correspondent. Usually \"from NAME\", but if you sent it yourself, it
+ will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
+%s subject
+%d date
+%m message-id.
+
+You may use normal field width specification between the % and the letter.
+This is for example useful to limit the length of the subject.
+
+Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
+ :group 'org-link-store
+ :type 'string)
+
+(defcustom org-from-is-user-regexp
+ (let (r1 r2)
+ (when (and user-mail-address (not (string= user-mail-address "")))
+ (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
+ (when (and user-full-name (not (string= user-full-name "")))
+ (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
+ (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
+ "Regexp matched against the \"From:\" header of an email or usenet message.
+It should match if the message is from the user him/herself."
+ :group 'org-link-store
+ :type 'regexp)
+
+(defcustom org-context-in-file-links t
+ "Non-nil means file links from `org-store-link' contain context.
+\\<org-mode-map>
+A search string will be added to the file name with :: as separator
+and used to find the context when the link is activated by the command
+`org-open-at-point'. When this option is t, the entire active region
+will be placed in the search string of the file link. If set to a
+positive integer, only the first n lines of context will be stored.
+
+Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
+\\[org-store-link]')
+negates this setting for the duration of the command."
+ :group 'org-link-store
+ :type '(choice boolean integer))
+
+(defcustom org-keep-stored-link-after-insertion nil
+ "Non-nil means keep link in list for entire session.
+\\<org-mode-map>
+The command `org-store-link' adds a link pointing to the current
+location to an internal list. These links accumulate during a session.
+The command `org-insert-link' can be used to insert links into any
+Org file (offering completion for all stored links).
+
+When this option is nil, every link which has been inserted once using
+`\\[org-insert-link]' will be removed from the list, to make completing the \
+unused
+links more efficient."
+ :group 'org-link-store
+ :type 'boolean)
+
+(defgroup org-link-follow nil
+ "Options concerning following links in Org mode."
+ :tag "Org Follow Link"
+ :group 'org-link)
+
+(defcustom org-link-translation-function nil
+ "Function to translate links with different syntax to Org syntax.
+This can be used to translate links created for example by the Planner
+or emacs-wiki packages to Org syntax.
+The function must accept two parameters, a TYPE containing the link
+protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
+which is everything after the link protocol. It should return a cons
+with possibly modified values of type and path.
+Org contains a function for this, so if you set this variable to
+`org-translate-link-from-planner', you should be able follow many
+links created by planner."
+ :group 'org-link-follow
+ :type '(choice (const nil) (function)))
+
+(defcustom org-follow-link-hook nil
+ "Hook that is run after a link has been followed."
+ :group 'org-link-follow
+ :type 'hook)
+
+(defcustom org-tab-follows-link nil
+ "Non-nil means on links TAB will follow the link.
+Needs to be set before org.el is loaded.
+This really should not be used, it does not make sense, and the
+implementation is bad."
+ :group 'org-link-follow
+ :type 'boolean)
+
+(defcustom org-return-follows-link nil
+ "Non-nil means on links RET will follow the link.
+In tables, the special behavior of RET has precedence."
+ :group 'org-link-follow
+ :type 'boolean)
+
+(defcustom org-mouse-1-follows-link
+ (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
+ "Non-nil means mouse-1 on a link will follow the link.
+A longer mouse click will still set point. Needs to be set
+before org.el is loaded."
+ :group 'org-link-follow
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "A double click follows the link" double)
+ (const :tag "Unconditionally follow the link with mouse-1" t)
+ (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
+
+(defcustom org-mark-ring-length 4
+ "Number of different positions to be recorded in the ring.
+Changing this requires a restart of Emacs to work correctly."
+ :group 'org-link-follow
+ :type 'integer)
+
+(defcustom org-link-search-must-match-exact-headline 'query-to-create
+ "Non-nil means internal fuzzy links can only match headlines.
+
+When nil, the a fuzzy link may point to a target or a named
+construct in the document. When set to the special value
+`query-to-create', offer to create a new headline when none
+matched.
+
+Spaces and statistics cookies are ignored during heading searches."
+ :group 'org-link-follow
+ :version "24.1"
+ :type '(choice
+ (const :tag "Use fuzzy text search" nil)
+ (const :tag "Match only exact headline" t)
+ (const :tag "Match exact headline or query to create it"
+ query-to-create))
+ :safe #'symbolp)
+
+(defcustom org-link-frame-setup
+ '((vm . vm-visit-folder-other-frame)
+ (vm-imap . vm-visit-imap-folder-other-frame)
+ (gnus . org-gnus-no-new-news)
+ (file . find-file-other-window)
+ (wl . wl-other-frame))
+ "Setup the frame configuration for following links.
+When following a link with Emacs, it may often be useful to display
+this link in another window or frame. This variable can be used to
+set this up for the different types of links.
+For VM, use any of
+ `vm-visit-folder'
+ `vm-visit-folder-other-window'
+ `vm-visit-folder-other-frame'
+For Gnus, use any of
+ `gnus'
+ `gnus-other-frame'
+ `org-gnus-no-new-news'
+For FILE, use any of
+ `find-file'
+ `find-file-other-window'
+ `find-file-other-frame'
+For Wanderlust use any of
+ `wl'
+ `wl-other-frame'
+For the calendar, use the variable `calendar-setup'.
+For BBDB, it is currently only possible to display the matches in
+another window."
+ :group 'org-link-follow
+ :type '(list
+ (cons (const vm)
+ (choice
+ (const vm-visit-folder)
+ (const vm-visit-folder-other-window)
+ (const vm-visit-folder-other-frame)))
+ (cons (const vm-imap)
+ (choice
+ (const vm-visit-imap-folder)
+ (const vm-visit-imap-folder-other-window)
+ (const vm-visit-imap-folder-other-frame)))
+ (cons (const gnus)
+ (choice
+ (const gnus)
+ (const gnus-other-frame)
+ (const org-gnus-no-new-news)))
+ (cons (const file)
+ (choice
+ (const find-file)
+ (const find-file-other-window)
+ (const find-file-other-frame)))
+ (cons (const wl)
+ (choice
+ (const wl)
+ (const wl-other-frame)))))
+
+(defcustom org-display-internal-link-with-indirect-buffer nil
+ "Non-nil means use indirect buffer to display infile links.
+Activating internal links (from one location in a file to another location
+in the same file) normally just jumps to the location. When the link is
+activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
+is displayed in
+another window. When this option is set, the other window actually displays
+an indirect buffer clone of the current buffer, to avoid any visibility
+changes to the current buffer."
+ :group 'org-link-follow
+ :type 'boolean)
+
+(defcustom org-open-non-existing-files nil
+ "Non-nil means `org-open-file' will open non-existing files.
+When nil, an error will be generated.
+This variable applies only to external applications because they
+might choke on non-existing files. If the link is to a file that
+will be opened in Emacs, the variable is ignored."
+ :group 'org-link-follow
+ :type 'boolean)
+
+(defcustom org-open-directory-means-index-dot-org nil
+ "Non-nil means a link to a directory really means to index.org.
+When nil, following a directory link will run dired or open a finder/explorer
+window on that directory."
+ :group 'org-link-follow
+ :type 'boolean)
+
+(defcustom org-confirm-shell-link-function 'yes-or-no-p
+ "Non-nil means ask for confirmation before executing shell links.
+Shell links can be dangerous: just think about a link
+
+ [[shell:rm -rf ~/*][Google Search]]
+
+This link would show up in your Org document as \"Google Search\",
+but really it would remove your entire home directory.
+Therefore we advise against setting this variable to nil.
+Just change it to `y-or-n-p' if you want to confirm with a
+single keystroke rather than having to type \"yes\"."
+ :group 'org-link-follow
+ :type '(choice
+ (const :tag "with yes-or-no (safer)" yes-or-no-p)
+ (const :tag "with y-or-n (faster)" y-or-n-p)
+ (const :tag "no confirmation (dangerous)" nil)))
+(put 'org-confirm-shell-link-function
+ 'safe-local-variable
+ (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
+
+(defcustom org-confirm-shell-link-not-regexp ""
+ "A regexp to skip confirmation for shell links."
+ :group 'org-link-follow
+ :version "24.1"
+ :type 'regexp)
+
+(defcustom org-confirm-elisp-link-function 'yes-or-no-p
+ "Non-nil means ask for confirmation before executing Emacs Lisp links.
+Elisp links can be dangerous: just think about a link
+
+ [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
+
+This link would show up in your Org document as \"Google Search\",
+but really it would remove your entire home directory.
+Therefore we advise against setting this variable to nil.
+Just change it to `y-or-n-p' if you want to confirm with a
+single keystroke rather than having to type \"yes\"."
+ :group 'org-link-follow
+ :type '(choice
+ (const :tag "with yes-or-no (safer)" yes-or-no-p)
+ (const :tag "with y-or-n (faster)" y-or-n-p)
+ (const :tag "no confirmation (dangerous)" nil)))
+(put 'org-confirm-shell-link-function
+ 'safe-local-variable
+ (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
+
+(defcustom org-confirm-elisp-link-not-regexp ""
+ "A regexp to skip confirmation for Elisp links."
+ :group 'org-link-follow
+ :version "24.1"
+ :type 'regexp)
+
+(defconst org-file-apps-defaults-gnu
+ '((remote . emacs)
+ (system . mailcap)
+ (t . mailcap))
+ "Default file applications on a UNIX or GNU/Linux system.
+See `org-file-apps'.")
+
+(defconst org-file-apps-defaults-macosx
+ '((remote . emacs)
+ (system . "open %s")
+ ("ps.gz" . "gv %s")
+ ("eps.gz" . "gv %s")
+ ("dvi" . "xdvi %s")
+ ("fig" . "xfig %s")
+ (t . "open %s"))
+ "Default file applications on a macOS system.
+The system \"open\" is known as a default, but we use X11 applications
+for some files for which the OS does not have a good default.
+See `org-file-apps'.")
+
+(defconst org-file-apps-defaults-windowsnt
+ (list '(remote . emacs)
+ (cons 'system (lambda (file _path)
+ (with-no-warnings (w32-shell-execute "open" file))))
+ (cons t (lambda (file _path)
+ (with-no-warnings (w32-shell-execute "open" file)))))
+ "Default file applications on a Windows NT system.
+The system \"open\" is used for most files.
+See `org-file-apps'.")
+
+(defcustom org-file-apps
+ '((auto-mode . emacs)
+ ("\\.mm\\'" . default)
+ ("\\.x?html?\\'" . default)
+ ("\\.pdf\\'" . default))
+ "External applications for opening `file:path' items in a document.
+\\<org-mode-map>\
+
+Org mode uses system defaults for different file types, but
+you can use this variable to set the application for a given file
+extension. The entries in this list are cons cells where the car identifies
+files and the cdr the corresponding command.
+
+Possible values for the file identifier are:
+
+ \"string\" A string as a file identifier can be interpreted in different
+ ways, depending on its contents:
+
+ - Alphanumeric characters only:
+ Match links with this file extension.
+ Example: (\"pdf\" . \"evince %s\")
+ to open PDFs with evince.
+
+ - Regular expression: Match links where the
+ filename matches the regexp. If you want to
+ use groups here, use shy groups.
+
+ Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
+ (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
+ to open *.html and *.xhtml with firefox.
+
+ - Regular expression which contains (non-shy) groups:
+ Match links where the whole link, including \"::\", and
+ anything after that, matches the regexp.
+ In a custom command string, %1, %2, etc. are replaced with
+ the parts of the link that were matched by the groups.
+ For backwards compatibility, if a command string is given
+ that does not use any of the group matches, this case is
+ handled identically to the second one (i.e. match against
+ file name only).
+ In a custom function, you can access the group matches with
+ (match-string n link).
+
+ Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
+\"evince -p %1 %s\")
+ to open [[file:document.pdf::5]] with evince at page 5.
+
+ `directory' Matches a directory
+ `remote' Matches a remote file, accessible through tramp or efs.
+ Remote files most likely should be visited through Emacs
+ because external applications cannot handle such paths.
+`auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
+ so all files Emacs knows how to handle. Using this with
+ command `emacs' will open most files in Emacs. Beware that this
+ will also open html files inside Emacs, unless you add
+ (\"html\" . default) to the list as well.
+ `system' The system command to open files, like `open' on Windows
+ and macOS, and mailcap under GNU/Linux. This is the command
+ that will be selected if you call `org-open-at-point' with a
+ double prefix argument (`\\[universal-argument] \
+\\[universal-argument] \\[org-open-at-point]').
+ t Default for files not matched by any of the other options.
+
+Possible values for the command are:
+
+ `emacs' The file will be visited by the current Emacs process.
+ `default' Use the default application for this file type, which is the
+ association for t in the list, most likely in the system-specific
+ part. This can be used to overrule an unwanted setting in the
+ system-specific variable.
+ `system' Use the system command for opening files, like \"open\".
+ This command is specified by the entry whose car is `system'.
+ Most likely, the system-specific version of this variable
+ does define this command, but you can overrule/replace it
+ here.
+`mailcap' Use command specified in the mailcaps.
+ string A command to be executed by a shell; %s will be replaced
+ by the path to the file.
+ function A Lisp function, which will be called with two arguments:
+ the file path and the original link string, without the
+ \"file:\" prefix.
+
+For more examples, see the system specific constants
+`org-file-apps-defaults-macosx'
+`org-file-apps-defaults-windowsnt'
+`org-file-apps-defaults-gnu'."
+ :group 'org-link-follow
+ :type '(repeat
+ (cons (choice :value ""
+ (string :tag "Extension")
+ (const :tag "System command to open files" system)
+ (const :tag "Default for unrecognized files" t)
+ (const :tag "Remote file" remote)
+ (const :tag "Links to a directory" directory)
+ (const :tag "Any files that have Emacs modes"
+ auto-mode))
+ (choice :value ""
+ (const :tag "Visit with Emacs" emacs)
+ (const :tag "Use default" default)
+ (const :tag "Use the system command" system)
+ (string :tag "Command")
+ (function :tag "Function")))))
+
+(defcustom org-doi-server-url "http://dx.doi.org/"
+ "The URL of the DOI server."
+ :type 'string
+ :version "24.3"
+ :group 'org-link-follow)
+
+(defgroup org-refile nil
+ "Options concerning refiling entries in Org mode."
+ :tag "Org Refile"
+ :group 'org)
+
+(defcustom org-directory "~/org"
+ "Directory with Org files.
+This is just a default location to look for Org files. There is no need
+at all to put your files into this directory. It is used in the
+following situations:
+
+1. When a capture template specifies a target file that is not an
+ absolute path. The path will then be interpreted relative to
+ `org-directory'
+2. When the value of variable `org-agenda-files' is a single file, any
+ relative paths in this file will be taken as relative to
+ `org-directory'."
+ :group 'org-refile
+ :group 'org-capture
+ :type 'directory)
+
+(defcustom org-default-notes-file (convert-standard-filename "~/.notes")
+ "Default target for storing notes.
+Used as a fall back file for org-capture.el, for templates that
+do not specify a target file."
+ :group 'org-refile
+ :group 'org-capture
+ :type 'file)
+
+(defcustom org-goto-interface 'outline
+ "The default interface to be used for `org-goto'.
+Allowed values are:
+outline The interface shows an outline of the relevant file
+ and the correct heading is found by moving through
+ the outline or by searching with incremental search.
+outline-path-completion Headlines in the current buffer are offered via
+ completion. This is the interface also used by
+ the refile command."
+ :group 'org-refile
+ :type '(choice
+ (const :tag "Outline" outline)
+ (const :tag "Outline-path-completion" outline-path-completion)))
+
+(defcustom org-goto-max-level 5
+ "Maximum target level when running `org-goto' with refile interface."
+ :group 'org-refile
+ :type 'integer)
+
+(defcustom org-reverse-note-order nil
+ "Non-nil means store new notes at the beginning of a file or entry.
+When nil, new notes will be filed to the end of a file or entry.
+This can also be a list with cons cells of regular expressions that
+are matched against file names, and values."
+ :group 'org-capture
+ :group 'org-refile
+ :type '(choice
+ (const :tag "Reverse always" t)
+ (const :tag "Reverse never" nil)
+ (repeat :tag "By file name regexp"
+ (cons regexp boolean))))
+
+(defcustom org-log-refile nil
+ "Information to record when a task is refiled.
+
+Possible values are:
+
+nil Don't add anything
+time Add a time stamp to the task
+note Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: nologrefile
+ #+STARTUP: logrefile
+ #+STARTUP: lognoterefile
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords.
+
+When bulk-refiling from the agenda, the value `note' is forbidden and
+will temporarily be changed to `time'."
+ :group 'org-refile
+ :group 'org-progress
+ :version "24.1"
+ :type '(choice
+ (const :tag "No logging" nil)
+ (const :tag "Record timestamp" time)
+ (const :tag "Record timestamp with note." note)))
+
+(defcustom org-refile-targets nil
+ "Targets for refiling entries with `\\[org-refile]'.
+This is a list of cons cells. Each cell contains:
+- a specification of the files to be considered, either a list of files,
+ or a symbol whose function or variable value will be used to retrieve
+ a file name or a list of file names. If you use `org-agenda-files' for
+ that, all agenda files will be scanned for targets. Nil means consider
+ headings in the current buffer.
+- A specification of how to find candidate refile targets. This may be
+ any of:
+ - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
+ This tag has to be present in all target headlines, inheritance will
+ not be considered.
+ - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
+ todo keyword.
+ - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
+ headlines that are refiling targets.
+ - a cons cell (:level . N). Any headline of level N is considered a target.
+ Note that, when `org-odd-levels-only' is set, level corresponds to
+ order in hierarchy, not to the number of stars.
+ - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
+ Note that, when `org-odd-levels-only' is set, level corresponds to
+ order in hierarchy, not to the number of stars.
+
+Each element of this list generates a set of possible targets.
+The union of these sets is presented (with completion) to
+the user by `org-refile'.
+
+You can set the variable `org-refile-target-verify-function' to a function
+to verify each headline found by the simple criteria above.
+
+When this variable is nil, all top-level headlines in the current buffer
+are used, equivalent to the value `((nil . (:level . 1))'."
+ :group 'org-refile
+ :type '(repeat
+ (cons
+ (choice :value org-agenda-files
+ (const :tag "All agenda files" org-agenda-files)
+ (const :tag "Current buffer" nil)
+ (function) (variable) (file))
+ (choice :tag "Identify target headline by"
+ (cons :tag "Specific tag" (const :value :tag) (string))
+ (cons :tag "TODO keyword" (const :value :todo) (string))
+ (cons :tag "Regular expression" (const :value :regexp) (regexp))
+ (cons :tag "Level number" (const :value :level) (integer))
+ (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
+
+(defcustom org-refile-target-verify-function nil
+ "Function to verify if the headline at point should be a refile target.
+The function will be called without arguments, with point at the
+beginning of the headline. It should return t and leave point
+where it is if the headline is a valid target for refiling.
+
+If the target should not be selected, the function must return nil.
+In addition to this, it may move point to a place from where the search
+should be continued. For example, the function may decide that the entire
+subtree of the current entry should be excluded and move point to the end
+of the subtree."
+ :group 'org-refile
+ :type '(choice
+ (const nil)
+ (function)))
+
+(defcustom org-refile-use-cache nil
+ "Non-nil means cache refile targets to speed up the process.
+\\<org-mode-map>\
+The cache for a particular file will be updated automatically when
+the buffer has been killed, or when any of the marker used for flagging
+refile targets no longer points at a live buffer.
+If you have added new entries to a buffer that might themselves be targets,
+you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
+if you find that easier, \
+`\\[universal-argument] \\[universal-argument] \\[universal-argument] \
+\\[org-refile]'."
+ :group 'org-refile
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-refile-use-outline-path nil
+ "Non-nil means provide refile targets as paths.
+So a level 3 headline will be available as level1/level2/level3.
+
+When the value is `file', also include the file name (without directory)
+into the path. In this case, you can also stop the completion after
+the file name, to get entries inserted as top level in the file.
+
+When `full-file-path', include the full file path."
+ :group 'org-refile
+ :type '(choice
+ (const :tag "Not" nil)
+ (const :tag "Yes" t)
+ (const :tag "Start with file name" file)
+ (const :tag "Start with full file path" full-file-path)))
+
+(defcustom org-outline-path-complete-in-steps t
+ "Non-nil means complete the outline path in hierarchical steps.
+When Org uses the refile interface to select an outline path (see
+`org-refile-use-outline-path'), the completion of the path can be
+done in a single go, or it can be done in steps down the headline
+hierarchy. Going in steps is probably the best if you do not use
+a special completion package like `ido' or `icicles'. However,
+when using these packages, going in one step can be very fast,
+while still showing the whole path to the entry."
+ :group 'org-refile
+ :type 'boolean)
+
+(defcustom org-refile-allow-creating-parent-nodes nil
+ "Non-nil means allow the creation of new nodes as refile targets.
+New nodes are then created by adding \"/new node name\" to the completion
+of an existing node. When the value of this variable is `confirm',
+new node creation must be confirmed by the user (recommended).
+When nil, the completion must match an existing entry.
+
+Note that, if the new heading is not seen by the criteria
+listed in `org-refile-targets', multiple instances of the same
+heading would be created by trying again to file under the new
+heading."
+ :group 'org-refile
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Always" t)
+ (const :tag "Prompt for confirmation" confirm)))
+
+(defcustom org-refile-active-region-within-subtree nil
+ "Non-nil means also refile active region within a subtree.
+
+By default `org-refile' doesn't allow refiling regions if they
+don't contain a set of subtrees, but it might be convenient to
+do so sometimes: in that case, the first line of the region is
+converted to a headline before refiling."
+ :group 'org-refile
+ :version "24.1"
+ :type 'boolean)
+
+(defgroup org-todo nil
+ "Options concerning TODO items in Org mode."
+ :tag "Org TODO"
+ :group 'org)
+
+(defgroup org-progress nil
+ "Options concerning Progress logging in Org mode."
+ :tag "Org Progress"
+ :group 'org-time)
+
+(defvar org-todo-interpretation-widgets
+ '((:tag "Sequence (cycling hits every state)" sequence)
+ (:tag "Type (cycling directly to DONE)" type))
+ "The available interpretation symbols for customizing `org-todo-keywords'.
+Interested libraries should add to this list.")
+
+(defcustom org-todo-keywords '((sequence "TODO" "DONE"))
+ "List of TODO entry keyword sequences and their interpretation.
+\\<org-mode-map>This is a list of sequences.
+
+Each sequence starts with a symbol, either `sequence' or `type',
+indicating if the keywords should be interpreted as a sequence of
+action steps, or as different types of TODO items. The first
+keywords are states requiring action - these states will select a headline
+for inclusion into the global TODO list Org produces. If one of the
+\"keywords\" is the vertical bar, \"|\", the remaining keywords
+signify that no further action is necessary. If \"|\" is not found,
+the last keyword is treated as the only DONE state of the sequence.
+
+The command `\\[org-todo]' cycles an entry through these states, and one
+additional state where no keyword is present. For details about this
+cycling, see the manual.
+
+TODO keywords and interpretation can also be set on a per-file basis with
+the special #+SEQ_TODO and #+TYP_TODO lines.
+
+Each keyword can optionally specify a character for fast state selection
+\(in combination with the variable `org-use-fast-todo-selection')
+and specifiers for state change logging, using the same syntax that
+is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
+the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
+indicates to record a time stamp each time this state is selected.
+
+Each keyword may also specify if a timestamp or a note should be
+recorded when entering or leaving the state, by adding additional
+characters in the parenthesis after the keyword. This looks like this:
+\"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
+record only the time of the state change. With X and Y being either
+\"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
+Y when leaving the state if and only if the *target* state does not
+define X. You may omit any of the fast-selection key or X or /Y,
+so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
+
+For backward compatibility, this variable may also be just a list
+of keywords. In this case the interpretation (sequence or type) will be
+taken from the (otherwise obsolete) variable `org-todo-interpretation'."
+ :group 'org-todo
+ :group 'org-keywords
+ :type '(choice
+ (repeat :tag "Old syntax, just keywords"
+ (string :tag "Keyword"))
+ (repeat :tag "New syntax"
+ (cons
+ (choice
+ :tag "Interpretation"
+ ;;Quick and dirty way to see
+ ;;`org-todo-interpretations'. This takes the
+ ;;place of item arguments
+ :convert-widget
+ (lambda (widget)
+ (widget-put widget
+ :args (mapcar
+ (lambda (x)
+ (widget-convert
+ (cons 'const x)))
+ org-todo-interpretation-widgets))
+ widget))
+ (repeat
+ (string :tag "Keyword"))))))
+
+(defvar-local org-todo-keywords-1 nil
+ "All TODO and DONE keywords active in a buffer.")
+(defvar org-todo-keywords-for-agenda nil)
+(defvar org-done-keywords-for-agenda nil)
+(defvar org-todo-keyword-alist-for-agenda nil)
+(defvar org-tag-alist-for-agenda nil
+ "Alist of all tags from all agenda files.")
+(defvar org-tag-groups-alist-for-agenda nil
+ "Alist of all groups tags from all current agenda files.")
+(defvar-local org-tag-groups-alist nil)
+(defvar org-agenda-contributing-files nil)
+(defvar-local org-current-tag-alist nil
+ "Alist of all tag groups in current buffer.
+This variable takes into consideration `org-tag-alist',
+`org-tag-persistent-alist' and TAGS keywords in the buffer.")
+(defvar-local org-not-done-keywords nil)
+(defvar-local org-done-keywords nil)
+(defvar-local org-todo-heads nil)
+(defvar-local org-todo-sets nil)
+(defvar-local org-todo-log-states nil)
+(defvar-local org-todo-kwd-alist nil)
+(defvar-local org-todo-key-alist nil)
+(defvar-local org-todo-key-trigger nil)
+
+(defcustom org-todo-interpretation 'sequence
+ "Controls how TODO keywords are interpreted.
+This variable is in principle obsolete and is only used for
+backward compatibility, if the interpretation of todo keywords is
+not given already in `org-todo-keywords'. See that variable for
+more information."
+ :group 'org-todo
+ :group 'org-keywords
+ :type '(choice (const sequence)
+ (const type)))
+
+(defcustom org-use-fast-todo-selection t
+ "\\<org-mode-map>\
+Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
+This variable describes if and under what circumstances the cycling
+mechanism for TODO keywords will be replaced by a single-key, direct
+selection scheme.
+
+When nil, fast selection is never used.
+
+When the symbol `prefix', it will be used when `org-todo' is called
+with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
+in an Org buffer, and
+`\\[universal-argument] t' in an agenda buffer.
+
+When t, fast selection is used by default. In this case, the prefix
+argument forces cycling instead.
+
+In all cases, the special interface is only used if access keys have
+actually been assigned by the user, i.e. if keywords in the configuration
+are followed by a letter in parenthesis, like TODO(t)."
+ :group 'org-todo
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "By default" t)
+ (const :tag "Only with C-u C-c C-t" prefix)))
+
+(defcustom org-provide-todo-statistics t
+ "Non-nil means update todo statistics after insert and toggle.
+ALL-HEADLINES means update todo statistics by including headlines
+with no TODO keyword as well, counting them as not done.
+A list of TODO keywords means the same, but skip keywords that are
+not in this list.
+When set to a list of two lists, the first list contains keywords
+to consider as TODO keywords, the second list contains keywords
+to consider as DONE keywords.
+
+When this is set, todo statistics is updated in the parent of the
+current entry each time a todo state is changed."
+ :group 'org-todo
+ :type '(choice
+ (const :tag "Yes, only for TODO entries" t)
+ (const :tag "Yes, including all entries" all-headlines)
+ (repeat :tag "Yes, for TODOs in this list"
+ (string :tag "TODO keyword"))
+ (list :tag "Yes, for TODOs and DONEs in these lists"
+ (repeat (string :tag "TODO keyword"))
+ (repeat (string :tag "DONE keyword")))
+ (other :tag "No TODO statistics" nil)))
+
+(defcustom org-hierarchical-todo-statistics t
+ "Non-nil means TODO statistics covers just direct children.
+When nil, all entries in the subtree are considered.
+This has only an effect if `org-provide-todo-statistics' is set.
+To set this to nil for only a single subtree, use a COOKIE_DATA
+property and include the word \"recursive\" into the value."
+ :group 'org-todo
+ :type 'boolean)
+
+(defcustom org-after-todo-state-change-hook nil
+ "Hook which is run after the state of a TODO item was changed.
+The new state (a string with a TODO keyword, or nil) is available in the
+Lisp variable `org-state'."
+ :group 'org-todo
+ :type 'hook)
+
+(defvar org-blocker-hook nil
+ "Hook for functions that are allowed to block a state change.
+
+Functions in this hook should not modify the buffer.
+Each function gets as its single argument a property list,
+see `org-trigger-hook' for more information about this list.
+
+If any of the functions in this hook returns nil, the state change
+is blocked.")
+
+(defvar org-trigger-hook nil
+ "Hook for functions that are triggered by a state change.
+
+Each function gets as its single argument a property list with at
+least the following elements:
+
+ (:type type-of-change :position pos-at-entry-start
+ :from old-state :to new-state)
+
+Depending on the type, more properties may be present.
+
+This mechanism is currently implemented for:
+
+TODO state changes
+------------------
+:type todo-state-change
+:from previous state (keyword as a string), or nil, or a symbol
+ `todo' or `done', to indicate the general type of state.
+:to new state, like in :from")
+
+(defcustom org-enforce-todo-dependencies nil
+ "Non-nil means undone TODO entries will block switching the parent to DONE.
+Also, if a parent has an :ORDERED: property, switching an entry to DONE will
+be blocked if any prior sibling is not yet done.
+Finally, if the parent is blocked because of ordered siblings of its own,
+the child will also be blocked."
+ :set (lambda (var val)
+ (set var val)
+ (if val
+ (add-hook 'org-blocker-hook
+ 'org-block-todo-from-children-or-siblings-or-parent)
+ (remove-hook 'org-blocker-hook
+ 'org-block-todo-from-children-or-siblings-or-parent)))
+ :group 'org-todo
+ :type 'boolean)
+
+(defcustom org-enforce-todo-checkbox-dependencies nil
+ "Non-nil means unchecked boxes will block switching the parent to DONE.
+When this is nil, checkboxes have no influence on switching TODO states.
+When non-nil, you first need to check off all check boxes before the TODO
+entry can be switched to DONE.
+This variable needs to be set before org.el is loaded, and you need to
+restart Emacs after a change to make the change effective. The only way
+to change is while Emacs is running is through the customize interface."
+ :set (lambda (var val)
+ (set var val)
+ (if val
+ (add-hook 'org-blocker-hook
+ 'org-block-todo-from-checkboxes)
+ (remove-hook 'org-blocker-hook
+ 'org-block-todo-from-checkboxes)))
+ :group 'org-todo
+ :type 'boolean)
+
+(defcustom org-treat-insert-todo-heading-as-state-change nil
+ "Non-nil means inserting a TODO heading is treated as state change.
+So when the command `\\[org-insert-todo-heading]' is used, state change
+logging will apply if appropriate. When nil, the new TODO item will
+be inserted directly, and no logging will take place."
+ :group 'org-todo
+ :type 'boolean)
+
+(defcustom org-treat-S-cursor-todo-selection-as-state-change t
+ "Non-nil means switching TODO states with S-cursor counts as state change.
+This is the default behavior. However, setting this to nil allows a
+convenient way to select a TODO state and bypass any logging associated
+with that."
+ :group 'org-todo
+ :type 'boolean)
+
+(defcustom org-todo-state-tags-triggers nil
+ "Tag changes that should be triggered by TODO state changes.
+This is a list. Each entry is
+
+ (state-change (tag . flag) .......)
+
+State-change can be a string with a state, and empty string to indicate the
+state that has no TODO keyword, or it can be one of the symbols `todo'
+or `done', meaning any not-done or done state, respectively."
+ :group 'org-todo
+ :group 'org-tags
+ :type '(repeat
+ (cons (choice :tag "When changing to"
+ (const :tag "Not-done state" todo)
+ (const :tag "Done state" done)
+ (string :tag "State"))
+ (repeat
+ (cons :tag "Tag action"
+ (string :tag "Tag")
+ (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
+
+(defcustom org-log-done nil
+ "Information to record when a task moves to the DONE state.
+
+Possible values are:
+
+nil Don't add anything, just change the keyword
+time Add a time stamp to the task
+note Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: nologdone
+ #+STARTUP: logdone
+ #+STARTUP: lognotedone
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords."
+ :group 'org-todo
+ :group 'org-progress
+ :type '(choice
+ (const :tag "No logging" nil)
+ (const :tag "Record CLOSED timestamp" time)
+ (const :tag "Record CLOSED timestamp with note." note)))
+
+;; Normalize old uses of org-log-done.
+(cond
+ ((eq org-log-done t) (setq org-log-done 'time))
+ ((and (listp org-log-done) (memq 'done org-log-done))
+ (setq org-log-done 'note)))
+
+(defcustom org-log-reschedule nil
+ "Information to record when the scheduling date of a tasks is modified.
+
+Possible values are:
+
+nil Don't add anything, just change the date
+time Add a time stamp to the task
+note Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: nologreschedule
+ #+STARTUP: logreschedule
+ #+STARTUP: lognotereschedule"
+ :group 'org-todo
+ :group 'org-progress
+ :type '(choice
+ (const :tag "No logging" nil)
+ (const :tag "Record timestamp" time)
+ (const :tag "Record timestamp with note." note)))
+
+(defcustom org-log-redeadline nil
+ "Information to record when the deadline date of a tasks is modified.
+
+Possible values are:
+
+nil Don't add anything, just change the date
+time Add a time stamp to the task
+note Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: nologredeadline
+ #+STARTUP: logredeadline
+ #+STARTUP: lognoteredeadline
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords."
+ :group 'org-todo
+ :group 'org-progress
+ :type '(choice
+ (const :tag "No logging" nil)
+ (const :tag "Record timestamp" time)
+ (const :tag "Record timestamp with note." note)))
+
+(defcustom org-log-note-clock-out nil
+ "Non-nil means record a note when clocking out of an item.
+This can also be configured on a per-file basis by adding one of
+the following lines anywhere in the buffer:
+
+ #+STARTUP: lognoteclock-out
+ #+STARTUP: nolognoteclock-out"
+ :group 'org-todo
+ :group 'org-progress
+ :type 'boolean)
+
+(defcustom org-log-done-with-time t
+ "Non-nil means the CLOSED time stamp will contain date and time.
+When nil, only the date will be recorded."
+ :group 'org-progress
+ :type 'boolean)
+
+(defcustom org-log-note-headings
+ '((done . "CLOSING NOTE %t")
+ (state . "State %-12s from %-12S %t")
+ (note . "Note taken on %t")
+ (reschedule . "Rescheduled from %S on %t")
+ (delschedule . "Not scheduled, was %S on %t")
+ (redeadline . "New deadline from %S on %t")
+ (deldeadline . "Removed deadline, was %S on %t")
+ (refile . "Refiled on %t")
+ (clock-out . ""))
+ "Headings for notes added to entries.
+
+The value is an alist, with the car being a symbol indicating the
+note context, and the cdr is the heading to be used. The heading
+may also be the empty string. The following placeholders can be
+used:
+
+ %t a time stamp.
+ %T an active time stamp instead the default inactive one
+ %d a short-format time stamp.
+ %D an active short-format time stamp.
+ %s the new TODO state or time stamp (inactive), in double quotes.
+ %S the old TODO state or time stamp (inactive), in double quotes.
+ %u the user name.
+ %U full user name.
+
+In fact, it is not a good idea to change the `state' entry,
+because Agenda Log mode depends on the format of these entries."
+ :group 'org-todo
+ :group 'org-progress
+ :type '(list :greedy t
+ (cons (const :tag "Heading when closing an item" done) string)
+ (cons (const :tag
+ "Heading when changing todo state (todo sequence only)"
+ state) string)
+ (cons (const :tag "Heading when just taking a note" note) string)
+ (cons (const :tag "Heading when rescheduling" reschedule) string)
+ (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
+ (cons (const :tag "Heading when changing deadline" redeadline) string)
+ (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
+ (cons (const :tag "Heading when refiling" refile) string)
+ (cons (const :tag "Heading when clocking out" clock-out) string)))
+
+(unless (assq 'note org-log-note-headings)
+ (push '(note . "%t") org-log-note-headings))
+
+(defcustom org-log-into-drawer nil
+ "Non-nil means insert state change notes and time stamps into a drawer.
+When nil, state changes notes will be inserted after the headline and
+any scheduling and clock lines, but not inside a drawer.
+
+The value of this variable should be the name of the drawer to use.
+LOGBOOK is proposed as the default drawer for this purpose, you can
+also set this to a string to define the drawer of your choice.
+
+A value of t is also allowed, representing \"LOGBOOK\".
+
+A value of t or nil can also be set with on a per-file-basis with
+
+ #+STARTUP: logdrawer
+ #+STARTUP: nologdrawer
+
+If this variable is set, `org-log-state-notes-insert-after-drawers'
+will be ignored.
+
+You can set the property LOG_INTO_DRAWER to overrule this setting for
+a subtree.
+
+Do not check directly this variable in a Lisp program. Call
+function `org-log-into-drawer' instead."
+ :group 'org-todo
+ :group 'org-progress
+ :type '(choice
+ (const :tag "Not into a drawer" nil)
+ (const :tag "LOGBOOK" t)
+ (string :tag "Other")))
+
+(defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
+
+(defun org-log-into-drawer ()
+ "Name of the log drawer, as a string, or nil.
+This is the value of `org-log-into-drawer'. However, if the
+current entry has or inherits a LOG_INTO_DRAWER property, it will
+be used instead of the default value."
+ (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
+ (cond ((equal p "nil") nil)
+ ((equal p "t") "LOGBOOK")
+ ((stringp p) p)
+ (p "LOGBOOK")
+ ((stringp org-log-into-drawer) org-log-into-drawer)
+ (org-log-into-drawer "LOGBOOK"))))
+
+(defcustom org-log-state-notes-insert-after-drawers nil
+ "Non-nil means insert state change notes after any drawers in entry.
+Only the drawers that *immediately* follow the headline and the
+deadline/scheduled line are skipped.
+When nil, insert notes right after the heading and perhaps the line
+with deadline/scheduling if present.
+
+This variable will have no effect if `org-log-into-drawer' is
+set."
+ :group 'org-todo
+ :group 'org-progress
+ :type 'boolean)
+
+(defcustom org-log-states-order-reversed t
+ "Non-nil means the latest state note will be directly after heading.
+When nil, the state change notes will be ordered according to time.
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: logstatesreversed
+ #+STARTUP: nologstatesreversed"
+ :group 'org-todo
+ :group 'org-progress
+ :type 'boolean)
+
+(defcustom org-todo-repeat-to-state nil
+ "The TODO state to which a repeater should return the repeating task.
+By default this is the first task in a TODO sequence, or the previous state
+in a TODO_TYP set. But you can specify another task here.
+alternatively, set the :REPEAT_TO_STATE: property of the entry."
+ :group 'org-todo
+ :version "24.1"
+ :type '(choice (const :tag "Head of sequence" nil)
+ (string :tag "Specific state")))
+
+(defcustom org-log-repeat 'time
+ "Non-nil means record moving through the DONE state when triggering repeat.
+An auto-repeating task is immediately switched back to TODO when
+marked DONE. If you are not logging state changes (by adding \"@\"
+or \"!\" to the TODO keyword definition), or set `org-log-done' to
+record a closing note, there will be no record of the task moving
+through DONE. This variable forces taking a note anyway.
+
+nil Don't force a record
+time Record a time stamp
+note Prompt for a note and add it with template `org-log-note-headings'
+
+This option can also be set with on a per-file-basis with
+
+ #+STARTUP: nologrepeat
+ #+STARTUP: logrepeat
+ #+STARTUP: lognoterepeat
+
+You can have local logging settings for a subtree by setting the LOGGING
+property to one or more of these keywords."
+ :group 'org-todo
+ :group 'org-progress
+ :type '(choice
+ (const :tag "Don't force a record" nil)
+ (const :tag "Force recording the DONE state" time)
+ (const :tag "Force recording a note with the DONE state" note)))
+
+
+(defgroup org-priorities nil
+ "Priorities in Org mode."
+ :tag "Org Priorities"
+ :group 'org-todo)
+
+(defcustom org-enable-priority-commands t
+ "Non-nil means priority commands are active.
+When nil, these commands will be disabled, so that you never accidentally
+set a priority."
+ :group 'org-priorities
+ :type 'boolean)
+
+(defcustom org-highest-priority ?A
+ "The highest priority of TODO items. A character like ?A, ?B etc.
+Must have a smaller ASCII number than `org-lowest-priority'."
+ :group 'org-priorities
+ :type 'character)
+
+(defcustom org-lowest-priority ?C
+ "The lowest priority of TODO items. A character like ?A, ?B etc.
+Must have a larger ASCII number than `org-highest-priority'."
+ :group 'org-priorities
+ :type 'character)
+
+(defcustom org-default-priority ?B
+ "The default priority of TODO items.
+This is the priority an item gets if no explicit priority is given.
+When starting to cycle on an empty priority the first step in the cycle
+depends on `org-priority-start-cycle-with-default'. The resulting first
+step priority must not exceed the range from `org-highest-priority' to
+`org-lowest-priority' which means that `org-default-priority' has to be
+in this range exclusive or inclusive the range boundaries. Else the
+first step refuses to set the default and the second will fall back
+to (depending on the command used) the highest or lowest priority."
+ :group 'org-priorities
+ :type 'character)
+
+(defcustom org-priority-start-cycle-with-default t
+ "Non-nil means start with default priority when starting to cycle.
+When this is nil, the first step in the cycle will be (depending on the
+command used) one higher or lower than the default priority.
+See also `org-default-priority'."
+ :group 'org-priorities
+ :type 'boolean)
+
+(defcustom org-get-priority-function nil
+ "Function to extract the priority from a string.
+The string is normally the headline. If this is nil Org computes the
+priority from the priority cookie like [#A] in the headline. It returns
+an integer, increasing by 1000 for each priority level.
+The user can set a different function here, which should take a string
+as an argument and return the numeric priority."
+ :group 'org-priorities
+ :version "24.1"
+ :type '(choice
+ (const nil)
+ (function)))
+
+(defgroup org-time nil
+ "Options concerning time stamps and deadlines in Org mode."
+ :tag "Org Time"
+ :group 'org)
+
+(defcustom org-time-stamp-rounding-minutes '(0 5)
+ "Number of minutes to round time stamps to.
+\\<org-mode-map>\
+These are two values, the first applies when first creating a time stamp.
+The second applies when changing it with the commands `S-up' and `S-down'.
+When changing the time stamp, this means that it will change in steps
+of N minutes, as given by the second value.
+
+When a setting is 0 or 1, insert the time unmodified. Useful rounding
+numbers should be factors of 60, so for example 5, 10, 15.
+
+When this is larger than 1, you can still force an exact time stamp by using
+a double prefix argument to a time stamp command like \
+`\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
+and by using a prefix arg to `S-up/down' to specify the exact number
+of minutes to shift."
+ :group 'org-time
+ :get (lambda (var) ; Make sure both elements are there
+ (if (integerp (default-value var))
+ (list (default-value var) 5)
+ (default-value var)))
+ :type '(list
+ (integer :tag "when inserting times")
+ (integer :tag "when modifying times")))
+
+;; Normalize old customizations of this variable.
+(when (integerp org-time-stamp-rounding-minutes)
+ (setq org-time-stamp-rounding-minutes
+ (list org-time-stamp-rounding-minutes
+ org-time-stamp-rounding-minutes)))
+
+(defcustom org-display-custom-times nil
+ "Non-nil means overlay custom formats over all time stamps.
+The formats are defined through the variable `org-time-stamp-custom-formats'.
+To turn this on on a per-file basis, insert anywhere in the file:
+ #+STARTUP: customtime"
+ :group 'org-time
+ :set 'set-default
+ :type 'sexp)
+(make-variable-buffer-local 'org-display-custom-times)
+
+(defcustom org-time-stamp-custom-formats
+ '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
+ "Custom formats for time stamps. See `format-time-string' for the syntax.
+These are overlaid over the default ISO format if the variable
+`org-display-custom-times' is set. Time like %H:%M should be at the
+end of the second format. The custom formats are also honored by export
+commands, if custom time display is turned on at the time of export."
+ :group 'org-time
+ :type 'sexp)
+
+(defun org-time-stamp-format (&optional long inactive)
+ "Get the right format for a time string."
+ (let ((f (if long (cdr org-time-stamp-formats)
+ (car org-time-stamp-formats))))
+ (if inactive
+ (concat "[" (substring f 1 -1) "]")
+ f)))
+
+(defcustom org-time-clocksum-format
+ '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
+ "The format string used when creating CLOCKSUM lines.
+This is also used when Org mode generates a time duration.
+
+The value can be a single format string containing two
+%-sequences, which will be filled with the number of hours and
+minutes in that order.
+
+Alternatively, the value can be a plist associating any of the
+keys :years, :months, :weeks, :days, :hours or :minutes with
+format strings. The time duration is formatted using only the
+time components that are needed and concatenating the results.
+If a time unit in absent, it falls back to the next smallest
+unit.
+
+The keys :require-years, :require-months, :require-days,
+:require-weeks, :require-hours, :require-minutes are also
+meaningful. A non-nil value for these keys indicates that the
+corresponding time component should always be included, even if
+its value is 0.
+
+
+For example,
+
+ (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
+ :require-minutes t)
+
+means durations longer than a day will be expressed in days,
+hours and minutes, and durations less than a day will always be
+expressed in hours and minutes (even for durations less than an
+hour).
+
+The value
+
+ (:days \"%dd\" :minutes \"%dm\")
+
+means durations longer than a day will be expressed in days and
+minutes, and durations less than a day will be expressed entirely
+in minutes (even for durations longer than an hour)."
+ :group 'org-time
+ :group 'org-clock
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice (string :tag "Format string")
+ (set :tag "Plist"
+ (group :inline t (const :tag "Years" :years)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show years" :require-years)
+ (const t))
+ (group :inline t (const :tag "Months" :months)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show months" :require-months)
+ (const t))
+ (group :inline t (const :tag "Weeks" :weeks)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show weeks" :require-weeks)
+ (const t))
+ (group :inline t (const :tag "Days" :days)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show days" :require-days)
+ (const t))
+ (group :inline t (const :tag "Hours" :hours)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show hours" :require-hours)
+ (const t))
+ (group :inline t (const :tag "Minutes" :minutes)
+ (string :tag "Format string"))
+ (group :inline t
+ (const :tag "Always show minutes" :require-minutes)
+ (const t)))))
+
+(defcustom org-time-clocksum-use-fractional nil
+ "When non-nil, `\\[org-clock-display]' uses fractional times.
+See `org-time-clocksum-format' for more on time clock formats."
+ :group 'org-time
+ :group 'org-clock
+ :version "24.3"
+ :type 'boolean)
+
+(defcustom org-time-clocksum-use-effort-durations nil
+ "When non-nil, `\\[org-clock-display]' uses effort durations.
+E.g. by default, one day is considered to be a 8 hours effort,
+so a task that has been clocked for 16 hours will be displayed
+as during 2 days in the clock display or in the clocktable.
+
+See `org-effort-durations' on how to set effort durations
+and `org-time-clocksum-format' for more on time clock formats."
+ :group 'org-time
+ :group 'org-clock
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-time-clocksum-fractional-format "%.2f"
+ "The format string used when creating CLOCKSUM lines,
+or when Org mode generates a time duration, if
+`org-time-clocksum-use-fractional' is enabled.
+
+The value can be a single format string containing one
+%-sequence, which will be filled with the number of hours as
+a float.
+
+Alternatively, the value can be a plist associating any of the
+keys :years, :months, :weeks, :days, :hours or :minutes with
+a format string. The time duration is formatted using the
+largest time unit which gives a non-zero integer part. If all
+specified formats have zero integer part, the smallest time unit
+is used."
+ :group 'org-time
+ :type '(choice (string :tag "Format string")
+ (set (group :inline t (const :tag "Years" :years)
+ (string :tag "Format string"))
+ (group :inline t (const :tag "Months" :months)
+ (string :tag "Format string"))
+ (group :inline t (const :tag "Weeks" :weeks)
+ (string :tag "Format string"))
+ (group :inline t (const :tag "Days" :days)
+ (string :tag "Format string"))
+ (group :inline t (const :tag "Hours" :hours)
+ (string :tag "Format string"))
+ (group :inline t (const :tag "Minutes" :minutes)
+ (string :tag "Format string")))))
+
+(defcustom org-deadline-warning-days 14
+ "Number of days before expiration during which a deadline becomes active.
+This variable governs the display in sparse trees and in the agenda.
+When 0 or negative, it means use this number (the absolute value of it)
+even if a deadline has a different individual lead time specified.
+
+Custom commands can set this variable in the options section."
+ :group 'org-time
+ :group 'org-agenda-daily/weekly
+ :type 'integer)
+
+(defcustom org-scheduled-delay-days 0
+ "Number of days before a scheduled item becomes active.
+This variable governs the display in sparse trees and in the agenda.
+The default value (i.e. 0) means: don't delay scheduled item.
+When negative, it means use this number (the absolute value of it)
+even if a scheduled item has a different individual delay time
+specified.
+
+Custom commands can set this variable in the options section."
+ :group 'org-time
+ :group 'org-agenda-daily/weekly
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-read-date-prefer-future t
+ "Non-nil means assume future for incomplete date input from user.
+This affects the following situations:
+1. The user gives a month but not a year.
+ For example, if it is April and you enter \"feb 2\", this will be read
+ as Feb 2, *next* year. \"May 5\", however, will be this year.
+2. The user gives a day, but no month.
+ For example, if today is the 15th, and you enter \"3\", Org will read
+ this as the third of *next* month. However, if you enter \"17\",
+ it will be considered as *this* month.
+
+If you set this variable to the symbol `time', then also the following
+will work:
+
+3. If the user gives a time.
+ If the time is before now, it will be interpreted as tomorrow.
+
+Currently none of this works for ISO week specifications.
+
+When this option is nil, the current day, month and year will always be
+used as defaults.
+
+See also `org-agenda-jump-prefer-future'."
+ :group 'org-time
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "Check month and day" t)
+ (const :tag "Check month, day, and time" time)))
+
+(defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
+ "Should the agenda jump command prefer the future for incomplete dates?
+The default is to do the same as configured in `org-read-date-prefer-future'.
+But you can also set a deviating value here.
+This may t or nil, or the symbol `org-read-date-prefer-future'."
+ :group 'org-agenda
+ :group 'org-time
+ :version "24.1"
+ :type '(choice
+ (const :tag "Use org-read-date-prefer-future"
+ org-read-date-prefer-future)
+ (const :tag "Never" nil)
+ (const :tag "Always" t)))
+
+(defcustom org-read-date-force-compatible-dates t
+ "Should date/time prompt force dates that are guaranteed to work in Emacs?
+
+Depending on the system Emacs is running on, certain dates cannot
+be represented with the type used internally to represent time.
+Dates between 1970-1-1 and 2038-1-1 can always be represented
+correctly. Some systems allow for earlier dates, some for later,
+some for both. One way to find out it to insert any date into an
+Org buffer, putting the cursor on the year and hitting S-up and
+S-down to test the range.
+
+When this variable is set to t, the date/time prompt will not let
+you specify dates outside the 1970-2037 range, so it is certain that
+these dates will work in whatever version of Emacs you are
+running, and also that you can move a file from one Emacs implementation
+to another. WHenever Org is forcing the year for you, it will display
+a message and beep.
+
+When this variable is nil, Org will check if the date is
+representable in the specific Emacs implementation you are using.
+If not, it will force a year, usually the current year, and beep
+to remind you. Currently this setting is not recommended because
+the likelihood that you will open your Org files in an Emacs that
+has limited date range is not negligible.
+
+A workaround for this problem is to use diary sexp dates for time
+stamps outside of this range."
+ :group 'org-time
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-read-date-display-live t
+ "Non-nil means display current interpretation of date prompt live.
+This display will be in an overlay, in the minibuffer."
+ :group 'org-time
+ :type 'boolean)
+
+(defcustom org-read-date-popup-calendar t
+ "Non-nil means pop up a calendar when prompting for a date.
+In the calendar, the date can be selected with mouse-1. However, the
+minibuffer will also be active, and you can simply enter the date as well.
+When nil, only the minibuffer will be available."
+ :group 'org-time
+ :type 'boolean)
+(defvaralias 'org-popup-calendar-for-date-prompt
+ 'org-read-date-popup-calendar)
+
+(defcustom org-extend-today-until 0
+ "The hour when your day really ends. Must be an integer.
+This has influence for the following applications:
+- When switching the agenda to \"today\". It it is still earlier than
+ the time given here, the day recognized as TODAY is actually yesterday.
+- When a date is read from the user and it is still before the time given
+ here, the current date and time will be assumed to be yesterday, 23:59.
+ Also, timestamps inserted in capture templates follow this rule.
+
+IMPORTANT: This is a feature whose implementation is and likely will
+remain incomplete. Really, it is only here because past midnight seems to
+be the favorite working time of John Wiegley :-)"
+ :group 'org-time
+ :type 'integer)
+
+(defcustom org-use-effective-time nil
+ "If non-nil, consider `org-extend-today-until' when creating timestamps.
+For example, if `org-extend-today-until' is 8, and it's 4am, then the
+\"effective time\" of any timestamps between midnight and 8am will be
+23:59 of the previous day."
+ :group 'org-time
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-use-last-clock-out-time-as-effective-time nil
+ "When non-nil, use the last clock out time for `org-todo'.
+Note that this option has precedence over the combined use of
+`org-use-effective-time' and `org-extend-today-until'."
+ :group 'org-time
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-edit-timestamp-down-means-later nil
+ "Non-nil means S-down will increase the time in a time stamp.
+When nil, S-up will increase."
+ :group 'org-time
+ :type 'boolean)
+
+(defcustom org-calendar-follow-timestamp-change t
+ "Non-nil means make the calendar window follow timestamp changes.
+When a timestamp is modified and the calendar window is visible, it will be
+moved to the new date."
+ :group 'org-time
+ :type 'boolean)
+
+(defgroup org-tags nil
+ "Options concerning tags in Org mode."
+ :tag "Org Tags"
+ :group 'org)
+
+(defcustom org-tag-alist nil
+ "Default tags available in Org files.
+
+The value of this variable is an alist. Associations either:
+
+ (TAG)
+ (TAG . SELECT)
+ (SPECIAL)
+
+where TAG is a tag as a string, SELECT is character, used to
+select that tag through the fast tag selection interface, and
+SPECIAL is one of the following keywords: `:startgroup',
+`:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
+`:newline'. These keywords are used to define a hierarchy of
+tags. See manual for details.
+
+When this variable is nil, Org mode bases tag input on what is
+already in the buffer. The value can be overridden locally by
+using a TAGS keyword, e.g.,
+
+ #+TAGS: tag1 tag2
+
+See also `org-tag-persistent-alist' to sidestep this behavior."
+ :group 'org-tags
+ :type '(repeat
+ (choice
+ (cons (string :tag "Tag name")
+ (character :tag "Access char"))
+ (const :tag "Start radio group" (:startgroup))
+ (const :tag "Start tag group, non distinct" (:startgrouptag))
+ (const :tag "Group tags delimiter" (:grouptags))
+ (const :tag "End radio group" (:endgroup))
+ (const :tag "End tag group, non distinct" (:endgrouptag))
+ (const :tag "New line" (:newline)))))
+
+(defcustom org-tag-persistent-alist nil
+ "Tags always available in Org files.
+
+The value of this variable is an alist. Associations either:
+
+ (TAG)
+ (TAG . SELECT)
+ (SPECIAL)
+
+where TAG is a tag as a string, SELECT is a character, used to
+select that tag through the fast tag selection interface, and
+SPECIAL is one of the following keywords: `:startgroup',
+`:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
+`:newline'. These keywords are used to define a hierarchy of
+tags. See manual for details.
+
+Unlike to `org-tag-alist', tags defined in this variable do not
+depend on a local TAGS keyword. Instead, to disable these tags
+on a per-file basis, insert anywhere in the file:
+
+ #+STARTUP: noptag"
+ :group 'org-tags
+ :type '(repeat
+ (choice
+ (cons (string :tag "Tag name")
+ (character :tag "Access char"))
+ (const :tag "Start radio group" (:startgroup))
+ (const :tag "Start tag group, non distinct" (:startgrouptag))
+ (const :tag "Group tags delimiter" (:grouptags))
+ (const :tag "End radio group" (:endgroup))
+ (const :tag "End tag group, non distinct" (:endgrouptag))
+ (const :tag "New line" (:newline)))))
+
+(defcustom org-complete-tags-always-offer-all-agenda-tags nil
+ "If non-nil, always offer completion for all tags of all agenda files.
+Instead of customizing this variable directly, you might want to
+set it locally for capture buffers, because there no list of
+tags in that file can be created dynamically (there are none).
+
+ (add-hook \\='org-capture-mode-hook
+ (lambda ()
+ (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
+ :group 'org-tags
+ :version "24.1"
+ :type 'boolean)
+
+(defvar org-file-tags nil
+ "List of tags that can be inherited by all entries in the file.
+The tags will be inherited if the variable `org-use-tag-inheritance'
+says they should be.
+This variable is populated from #+FILETAGS lines.")
+
+(defcustom org-use-fast-tag-selection 'auto
+ "Non-nil means use fast tag selection scheme.
+This is a special interface to select and deselect tags with single keys.
+When nil, fast selection is never used.
+When the symbol `auto', fast selection is used if and only if selection
+characters for tags have been configured, either through the variable
+`org-tag-alist' or through a #+TAGS line in the buffer.
+When t, fast selection is always used and selection keys are assigned
+automatically if necessary."
+ :group 'org-tags
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "Never" nil)
+ (const :tag "When selection characters are configured" auto)))
+
+(defcustom org-fast-tag-selection-single-key nil
+ "Non-nil means fast tag selection exits after first change.
+When nil, you have to press RET to exit it.
+During fast tag selection, you can toggle this flag with `C-c'.
+This variable can also have the value `expert'. In this case, the window
+displaying the tags menu is not even shown, until you press C-c again."
+ :group 'org-tags
+ :type '(choice
+ (const :tag "No" nil)
+ (const :tag "Yes" t)
+ (const :tag "Expert" expert)))
+
+(defvar org-fast-tag-selection-include-todo nil
+ "Non-nil means fast tags selection interface will also offer TODO states.
+This is an undocumented feature, you should not rely on it.")
+
+(defcustom org-tags-column -77
+ "The column to which tags should be indented in a headline.
+If this number is positive, it specifies the column. If it is negative,
+it means that the tags should be flushright to that column. For example,
+-80 works well for a normal 80 character screen.
+When 0, place tags directly after headline text, with only one space in
+between."
+ :group 'org-tags
+ :type 'integer)
+
+(defcustom org-auto-align-tags t
+ "Non-nil keeps tags aligned when modifying headlines.
+Some operations (i.e. demoting) change the length of a headline and
+therefore shift the tags around. With this option turned on, after
+each such operation the tags are again aligned to `org-tags-column'."
+ :group 'org-tags
+ :type 'boolean)
+
+(defcustom org-use-tag-inheritance t
+ "Non-nil means tags in levels apply also for sublevels.
+When nil, only the tags directly given in a specific line apply there.
+This may also be a list of tags that should be inherited, or a regexp that
+matches tags that should be inherited. Additional control is possible
+with the variable `org-tags-exclude-from-inheritance' which gives an
+explicit list of tags to be excluded from inheritance, even if the value of
+`org-use-tag-inheritance' would select it for inheritance.
+
+If this option is t, a match early-on in a tree can lead to a large
+number of matches in the subtree when constructing the agenda or creating
+a sparse tree. If you only want to see the first match in a tree during
+a search, check out the variable `org-tags-match-list-sublevels'."
+ :group 'org-tags
+ :type '(choice
+ (const :tag "Not" nil)
+ (const :tag "Always" t)
+ (repeat :tag "Specific tags" (string :tag "Tag"))
+ (regexp :tag "Tags matched by regexp")))
+
+(defcustom org-tags-exclude-from-inheritance nil
+ "List of tags that should never be inherited.
+This is a way to exclude a few tags from inheritance. For way to do
+the opposite, to actively allow inheritance for selected tags,
+see the variable `org-use-tag-inheritance'."
+ :group 'org-tags
+ :type '(repeat (string :tag "Tag")))
+
+(defun org-tag-inherit-p (tag)
+ "Check if TAG is one that should be inherited."
+ (cond
+ ((member tag org-tags-exclude-from-inheritance) nil)
+ ((eq org-use-tag-inheritance t) t)
+ ((not org-use-tag-inheritance) nil)
+ ((stringp org-use-tag-inheritance)
+ (string-match org-use-tag-inheritance tag))
+ ((listp org-use-tag-inheritance)
+ (member tag org-use-tag-inheritance))
+ (t (error "Invalid setting of `org-use-tag-inheritance'"))))
+
+(defcustom org-tags-match-list-sublevels t
+ "Non-nil means list also sublevels of headlines matching a search.
+This variable applies to tags/property searches, and also to stuck
+projects because this search is based on a tags match as well.
+
+When set to the symbol `indented', sublevels are indented with
+leading dots.
+
+Because of tag inheritance (see variable `org-use-tag-inheritance'),
+the sublevels of a headline matching a tag search often also match
+the same search. Listing all of them can create very long lists.
+Setting this variable to nil causes subtrees of a match to be skipped.
+
+This variable is semi-obsolete and probably should always be true. It
+is better to limit inheritance to certain tags using the variables
+`org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
+ :group 'org-tags
+ :type '(choice
+ (const :tag "No, don't list them" nil)
+ (const :tag "Yes, do list them" t)
+ (const :tag "List them, indented with leading dots" indented)))
+
+(defcustom org-tags-sort-function nil
+ "When set, tags are sorted using this function as a comparator."
+ :group 'org-tags
+ :type '(choice
+ (const :tag "No sorting" nil)
+ (const :tag "Alphabetical" string<)
+ (const :tag "Reverse alphabetical" string>)
+ (function :tag "Custom function" nil)))
+
+(defvar org-tags-history nil
+ "History of minibuffer reads for tags.")
+(defvar org-last-tags-completion-table nil
+ "The last used completion table for tags.")
+(defvar org-after-tags-change-hook nil
+ "Hook that is run after the tags in a line have changed.")
+
+(defgroup org-properties nil
+ "Options concerning properties in Org mode."
+ :tag "Org Properties"
+ :group 'org)
+
+(defcustom org-property-format "%-10s %s"
+ "How property key/value pairs should be formatted by `indent-line'.
+When `indent-line' hits a property definition, it will format the line
+according to this format, mainly to make sure that the values are
+lined-up with respect to each other."
+ :group 'org-properties
+ :type 'string)
+
+(defcustom org-properties-postprocess-alist nil
+ "Alist of properties and functions to adjust inserted values.
+Elements of this alist must be of the form
+
+ ([string] [function])
+
+where [string] must be a property name and [function] must be a
+lambda expression: this lambda expression must take one argument,
+the value to adjust, and return the new value as a string.
+
+For example, this element will allow the property \"Remaining\"
+to be updated wrt the relation between the \"Effort\" property
+and the clock summary:
+
+ ((\"Remaining\" (lambda(value)
+ (let ((clocksum (org-clock-sum-current-item))
+ (effort (org-duration-string-to-minutes
+ (org-entry-get (point) \"Effort\"))))
+ (org-minutes-to-clocksum-string (- effort clocksum))))))"
+ :group 'org-properties
+ :version "24.1"
+ :type '(alist :key-type (string :tag "Property")
+ :value-type (function :tag "Function")))
+
+(defcustom org-use-property-inheritance nil
+ "Non-nil means properties apply also for sublevels.
+
+This setting is chiefly used during property searches. Turning it on can
+cause significant overhead when doing a search, which is why it is not
+on by default.
+
+When nil, only the properties directly given in the current entry count.
+When t, every property is inherited. The value may also be a list of
+properties that should have inheritance, or a regular expression matching
+properties that should be inherited.
+
+However, note that some special properties use inheritance under special
+circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
+and the properties ending in \"_ALL\" when they are used as descriptor
+for valid values of a property.
+
+Note for programmers:
+When querying an entry with `org-entry-get', you can control if inheritance
+should be used. By default, `org-entry-get' looks only at the local
+properties. You can request inheritance by setting the inherit argument
+to t (to force inheritance) or to `selective' (to respect the setting
+in this variable)."
+ :group 'org-properties
+ :type '(choice
+ (const :tag "Not" nil)
+ (const :tag "Always" t)
+ (repeat :tag "Specific properties" (string :tag "Property"))
+ (regexp :tag "Properties matched by regexp")))
+
+(defun org-property-inherit-p (property)
+ "Return a non-nil value if PROPERTY should be inherited."
+ (cond
+ ((eq org-use-property-inheritance t) t)
+ ((not org-use-property-inheritance) nil)
+ ((stringp org-use-property-inheritance)
+ (string-match org-use-property-inheritance property))
+ ((listp org-use-property-inheritance)
+ (member-ignore-case property org-use-property-inheritance))
+ (t (error "Invalid setting of `org-use-property-inheritance'"))))
+
+(defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
+ "The default column format, if no other format has been defined.
+This variable can be set on the per-file basis by inserting a line
+
+#+COLUMNS: %25ITEM ....."
+ :group 'org-properties
+ :type 'string)
+
+(defcustom org-columns-ellipses ".."
+ "The ellipses to be used when a field in column view is truncated.
+When this is the empty string, as many characters as possible are shown,
+but then there will be no visual indication that the field has been truncated.
+When this is a string of length N, the last N characters of a truncated
+field are replaced by this string. If the column is narrower than the
+ellipses string, only part of the ellipses string will be shown."
+ :group 'org-properties
+ :type 'string)
+
+(defconst org-global-properties-fixed
+ '(("VISIBILITY_ALL" . "folded children content all")
+ ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
+ "List of property/value pairs that can be inherited by any entry.
+
+These are fixed values, for the preset properties. The user variable
+that can be used to add to this list is `org-global-properties'.
+
+The entries in this list are cons cells where the car is a property
+name and cdr is a string with the value. If the value represents
+multiple items like an \"_ALL\" property, separate the items by
+spaces.")
+
+(defcustom org-global-properties nil
+ "List of property/value pairs that can be inherited by any entry.
+
+This list will be combined with the constant `org-global-properties-fixed'.
+
+The entries in this list are cons cells where the car is a property
+name and cdr is a string with the value.
+
+You can set buffer-local values for the same purpose in the variable
+`org-file-properties' this by adding lines like
+
+#+PROPERTY: NAME VALUE"
+ :group 'org-properties
+ :type '(repeat
+ (cons (string :tag "Property")
+ (string :tag "Value"))))
+
+(defvar-local org-file-properties nil
+ "List of property/value pairs that can be inherited by any entry.
+Valid for the current buffer.
+This variable is populated from #+PROPERTY lines.")
+
+(defgroup org-agenda nil
+ "Options concerning agenda views in Org mode."
+ :tag "Org Agenda"
+ :group 'org)
+
+(defvar-local org-category nil
+ "Variable used by org files to set a category for agenda display.
+Such files should use a file variable to set it, for example
+
+# -*- mode: org; org-category: \"ELisp\"
+
+or contain a special line
+
+#+CATEGORY: ELisp
+
+If the file does not specify a category, then file's base name
+is used instead.")
+(put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
+
+(defcustom org-agenda-files nil
+ "The files to be used for agenda display.
+
+If an entry is a directory, all files in that directory that are matched
+by `org-agenda-file-regexp' will be part of the file list.
+
+If the value of the variable is not a list but a single file name, then
+the list of agenda files is actually stored and maintained in that file,
+one agenda file per line. In this file paths can be given relative to
+`org-directory'. Tilde expansion and environment variable substitution
+are also made.
+
+Entries may be added to this list with `\\[org-agenda-file-to-front]'
+and removed with `\\[org-remove-file]'."
+ :group 'org-agenda
+ :type '(choice
+ (repeat :tag "List of files and directories" file)
+ (file :tag "Store list in a file\n" :value "~/.agenda_files")))
+
+(defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
+ "Regular expression to match files for `org-agenda-files'.
+If any element in the list in that variable contains a directory instead
+of a normal file, all files in that directory that are matched by this
+regular expression will be included."
+ :group 'org-agenda
+ :type 'regexp)
+
+(defcustom org-agenda-text-search-extra-files nil
+ "List of extra files to be searched by text search commands.
+These files will be searched in addition to the agenda files by the
+commands `org-search-view' (`\\[org-agenda] s') \
+and `org-occur-in-agenda-files'.
+Note that these files will only be searched for text search commands,
+not for the other agenda views like todo lists, tag searches or the weekly
+agenda. This variable is intended to list notes and possibly archive files
+that should also be searched by these two commands.
+In fact, if the first element in the list is the symbol `agenda-archives',
+then all archive files of all agenda files will be added to the search
+scope."
+ :group 'org-agenda
+ :type '(set :greedy t
+ (const :tag "Agenda Archives" agenda-archives)
+ (repeat :inline t (file))))
+
+(defvaralias 'org-agenda-multi-occur-extra-files
+ 'org-agenda-text-search-extra-files)
+
+(defcustom org-agenda-skip-unavailable-files nil
+ "Non-nil means to just skip non-reachable files in `org-agenda-files'.
+A nil value means to remove them, after a query, from the list."
+ :group 'org-agenda
+ :type 'boolean)
+
+(defcustom org-calendar-to-agenda-key [?c]
+ "The key to be installed in `calendar-mode-map' for switching to the agenda.
+The command `org-calendar-goto-agenda' will be bound to this key. The
+default is the character `c' because then `c' can be used to switch back and
+forth between agenda and calendar."
+ :group 'org-agenda
+ :type 'sexp)
+
+(defcustom org-calendar-insert-diary-entry-key [?i]
+ "The key to be installed in `calendar-mode-map' for adding diary entries.
+This option is irrelevant until `org-agenda-diary-file' has been configured
+to point to an Org file. When that is the case, the command
+`org-agenda-diary-entry' will be bound to the key given here, by default
+`i'. In the calendar, `i' normally adds entries to `diary-file'. So
+if you want to continue doing this, you need to change this to a different
+key."
+ :group 'org-agenda
+ :type 'sexp)
+
+(defcustom org-agenda-diary-file 'diary-file
+ "File to which to add new entries with the `i' key in agenda and calendar.
+When this is the symbol `diary-file', the functionality in the Emacs
+calendar will be used to add entries to the `diary-file'. But when this
+points to a file, `org-agenda-diary-entry' will be used instead."
+ :group 'org-agenda
+ :type '(choice
+ (const :tag "The standard Emacs diary file" diary-file)
+ (file :tag "Special Org file diary entries")))
+
+(eval-after-load "calendar"
+ '(progn
+ (org-defkey calendar-mode-map org-calendar-to-agenda-key
+ 'org-calendar-goto-agenda)
+ (add-hook 'calendar-mode-hook
+ (lambda ()
+ (unless (eq org-agenda-diary-file 'diary-file)
+ (define-key calendar-mode-map
+ org-calendar-insert-diary-entry-key
+ 'org-agenda-diary-entry))))))
+
+(defgroup org-latex nil
+ "Options for embedding LaTeX code into Org mode."
+ :tag "Org LaTeX"
+ :group 'org)
+
+(defcustom org-format-latex-options
+ '(:foreground default :background default :scale 1.0
+ :html-foreground "Black" :html-background "Transparent"
+ :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
+ "Options for creating images from LaTeX fragments.
+This is a property list with the following properties:
+:foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
+ `default' means use the foreground of the default face.
+ `auto' means use the foreground from the text face.
+:background the background color, or \"Transparent\".
+ `default' means use the background of the default face.
+ `auto' means use the background from the text face.
+:scale a scaling factor for the size of the images, to get more pixels
+:html-foreground, :html-background, :html-scale
+ the same numbers for HTML export.
+:matchers a list indicating which matchers should be used to
+ find LaTeX fragments. Valid members of this list are:
+ \"begin\" find environments
+ \"$1\" find single characters surrounded by $.$
+ \"$\" find math expressions surrounded by $...$
+ \"$$\" find math expressions surrounded by $$....$$
+ \"\\(\" find math expressions surrounded by \\(...\\)
+ \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
+ :group 'org-latex
+ :type 'plist)
+
+(defcustom org-format-latex-signal-error t
+ "Non-nil means signal an error when image creation of LaTeX snippets fails.
+When nil, just push out a message."
+ :group 'org-latex
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-latex-to-mathml-jar-file nil
+ "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
+Use this to specify additional executable file say a jar file.
+
+When using MathToWeb as the converter, specify the full-path to
+your mathtoweb.jar file."
+ :group 'org-latex
+ :version "24.1"
+ :type '(choice
+ (const :tag "None" nil)
+ (file :tag "JAR file" :must-match t)))
+
+(defcustom org-latex-to-mathml-convert-command nil
+ "Command to convert LaTeX fragments to MathML.
+Replace format-specifiers in the command as noted below and use
+`shell-command' to convert LaTeX to MathML.
+%j: Executable file in fully expanded form as specified by
+ `org-latex-to-mathml-jar-file'.
+%I: Input LaTeX file in fully expanded form.
+%i: The latex fragment to be converted.
+%o: Output MathML file.
+
+This command is used by `org-create-math-formula'.
+
+When using MathToWeb as the converter, set this option to
+\"java -jar %j -unicode -force -df %o %I\".
+
+When using LaTeXML set this option to
+\"latexmlmath \"%i\" --presentationmathml=%o\"."
+ :group 'org-latex
+ :version "24.1"
+ :type '(choice
+ (const :tag "None" nil)
+ (string :tag "\nShell command")))
+
+(defcustom org-preview-latex-default-process 'dvipng
+ "The default process to convert LaTeX fragments to image files.
+All available processes and theirs documents can be found in
+`org-preview-latex-process-alist', which see."
+ :group 'org-latex
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type 'symbol)
+
+(defcustom org-preview-latex-process-alist
+ '((dvipng
+ :programs ("latex" "dvipng")
+ :description "dvi > png"
+ :message "you need to install the programs: latex and dvipng."
+ :image-input-type "dvi"
+ :image-output-type "png"
+ :image-size-adjust (1.0 . 1.0)
+ :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
+ :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
+ (dvisvgm
+ :programs ("latex" "dvisvgm")
+ :description "dvi > svg"
+ :message "you need to install the programs: latex and dvisvgm."
+ :use-xcolor t
+ :image-input-type "dvi"
+ :image-output-type "svg"
+ :image-size-adjust (1.7 . 1.5)
+ :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
+ :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
+ (imagemagick
+ :programs ("latex" "convert")
+ :description "pdf > png"
+ :message "you need to install the programs: latex and imagemagick."
+ :use-xcolor t
+ :image-input-type "pdf"
+ :image-output-type "png"
+ :image-size-adjust (1.0 . 1.0)
+ :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
+ :image-converter
+ ("convert -density %D -trim -antialias %f -quality 100 %O")))
+ "Definitions of external processes for LaTeX previewing.
+Org mode can use some external commands to generate TeX snippet's images for
+previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
+`org-create-formula-image' how to call them.
+
+The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
+PROPERTIES accepts the following attributes:
+
+ :programs list of strings, required programs.
+ :description string, describe the process.
+ :message string, message it when required programs cannot be found.
+ :image-input-type string, input file type of image converter (e.g., \"dvi\").
+ :image-output-type string, output file type of image converter (e.g., \"png\").
+ :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
+ deal with background and foreground color of image.
+ Otherwise, dvipng style background and foregroud color
+ format are generated. You may then refer to them in
+ command options with \"%F\" and \"%B\".
+ :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
+ image size showed in buffer and the cdr element is for
+ HTML file. This option is only useful for process
+ developers, users should use variable
+ `org-format-latex-options' instead.
+ :post-clean list of strings, files matched are to be cleaned up once
+ the image is generated. When nil, the files with \".dvi\",
+ \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
+ \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
+ be cleaned up.
+ :latex-header list of strings, the LaTeX header of the snippet file.
+ When nil, the fallback value is used instead, which is
+ controlled by `org-format-latex-header',
+ `org-latex-default-packages-alist' and
+ `org-latex-packages-alist', which see.
+ :latex-compiler list of LaTeX commands, as strings. Each of them is given
+ to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
+ replaced with values defined below.
+ :image-converter list of image converter commands strings. Each of them is
+ given to the shell and supports any of the following
+ place-holders defined below.
+
+Place-holders used by `:image-converter' and `:latex-compiler':
+
+ %f input file name
+ %b base name of input file
+ %o base directory of input file
+ %O absolute output file name
+
+Place-holders only used by `:image-converter':
+
+ %F foreground of image
+ %B background of image
+ %D dpi, which is used to adjust image size by some processing commands.
+ %S the image size scale ratio, which is used to adjust image size by some
+ processing commands."
+ :group 'org-latex
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type '(alist :tag "LaTeX to image backends"
+ :value-type (plist)))
+
+(defcustom org-preview-latex-image-directory "ltximg/"
+ "Path to store latex preview images.
+A relative path here creates many directories relative to the
+processed org files paths. An absolute path puts all preview
+images at the same place."
+ :group 'org-latex
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type 'string)
+
+(defun org-format-latex-mathml-available-p ()
+ "Return t if `org-latex-to-mathml-convert-command' is usable."
+ (save-match-data
+ (when (and (boundp 'org-latex-to-mathml-convert-command)
+ org-latex-to-mathml-convert-command)
+ (let ((executable (car (split-string
+ org-latex-to-mathml-convert-command))))
+ (when (executable-find executable)
+ (if (string-match
+ "%j" org-latex-to-mathml-convert-command)
+ (file-readable-p org-latex-to-mathml-jar-file)
+ t))))))
+
+(defcustom org-format-latex-header "\\documentclass{article}
+\\usepackage[usenames]{color}
+\[PACKAGES]
+\[DEFAULT-PACKAGES]
+\\pagestyle{empty} % do not remove
+% The settings below are copied from fullpage.sty
+\\setlength{\\textwidth}{\\paperwidth}
+\\addtolength{\\textwidth}{-3cm}
+\\setlength{\\oddsidemargin}{1.5cm}
+\\addtolength{\\oddsidemargin}{-2.54cm}
+\\setlength{\\evensidemargin}{\\oddsidemargin}
+\\setlength{\\textheight}{\\paperheight}
+\\addtolength{\\textheight}{-\\headheight}
+\\addtolength{\\textheight}{-\\headsep}
+\\addtolength{\\textheight}{-\\footskip}
+\\addtolength{\\textheight}{-3cm}
+\\setlength{\\topmargin}{1.5cm}
+\\addtolength{\\topmargin}{-2.54cm}"
+ "The document header used for processing LaTeX fragments.
+It is imperative that this header make sure that no page number
+appears on the page. The package defined in the variables
+`org-latex-default-packages-alist' and `org-latex-packages-alist'
+will either replace the placeholder \"[PACKAGES]\" in this
+header, or they will be appended."
+ :group 'org-latex
+ :type 'string)
+
+(defun org-set-packages-alist (var val)
+ "Set the packages alist and make sure it has 3 elements per entry."
+ (set var (mapcar (lambda (x)
+ (if (and (consp x) (= (length x) 2))
+ (list (car x) (nth 1 x) t)
+ x))
+ val)))
+
+(defun org-get-packages-alist (var)
+ "Get the packages alist and make sure it has 3 elements per entry."
+ (mapcar (lambda (x)
+ (if (and (consp x) (= (length x) 2))
+ (list (car x) (nth 1 x) t)
+ x))
+ (default-value var)))
+
+(defcustom org-latex-default-packages-alist
+ '(("AUTO" "inputenc" t ("pdflatex"))
+ ("T1" "fontenc" t ("pdflatex"))
+ ("" "graphicx" t)
+ ("" "grffile" t)
+ ("" "longtable" nil)
+ ("" "wrapfig" nil)
+ ("" "rotating" nil)
+ ("normalem" "ulem" t)
+ ("" "amsmath" t)
+ ("" "textcomp" t)
+ ("" "amssymb" t)
+ ("" "capt-of" nil)
+ ("" "hyperref" nil))
+ "Alist of default packages to be inserted in the header.
+
+Change this only if one of the packages here causes an
+incompatibility with another package you are using.
+
+The packages in this list are needed by one part or another of
+Org mode to function properly:
+
+- inputenc, fontenc: for basic font and character selection
+- graphicx: for including images
+- grffile: allow periods and spaces in graphics file names
+- longtable: For multipage tables
+- wrapfig: for figure placement
+- rotating: for sideways figures and tables
+- ulem: for underline and strike-through
+- amsmath: for subscript and superscript and math environments
+- textcomp, amssymb: for various symbols used
+ for interpreting the entities in `org-entities'. You can skip
+ some of these packages if you don't use any of their symbols.
+- capt-of: for captions outside of floats
+- hyperref: for cross references
+
+Therefore you should not modify this variable unless you know
+what you are doing. The one reason to change it anyway is that
+you might be loading some other package that conflicts with one
+of the default packages. Each element is either a cell or
+a string.
+
+A cell is of the format
+
+ (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
+
+If SNIPPET-FLAG is non-nil, the package also needs to be included
+when compiling LaTeX snippets into images for inclusion into
+non-LaTeX output. COMPILERS is a list of compilers that should
+include the package, see `org-latex-compiler'. If the document
+compiler is not in the list, and the list is non-nil, the package
+will not be inserted in the final document.
+
+A string will be inserted as-is in the header of the document."
+ :group 'org-latex
+ :group 'org-export-latex
+ :set 'org-set-packages-alist
+ :get 'org-get-packages-alist
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(repeat
+ (choice
+ (list :tag "options/package pair"
+ (string :tag "options")
+ (string :tag "package")
+ (boolean :tag "Snippet"))
+ (string :tag "A line of LaTeX"))))
+
+(defcustom org-latex-packages-alist nil
+ "Alist of packages to be inserted in every LaTeX header.
+
+These will be inserted after `org-latex-default-packages-alist'.
+Each element is either a cell or a string.
+
+A cell is of the format:
+
+ (\"options\" \"package\" SNIPPET-FLAG)
+
+SNIPPET-FLAG, when non-nil, indicates that this package is also
+needed when turning LaTeX snippets into images for inclusion into
+non-LaTeX output.
+
+A string will be inserted as-is in the header of the document.
+
+Make sure that you only list packages here which:
+
+ - you want in every file;
+ - do not conflict with the setup in `org-format-latex-header';
+ - do not conflict with the default packages in
+ `org-latex-default-packages-alist'."
+ :group 'org-latex
+ :group 'org-export-latex
+ :set 'org-set-packages-alist
+ :get 'org-get-packages-alist
+ :type '(repeat
+ (choice
+ (list :tag "options/package pair"
+ (string :tag "options")
+ (string :tag "package")
+ (boolean :tag "Snippet"))
+ (string :tag "A line of LaTeX"))))
+
+(defgroup org-appearance nil
+ "Settings for Org mode appearance."
+ :tag "Org Appearance"
+ :group 'org)
+
+(defcustom org-level-color-stars-only nil
+ "Non-nil means fontify only the stars in each headline.
+When nil, the entire headline is fontified.
+Changing it requires restart of `font-lock-mode' to become effective
+also in regions already fontified."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-hide-leading-stars nil
+ "Non-nil means hide the first N-1 stars in a headline.
+This works by using the face `org-hide' for these stars. This
+face is white for a light background, and black for a dark
+background. You may have to customize the face `org-hide' to
+make this work.
+Changing it requires restart of `font-lock-mode' to become effective
+also in regions already fontified.
+You may also set this on a per-file basis by adding one of the following
+lines to the buffer:
+
+ #+STARTUP: hidestars
+ #+STARTUP: showstars"
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-hidden-keywords nil
+ "List of symbols corresponding to keywords to be hidden the org buffer.
+For example, a value \\='(title) for this list will make the document's title
+appear in the buffer without the initial #+TITLE: keyword."
+ :group 'org-appearance
+ :version "24.1"
+ :type '(set (const :tag "#+AUTHOR" author)
+ (const :tag "#+DATE" date)
+ (const :tag "#+EMAIL" email)
+ (const :tag "#+TITLE" title)))
+
+(defcustom org-custom-properties nil
+ "List of properties (as strings) with a special meaning.
+The default use of these custom properties is to let the user
+hide them with `org-toggle-custom-properties-visibility'."
+ :group 'org-properties
+ :group 'org-appearance
+ :version "24.3"
+ :type '(repeat (string :tag "Property Name")))
+
+(defcustom org-fontify-done-headline nil
+ "Non-nil means change the face of a headline if it is marked DONE.
+Normally, only the TODO/DONE keyword indicates the state of a headline.
+When this is non-nil, the headline after the keyword is set to the
+`org-headline-done' as an additional indication."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-fontify-emphasized-text t
+ "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
+Changing this variable requires a restart of Emacs to take effect."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-fontify-whole-heading-line nil
+ "Non-nil means fontify the whole line for headings.
+This is useful when setting a background color for the
+org-level-* faces."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-highlight-latex-and-related nil
+ "Non-nil means highlight LaTeX related syntax in the buffer.
+When non nil, the value should be a list containing any of the
+following symbols:
+ `latex' Highlight LaTeX snippets and environments.
+ `script' Highlight subscript and superscript.
+ `entities' Highlight entities."
+ :group 'org-appearance
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "No highlighting" nil)
+ (set :greedy t :tag "Highlight"
+ (const :tag "LaTeX snippets and environments" latex)
+ (const :tag "Subscript and superscript" script)
+ (const :tag "Entities" entities))))
+
+(defcustom org-hide-emphasis-markers nil
+ "Non-nil mean font-lock should hide the emphasis marker characters."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-hide-macro-markers nil
+ "Non-nil mean font-lock should hide the brackets marking macro calls."
+ :group 'org-appearance
+ :type 'boolean)
+
+(defcustom org-pretty-entities nil
+ "Non-nil means show entities as UTF8 characters.
+When nil, the \\name form remains in the buffer."
+ :group 'org-appearance
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-pretty-entities-include-sub-superscripts t
+ "Non-nil means, pretty entity display includes formatting sub/superscripts."
+ :group 'org-appearance
+ :version "24.1"
+ :type 'boolean)
+
+(defvar org-emph-re nil
+ "Regular expression for matching emphasis.
+After a match, the match groups contain these elements:
+0 The match of the full regular expression, including the characters
+ before and after the proper match
+1 The character before the proper match, or empty at beginning of line
+2 The proper match, including the leading and trailing markers
+3 The leading marker like * or /, indicating the type of highlighting
+4 The text between the emphasis markers, not including the markers
+5 The character after the match, empty at the end of a line")
+(defvar org-verbatim-re nil
+ "Regular expression for matching verbatim text.")
+(defvar org-emphasis-regexp-components) ; defined just below
+(defvar org-emphasis-alist) ; defined just below
+(defun org-set-emph-re (var val)
+ "Set variable and compute the emphasis regular expression."
+ (set var val)
+ (when (and (boundp 'org-emphasis-alist)
+ (boundp 'org-emphasis-regexp-components)
+ org-emphasis-alist org-emphasis-regexp-components)
+ (let* ((e org-emphasis-regexp-components)
+ (pre (car e))
+ (post (nth 1 e))
+ (border (nth 2 e))
+ (body (nth 3 e))
+ (nl (nth 4 e))
+ (body1 (concat body "*?"))
+ (markers (mapconcat 'car org-emphasis-alist ""))
+ (vmarkers (mapconcat
+ (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
+ org-emphasis-alist "")))
+ ;; make sure special characters appear at the right position in the class
+ (if (string-match "\\^" markers)
+ (setq markers (concat (replace-match "" t t markers) "^")))
+ (if (string-match "-" markers)
+ (setq markers (concat (replace-match "" t t markers) "-")))
+ (if (string-match "\\^" vmarkers)
+ (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
+ (if (string-match "-" vmarkers)
+ (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
+ (if (> nl 0)
+ (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
+ (int-to-string nl) "\\}")))
+ ;; Make the regexp
+ (setq org-emph-re
+ (concat "\\([" pre "]\\|^\\)"
+ "\\("
+ "\\([" markers "]\\)"
+ "\\("
+ "[^" border "]\\|"
+ "[^" border "]"
+ body1
+ "[^" border "]"
+ "\\)"
+ "\\3\\)"
+ "\\([" post "]\\|$\\)"))
+ (setq org-verbatim-re
+ (concat "\\([" pre "]\\|^\\)"
+ "\\("
+ "\\([" vmarkers "]\\)"
+ "\\("
+ "[^" border "]\\|"
+ "[^" border "]"
+ body1
+ "[^" border "]"
+ "\\)"
+ "\\3\\)"
+ "\\([" post "]\\|$\\)")))))
+
+;; This used to be a defcustom (Org <8.0) but allowing the users to
+;; set this option proved cumbersome. See this message/thread:
+;; http://article.gmane.org/gmane.emacs.orgmode/68681
+(defvar org-emphasis-regexp-components
+ '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
+ "Components used to build the regular expression for emphasis.
+This is a list with five entries. Terminology: In an emphasis string
+like \" *strong word* \", we call the initial space PREMATCH, the final
+space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
+and \"trong wor\" is the body. The different components in this variable
+specify what is allowed/forbidden in each part:
+
+pre Chars allowed as prematch. Beginning of line will be allowed too.
+post Chars allowed as postmatch. End of line will be allowed too.
+border The chars *forbidden* as border characters.
+body-regexp A regexp like \".\" to match a body character. Don't use
+ non-shy groups here, and don't allow newline here.
+newline The maximum number of newlines allowed in an emphasis exp.
+
+You need to reload Org or to restart Emacs after customizing this.")
+
+(defcustom org-emphasis-alist
+ '(("*" bold)
+ ("/" italic)
+ ("_" underline)
+ ("=" org-verbatim verbatim)
+ ("~" org-code verbatim)
+ ("+" (:strike-through t)))
+ "Alist of characters and faces to emphasize text.
+Text starting and ending with a special character will be emphasized,
+for example *bold*, _underlined_ and /italic/. This variable sets the
+marker characters and the face to be used by font-lock for highlighting
+in Org buffers.
+
+You need to reload Org or to restart Emacs after customizing this."
+ :group 'org-appearance
+ :set 'org-set-emph-re
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(repeat
+ (list
+ (string :tag "Marker character")
+ (choice
+ (face :tag "Font-lock-face")
+ (plist :tag "Face property list"))
+ (option (const verbatim)))))
+
+(defvar org-protecting-blocks '("src" "example" "export")
+ "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
+This is needed for font-lock setup.")
+
+;;; Functions and variables from their packages
+;; Declared here to avoid compiler warnings
+(defvar mark-active)
+
+;; Various packages
+(declare-function calc-eval "calc" (str &optional separator &rest args))
+(declare-function calendar-forward-day "cal-move" (arg))
+(declare-function calendar-goto-date "cal-move" (date))
+(declare-function calendar-goto-today "cal-move" ())
+(declare-function calendar-iso-from-absolute "cal-iso" (date))
+(declare-function calendar-iso-to-absolute "cal-iso" (date))
+(declare-function cdlatex-compute-tables "ext:cdlatex" ())
+(declare-function cdlatex-tab "ext:cdlatex" ())
+(declare-function dired-get-filename
+ "dired"
+ (&optional localp no-error-if-not-filep))
+(declare-function iswitchb-read-buffer
+ "iswitchb"
+ (prompt &optional
+ default require-match _predicate start matches-set))
+(declare-function org-agenda-change-all-lines
+ "org-agenda"
+ (newhead hdmarker &optional fixface just-this))
+(declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
+ "org-agenda"
+ (&optional end))
+(declare-function org-agenda-copy-local-variable "org-agenda" (var))
+(declare-function org-agenda-format-item
+ "org-agenda"
+ (extra txt &optional level category tags dotime
+ remove-re habitp))
+(declare-function org-agenda-maybe-redo "org-agenda" ())
+(declare-function org-agenda-new-marker "org-agenda" (&optional pos))
+(declare-function org-agenda-save-markers-for-cut-and-paste
+ "org-agenda"
+ (beg end))
+(declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
+(declare-function org-agenda-skip "org-agenda" ())
+(declare-function org-attach-reveal "org-attach" (&optional if-exists))
+(declare-function org-gnus-follow-link "org-gnus" (&optional group article))
+(declare-function org-indent-mode "org-indent" (&optional arg))
+(declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
+(declare-function org-inlinetask-goto-end "org-inlinetask" ())
+(declare-function org-inlinetask-in-task-p "org-inlinetask" ())
+(declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
+(declare-function orgtbl-send-table "org-table" (&optional maybe))
+(declare-function parse-time-string "parse-time" (string))
+(declare-function speedbar-line-directory "speedbar" (&optional depth))
+
+(defvar align-mode-rules-list)
+(defvar calc-embedded-close-formula)
+(defvar calc-embedded-open-formula)
+(defvar calc-embedded-open-mode)
+(defvar font-lock-unfontify-region-function)
+(defvar iswitchb-temp-buflist)
+(defvar org-agenda-tags-todo-honor-ignore-options)
+(defvar remember-data-file)
+(defvar texmathp-why)
+
+;;;###autoload
+(defun turn-on-orgtbl ()
+ "Unconditionally turn on `orgtbl-mode'."
+ (require 'org-table)
+ (orgtbl-mode 1))
+
+(defun org-at-table-p (&optional table-type)
+ "Non-nil if the cursor is inside an Org table.
+If TABLE-TYPE is non-nil, also check for table.el-type tables.
+If `org-enable-table-editor' is nil, return nil unconditionally."
+ (and
+ org-enable-table-editor
+ (save-excursion
+ (beginning-of-line)
+ (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
+ (or (not (derived-mode-p 'org-mode))
+ (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
+ (and e (or table-type (eq (org-element-property :type e) 'org)))))))
+
+(defun org-at-table.el-p ()
+ "Non-nil when point is at a table.el table."
+ (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
+ (let ((element (org-element-at-point)))
+ (and (eq (org-element-type element) 'table)
+ (eq (org-element-property :type element) 'table.el)))))
+
+(defun org-at-table-hline-p ()
+ "Non-nil when point is inside a hline in a table.
+Assume point is already in a table. If `org-enable-table-editor'
+is nil, return nil unconditionally."
+ (and org-enable-table-editor
+ (save-excursion
+ (beginning-of-line)
+ (looking-at org-table-hline-regexp))))
+
+(defun org-table-map-tables (function &optional quietly)
+ "Apply FUNCTION to the start of all tables in the buffer."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward org-table-any-line-regexp nil t)
+ (unless quietly
+ (message "Mapping tables: %d%%"
+ (floor (* 100.0 (point)) (buffer-size))))
+ (beginning-of-line 1)
+ (when (and (looking-at org-table-line-regexp)
+ ;; Exclude tables in src/example/verbatim/clocktable blocks
+ (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
+ (save-excursion (funcall function))
+ (or (looking-at org-table-line-regexp)
+ (forward-char 1)))
+ (re-search-forward org-table-any-border-regexp nil 1)))
+ (unless quietly (message "Mapping tables: done")))
+
+(declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
+(declare-function org-clock-update-mode-line "org-clock" ())
+(declare-function org-resolve-clocks "org-clock"
+ (&optional also-non-dangling-p prompt last-valid))
+
+(defun org-at-TBLFM-p (&optional pos)
+ "Non-nil when point (or POS) is in #+TBLFM line."
+ (save-excursion
+ (goto-char (or pos (point)))
+ (beginning-of-line)
+ (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
+ (eq (org-element-type (org-element-at-point)) 'table))))
+
+(defvar org-clock-start-time)
+(defvar org-clock-marker (make-marker)
+ "Marker recording the last clock-in.")
+(defvar org-clock-hd-marker (make-marker)
+ "Marker recording the last clock-in, but the headline position.")
+(defvar org-clock-heading ""
+ "The heading of the current clock entry.")
+(defun org-clock-is-active ()
+ "Return the buffer where the clock is currently running.
+Return nil if no clock is running."
+ (marker-buffer org-clock-marker))
+
+(defun org-check-running-clock ()
+ "Check if the current buffer contains the running clock.
+If yes, offer to stop it and to save the buffer with the changes."
+ (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
+ (y-or-n-p (format "Clock-out in buffer %s before killing it? "
+ (buffer-name))))
+ (org-clock-out)
+ (when (y-or-n-p "Save changed buffer?")
+ (save-buffer))))
+
+(defun org-clocktable-try-shift (dir n)
+ "Check if this line starts a clock table, if yes, shift the time block."
+ (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
+ (org-clocktable-shift dir n)))
+
+;;;###autoload
+(defun org-clock-persistence-insinuate ()
+ "Set up hooks for clock persistence."
+ (require 'org-clock)
+ (add-hook 'org-mode-hook 'org-clock-load)
+ (add-hook 'kill-emacs-hook 'org-clock-save))
+
+(defgroup org-archive nil
+ "Options concerning archiving in Org mode."
+ :tag "Org Archive"
+ :group 'org-structure)
+
+(defcustom org-archive-location "%s_archive::"
+ "The location where subtrees should be archived.
+
+The value of this variable is a string, consisting of two parts,
+separated by a double-colon. The first part is a filename and
+the second part is a headline.
+
+When the filename is omitted, archiving happens in the same file.
+%s in the filename will be replaced by the current file
+name (without the directory part). Archiving to a different file
+is useful to keep archived entries from contributing to the
+Org Agenda.
+
+The archived entries will be filed as subtrees of the specified
+headline. When the headline is omitted, the subtrees are simply
+filed away at the end of the file, as top-level entries. Also in
+the heading you can use %s to represent the file name, this can be
+useful when using the same archive for a number of different files.
+
+Here are a few examples:
+\"%s_archive::\"
+ If the current file is Projects.org, archive in file
+ Projects.org_archive, as top-level trees. This is the default.
+
+\"::* Archived Tasks\"
+ Archive in the current file, under the top-level headline
+ \"* Archived Tasks\".
+
+\"~/org/archive.org::\"
+ Archive in file ~/org/archive.org (absolute path), as top-level trees.
+
+\"~/org/archive.org::* From %s\"
+ Archive in file ~/org/archive.org (absolute path), under headlines
+ \"From FILENAME\" where file name is the current file name.
+
+\"~/org/datetree.org::datetree/* Finished Tasks\"
+ The \"datetree/\" string is special, signifying to archive
+ items to the datetree. Items are placed in either the CLOSED
+ date of the item, or the current date if there is no CLOSED date.
+ The heading will be a subentry to the current date. There doesn't
+ need to be a heading, but there always needs to be a slash after
+ datetree. For example, to store archived items directly in the
+ datetree, use \"~/org/datetree.org::datetree/\".
+
+\"basement::** Finished Tasks\"
+ Archive in file ./basement (relative path), as level 3 trees
+ below the level 2 heading \"** Finished Tasks\".
+
+You may set this option on a per-file basis by adding to the buffer a
+line like
+
+#+ARCHIVE: basement::** Finished Tasks
+
+You may also define it locally for a subtree by setting an ARCHIVE property
+in the entry. If such a property is found in an entry, or anywhere up
+the hierarchy, it will be used."
+ :group 'org-archive
+ :type 'string)
+
+(defcustom org-agenda-skip-archived-trees t
+ "Non-nil means the agenda will skip any items located in archived trees.
+An archived tree is a tree marked with the tag ARCHIVE. The use of this
+variable is no longer recommended, you should leave it at the value t.
+Instead, use the key `v' to cycle the archives-mode in the agenda."
+ :group 'org-archive
+ :group 'org-agenda-skip
+ :type 'boolean)
+
+(defcustom org-columns-skip-archived-trees t
+ "Non-nil means ignore archived trees when creating column view."
+ :group 'org-archive
+ :group 'org-properties
+ :type 'boolean)
+
+(defcustom org-cycle-open-archived-trees nil
+ "Non-nil means `org-cycle' will open archived trees.
+An archived tree is a tree marked with the tag ARCHIVE.
+When nil, archived trees will stay folded. You can still open them with
+normal outline commands like `show-all', but not with the cycling commands."
+ :group 'org-archive
+ :group 'org-cycle
+ :type 'boolean)
+
+(defcustom org-sparse-tree-open-archived-trees nil
+ "Non-nil means sparse tree construction shows matches in archived trees.
+When nil, matches in these trees are highlighted, but the trees are kept in
+collapsed state."
+ :group 'org-archive
+ :group 'org-sparse-trees
+ :type 'boolean)
+
+(defcustom org-sparse-tree-default-date-type nil
+ "The default date type when building a sparse tree.
+When this is nil, a date is a scheduled or a deadline timestamp.
+Otherwise, these types are allowed:
+
+ all: all timestamps
+ active: only active timestamps (<...>)
+ inactive: only inactive timestamps ([...])
+ scheduled: only scheduled timestamps
+ deadline: only deadline timestamps"
+ :type '(choice (const :tag "Scheduled or deadline" nil)
+ (const :tag "All timestamps" all)
+ (const :tag "Only active timestamps" active)
+ (const :tag "Only inactive timestamps" inactive)
+ (const :tag "Only scheduled timestamps" scheduled)
+ (const :tag "Only deadline timestamps" deadline)
+ (const :tag "Only closed timestamps" closed))
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :group 'org-sparse-trees)
+
+(defun org-cycle-hide-archived-subtrees (state)
+ "Re-hide all archived subtrees after a visibility state change."
+ (when (and (not org-cycle-open-archived-trees)
+ (not (memq state '(overview folded))))
+ (save-excursion
+ (let* ((globalp (memq state '(contents all)))
+ (beg (if globalp (point-min) (point)))
+ (end (if globalp (point-max) (org-end-of-subtree t))))
+ (org-hide-archived-subtrees beg end)
+ (goto-char beg)
+ (when (looking-at-p (concat ".*:" org-archive-tag ":"))
+ (message "%s" (substitute-command-keys
+ "Subtree is archived and stays closed. Use \
+`\\[org-force-cycle-archived]' to cycle it anyway.")))))))
+
+(defun org-force-cycle-archived ()
+ "Cycle subtree even if it is archived."
+ (interactive)
+ (setq this-command 'org-cycle)
+ (let ((org-cycle-open-archived-trees t))
+ (call-interactively 'org-cycle)))
+
+(defun org-hide-archived-subtrees (beg end)
+ "Re-hide all archived subtrees after a visibility state change."
+ (org-with-wide-buffer
+ (let ((case-fold-search nil)
+ (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
+ (goto-char beg)
+ ;; Include headline point is currently on.
+ (beginning-of-line)
+ (while (and (< (point) end) (re-search-forward re end t))
+ (when (member org-archive-tag (org-get-tags))
+ (org-flag-subtree t)
+ (org-end-of-subtree t))))))
+
+(declare-function outline-end-of-heading "outline" ())
+(declare-function outline-flag-region "outline" (from to flag))
+(defun org-flag-subtree (flag)
+ (save-excursion
+ (org-back-to-heading t)
+ (outline-end-of-heading)
+ (outline-flag-region (point)
+ (progn (org-end-of-subtree t) (point))
+ flag)))
+
+(defalias 'org-advertized-archive-subtree 'org-archive-subtree)
+
+;; Declare Column View Code
+
+(declare-function org-columns-get-format-and-top-level "org-colview" ())
+(declare-function org-columns-compute "org-colview" (property))
+
+;; Declare ID code
+
+(declare-function org-id-store-link "org-id")
+(declare-function org-id-locations-load "org-id")
+(declare-function org-id-locations-save "org-id")
+(defvar org-id-track-globally)
+
+;;; Variables for pre-computed regular expressions, all buffer local
+
+(defvar-local org-todo-regexp nil
+ "Matches any of the TODO state keywords.
+Since TODO keywords are case-sensitive, `case-fold-search' is
+expected to be bound to nil when matching against this regexp.")
+
+(defvar-local org-not-done-regexp nil
+ "Matches any of the TODO state keywords except the last one.
+Since TODO keywords are case-sensitive, `case-fold-search' is
+expected to be bound to nil when matching against this regexp.")
+
+(defvar-local org-not-done-heading-regexp nil
+ "Matches a TODO headline that is not done.
+Since TODO keywords are case-sensitive, `case-fold-search' is
+expected to be bound to nil when matching against this regexp.")
+
+(defvar-local org-todo-line-regexp nil
+ "Matches a headline and puts TODO state into group 2 if present.
+Since TODO keywords are case-sensitive, `case-fold-search' is
+expected to be bound to nil when matching against this regexp.")
+
+(defvar-local org-complex-heading-regexp nil
+ "Matches a headline and puts everything into groups:
+
+group 1: Stars
+group 2: The TODO keyword, maybe
+group 3: Priority cookie
+group 4: True headline
+group 5: Tags
+
+Since TODO keywords are case-sensitive, `case-fold-search' is
+expected to be bound to nil when matching against this regexp.")
+
+(defvar-local org-complex-heading-regexp-format nil
+ "Printf format to make regexp to match an exact headline.
+This regexp will match the headline of any node which has the
+exact headline text that is put into the format, but may have any
+TODO state, priority and tags.")
+
+(defvar-local org-todo-line-tags-regexp nil
+ "Matches a headline and puts TODO state into group 2 if present.
+Also put tags into group 4 if tags are present.")
+
+(defconst org-plain-time-of-day-regexp
+ (concat
+ "\\(\\<[012]?[0-9]"
+ "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
+ "\\(--?"
+ "\\(\\<[012]?[0-9]"
+ "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
+ "\\)?")
+ "Regular expression to match a plain time or time range.
+Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
+groups carry important information:
+0 the full match
+1 the first time, range or not
+8 the second time, if it is a range.")
+
+(defconst org-plain-time-extension-regexp
+ (concat
+ "\\(\\<[012]?[0-9]"
+ "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
+ "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
+ "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
+Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
+groups carry important information:
+0 the full match
+7 hours of duration
+9 minutes of duration")
+
+(defconst org-stamp-time-of-day-regexp
+ (concat
+ "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
+ "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
+ "\\(--?"
+ "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
+ "Regular expression to match a timestamp time or time range.
+After a match, the following groups carry important information:
+0 the full match
+1 date plus weekday, for back referencing to make sure both times are on the same day
+2 the first time, range or not
+4 the second time, if it is a range.")
+
+(defconst org-startup-options
+ '(("fold" org-startup-folded t)
+ ("overview" org-startup-folded t)
+ ("nofold" org-startup-folded nil)
+ ("showall" org-startup-folded nil)
+ ("showeverything" org-startup-folded showeverything)
+ ("content" org-startup-folded content)
+ ("indent" org-startup-indented t)
+ ("noindent" org-startup-indented nil)
+ ("hidestars" org-hide-leading-stars t)
+ ("showstars" org-hide-leading-stars nil)
+ ("odd" org-odd-levels-only t)
+ ("oddeven" org-odd-levels-only nil)
+ ("align" org-startup-align-all-tables t)
+ ("noalign" org-startup-align-all-tables nil)
+ ("inlineimages" org-startup-with-inline-images t)
+ ("noinlineimages" org-startup-with-inline-images nil)
+ ("latexpreview" org-startup-with-latex-preview t)
+ ("nolatexpreview" org-startup-with-latex-preview nil)
+ ("customtime" org-display-custom-times t)
+ ("logdone" org-log-done time)
+ ("lognotedone" org-log-done note)
+ ("nologdone" org-log-done nil)
+ ("lognoteclock-out" org-log-note-clock-out t)
+ ("nolognoteclock-out" org-log-note-clock-out nil)
+ ("logrepeat" org-log-repeat state)
+ ("lognoterepeat" org-log-repeat note)
+ ("logdrawer" org-log-into-drawer t)
+ ("nologdrawer" org-log-into-drawer nil)
+ ("logstatesreversed" org-log-states-order-reversed t)
+ ("nologstatesreversed" org-log-states-order-reversed nil)
+ ("nologrepeat" org-log-repeat nil)
+ ("logreschedule" org-log-reschedule time)
+ ("lognotereschedule" org-log-reschedule note)
+ ("nologreschedule" org-log-reschedule nil)
+ ("logredeadline" org-log-redeadline time)
+ ("lognoteredeadline" org-log-redeadline note)
+ ("nologredeadline" org-log-redeadline nil)
+ ("logrefile" org-log-refile time)
+ ("lognoterefile" org-log-refile note)
+ ("nologrefile" org-log-refile nil)
+ ("fninline" org-footnote-define-inline t)
+ ("nofninline" org-footnote-define-inline nil)
+ ("fnlocal" org-footnote-section nil)
+ ("fnauto" org-footnote-auto-label t)
+ ("fnprompt" org-footnote-auto-label nil)
+ ("fnconfirm" org-footnote-auto-label confirm)
+ ("fnplain" org-footnote-auto-label plain)
+ ("fnadjust" org-footnote-auto-adjust t)
+ ("nofnadjust" org-footnote-auto-adjust nil)
+ ("constcgs" constants-unit-system cgs)
+ ("constSI" constants-unit-system SI)
+ ("noptag" org-tag-persistent-alist nil)
+ ("hideblocks" org-hide-block-startup t)
+ ("nohideblocks" org-hide-block-startup nil)
+ ("beamer" org-startup-with-beamer-mode t)
+ ("entitiespretty" org-pretty-entities t)
+ ("entitiesplain" org-pretty-entities nil))
+ "Variable associated with STARTUP options for org-mode.
+Each element is a list of three items: the startup options (as written
+in the #+STARTUP line), the corresponding variable, and the value to set
+this variable to if the option is found. An optional forth element PUSH
+means to push this value onto the list in the variable.")
+
+(defcustom org-group-tags t
+ "When non-nil (the default), use group tags.
+This can be turned on/off through `org-toggle-tags-groups'."
+ :group 'org-tags
+ :group 'org-startup
+ :type 'boolean)
+
+(defvar org-inhibit-startup nil) ; Dynamically-scoped param.
+
+(defun org-toggle-tags-groups ()
+ "Toggle support for group tags.
+Support for group tags is controlled by the option
+`org-group-tags', which is non-nil by default."
+ (interactive)
+ (setq org-group-tags (not org-group-tags))
+ (cond ((and (derived-mode-p 'org-agenda-mode)
+ org-group-tags)
+ (org-agenda-redo))
+ ((derived-mode-p 'org-mode)
+ (let ((org-inhibit-startup t)) (org-mode))))
+ (message "Groups tags support has been turned %s"
+ (if org-group-tags "on" "off")))
+
+(defun org-set-regexps-and-options (&optional tags-only)
+ "Precompute regular expressions used in the current buffer.
+When optional argument TAGS-ONLY is non-nil, only compute tags
+related expressions."
+ (when (derived-mode-p 'org-mode)
+ (let ((alist (org--setup-collect-keywords
+ (org-make-options-regexp
+ (append '("FILETAGS" "TAGS" "SETUPFILE")
+ (and (not tags-only)
+ '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
+ "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
+ "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
+ ;; Startup options. Get this early since it does change
+ ;; behavior for other options (e.g., tags).
+ (let ((startup (cdr (assq 'startup alist))))
+ (dolist (option startup)
+ (let ((entry (assoc-string option org-startup-options t)))
+ (when entry
+ (let ((var (nth 1 entry))
+ (val (nth 2 entry)))
+ (if (not (nth 3 entry)) (set (make-local-variable var) val)
+ (unless (listp (symbol-value var))
+ (set (make-local-variable var) nil))
+ (add-to-list var val)))))))
+ (setq-local org-file-tags
+ (mapcar #'org-add-prop-inherited
+ (cdr (assq 'filetags alist))))
+ (setq org-current-tag-alist
+ (append org-tag-persistent-alist
+ (let ((tags (cdr (assq 'tags alist))))
+ (if tags (org-tag-string-to-alist tags)
+ org-tag-alist))))
+ (setq org-tag-groups-alist
+ (org-tag-alist-to-groups org-current-tag-alist))
+ (unless tags-only
+ ;; File properties.
+ (setq-local org-file-properties (cdr (assq 'property alist)))
+ ;; Archive location.
+ (let ((archive (cdr (assq 'archive alist))))
+ (when archive (setq-local org-archive-location archive)))
+ ;; Category.
+ (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
+ (when cat
+ (setq-local org-category (intern cat))
+ (setq-local org-file-properties
+ (org--update-property-plist
+ "CATEGORY" cat org-file-properties))))
+ ;; Columns.
+ (let ((column (cdr (assq 'columns alist))))
+ (when column (setq-local org-columns-default-format column)))
+ ;; Constants.
+ (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
+ ;; Link abbreviations.
+ (let ((links (cdr (assq 'link alist))))
+ (when links (setq org-link-abbrev-alist-local (nreverse links))))
+ ;; Priorities.
+ (let ((priorities (cdr (assq 'priorities alist))))
+ (when priorities
+ (setq-local org-highest-priority (nth 0 priorities))
+ (setq-local org-lowest-priority (nth 1 priorities))
+ (setq-local org-default-priority (nth 2 priorities))))
+ ;; Scripts.
+ (let ((scripts (assq 'scripts alist)))
+ (when scripts
+ (setq-local org-use-sub-superscripts (cdr scripts))))
+ ;; TODO keywords.
+ (setq-local org-todo-kwd-alist nil)
+ (setq-local org-todo-key-alist nil)
+ (setq-local org-todo-key-trigger nil)
+ (setq-local org-todo-keywords-1 nil)
+ (setq-local org-done-keywords nil)
+ (setq-local org-todo-heads nil)
+ (setq-local org-todo-sets nil)
+ (setq-local org-todo-log-states nil)
+ (let ((todo-sequences
+ (or (nreverse (cdr (assq 'todo alist)))
+ (let ((d (default-value 'org-todo-keywords)))
+ (if (not (stringp (car d))) d
+ ;; XXX: Backward compatibility code.
+ (list (cons org-todo-interpretation d)))))))
+ (dolist (sequence todo-sequences)
+ (let* ((sequence (or (run-hook-with-args-until-success
+ 'org-todo-setup-filter-hook sequence)
+ sequence))
+ (sequence-type (car sequence))
+ (keywords (cdr sequence))
+ (sep (member "|" keywords))
+ names alist)
+ (dolist (k (remove "|" keywords))
+ (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
+ k)
+ (error "Invalid TODO keyword %s" k))
+ (let ((name (match-string 1 k))
+ (key (match-string 2 k))
+ (log (org-extract-log-state-settings k)))
+ (push name names)
+ (push (cons name (and key (string-to-char key))) alist)
+ (when log (push log org-todo-log-states))))
+ (let* ((names (nreverse names))
+ (done (if sep (org-remove-keyword-keys (cdr sep))
+ (last names)))
+ (head (car names))
+ (tail (list sequence-type head (car done) (org-last done))))
+ (add-to-list 'org-todo-heads head 'append)
+ (push names org-todo-sets)
+ (setq org-done-keywords (append org-done-keywords done nil))
+ (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
+ (setq org-todo-key-alist
+ (append org-todo-key-alist
+ (and alist
+ (append '((:startgroup))
+ (nreverse alist)
+ '((:endgroup))))))
+ (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
+ (setq org-todo-sets (nreverse org-todo-sets)
+ org-todo-kwd-alist (nreverse org-todo-kwd-alist)
+ org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
+ org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
+ ;; Compute the regular expressions and other local variables.
+ ;; Using `org-outline-regexp-bol' would complicate them much,
+ ;; because of the fixed white space at the end of that string.
+ (unless org-done-keywords
+ (setq org-done-keywords
+ (and org-todo-keywords-1 (last org-todo-keywords-1))))
+ (setq org-not-done-keywords
+ (org-delete-all org-done-keywords
+ (copy-sequence org-todo-keywords-1))
+ org-todo-regexp (regexp-opt org-todo-keywords-1 t)
+ org-not-done-regexp (regexp-opt org-not-done-keywords t)
+ org-not-done-heading-regexp
+ (format org-heading-keyword-regexp-format org-not-done-regexp)
+ org-todo-line-regexp
+ (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
+ org-complex-heading-regexp
+ (concat "^\\(\\*+\\)"
+ "\\(?: +" org-todo-regexp "\\)?"
+ "\\(?: +\\(\\[#.\\]\\)\\)?"
+ "\\(?: +\\(.*?\\)\\)??"
+ "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
+ "[ \t]*$")
+ org-complex-heading-regexp-format
+ (concat "^\\(\\*+\\)"
+ "\\(?: +" org-todo-regexp "\\)?"
+ "\\(?: +\\(\\[#.\\]\\)\\)?"
+ "\\(?: +"
+ ;; Stats cookies can be stuck to body.
+ "\\(?:\\[[0-9%%/]+\\] *\\)*"
+ "\\(%s\\)"
+ "\\(?: *\\[[0-9%%/]+\\]\\)*"
+ "\\)"
+ "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
+ "[ \t]*$")
+ org-todo-line-tags-regexp
+ (concat "^\\(\\*+\\)"
+ "\\(?: +" org-todo-regexp "\\)?"
+ "\\(?: +\\(.*?\\)\\)??"
+ "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
+ "[ \t]*$"))
+ (org-compute-latex-and-related-regexp)))))
+
+(defun org--setup-collect-keywords (regexp &optional files alist)
+ "Return setup keywords values as an alist.
+
+REGEXP matches a subset of setup keywords. FILES is a list of
+file names already visited. It is used to avoid circular setup
+files. ALIST, when non-nil, is the alist computed so far.
+
+Return value contains the following keys: `archive', `category',
+`columns', `constants', `filetags', `link', `priorities',
+`property', `scripts', `startup', `tags' and `todo'."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((case-fold-search t))
+ (while (re-search-forward regexp nil t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (let ((key (org-element-property :key element))
+ (value (org-element-property :value element)))
+ (cond
+ ((equal key "ARCHIVE")
+ (when (org-string-nw-p value)
+ (push (cons 'archive value) alist)))
+ ((equal key "CATEGORY") (push (cons 'category value) alist))
+ ((equal key "COLUMNS") (push (cons 'columns value) alist))
+ ((equal key "CONSTANTS")
+ (let* ((constants (assq 'constants alist))
+ (store (cdr constants)))
+ (dolist (pair (org-split-string value))
+ (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
+ pair)
+ (let* ((name (match-string 1 pair))
+ (value (match-string 2 pair))
+ (old (assoc name store)))
+ (if old (setcdr old value)
+ (push (cons name value) store)))))
+ (if constants (setcdr constants store)
+ (push (cons 'constants store) alist))))
+ ((equal key "FILETAGS")
+ (when (org-string-nw-p value)
+ (let ((old (assq 'filetags alist))
+ (new (apply #'nconc
+ (mapcar (lambda (x) (org-split-string x ":"))
+ (org-split-string value)))))
+ (if old (setcdr old (append new (cdr old)))
+ (push (cons 'filetags new) alist)))))
+ ((equal key "LINK")
+ (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
+ (let ((links (assq 'link alist))
+ (pair (cons (match-string-no-properties 1 value)
+ (match-string-no-properties 2 value))))
+ (if links (push pair (cdr links))
+ (push (list 'link pair) alist)))))
+ ((equal key "OPTIONS")
+ (when (and (org-string-nw-p value)
+ (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
+ (push (cons 'scripts (read (match-string 1 value))) alist)))
+ ((equal key "PRIORITIES")
+ (push (cons 'priorities
+ (let ((prio (org-split-string value)))
+ (if (< (length prio) 3) '(?A ?C ?B)
+ (mapcar #'string-to-char prio))))
+ alist))
+ ((equal key "PROPERTY")
+ (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
+ (let* ((property (assq 'property alist))
+ (value (org--update-property-plist
+ (match-string-no-properties 1 value)
+ (match-string-no-properties 2 value)
+ (cdr property))))
+ (if property (setcdr property value)
+ (push (cons 'property value) alist)))))
+ ((equal key "STARTUP")
+ (let ((startup (assq 'startup alist)))
+ (if startup
+ (setcdr startup
+ (append (cdr startup) (org-split-string value)))
+ (push (cons 'startup (org-split-string value)) alist))))
+ ((equal key "TAGS")
+ (let ((tag-cell (assq 'tags alist)))
+ (if tag-cell
+ (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
+ (push (cons 'tags value) alist))))
+ ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
+ (let ((todo (assq 'todo alist))
+ (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
+ (org-split-string value))))
+ (if todo (push value (cdr todo))
+ (push (list 'todo value) alist))))
+ ((equal key "SETUPFILE")
+ (unless buffer-read-only ; Do not check in Gnus messages.
+ (let ((f (and (org-string-nw-p value)
+ (expand-file-name
+ (org-unbracket-string "\"" "\"" value)))))
+ (when (and f (file-readable-p f) (not (member f files)))
+ (with-temp-buffer
+ (setq default-directory (file-name-directory f))
+ (insert-file-contents f)
+ (setq alist
+ ;; Fake Org mode to benefit from cache
+ ;; without recurring needlessly.
+ (let ((major-mode 'org-mode))
+ (org--setup-collect-keywords
+ regexp (cons f files) alist)))))))))))))))
+ alist)
+
+(defun org-tag-string-to-alist (s)
+ "Return tag alist associated to string S.
+S is a value for TAGS keyword or produced with
+`org-tag-alist-to-string'. Return value is an alist suitable for
+`org-tag-alist' or `org-tag-persistent-alist'."
+ (let ((lines (mapcar #'split-string (split-string s "\n" t)))
+ (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
+ "\\|{.+?}\\)" ; regular expression
+ "\\(?:(\\(.\\))\\)?\\'"))
+ alist group-flag)
+ (dolist (tokens lines (cdr (nreverse alist)))
+ (push '(:newline) alist)
+ (while tokens
+ (let ((token (pop tokens)))
+ (pcase token
+ ("{"
+ (push '(:startgroup) alist)
+ (when (equal (nth 1 tokens) ":") (setq group-flag t)))
+ ("}"
+ (push '(:endgroup) alist)
+ (setq group-flag nil))
+ ("["
+ (push '(:startgrouptag) alist)
+ (when (equal (nth 1 tokens) ":") (setq group-flag t)))
+ ("]"
+ (push '(:endgrouptag) alist)
+ (setq group-flag nil))
+ (":"
+ (push '(:grouptags) alist))
+ ((guard (string-match tag-re token))
+ (let ((tag (match-string 1 token))
+ (key (and (match-beginning 2)
+ (string-to-char (match-string 2 token)))))
+ ;; Push all tags in groups, no matter if they already
+ ;; appear somewhere else in the list.
+ (when (or group-flag (not (assoc tag alist)))
+ (push (cons tag key) alist))))))))))
+
+(defun org-tag-alist-to-string (alist &optional skip-key)
+ "Return tag string associated to ALIST.
+
+ALIST is an alist, as defined in `org-tag-alist' or
+`org-tag-persistent-alist', or produced with
+`org-tag-string-to-alist'.
+
+Return value is a string suitable as a value for \"TAGS\"
+keyword.
+
+When optional argument SKIP-KEY is non-nil, skip selection keys
+next to tags."
+ (mapconcat (lambda (token)
+ (pcase token
+ (`(:startgroup) "{")
+ (`(:endgroup) "}")
+ (`(:startgrouptag) "[")
+ (`(:endgrouptag) "]")
+ (`(:grouptags) ":")
+ (`(:newline) "\\n")
+ ((and
+ (guard (not skip-key))
+ `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
+ (format "%s(%c)" tag key))
+ (`(,(and tag (pred stringp)) . ,_) tag)
+ (_ (user-error "Invalid tag token: %S" token))))
+ alist
+ " "))
+
+(defun org-tag-alist-to-groups (alist)
+ "Return group alist from tag ALIST.
+ALIST is an alist, as defined in `org-tag-alist' or
+`org-tag-persistent-alist', or produced with
+`org-tag-string-to-alist'. Return value is an alist following
+the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
+a string, summarizing TAGS, as a list of strings."
+ (let (groups group-status current-group)
+ (dolist (token alist (nreverse groups))
+ (pcase token
+ (`(,(or :startgroup :startgrouptag)) (setq group-status t))
+ (`(,(or :endgroup :endgrouptag))
+ (when (eq group-status 'append)
+ (push (nreverse current-group) groups))
+ (setq group-status nil))
+ (`(:grouptags) (setq group-status 'append))
+ ((and `(,tag . ,_) (guard group-status))
+ (if (eq group-status 'append) (push tag current-group)
+ (setq current-group (list tag))))
+ (_ nil)))))
+
+(defun org-file-contents (file &optional noerror)
+ "Return the contents of FILE, as a string."
+ (if (and file (file-readable-p file))
+ (with-temp-buffer
+ (insert-file-contents file)
+ (buffer-string))
+ (funcall (if noerror 'message 'error)
+ "Cannot read file \"%s\"%s"
+ file
+ (let ((from (buffer-file-name (buffer-base-buffer))))
+ (if from (concat " (referenced in file \"" from "\")") "")))))
+
+(defun org-extract-log-state-settings (x)
+ "Extract the log state setting from a TODO keyword string.
+This will extract info from a string like \"WAIT(w@/!)\"."
+ (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
+ (let ((kw (match-string 1 x))
+ (log1 (and (match-end 3) (match-string 3 x)))
+ (log2 (and (match-end 4) (match-string 4 x))))
+ (and (or log1 log2)
+ (list kw
+ (and log1 (if (equal log1 "!") 'time 'note))
+ (and log2 (if (equal log2 "!") 'time 'note)))))))
+
+(defun org-remove-keyword-keys (list)
+ "Remove a pair of parenthesis at the end of each string in LIST."
+ (mapcar (lambda (x)
+ (if (string-match "(.*)$" x)
+ (substring x 0 (match-beginning 0))
+ x))
+ list))
+
+(defun org-assign-fast-keys (alist)
+ "Assign fast keys to a keyword-key alist.
+Respect keys that are already there."
+ (let (new e (alt ?0))
+ (while (setq e (pop alist))
+ (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
+ (cdr e)) ;; Key already assigned.
+ (push e new)
+ (let ((clist (string-to-list (downcase (car e))))
+ (used (append new alist)))
+ (when (= (car clist) ?@)
+ (pop clist))
+ (while (and clist (rassoc (car clist) used))
+ (pop clist))
+ (unless clist
+ (while (rassoc alt used)
+ (cl-incf alt)))
+ (push (cons (car e) (or (car clist) alt)) new))))
+ (nreverse new)))
+
+;;; Some variables used in various places
+
+(defvar org-window-configuration nil
+ "Used in various places to store a window configuration.")
+(defvar org-selected-window nil
+ "Used in various places to store a window configuration.")
+(defvar org-finish-function nil
+ "Function to be called when `C-c C-c' is used.
+This is for getting out of special buffers like capture.")
+(defvar org-last-state)
+
+;; Defined somewhere in this file, but used before definition.
+(defvar org-entities) ;; defined in org-entities.el
+(defvar org-struct-menu)
+(defvar org-org-menu)
+(defvar org-tbl-menu)
+
+;;;; Define the Org mode
+
+;; We use a before-change function to check if a table might need
+;; an update.
+(defvar org-table-may-need-update t
+ "Indicates that a table might need an update.
+This variable is set by `org-before-change-function'.
+`org-table-align' sets it back to nil.")
+(defun org-before-change-function (_beg _end)
+ "Every change indicates that a table might need an update."
+ (setq org-table-may-need-update t))
+(defvar org-mode-map)
+(defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
+(defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
+(defvar org-inhibit-logging nil) ; Dynamically-scoped param.
+(defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
+(defvar org-table-buffer-is-an nil)
+
+(defvar bidi-paragraph-direction)
+(defvar buffer-face-mode-face)
+
+(require 'outline)
+
+;; Other stuff we need.
+(require 'time-date)
+(unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
+(require 'easymenu)
+(autoload 'easy-menu-add "easymenu")
+(require 'overlay)
+
+;; (require 'org-macs) moved higher up in the file before it is first used
+(require 'org-entities)
+;; (require 'org-compat) moved higher up in the file before it is first used
+(require 'org-faces)
+(require 'org-list)
+(require 'org-pcomplete)
+(require 'org-src)
+(require 'org-footnote)
+(require 'org-macro)
+
+;; babel
+(require 'ob)
+
+;;;###autoload
+(define-derived-mode org-mode outline-mode "Org"
+ "Outline-based notes management and organizer, alias
+\"Carsten's outline-mode for keeping track of everything.\"
+
+Org mode develops organizational tasks around a NOTES file which
+contains information about projects as plain text. Org mode is
+implemented on top of Outline mode, which is ideal to keep the content
+of large files well structured. It supports ToDo items, deadlines and
+time stamps, which magically appear in the diary listing of the Emacs
+calendar. Tables are easily created with a built-in table editor.
+Plain text URL-like links connect to websites, emails (VM), Usenet
+messages (Gnus), BBDB entries, and any files related to the project.
+For printing and sharing of notes, an Org file (or a part of it)
+can be exported as a structured ASCII or HTML file.
+
+The following commands are available:
+
+\\{org-mode-map}"
+
+ ;; Get rid of Outline menus, they are not needed
+ ;; Need to do this here because define-derived-mode sets up
+ ;; the keymap so late. Still, it is a waste to call this each time
+ ;; we switch another buffer into Org mode.
+ (define-key org-mode-map [menu-bar headings] 'undefined)
+ (define-key org-mode-map [menu-bar hide] 'undefined)
+ (define-key org-mode-map [menu-bar show] 'undefined)
+
+ (org-load-modules-maybe)
+ (org-install-agenda-files-menu)
+ (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
+ (add-to-invisibility-spec '(org-cwidth))
+ (add-to-invisibility-spec '(org-hide-block . t))
+ (setq-local outline-regexp org-outline-regexp)
+ (setq-local outline-level 'org-outline-level)
+ (setq bidi-paragraph-direction 'left-to-right)
+ (when (and org-ellipsis
+ (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
+ (fboundp 'make-glyph-code))
+ (unless org-display-table
+ (setq org-display-table (make-display-table)))
+ (set-display-table-slot
+ org-display-table 4
+ (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
+ (if (stringp org-ellipsis) org-ellipsis "..."))))
+ (setq buffer-display-table org-display-table))
+ (org-set-regexps-and-options)
+ (org-set-font-lock-defaults)
+ (when (and org-tag-faces (not org-tags-special-faces-re))
+ ;; tag faces set outside customize.... force initialization.
+ (org-set-tag-faces 'org-tag-faces org-tag-faces))
+ ;; Calc embedded
+ (setq-local calc-embedded-open-mode "# ")
+ ;; Modify a few syntax entries
+ (modify-syntax-entry ?@ "w")
+ (modify-syntax-entry ?\" "\"")
+ (modify-syntax-entry ?\\ "_")
+ (modify-syntax-entry ?~ "_")
+ (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
+ ;; Activate before-change-function
+ (setq-local org-table-may-need-update t)
+ (add-hook 'before-change-functions 'org-before-change-function nil 'local)
+ ;; Check for running clock before killing a buffer
+ (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
+ ;; Initialize macros templates.
+ (org-macro-initialize-templates)
+ ;; Initialize radio targets.
+ (org-update-radio-target-regexp)
+ ;; Indentation.
+ (setq-local indent-line-function 'org-indent-line)
+ (setq-local indent-region-function 'org-indent-region)
+ ;; Filling and auto-filling.
+ (org-setup-filling)
+ ;; Comments.
+ (org-setup-comments-handling)
+ ;; Initialize cache.
+ (org-element-cache-reset)
+ ;; Beginning/end of defun
+ (setq-local beginning-of-defun-function 'org-backward-element)
+ (setq-local end-of-defun-function
+ (lambda ()
+ (if (not (org-at-heading-p))
+ (org-forward-element)
+ (org-forward-element)
+ (forward-char -1))))
+ ;; Next error for sparse trees
+ (setq-local next-error-function 'org-occur-next-match)
+ ;; Make sure dependence stuff works reliably, even for users who set it
+ ;; too late :-(
+ (if org-enforce-todo-dependencies
+ (add-hook 'org-blocker-hook
+ 'org-block-todo-from-children-or-siblings-or-parent)
+ (remove-hook 'org-blocker-hook
+ 'org-block-todo-from-children-or-siblings-or-parent))
+ (if org-enforce-todo-checkbox-dependencies
+ (add-hook 'org-blocker-hook
+ 'org-block-todo-from-checkboxes)
+ (remove-hook 'org-blocker-hook
+ 'org-block-todo-from-checkboxes))
+
+ ;; Align options lines
+ (setq-local
+ align-mode-rules-list
+ '((org-in-buffer-settings
+ (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
+ (modes . '(org-mode)))))
+
+ ;; Imenu
+ (setq-local imenu-create-index-function 'org-imenu-get-tree)
+
+ ;; Make isearch reveal context
+ (setq-local outline-isearch-open-invisible-function
+ (lambda (&rest _) (org-show-context 'isearch)))
+
+ ;; Setup the pcomplete hooks
+ (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
+ (setq-local pcomplete-command-name-function 'org-command-at-point)
+ (setq-local pcomplete-default-completion-function 'ignore)
+ (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
+ (setq-local pcomplete-termination-string "")
+ (setq-local buffer-face-mode-face 'org-default)
+
+ ;; If empty file that did not turn on Org mode automatically, make
+ ;; it to.
+ (when (and org-insert-mode-line-in-empty-file
+ (called-interactively-p 'any)
+ (= (point-min) (point-max)))
+ (insert "# -*- mode: org -*-\n\n"))
+ (unless org-inhibit-startup
+ (org-unmodified
+ (when org-startup-with-beamer-mode (org-beamer-mode))
+ (when org-startup-align-all-tables
+ (org-table-map-tables #'org-table-align t))
+ (when org-startup-with-inline-images (org-display-inline-images))
+ (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
+ (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
+ (when org-startup-truncated (setq truncate-lines t))
+ (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
+ (org-refresh-effort-properties)))
+ ;; Try to set `org-hide' face correctly.
+ (let ((foreground (org-find-invisible-foreground)))
+ (when foreground
+ (set-face-foreground 'org-hide foreground))))
+
+;; Update `customize-package-emacs-version-alist'
+(add-to-list 'customize-package-emacs-version-alist
+ '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
+ ("7.8.11" . "24.1") ("7.9.4" . "24.3")
+ ("8.2.6" . "24.4") ("8.2.10" . "24.5")
+ ("9.0" . "26.1")))
+
+(defvar org-mode-transpose-word-syntax-table
+ (let ((st (make-syntax-table text-mode-syntax-table)))
+ (dolist (c org-emphasis-alist st)
+ (modify-syntax-entry (string-to-char (car c)) "w p" st))))
+
+(when (fboundp 'abbrev-table-put)
+ (abbrev-table-put org-mode-abbrev-table
+ :parents (list text-mode-abbrev-table)))
+
+(defun org-find-invisible-foreground ()
+ (let ((candidates (remove
+ "unspecified-bg"
+ (nconc
+ (list (face-background 'default)
+ (face-background 'org-default))
+ (mapcar
+ (lambda (alist)
+ (when (boundp alist)
+ (cdr (assq 'background-color (symbol-value alist)))))
+ '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
+ (list (face-foreground 'org-hide))))))
+ (car (remove nil candidates))))
+
+(defun org-current-time (&optional rounding-minutes past)
+ "Current time, possibly rounded to ROUNDING-MINUTES.
+When ROUNDING-MINUTES is not an integer, fall back on the car of
+`org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
+the rounding returns a past time."
+ (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
+ (car org-time-stamp-rounding-minutes)))
+ (time (decode-time)) res)
+ (if (< r 1)
+ (current-time)
+ (setq res
+ (apply 'encode-time
+ (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
+ (nthcdr 2 time))))
+ (if (and past (< (float-time (time-subtract (current-time) res)) 0))
+ (seconds-to-time (- (float-time res) (* r 60)))
+ res))))
+
+(defun org-today ()
+ "Return today date, considering `org-extend-today-until'."
+ (time-to-days
+ (time-subtract (current-time)
+ (list 0 (* 3600 org-extend-today-until) 0))))
+
+;;;; Font-Lock stuff, including the activators
+
+(defvar org-mouse-map (make-sparse-keymap))
+(org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
+(org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
+(when org-mouse-1-follows-link
+ (org-defkey org-mouse-map [follow-link] 'mouse-face))
+(when org-tab-follows-link
+ (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
+ (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
+
+(require 'font-lock)
+
+(defconst org-non-link-chars "]\t\n\r<>")
+(defvar org-link-types-re nil
+ "Matches a link that has a url-like prefix like \"http:\"")
+(defvar org-link-re-with-space nil
+ "Matches a link with spaces, optional angular brackets around it.")
+(defvar org-link-re-with-space2 nil
+ "Matches a link with spaces, optional angular brackets around it.")
+(defvar org-link-re-with-space3 nil
+ "Matches a link with spaces, only for internal part in bracket links.")
+(defvar org-angle-link-re nil
+ "Matches link with angular brackets, spaces are allowed.")
+(defvar org-plain-link-re nil
+ "Matches plain link, without spaces.")
+(defvar org-bracket-link-regexp nil
+ "Matches a link in double brackets.")
+(defvar org-bracket-link-analytic-regexp nil
+ "Regular expression used to analyze links.
+Here is what the match groups contain after a match:
+1: http:
+2: http
+3: path
+4: [desc]
+5: desc")
+(defvar org-bracket-link-analytic-regexp++ nil
+ "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
+(defvar org-any-link-re nil
+ "Regular expression matching any link.")
+
+(defconst org-match-sexp-depth 3
+ "Number of stacked braces for sub/superscript matching.")
+
+(defun org-create-multibrace-regexp (left right n)
+ "Create a regular expression which will match a balanced sexp.
+Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
+as single character strings.
+The regexp returned will match the entire expression including the
+delimiters. It will also define a single group which contains the
+match except for the outermost delimiters. The maximum depth of
+stacked delimiters is N. Escaping delimiters is not possible."
+ (let* ((nothing (concat "[^" left right "]*?"))
+ (or "\\|")
+ (re nothing)
+ (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
+ (while (> n 1)
+ (setq n (1- n)
+ re (concat re or next)
+ next (concat "\\(?:" nothing left next right "\\)+" nothing)))
+ (concat left "\\(" re "\\)" right)))
+
+(defconst org-match-substring-regexp
+ (concat
+ "\\(\\S-\\)\\([_^]\\)\\("
+ "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
+ "\\|"
+ "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
+ "\\|"
+ "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
+ "The regular expression matching a sub- or superscript.")
+
+(defconst org-match-substring-with-braces-regexp
+ (concat
+ "\\(\\S-\\)\\([_^]\\)"
+ "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
+ "The regular expression matching a sub- or superscript, forcing braces.")
+
+(defun org-make-link-regexps ()
+ "Update the link regular expressions.
+This should be called after the variable `org-link-parameters' has changed."
+ (let ((types-re (regexp-opt (org-link-types) t)))
+ (setq org-link-types-re
+ (concat "\\`" types-re ":")
+ org-link-re-with-space
+ (concat "<?" types-re ":"
+ "\\([^" org-non-link-chars " ]"
+ "[^" org-non-link-chars "]*"
+ "[^" org-non-link-chars " ]\\)>?")
+ org-link-re-with-space2
+ (concat "<?" types-re ":"
+ "\\([^" org-non-link-chars " ]"
+ "[^\t\n\r]*"
+ "[^" org-non-link-chars " ]\\)>?")
+ org-link-re-with-space3
+ (concat "<?" types-re ":"
+ "\\([^" org-non-link-chars " ]"
+ "[^\t\n\r]*\\)")
+ org-angle-link-re
+ (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
+ types-re)
+ org-plain-link-re
+ (concat
+ "\\<" types-re ":"
+ "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
+ ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
+ org-bracket-link-regexp
+ "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
+ org-bracket-link-analytic-regexp
+ (concat
+ "\\[\\["
+ "\\(" types-re ":\\)?"
+ "\\([^]]+\\)"
+ "\\]"
+ "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
+ "\\]")
+ org-bracket-link-analytic-regexp++
+ (concat
+ "\\[\\["
+ "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
+ "\\([^]]+\\)"
+ "\\]"
+ "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
+ "\\]")
+ org-any-link-re
+ (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
+ org-angle-link-re "\\)\\|\\("
+ org-plain-link-re "\\)"))))
+
+(org-make-link-regexps)
+
+(defvar org-emph-face nil)
+
+(defun org-do-emphasis-faces (limit)
+ "Run through the buffer and emphasize strings."
+ (let (rtn a)
+ (while (and (not rtn) (re-search-forward org-emph-re limit t))
+ (let* ((border (char-after (match-beginning 3)))
+ (bre (regexp-quote (char-to-string border))))
+ (when (and (not (= border (char-after (match-beginning 4))))
+ (not (string-match-p (concat bre ".*" bre)
+ (replace-regexp-in-string
+ "\n" " "
+ (substring (match-string 2) 1 -1)))))
+ (setq rtn t)
+ (setq a (assoc (match-string 3) org-emphasis-alist))
+ (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
+ 'face
+ (nth 1 a))
+ (and (nth 2 a)
+ (org-remove-flyspell-overlays-in
+ (match-beginning 0) (match-end 0)))
+ (add-text-properties (match-beginning 2) (match-end 2)
+ '(font-lock-multiline t org-emphasis t))
+ (when org-hide-emphasis-markers
+ (add-text-properties (match-end 4) (match-beginning 5)
+ '(invisible org-link))
+ (add-text-properties (match-beginning 3) (match-end 3)
+ '(invisible org-link)))))
+ (goto-char (1+ (match-beginning 0))))
+ rtn))
+
+(defun org-emphasize (&optional char)
+ "Insert or change an emphasis, i.e. a font like bold or italic.
+If there is an active region, change that region to a new emphasis.
+If there is no region, just insert the marker characters and position
+the cursor between them.
+CHAR should be the marker character. If it is a space, it means to
+remove the emphasis of the selected region.
+If CHAR is not given (for example in an interactive call) it will be
+prompted for."
+ (interactive)
+ (let ((erc org-emphasis-regexp-components)
+ (string "") beg end move s)
+ (if (org-region-active-p)
+ (setq beg (region-beginning)
+ end (region-end)
+ string (buffer-substring beg end))
+ (setq move t))
+
+ (unless char
+ (message "Emphasis marker or tag: [%s]"
+ (mapconcat #'car org-emphasis-alist ""))
+ (setq char (read-char-exclusive)))
+ (if (equal char ?\s)
+ (setq s ""
+ move nil)
+ (unless (assoc (char-to-string char) org-emphasis-alist)
+ (user-error "No such emphasis marker: \"%c\"" char))
+ (setq s (char-to-string char)))
+ (while (and (> (length string) 1)
+ (equal (substring string 0 1) (substring string -1))
+ (assoc (substring string 0 1) org-emphasis-alist))
+ (setq string (substring string 1 -1)))
+ (setq string (concat s string s))
+ (when beg (delete-region beg end))
+ (unless (or (bolp)
+ (string-match (concat "[" (nth 0 erc) "\n]")
+ (char-to-string (char-before (point)))))
+ (insert " "))
+ (unless (or (eobp)
+ (string-match (concat "[" (nth 1 erc) "\n]")
+ (char-to-string (char-after (point)))))
+ (insert " ") (backward-char 1))
+ (insert string)
+ (and move (backward-char 1))))
+
+(defconst org-nonsticky-props
+ '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
+
+(defsubst org-rear-nonsticky-at (pos)
+ (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
+
+(defun org-activate-links (limit)
+ "Add link properties to links.
+This includes angle, plain, and bracket links."
+ (catch :exit
+ (while (re-search-forward org-any-link-re limit t)
+ (let* ((start (match-beginning 0))
+ (end (match-end 0))
+ (style (cond ((eq ?< (char-after start)) 'angle)
+ ((eq ?\[ (char-after (1+ start))) 'bracket)
+ (t 'plain))))
+ (when (and (memq style org-highlight-links)
+ ;; Do not confuse plain links with tags.
+ (not (and (eq style 'plain)
+ (let ((face (get-text-property
+ (max (1- start) (point-min)) 'face)))
+ (if (consp face) (memq 'org-tag face)
+ (eq 'org-tag face))))))
+ (let* ((link-object (save-excursion
+ (goto-char start)
+ (save-match-data (org-element-link-parser))))
+ (link (org-element-property :raw-link link-object))
+ (type (org-element-property :type link-object))
+ (path (org-element-property :path link-object))
+ (properties ;for link's visible part
+ (list
+ 'face (pcase (org-link-get-parameter type :face)
+ ((and (pred functionp) face) (funcall face path))
+ ((and (pred facep) face) face)
+ ((and (pred consp) face) face) ;anonymous
+ (_ 'org-link))
+ 'mouse-face (or (org-link-get-parameter type :mouse-face)
+ 'highlight)
+ 'keymap (or (org-link-get-parameter type :keymap)
+ org-mouse-map)
+ 'help-echo (pcase (org-link-get-parameter type :help-echo)
+ ((and (pred stringp) echo) echo)
+ ((and (pred functionp) echo) echo)
+ (_ (concat "LINK: " link)))
+ 'htmlize-link (pcase (org-link-get-parameter type
+ :htmlize-link)
+ ((and (pred functionp) f) (funcall f))
+ (_ `(:uri ,link)))
+ 'font-lock-multiline t)))
+ (org-remove-flyspell-overlays-in start end)
+ (org-rear-nonsticky-at end)
+ (if (not (eq 'bracket style))
+ (add-text-properties start end properties)
+ ;; Handle invisible parts in bracket links.
+ (remove-text-properties start end '(invisible nil))
+ (let ((hidden
+ (append `(invisible
+ ,(or (org-link-get-parameter type :display)
+ 'org-link))
+ properties))
+ (visible-start (or (match-beginning 4) (match-beginning 2)))
+ (visible-end (or (match-end 4) (match-end 2))))
+ (add-text-properties start visible-start hidden)
+ (add-text-properties visible-start visible-end properties)
+ (add-text-properties visible-end end hidden)
+ (org-rear-nonsticky-at visible-start)
+ (org-rear-nonsticky-at visible-end)))
+ (let ((f (org-link-get-parameter type :activate-func)))
+ (when (functionp f)
+ (funcall f start end path (eq style 'bracket))))
+ (throw :exit t))))) ;signal success
+ nil))
+
+(defun org-activate-code (limit)
+ (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
+ (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+ (remove-text-properties (match-beginning 0) (match-end 0)
+ '(display t invisible t intangible t))
+ t))
+
+(defcustom org-src-fontify-natively t
+ "When non-nil, fontify code in code blocks.
+See also the `org-block' face."
+ :type 'boolean
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :group 'org-appearance
+ :group 'org-babel)
+
+(defcustom org-allow-promoting-top-level-subtree nil
+ "When non-nil, allow promoting a top level subtree.
+The leading star of the top level headline will be replaced
+by a #."
+ :type 'boolean
+ :version "24.1"
+ :group 'org-appearance)
+
+(defun org-fontify-meta-lines-and-blocks (limit)
+ (condition-case nil
+ (org-fontify-meta-lines-and-blocks-1 limit)
+ (error (message "org-mode fontification error in %S at %d"
+ (current-buffer)
+ (line-number-at-pos)))))
+
+(defun org-fontify-meta-lines-and-blocks-1 (limit)
+ "Fontify #+ lines and blocks."
+ (let ((case-fold-search t))
+ (when (re-search-forward
+ "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
+ limit t)
+ (let ((beg (match-beginning 0))
+ (block-start (match-end 0))
+ (block-end nil)
+ (lang (match-string 7))
+ (beg1 (line-beginning-position 2))
+ (dc1 (downcase (match-string 2)))
+ (dc3 (downcase (match-string 3)))
+ end end1 quoting block-type)
+ (cond
+ ((and (match-end 4) (equal dc3 "+begin"))
+ ;; Truly a block
+ (setq block-type (downcase (match-string 5))
+ quoting (member block-type org-protecting-blocks))
+ (when (re-search-forward
+ (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
+ nil t) ;; on purpose, we look further than LIMIT
+ (setq end (min (point-max) (match-end 0))
+ end1 (min (point-max) (1- (match-beginning 0))))
+ (setq block-end (match-beginning 0))
+ (when quoting
+ (org-remove-flyspell-overlays-in beg1 end1)
+ (remove-text-properties beg end
+ '(display t invisible t intangible t)))
+ (add-text-properties
+ beg end '(font-lock-fontified t font-lock-multiline t))
+ (add-text-properties beg beg1 '(face org-meta-line))
+ (org-remove-flyspell-overlays-in beg beg1)
+ (add-text-properties ; For end_src
+ end1 (min (point-max) (1+ end)) '(face org-meta-line))
+ (org-remove-flyspell-overlays-in end1 end)
+ (cond
+ ((and lang (not (string= lang "")) org-src-fontify-natively)
+ (org-src-font-lock-fontify-block lang block-start block-end)
+ (add-text-properties beg1 block-end '(src-block t)))
+ (quoting
+ (add-text-properties beg1 (min (point-max) (1+ end1))
+ (list 'face
+ (list :inherit
+ (let ((face-name
+ (intern (format "org-block-%s" lang))))
+ (append (and (facep face-name) (list face-name))
+ '(org-block))))))) ; end of source block
+ ((not org-fontify-quote-and-verse-blocks))
+ ((string= block-type "quote")
+ (add-face-text-property
+ beg1 (min (point-max) (1+ end1)) 'org-quote t))
+ ((string= block-type "verse")
+ (add-face-text-property
+ beg1 (min (point-max) (1+ end1)) 'org-verse t)))
+ (add-text-properties beg beg1 '(face org-block-begin-line))
+ (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
+ '(face org-block-end-line))
+ t))
+ ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
+ (org-remove-flyspell-overlays-in
+ (match-beginning 0)
+ (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
+ (add-text-properties
+ beg (match-end 3)
+ (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
+ '(font-lock-fontified t invisible t)
+ '(font-lock-fontified t face org-document-info-keyword)))
+ (add-text-properties
+ (match-beginning 6) (min (point-max) (1+ (match-end 6)))
+ (if (string-equal dc1 "+title:")
+ '(font-lock-fontified t face org-document-title)
+ '(font-lock-fontified t face org-document-info))))
+ ((string-prefix-p "+caption" dc1)
+ (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
+ (remove-text-properties (match-beginning 0) (match-end 0)
+ '(display t invisible t intangible t))
+ ;; Handle short captions.
+ (save-excursion
+ (beginning-of-line)
+ (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
+ (add-text-properties (line-beginning-position) (match-end 1)
+ '(font-lock-fontified t face org-meta-line))
+ (add-text-properties (match-end 0) (line-end-position)
+ '(font-lock-fontified t face org-block))
+ t)
+ ((member dc3 '(" " ""))
+ (org-remove-flyspell-overlays-in beg (match-end 0))
+ (add-text-properties
+ beg (match-end 0)
+ '(font-lock-fontified t face font-lock-comment-face)))
+ (t ;; just any other in-buffer setting, but not indented
+ (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+ (remove-text-properties (match-beginning 0) (match-end 0)
+ '(display t invisible t intangible t))
+ (add-text-properties beg (match-end 0)
+ '(font-lock-fontified t face org-meta-line))
+ t))))))
+
+(defun org-fontify-drawers (limit)
+ "Fontify drawers."
+ (when (re-search-forward org-drawer-regexp limit t)
+ (add-text-properties
+ (match-beginning 0) (match-end 0)
+ '(font-lock-fontified t face org-special-keyword))
+ (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+ t))
+
+(defun org-fontify-macros (limit)
+ "Fontify macros."
+ (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
+ (add-text-properties
+ (match-beginning 0) (match-end 0)
+ '(font-lock-fontified t face org-macro))
+ (when org-hide-macro-markers
+ (add-text-properties (match-end 2) (match-beginning 2)
+ '(invisible t))
+ (add-text-properties (match-beginning 1) (match-end 1)
+ '(invisible t)))
+ (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+ t))
+
+(defun org-activate-footnote-links (limit)
+ "Add text properties for footnotes."
+ (let ((fn (org-footnote-next-reference-or-definition limit)))
+ (when fn
+ (let* ((beg (nth 1 fn))
+ (end (nth 2 fn))
+ (label (car fn))
+ (referencep (/= (line-beginning-position) beg)))
+ (when (and referencep (nth 3 fn))
+ (save-excursion
+ (goto-char beg)
+ (search-forward (or label "fn:"))
+ (org-remove-flyspell-overlays-in beg (match-end 0))))
+ (add-text-properties beg end
+ (list 'mouse-face 'highlight
+ 'keymap org-mouse-map
+ 'help-echo
+ (if referencep "Footnote reference"
+ "Footnote definition")
+ 'font-lock-fontified t
+ 'font-lock-multiline t
+ 'face 'org-footnote))))))
+
+(defun org-activate-dates (limit)
+ "Add text properties for dates."
+ (when (and (re-search-forward org-tsr-regexp-both limit t)
+ (not (equal (char-before (match-beginning 0)) 91)))
+ (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
+ (add-text-properties (match-beginning 0) (match-end 0)
+ (list 'mouse-face 'highlight
+ 'keymap org-mouse-map))
+ (org-rear-nonsticky-at (match-end 0))
+ (when org-display-custom-times
+ (if (match-end 3)
+ (org-display-custom-time (match-beginning 3) (match-end 3))
+ (org-display-custom-time (match-beginning 1) (match-end 1))))
+ t))
+
+(defvar-local org-target-link-regexp nil
+ "Regular expression matching radio targets in plain text.")
+
+(defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
+ (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
+ border border border))
+ "Regular expression matching a link target.")
+
+(defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
+ "Regular expression matching a radio target.")
+
+(defconst org-any-target-regexp
+ (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
+ "Regular expression matching any target.")
+
+(defun org-activate-target-links (limit)
+ "Add text properties for target matches."
+ (when org-target-link-regexp
+ (let ((case-fold-search t))
+ (when (re-search-forward org-target-link-regexp limit t)
+ (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
+ (add-text-properties (match-beginning 1) (match-end 1)
+ (list 'mouse-face 'highlight
+ 'keymap org-mouse-map
+ 'help-echo "Radio target link"
+ 'org-linked-text t))
+ (org-rear-nonsticky-at (match-end 1))
+ t))))
+
+(defun org-update-radio-target-regexp ()
+ "Find all radio targets in this file and update the regular expression.
+Also refresh fontification if needed."
+ (interactive)
+ (let ((old-regexp org-target-link-regexp)
+ (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
+ (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
+ (targets
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let (rtn)
+ (while (re-search-forward org-radio-target-regexp nil t)
+ ;; Make sure point is really within the object.
+ (backward-char)
+ (let ((obj (org-element-context)))
+ (when (eq (org-element-type obj) 'radio-target)
+ (cl-pushnew (org-element-property :value obj) rtn
+ :test #'equal))))
+ rtn))))
+ (setq org-target-link-regexp
+ (and targets
+ (concat before-re
+ (mapconcat
+ (lambda (x)
+ (replace-regexp-in-string
+ " +" "\\s-+" (regexp-quote x) t t))
+ targets
+ "\\|")
+ after-re)))
+ (unless (equal old-regexp org-target-link-regexp)
+ ;; Clean-up cache.
+ (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
+ ((not org-target-link-regexp) old-regexp)
+ (t
+ (concat before-re
+ (mapconcat
+ (lambda (re)
+ (substring re (length before-re)
+ (- (length after-re))))
+ (list old-regexp org-target-link-regexp)
+ "\\|")
+ after-re)))))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (org-element-cache-refresh (match-beginning 1)))))
+ ;; Re fontify buffer.
+ (when (memq 'radio org-highlight-links)
+ (org-restart-font-lock)))))
+
+(defun org-hide-wide-columns (limit)
+ (let (s e)
+ (setq s (text-property-any (point) (or limit (point-max))
+ 'org-cwidth t))
+ (when s
+ (setq e (next-single-property-change s 'org-cwidth))
+ (add-text-properties s e '(invisible org-cwidth))
+ (goto-char e)
+ t)))
+
+(defvar org-latex-and-related-regexp nil
+ "Regular expression for highlighting LaTeX, entities and sub/superscript.")
+
+(defun org-compute-latex-and-related-regexp ()
+ "Compute regular expression for LaTeX, entities and sub/superscript.
+Result depends on variable `org-highlight-latex-and-related'."
+ (setq-local
+ org-latex-and-related-regexp
+ (let* ((re-sub
+ (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
+ ((eq org-use-sub-superscripts '{})
+ (list org-match-substring-with-braces-regexp))
+ (org-use-sub-superscripts (list org-match-substring-regexp))))
+ (re-latex
+ (when (memq 'latex org-highlight-latex-and-related)
+ (let ((matchers (plist-get org-format-latex-options :matchers)))
+ (delq nil
+ (mapcar (lambda (x)
+ (and (member (car x) matchers) (nth 1 x)))
+ org-latex-regexps)))))
+ (re-entities
+ (when (memq 'entities org-highlight-latex-and-related)
+ (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
+ (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
+
+(defun org-do-latex-and-related (limit)
+ "Highlight LaTeX snippets and environments, entities and sub/superscript.
+LIMIT bounds the search for syntax to highlight. Stop at first
+highlighted object, if any. Return t if some highlighting was
+done, nil otherwise."
+ (when (org-string-nw-p org-latex-and-related-regexp)
+ (catch 'found
+ (while (re-search-forward org-latex-and-related-regexp limit t)
+ (unless
+ (cl-some
+ (lambda (f)
+ (memq f '(org-code org-verbatim underline org-special-keyword)))
+ (save-excursion
+ (goto-char (1+ (match-beginning 0)))
+ (face-at-point nil t)))
+ (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
+ '(?_ ?^))
+ 1
+ 0)))
+ (font-lock-prepend-text-property
+ (+ offset (match-beginning 0)) (match-end 0)
+ 'face 'org-latex-and-related)
+ (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
+ '(font-lock-multiline t)))
+ (throw 'found t)))
+ nil)))
+
+(defun org-restart-font-lock ()
+ "Restart `font-lock-mode', to force refontification."
+ (when (and (boundp 'font-lock-mode) font-lock-mode)
+ (font-lock-mode -1)
+ (font-lock-mode 1)))
+
+(defun org-activate-tags (limit)
+ (when (re-search-forward
+ "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
+ (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
+ (add-text-properties (match-beginning 1) (match-end 1)
+ (list 'mouse-face 'highlight
+ 'keymap org-mouse-map))
+ (org-rear-nonsticky-at (match-end 1))
+ t))
+
+(defun org-outline-level ()
+ "Compute the outline level of the heading at point.
+
+If this is called at a normal headline, the level is the number
+of stars. Use `org-reduced-level' to remove the effect of
+`org-odd-levels'. Unlike to `org-current-level', this function
+takes into consideration inlinetasks."
+ (org-with-wide-buffer
+ (end-of-line)
+ (if (re-search-backward org-outline-regexp-bol nil t)
+ (1- (- (match-end 0) (match-beginning 0)))
+ 0)))
+
+(defvar org-font-lock-keywords nil)
+
+(defsubst org-re-property (property &optional literal allow-null value)
+ "Return a regexp matching a PROPERTY line.
+
+When optional argument LITERAL is non-nil, do not quote PROPERTY.
+This is useful when PROPERTY is a regexp. When ALLOW-NULL is
+non-nil, match properties even without a value.
+
+Match group 3 is set to the value when it exists. If there is no
+value and ALLOW-NULL is non-nil, it is set to the empty string.
+
+With optional argument VALUE, match only property lines with
+that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
+unless LITERAL is non-nil."
+ (concat
+ "^\\(?4:[ \t]*\\)"
+ (format "\\(?1::\\(?2:%s\\):\\)"
+ (if literal property (regexp-quote property)))
+ (cond (value
+ (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
+ (if literal value (regexp-quote value))))
+ (allow-null
+ "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
+ (t
+ "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
+
+(defconst org-property-re
+ (org-re-property "\\S-+" 'literal t)
+ "Regular expression matching a property line.
+There are four matching groups:
+1: :PROPKEY: including the leading and trailing colon,
+2: PROPKEY without the leading and trailing colon,
+3: PROPVAL without leading or trailing spaces,
+4: the indentation of the current line,
+5: trailing whitespace.")
+
+(defvar org-font-lock-hook nil
+ "Functions to be called for special font lock stuff.")
+
+(defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
+
+(defvar org-font-lock-set-keywords-hook nil
+ "Functions that can manipulate `org-font-lock-extra-keywords'.
+This is called after `org-font-lock-extra-keywords' is defined, but before
+it is installed to be used by font lock. This can be useful if something
+needs to be inserted at a specific position in the font-lock sequence.")
+
+(defun org-font-lock-hook (limit)
+ "Run `org-font-lock-hook' within LIMIT."
+ (run-hook-with-args 'org-font-lock-hook limit))
+
+(defun org-set-font-lock-defaults ()
+ "Set font lock defaults for the current buffer."
+ (let* ((em org-fontify-emphasized-text)
+ (lk org-highlight-links)
+ (org-font-lock-extra-keywords
+ (list
+ ;; Call the hook
+ '(org-font-lock-hook)
+ ;; Headlines
+ `(,(if org-fontify-whole-heading-line
+ "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
+ "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
+ (1 (org-get-level-face 1))
+ (2 (org-get-level-face 2))
+ (3 (org-get-level-face 3)))
+ ;; Table lines
+ '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
+ (1 'org-table t))
+ ;; Table internals
+ '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
+ '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
+ '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
+ '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
+ ;; Drawers
+ '(org-fontify-drawers)
+ ;; Properties
+ (list org-property-re
+ '(1 'org-special-keyword t)
+ '(3 'org-property-value t))
+ ;; Link related fontification.
+ '(org-activate-links)
+ (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
+ (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
+ (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
+ (when (memq 'footnote lk) '(org-activate-footnote-links))
+ ;; Targets.
+ (list org-any-target-regexp '(0 'org-target t))
+ ;; Diary sexps.
+ '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
+ ;; Macro
+ '(org-fontify-macros)
+ '(org-hide-wide-columns (0 nil append))
+ ;; TODO keyword
+ (list (format org-heading-keyword-regexp-format
+ org-todo-regexp)
+ '(2 (org-get-todo-face 2) t))
+ ;; DONE
+ (if org-fontify-done-headline
+ (list (format org-heading-keyword-regexp-format
+ (concat
+ "\\(?:"
+ (mapconcat 'regexp-quote org-done-keywords "\\|")
+ "\\)"))
+ '(2 'org-headline-done t))
+ nil)
+ ;; Priorities
+ '(org-font-lock-add-priority-faces)
+ ;; Tags
+ '(org-font-lock-add-tag-faces)
+ ;; Tags groups
+ (when (and org-group-tags org-tag-groups-alist)
+ (list (concat org-outline-regexp-bol ".+\\(:"
+ (regexp-opt (mapcar 'car org-tag-groups-alist))
+ ":\\).*$")
+ '(1 'org-tag-group prepend)))
+ ;; Special keywords
+ (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
+ (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
+ (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
+ (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
+ ;; Emphasis
+ (when em '(org-do-emphasis-faces))
+ ;; Checkboxes
+ '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
+ 1 'org-checkbox prepend)
+ (when (cdr (assq 'checkbox org-list-automatic-rules))
+ '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
+ (0 (org-get-checkbox-statistics-face) t)))
+ ;; Description list items
+ '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
+ 1 'org-list-dt prepend)
+ ;; ARCHIVEd headings
+ (list (concat
+ org-outline-regexp-bol
+ "\\(.*:" org-archive-tag ":.*\\)")
+ '(1 'org-archived prepend))
+ ;; Specials
+ '(org-do-latex-and-related)
+ '(org-fontify-entities)
+ '(org-raise-scripts)
+ ;; Code
+ '(org-activate-code (1 'org-code t))
+ ;; COMMENT
+ (list (format
+ "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
+ org-todo-regexp
+ org-comment-string)
+ '(9 'org-special-keyword t))
+ ;; Blocks and meta lines
+ '(org-fontify-meta-lines-and-blocks))))
+ (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
+ (run-hooks 'org-font-lock-set-keywords-hook)
+ ;; Now set the full font-lock-keywords
+ (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
+ (setq-local font-lock-defaults
+ '(org-font-lock-keywords t nil nil backward-paragraph))
+ (kill-local-variable 'font-lock-keywords)
+ nil))
+
+(defun org-toggle-pretty-entities ()
+ "Toggle the composition display of entities as UTF8 characters."
+ (interactive)
+ (setq-local org-pretty-entities (not org-pretty-entities))
+ (org-restart-font-lock)
+ (if org-pretty-entities
+ (message "Entities are now displayed as UTF8 characters")
+ (save-restriction
+ (widen)
+ (decompose-region (point-min) (point-max))
+ (message "Entities are now displayed as plain text"))))
+
+(defvar-local org-custom-properties-overlays nil
+ "List of overlays used for custom properties.")
+
+(defun org-toggle-custom-properties-visibility ()
+ "Display or hide properties in `org-custom-properties'."
+ (interactive)
+ (if org-custom-properties-overlays
+ (progn (mapc #'delete-overlay org-custom-properties-overlays)
+ (setq org-custom-properties-overlays nil))
+ (when org-custom-properties
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
+ (while (re-search-forward regexp nil t)
+ (let ((end (cdr (save-match-data (org-get-property-block)))))
+ (when (and end (< (point) end))
+ ;; Hide first custom property in current drawer.
+ (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
+ (overlay-put o 'invisible t)
+ (overlay-put o 'org-custom-property t)
+ (push o org-custom-properties-overlays))
+ ;; Hide additional custom properties in the same drawer.
+ (while (re-search-forward regexp end t)
+ (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
+ (overlay-put o 'invisible t)
+ (overlay-put o 'org-custom-property t)
+ (push o org-custom-properties-overlays)))))
+ ;; Each entry is limited to a single property drawer.
+ (outline-next-heading)))))))
+
+(defun org-fontify-entities (limit)
+ "Find an entity to fontify."
+ (let (ee)
+ (when org-pretty-entities
+ (catch 'match
+ ;; "\_ "-family is left out on purpose. Only the first one,
+ ;; i.e., "\_ ", could be fontified anyway, and it would be
+ ;; confusing when adding a second white space character.
+ (while (re-search-forward
+ "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
+ limit t)
+ (when (and (not (org-at-comment-p))
+ (setq ee (org-entity-get (match-string 1)))
+ (= (length (nth 6 ee)) 1))
+ (let* ((end (if (equal (match-string 2) "{}")
+ (match-end 2)
+ (match-end 1))))
+ (add-text-properties
+ (match-beginning 0) end
+ (list 'font-lock-fontified t))
+ (compose-region (match-beginning 0) end
+ (nth 6 ee) nil)
+ (backward-char 1)
+ (throw 'match t))))
+ nil))))
+
+(defun org-fontify-like-in-org-mode (s &optional odd-levels)
+ "Fontify string S like in Org mode."
+ (with-temp-buffer
+ (insert s)
+ (let ((org-odd-levels-only odd-levels))
+ (org-mode)
+ (org-font-lock-ensure)
+ (buffer-string))))
+
+(defvar org-m nil)
+(defvar org-l nil)
+(defvar org-f nil)
+(defun org-get-level-face (n)
+ "Get the right face for match N in font-lock matching of headlines."
+ (setq org-l (- (match-end 2) (match-beginning 1) 1))
+ (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
+ (if org-cycle-level-faces
+ (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
+ (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
+ (cond
+ ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
+ ((eq n 2) org-f)
+ (t (unless org-level-color-stars-only org-f))))
+
+(defun org-face-from-face-or-color (context inherit face-or-color)
+ "Create a face list that inherits INHERIT, but sets the foreground color.
+When FACE-OR-COLOR is not a string, just return it."
+ (if (stringp face-or-color)
+ (list :inherit inherit
+ (cdr (assoc context org-faces-easy-properties))
+ face-or-color)
+ face-or-color))
+
+(defun org-get-todo-face (kwd)
+ "Get the right face for a TODO keyword KWD.
+If KWD is a number, get the corresponding match group."
+ (when (numberp kwd) (setq kwd (match-string kwd)))
+ (or (org-face-from-face-or-color
+ 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
+ (and (member kwd org-done-keywords) 'org-done)
+ 'org-todo))
+
+(defun org-get-priority-face (priority)
+ "Get the right face for PRIORITY.
+PRIORITY is a character."
+ (or (org-face-from-face-or-color
+ 'priority 'org-priority (cdr (assq priority org-priority-faces)))
+ 'org-priority))
+
+(defun org-get-tag-face (tag)
+ "Get the right face for TAG.
+If TAG is a number, get the corresponding match group."
+ (let ((tag (if (wholenump tag) (match-string tag) tag)))
+ (or (org-face-from-face-or-color
+ 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
+ 'org-tag)))
+
+(defun org-font-lock-add-priority-faces (limit)
+ "Add the special priority faces."
+ (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
+ (add-text-properties
+ (match-beginning 1) (match-end 1)
+ (list 'face (org-get-priority-face (string-to-char (match-string 2)))
+ 'font-lock-fontified t))))
+
+(defun org-font-lock-add-tag-faces (limit)
+ "Add the special tag faces."
+ (when (and org-tag-faces org-tags-special-faces-re)
+ (while (re-search-forward org-tags-special-faces-re limit t)
+ (add-text-properties (match-beginning 1) (match-end 1)
+ (list 'face (org-get-tag-face 1)
+ 'font-lock-fontified t))
+ (backward-char 1))))
+
+(defun org-unfontify-region (beg end &optional _maybe_loudly)
+ "Remove fontification and activation overlays from links."
+ (font-lock-default-unfontify-region beg end)
+ (let* ((buffer-undo-list t)
+ (inhibit-read-only t) (inhibit-point-motion-hooks t)
+ (inhibit-modification-hooks t)
+ deactivate-mark buffer-file-name buffer-file-truename)
+ (decompose-region beg end)
+ (remove-text-properties beg end
+ '(mouse-face t keymap t org-linked-text t
+ invisible t intangible t
+ org-emphasis t))
+ (org-remove-font-lock-display-properties beg end)))
+
+(defconst org-script-display '(((raise -0.3) (height 0.7))
+ ((raise 0.3) (height 0.7))
+ ((raise -0.5))
+ ((raise 0.5)))
+ "Display properties for showing superscripts and subscripts.")
+
+(defun org-remove-font-lock-display-properties (beg end)
+ "Remove specific display properties that have been added by font lock.
+The will remove the raise properties that are used to show superscripts
+and subscripts."
+ (let (next prop)
+ (while (< beg end)
+ (setq next (next-single-property-change beg 'display nil end)
+ prop (get-text-property beg 'display))
+ (when (member prop org-script-display)
+ (put-text-property beg next 'display nil))
+ (setq beg next))))
+
+(defun org-raise-scripts (limit)
+ "Add raise properties to sub/superscripts."
+ (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
+ (re-search-forward
+ (if (eq org-use-sub-superscripts t)
+ org-match-substring-regexp
+ org-match-substring-with-braces-regexp)
+ limit t))
+ (let* ((pos (point)) table-p comment-p
+ (mpos (match-beginning 3))
+ (emph-p (get-text-property mpos 'org-emphasis))
+ (link-p (get-text-property mpos 'mouse-face))
+ (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
+ (goto-char (point-at-bol))
+ (setq table-p (looking-at-p org-table-dataline-regexp)
+ comment-p (looking-at-p "^[ \t]*#[ +]"))
+ (goto-char pos)
+ ;; Handle a_b^c
+ (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
+ (unless (or comment-p emph-p link-p keyw-p)
+ (put-text-property (match-beginning 3) (match-end 0)
+ 'display
+ (if (equal (char-after (match-beginning 2)) ?^)
+ (nth (if table-p 3 1) org-script-display)
+ (nth (if table-p 2 0) org-script-display)))
+ (add-text-properties (match-beginning 2) (match-end 2)
+ (list 'invisible t
+ 'org-dwidth t 'org-dwidth-n 1))
+ (if (and (eq (char-after (match-beginning 3)) ?{)
+ (eq (char-before (match-end 3)) ?}))
+ (progn
+ (add-text-properties
+ (match-beginning 3) (1+ (match-beginning 3))
+ (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
+ (add-text-properties
+ (1- (match-end 3)) (match-end 3)
+ (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
+ t)))
+
+;;;; Visibility cycling, including org-goto and indirect buffer
+
+;;; Cycling
+
+(defvar-local org-cycle-global-status nil)
+(put 'org-cycle-global-status 'org-state t)
+(defvar-local org-cycle-subtree-status nil)
+(put 'org-cycle-subtree-status 'org-state t)
+
+(defvar org-inlinetask-min-level)
+
+(defun org-unlogged-message (&rest args)
+ "Display a message, but avoid logging it in the *Messages* buffer."
+ (let ((message-log-max nil))
+ (apply 'message args)))
+
+;;;###autoload
+(defun org-cycle (&optional arg)
+ "TAB-action and visibility cycling for Org mode.
+
+This is the command invoked in Org mode by the `TAB' key. Its main
+purpose is outline visibility cycling, but it also invokes other actions
+in special contexts.
+
+When this function is called with a `\\[universal-argument]' prefix, rotate \
+the entire
+buffer through 3 states (global cycling)
+ 1. OVERVIEW: Show only top-level headlines.
+ 2. CONTENTS: Show all headlines of all levels, but no body text.
+ 3. SHOW ALL: Show everything.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
+switch to the startup visibility,
+determined by the variable `org-startup-folded', and by any VISIBILITY
+properties in the buffer.
+
+With a `\\[universal-argument] \\[universal-argument] \
+\\[universal-argument]' prefix argument, show the entire buffer, including
+any drawers.
+
+When inside a table, re-align the table and move to the next field.
+
+When point is at the beginning of a headline, rotate the subtree started
+by this line through 3 different states (local cycling)
+ 1. FOLDED: Only the main headline is shown.
+ 2. CHILDREN: The main headline and the direct children are shown.
+ From this state, you can move to one of the children
+ and zoom in further.
+ 3. SUBTREE: Show the entire subtree, including body text.
+If there is no subtree, switch directly from CHILDREN to FOLDED.
+
+When point is at the beginning of an empty headline and the variable
+`org-cycle-level-after-item/entry-creation' is set, cycle the level
+of the headline by demoting and promoting it to likely levels. This
+speeds up creation document structure by pressing `TAB' once or several
+times right after creating a new headline.
+
+When there is a numeric prefix, go up to a heading with level ARG, do
+a `show-subtree' and return to the previous cursor position. If ARG
+is negative, go up that many levels.
+
+When point is not at the beginning of a headline, execute the global
+binding for `TAB', which is re-indenting the line. See the option
+`org-cycle-emulate-tab' for details.
+
+As a special case, if point is at the beginning of the buffer and there is
+no headline in line 1, this function will act as if called with prefix arg
+\(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
+prefix arg, but only
+if the variable `org-cycle-global-at-bob' is t."
+ (interactive "P")
+ (org-load-modules-maybe)
+ (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
+ (and org-cycle-level-after-item/entry-creation
+ (or (org-cycle-level)
+ (org-cycle-item-indentation))))
+ (let* ((limit-level
+ (or org-cycle-max-level
+ (and (boundp 'org-inlinetask-min-level)
+ org-inlinetask-min-level
+ (1- org-inlinetask-min-level))))
+ (nstars (and limit-level
+ (if org-odd-levels-only
+ (and limit-level (1- (* limit-level 2)))
+ limit-level)))
+ (org-outline-regexp
+ (if (not (derived-mode-p 'org-mode))
+ outline-regexp
+ (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
+ (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
+ (not (looking-at org-outline-regexp))))
+ (org-cycle-hook
+ (if bob-special
+ (delq 'org-optimize-window-after-visibility-change
+ (copy-sequence org-cycle-hook))
+ org-cycle-hook))
+ (pos (point)))
+
+ (cond
+
+ ((equal arg '(16))
+ (setq last-command 'dummy)
+ (org-set-startup-visibility)
+ (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
+
+ ((equal arg '(64))
+ (outline-show-all)
+ (org-unlogged-message "Entire buffer visible, including drawers"))
+
+ ((equal arg '(4)) (org-cycle-internal-global))
+
+ ;; Try hiding block at point.
+ ((org-hide-block-toggle-maybe))
+
+ ;; Try cdlatex TAB completion
+ ((org-try-cdlatex-tab))
+
+ ;; Table: enter it or move to the next field.
+ ((org-at-table-p 'any)
+ (if (org-at-table.el-p)
+ (message "%s" (substitute-command-keys "\\<org-mode-map>\
+Use `\\[org-edit-special]' to edit table.el tables"))
+ (if arg (org-table-edit-field t)
+ (org-table-justify-field-maybe)
+ (call-interactively 'org-table-next-field))))
+
+ ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
+
+ ;; Global cycling: delegate to `org-cycle-internal-global'.
+ (bob-special (org-cycle-internal-global))
+
+ ;; Drawers: delegate to `org-flag-drawer'.
+ ((save-excursion
+ (beginning-of-line 1)
+ (looking-at org-drawer-regexp))
+ (org-flag-drawer ; toggle block visibility
+ (not (get-char-property (match-end 0) 'invisible))))
+
+ ;; Show-subtree, ARG levels up from here.
+ ((integerp arg)
+ (save-excursion
+ (org-back-to-heading)
+ (outline-up-heading (if (< arg 0) (- arg)
+ (- (funcall outline-level) arg)))
+ (org-show-subtree)))
+
+ ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
+ ((and (featurep 'org-inlinetask)
+ (org-inlinetask-at-task-p)
+ (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
+ (org-inlinetask-toggle-visibility))
+
+ ;; At an item/headline: delegate to `org-cycle-internal-local'.
+ ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
+ (save-excursion (move-beginning-of-line 1)
+ (looking-at org-outline-regexp)))
+ (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
+ (org-cycle-internal-local))
+
+ ;; From there: TAB emulation and template completion.
+ (buffer-read-only (org-back-to-heading))
+
+ ((run-hook-with-args-until-success
+ 'org-tab-after-check-for-cycling-hook))
+
+ ((org-try-structure-completion))
+
+ ((run-hook-with-args-until-success
+ 'org-tab-before-tab-emulation-hook))
+
+ ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
+ (or (not (bolp))
+ (not (looking-at org-outline-regexp))))
+ (call-interactively (global-key-binding "\t")))
+
+ ((if (and (memq org-cycle-emulate-tab '(white whitestart))
+ (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
+ (or (and (eq org-cycle-emulate-tab 'white)
+ (= (match-end 0) (point-at-eol)))
+ (and (eq org-cycle-emulate-tab 'whitestart)
+ (>= (match-end 0) pos))))
+ t
+ (eq org-cycle-emulate-tab t))
+ (call-interactively (global-key-binding "\t")))
+
+ (t (save-excursion
+ (org-back-to-heading)
+ (org-cycle)))))))
+
+(defun org-cycle-internal-global ()
+ "Do the global cycling action."
+ ;; Hack to avoid display of messages for .org attachments in Gnus
+ (let ((ga (string-match "\\*fontification" (buffer-name))))
+ (cond
+ ((and (eq last-command this-command)
+ (eq org-cycle-global-status 'overview))
+ ;; We just created the overview - now do table of contents
+ ;; This can be slow in very large buffers, so indicate action
+ (run-hook-with-args 'org-pre-cycle-hook 'contents)
+ (unless ga (org-unlogged-message "CONTENTS..."))
+ (org-content)
+ (unless ga (org-unlogged-message "CONTENTS...done"))
+ (setq org-cycle-global-status 'contents)
+ (run-hook-with-args 'org-cycle-hook 'contents))
+
+ ((and (eq last-command this-command)
+ (eq org-cycle-global-status 'contents))
+ ;; We just showed the table of contents - now show everything
+ (run-hook-with-args 'org-pre-cycle-hook 'all)
+ (outline-show-all)
+ (unless ga (org-unlogged-message "SHOW ALL"))
+ (setq org-cycle-global-status 'all)
+ (run-hook-with-args 'org-cycle-hook 'all))
+
+ (t
+ ;; Default action: go to overview
+ (run-hook-with-args 'org-pre-cycle-hook 'overview)
+ (org-overview)
+ (unless ga (org-unlogged-message "OVERVIEW"))
+ (setq org-cycle-global-status 'overview)
+ (run-hook-with-args 'org-cycle-hook 'overview)))))
+
+(defvar org-called-with-limited-levels nil
+ "Non-nil when `org-with-limited-levels' is currently active.")
+
+(defun org-invisible-p (&optional pos)
+ "Non-nil if the character after POS is invisible.
+If POS is nil, use `point' instead."
+ (get-char-property (or pos (point)) 'invisible))
+
+(defun org-cycle-internal-local ()
+ "Do the local cycling action."
+ (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
+ ;; First, determine end of headline (EOH), end of subtree or item
+ ;; (EOS), and if item or heading has children (HAS-CHILDREN).
+ (save-excursion
+ (if (org-at-item-p)
+ (progn
+ (beginning-of-line)
+ (setq struct (org-list-struct))
+ (setq eoh (point-at-eol))
+ (setq eos (org-list-get-item-end-before-blank (point) struct))
+ (setq has-children (org-list-has-child-p (point) struct)))
+ (org-back-to-heading)
+ (setq eoh (save-excursion (outline-end-of-heading) (point)))
+ (setq eos (save-excursion (org-end-of-subtree t t)
+ (when (bolp) (backward-char)) (point)))
+ (setq has-children
+ (or (save-excursion
+ (let ((level (funcall outline-level)))
+ (outline-next-heading)
+ (and (org-at-heading-p t)
+ (> (funcall outline-level) level))))
+ (save-excursion
+ (org-list-search-forward (org-item-beginning-re) eos t)))))
+ ;; Determine end invisible part of buffer (EOL)
+ (beginning-of-line 2)
+ (while (and (not (eobp)) ;This is like `next-line'.
+ (get-char-property (1- (point)) 'invisible))
+ (goto-char (next-single-char-property-change (point) 'invisible))
+ (and (eolp) (beginning-of-line 2)))
+ (setq eol (point)))
+ ;; Find out what to do next and set `this-command'
+ (cond
+ ((= eos eoh)
+ ;; Nothing is hidden behind this heading
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-pre-cycle-hook 'empty))
+ (org-unlogged-message "EMPTY ENTRY")
+ (setq org-cycle-subtree-status nil)
+ (save-excursion
+ (goto-char eos)
+ (outline-next-heading)
+ (when (org-invisible-p) (org-flag-heading nil))))
+ ((and (or (>= eol eos)
+ (not (string-match "\\S-" (buffer-substring eol eos))))
+ (or has-children
+ (not (setq children-skipped
+ org-cycle-skip-children-state-if-no-children))))
+ ;; Entire subtree is hidden in one line: children view
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-pre-cycle-hook 'children))
+ (if (org-at-item-p)
+ (org-list-set-item-visibility (point-at-bol) struct 'children)
+ (org-show-entry)
+ (org-with-limited-levels (org-show-children))
+ ;; FIXME: This slows down the func way too much.
+ ;; How keep drawers hidden in subtree anyway?
+ ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
+ ;; (org-cycle-hide-drawers 'subtree))
+
+ ;; Fold every list in subtree to top-level items.
+ (when (eq org-cycle-include-plain-lists 'integrate)
+ (save-excursion
+ (org-back-to-heading)
+ (while (org-list-search-forward (org-item-beginning-re) eos t)
+ (beginning-of-line 1)
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (end (org-list-get-bottom-point struct)))
+ (dolist (e (org-list-get-all-items (point) struct prevs))
+ (org-list-set-item-visibility e struct 'folded))
+ (goto-char (if (< end eos) end eos)))))))
+ (org-unlogged-message "CHILDREN")
+ (save-excursion
+ (goto-char eos)
+ (outline-next-heading)
+ (when (org-invisible-p) (org-flag-heading nil)))
+ (setq org-cycle-subtree-status 'children)
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-cycle-hook 'children)))
+ ((or children-skipped
+ (and (eq last-command this-command)
+ (eq org-cycle-subtree-status 'children)))
+ ;; We just showed the children, or no children are there,
+ ;; now show everything.
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-pre-cycle-hook 'subtree))
+ (outline-flag-region eoh eos nil)
+ (org-unlogged-message
+ (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
+ (setq org-cycle-subtree-status 'subtree)
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-cycle-hook 'subtree)))
+ (t
+ ;; Default action: hide the subtree.
+ (run-hook-with-args 'org-pre-cycle-hook 'folded)
+ (outline-flag-region eoh eos t)
+ (org-unlogged-message "FOLDED")
+ (setq org-cycle-subtree-status 'folded)
+ (unless (org-before-first-heading-p)
+ (run-hook-with-args 'org-cycle-hook 'folded))))))
+
+;;;###autoload
+(defun org-global-cycle (&optional arg)
+ "Cycle the global visibility. For details see `org-cycle'.
+With `\\[universal-argument]' prefix ARG, switch to startup visibility.
+With a numeric prefix, show all headlines up to that level."
+ (interactive "P")
+ (let ((org-cycle-include-plain-lists
+ (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
+ (cond
+ ((integerp arg)
+ (outline-show-all)
+ (outline-hide-sublevels arg)
+ (setq org-cycle-global-status 'contents))
+ ((equal arg '(4))
+ (org-set-startup-visibility)
+ (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
+ (t
+ (org-cycle '(4))))))
+
+(defun org-set-startup-visibility ()
+ "Set the visibility required by startup options and properties."
+ (cond
+ ((eq org-startup-folded t)
+ (org-overview))
+ ((eq org-startup-folded 'content)
+ (org-content))
+ ((or (eq org-startup-folded 'showeverything)
+ (eq org-startup-folded nil))
+ (outline-show-all)))
+ (unless (eq org-startup-folded 'showeverything)
+ (when org-hide-block-startup (org-hide-block-all))
+ (org-set-visibility-according-to-property 'no-cleanup)
+ (org-cycle-hide-archived-subtrees 'all)
+ (org-cycle-hide-drawers 'all)
+ (org-cycle-show-empty-lines t)))
+
+(defun org-set-visibility-according-to-property (&optional no-cleanup)
+ "Switch subtree visibilities according to :VISIBILITY: property."
+ (interactive)
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
+ (if (not (org-at-property-p)) (outline-next-heading)
+ (let ((state (match-string 3)))
+ (save-excursion
+ (org-back-to-heading t)
+ (outline-hide-subtree)
+ (org-reveal)
+ (cond
+ ((equal state "folded")
+ (outline-hide-subtree))
+ ((equal state "children")
+ (org-show-hidden-entry)
+ (org-show-children))
+ ((equal state "content")
+ (save-excursion
+ (save-restriction
+ (org-narrow-to-subtree)
+ (org-content))))
+ ((member state '("all" "showall"))
+ (outline-show-subtree)))))))
+ (unless no-cleanup
+ (org-cycle-hide-archived-subtrees 'all)
+ (org-cycle-hide-drawers 'all)
+ (org-cycle-show-empty-lines 'all))))
+
+;; This function uses outline-regexp instead of the more fundamental
+;; org-outline-regexp so that org-cycle-global works outside of Org
+;; buffers, where outline-regexp is needed.
+(defun org-overview ()
+ "Switch to overview mode, showing only top-level headlines.
+This shows all headlines with a level equal or greater than the level
+of the first headline in the buffer. This is important, because if the
+first headline is not level one, then (hide-sublevels 1) gives confusing
+results."
+ (interactive)
+ (save-excursion
+ (let ((level
+ (save-excursion
+ (goto-char (point-min))
+ (when (re-search-forward (concat "^" outline-regexp) nil t)
+ (goto-char (match-beginning 0))
+ (funcall outline-level)))))
+ (and level (outline-hide-sublevels level)))))
+
+(defun org-content (&optional arg)
+ "Show all headlines in the buffer, like a table of contents.
+With numerical argument N, show content up to level N."
+ (interactive "P")
+ (org-overview)
+ (save-excursion
+ ;; Visit all headings and show their offspring
+ (and (integerp arg) (org-overview))
+ (goto-char (point-max))
+ (catch 'exit
+ (while (and (progn (condition-case nil
+ (outline-previous-visible-heading 1)
+ (error (goto-char (point-min))))
+ t)
+ (looking-at org-outline-regexp))
+ (if (integerp arg)
+ (org-show-children (1- arg))
+ (outline-show-branches))
+ (when (bobp) (throw 'exit nil))))))
+
+(defun org-optimize-window-after-visibility-change (state)
+ "Adjust the window after a change in outline visibility.
+This function is the default value of the hook `org-cycle-hook'."
+ (when (get-buffer-window (current-buffer))
+ (cond
+ ((eq state 'content) nil)
+ ((eq state 'all) nil)
+ ((eq state 'folded) nil)
+ ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
+ ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
+
+(defun org-remove-empty-overlays-at (pos)
+ "Remove outline overlays that do not contain non-white stuff."
+ (dolist (o (overlays-at pos))
+ (and (eq 'outline (overlay-get o 'invisible))
+ (not (string-match "\\S-" (buffer-substring (overlay-start o)
+ (overlay-end o))))
+ (delete-overlay o))))
+
+(defun org-clean-visibility-after-subtree-move ()
+ "Fix visibility issues after moving a subtree."
+ ;; First, find a reasonable region to look at:
+ ;; Start two siblings above, end three below
+ (let* ((beg (save-excursion
+ (and (org-get-last-sibling)
+ (org-get-last-sibling))
+ (point)))
+ (end (save-excursion
+ (and (org-get-next-sibling)
+ (org-get-next-sibling)
+ (org-get-next-sibling))
+ (if (org-at-heading-p)
+ (point-at-eol)
+ (point))))
+ (level (looking-at "\\*+"))
+ (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
+ (save-excursion
+ (save-restriction
+ (narrow-to-region beg end)
+ (when re
+ ;; Properly fold already folded siblings
+ (goto-char (point-min))
+ (while (re-search-forward re nil t)
+ (when (and (not (org-invisible-p))
+ (save-excursion
+ (goto-char (point-at-eol)) (org-invisible-p)))
+ (outline-hide-entry))))
+ (org-cycle-show-empty-lines 'overview)
+ (org-cycle-hide-drawers 'overview)))))
+
+(defun org-cycle-show-empty-lines (state)
+ "Show empty lines above all visible headlines.
+The region to be covered depends on STATE when called through
+`org-cycle-hook'. Lisp program can use t for STATE to get the
+entire buffer covered. Note that an empty line is only shown if there
+are at least `org-cycle-separator-lines' empty lines before the headline."
+ (when (/= org-cycle-separator-lines 0)
+ (save-excursion
+ (let* ((n (abs org-cycle-separator-lines))
+ (re (cond
+ ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
+ ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
+ (t (let ((ns (number-to-string (- n 2))))
+ (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
+ "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
+ beg end)
+ (cond
+ ((memq state '(overview contents t))
+ (setq beg (point-min) end (point-max)))
+ ((memq state '(children folded))
+ (setq beg (point)
+ end (progn (org-end-of-subtree t t)
+ (line-beginning-position 2)))))
+ (when beg
+ (goto-char beg)
+ (while (re-search-forward re end t)
+ (unless (get-char-property (match-end 1) 'invisible)
+ (let ((e (match-end 1))
+ (b (if (>= org-cycle-separator-lines 0)
+ (match-beginning 1)
+ (save-excursion
+ (goto-char (match-beginning 0))
+ (skip-chars-backward " \t\n")
+ (line-end-position)))))
+ (outline-flag-region b e nil))))))))
+ ;; Never hide empty lines at the end of the file.
+ (save-excursion
+ (goto-char (point-max))
+ (outline-previous-heading)
+ (outline-end-of-heading)
+ (when (and (looking-at "[ \t\n]+")
+ (= (match-end 0) (point-max)))
+ (outline-flag-region (point) (match-end 0) nil))))
+
+(defun org-show-empty-lines-in-parent ()
+ "Move to the parent and re-show empty lines before visible headlines."
+ (save-excursion
+ (let ((context (if (org-up-heading-safe) 'children 'overview)))
+ (org-cycle-show-empty-lines context))))
+
+(defun org-files-list ()
+ "Return `org-agenda-files' list, plus all open Org files.
+This is useful for operations that need to scan all of a user's
+open and agenda-wise Org files."
+ (let ((files (mapcar 'expand-file-name (org-agenda-files))))
+ (dolist (buf (buffer-list))
+ (with-current-buffer buf
+ (when (and (derived-mode-p 'org-mode) (buffer-file-name))
+ (cl-pushnew (expand-file-name (buffer-file-name)) files))))
+ files))
+
+(defsubst org-entry-beginning-position ()
+ "Return the beginning position of the current entry."
+ (save-excursion (org-back-to-heading t) (point)))
+
+(defsubst org-entry-end-position ()
+ "Return the end position of the current entry."
+ (save-excursion (outline-next-heading) (point)))
+
+(defun org-cycle-hide-drawers (state &optional exceptions)
+ "Re-hide all drawers after a visibility state change.
+When non-nil, optional argument EXCEPTIONS is a list of strings
+specifying which drawers should not be hidden."
+ (when (and (derived-mode-p 'org-mode)
+ (not (memq state '(overview folded contents))))
+ (save-excursion
+ (let* ((globalp (memq state '(contents all)))
+ (beg (if globalp (point-min) (point)))
+ (end (if globalp (point-max)
+ (if (eq state 'children)
+ (save-excursion (outline-next-heading) (point))
+ (org-end-of-subtree t)))))
+ (goto-char beg)
+ (while (re-search-forward org-drawer-regexp (max end (point)) t)
+ (unless (member-ignore-case (match-string 1) exceptions)
+ (let ((drawer (org-element-at-point)))
+ (when (memq (org-element-type drawer) '(drawer property-drawer))
+ (org-flag-drawer t drawer)
+ ;; Make sure to skip drawer entirely or we might flag
+ ;; it another time when matching its ending line with
+ ;; `org-drawer-regexp'.
+ (goto-char (org-element-property :end drawer))))))))))
+
+(defun org-flag-drawer (flag &optional element)
+ "When FLAG is non-nil, hide the drawer we are at.
+Otherwise make it visible. When optional argument ELEMENT is
+a parsed drawer, as returned by `org-element-at-point', hide or
+show that drawer instead."
+ (let ((drawer (or element
+ (and (save-excursion
+ (beginning-of-line)
+ (looking-at-p org-drawer-regexp))
+ (org-element-at-point)))))
+ (when (memq (org-element-type drawer) '(drawer property-drawer))
+ (let ((post (org-element-property :post-affiliated drawer)))
+ (save-excursion
+ (outline-flag-region
+ (progn (goto-char post) (line-end-position))
+ (progn (goto-char (org-element-property :end drawer))
+ (skip-chars-backward " \r\t\n")
+ (line-end-position))
+ flag))
+ ;; When the drawer is hidden away, make sure point lies in
+ ;; a visible part of the buffer.
+ (when (and flag (> (line-beginning-position) post))
+ (goto-char post))))))
+
+(defun org-subtree-end-visible-p ()
+ "Is the end of the current subtree visible?"
+ (pos-visible-in-window-p
+ (save-excursion (org-end-of-subtree t) (point))))
+
+(defun org-first-headline-recenter ()
+ "Move cursor to the first headline and recenter the headline."
+ (let ((window (get-buffer-window)))
+ (when window
+ (goto-char (point-min))
+ (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
+ (set-window-start window (line-beginning-position))))))
+
+;;; Saving and restoring visibility
+
+(defun org-outline-overlay-data (&optional use-markers)
+ "Return a list of the locations of all outline overlays.
+These are overlays with the `invisible' property value `outline'.
+The return value is a list of cons cells, with start and stop
+positions for each overlay.
+If USE-MARKERS is set, return the positions as markers."
+ (let (beg end)
+ (org-with-wide-buffer
+ (delq nil
+ (mapcar (lambda (o)
+ (when (eq (overlay-get o 'invisible) 'outline)
+ (setq beg (overlay-start o)
+ end (overlay-end o))
+ (and beg end (> end beg)
+ (if use-markers
+ (cons (copy-marker beg)
+ (copy-marker end t))
+ (cons beg end)))))
+ (overlays-in (point-min) (point-max)))))))
+
+(defun org-set-outline-overlay-data (data)
+ "Create visibility overlays for all positions in DATA.
+DATA should have been made by `org-outline-overlay-data'."
+ (org-with-wide-buffer
+ (outline-show-all)
+ (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
+
+;;; Folding of blocks
+
+(defvar-local org-hide-block-overlays nil
+ "Overlays hiding blocks.")
+
+(defun org-block-map (function &optional start end)
+ "Call FUNCTION at the head of all source blocks in the current buffer.
+Optional arguments START and END can be used to limit the range."
+ (let ((start (or start (point-min)))
+ (end (or end (point-max))))
+ (save-excursion
+ (goto-char start)
+ (while (and (< (point) end) (re-search-forward org-block-regexp end t))
+ (save-excursion
+ (save-match-data
+ (goto-char (match-beginning 0))
+ (funcall function)))))))
+
+(defun org-hide-block-toggle-all ()
+ "Toggle the visibility of all blocks in the current buffer."
+ (org-block-map 'org-hide-block-toggle))
+
+(defun org-hide-block-all ()
+ "Fold all blocks in the current buffer."
+ (interactive)
+ (org-show-block-all)
+ (org-block-map 'org-hide-block-toggle-maybe))
+
+(defun org-show-block-all ()
+ "Unfold all blocks in the current buffer."
+ (interactive)
+ (mapc #'delete-overlay org-hide-block-overlays)
+ (setq org-hide-block-overlays nil))
+
+(defun org-hide-block-toggle-maybe ()
+ "Toggle visibility of block at point.
+Unlike to `org-hide-block-toggle', this function does not throw
+an error. Return a non-nil value when toggling is successful."
+ (interactive)
+ (ignore-errors (org-hide-block-toggle)))
+
+(defun org-hide-block-toggle (&optional force)
+ "Toggle the visibility of the current block.
+When optional argument FORCE is `off', make block visible. If it
+is non-nil, hide it unconditionally. Throw an error when not at
+a block. Return a non-nil value when toggling is successful."
+ (interactive)
+ (let ((element (org-element-at-point)))
+ (unless (memq (org-element-type element)
+ '(center-block comment-block dynamic-block example-block
+ export-block quote-block special-block
+ src-block verse-block))
+ (user-error "Not at a block"))
+ (let* ((start (save-excursion
+ (goto-char (org-element-property :post-affiliated element))
+ (line-end-position)))
+ (end (save-excursion
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-end-position)))
+ (overlays (overlays-at start)))
+ (cond
+ ;; Do nothing when not before or at the block opening line or
+ ;; at the block closing line.
+ ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
+ ((and (not (eq force 'off))
+ (not (memq t (mapcar
+ (lambda (o)
+ (eq (overlay-get o 'invisible) 'org-hide-block))
+ overlays))))
+ (let ((ov (make-overlay start end)))
+ (overlay-put ov 'invisible 'org-hide-block)
+ ;; Make the block accessible to `isearch'.
+ (overlay-put
+ ov 'isearch-open-invisible
+ (lambda (ov)
+ (when (memq ov org-hide-block-overlays)
+ (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
+ (when (eq (overlay-get ov 'invisible) 'org-hide-block)
+ (delete-overlay ov))))
+ (push ov org-hide-block-overlays)
+ ;; When the block is hidden away, make sure point is left in
+ ;; a visible part of the buffer.
+ (when (> (line-beginning-position) start)
+ (goto-char start)
+ (beginning-of-line))
+ ;; Signal successful toggling.
+ t))
+ ((or (not force) (eq force 'off))
+ (dolist (ov overlays t)
+ (when (memq ov org-hide-block-overlays)
+ (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
+ (when (eq (overlay-get ov 'invisible) 'org-hide-block)
+ (delete-overlay ov))))))))
+
+;; Remove overlays when changing major mode
+(add-hook 'org-mode-hook
+ (lambda () (add-hook 'change-major-mode-hook
+ 'org-show-block-all 'append 'local)))
+
+;;; Org-goto
+
+(defvar org-goto-window-configuration nil)
+(defvar org-goto-marker nil)
+(defvar org-goto-map)
+(defun org-goto-map ()
+ "Set the keymap `org-goto'."
+ (setq org-goto-map
+ (let ((map (make-sparse-keymap)))
+ (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
+ mouse-drag-region universal-argument org-occur)))
+ (dolist (cmd cmds)
+ (substitute-key-definition cmd cmd map global-map)))
+ (suppress-keymap map)
+ (org-defkey map "\C-m" 'org-goto-ret)
+ (org-defkey map [(return)] 'org-goto-ret)
+ (org-defkey map [(left)] 'org-goto-left)
+ (org-defkey map [(right)] 'org-goto-right)
+ (org-defkey map [(control ?g)] 'org-goto-quit)
+ (org-defkey map "\C-i" 'org-cycle)
+ (org-defkey map [(tab)] 'org-cycle)
+ (org-defkey map [(down)] 'outline-next-visible-heading)
+ (org-defkey map [(up)] 'outline-previous-visible-heading)
+ (if org-goto-auto-isearch
+ (if (fboundp 'define-key-after)
+ (define-key-after map [t] 'org-goto-local-auto-isearch)
+ nil)
+ (org-defkey map "q" 'org-goto-quit)
+ (org-defkey map "n" 'outline-next-visible-heading)
+ (org-defkey map "p" 'outline-previous-visible-heading)
+ (org-defkey map "f" 'outline-forward-same-level)
+ (org-defkey map "b" 'outline-backward-same-level)
+ (org-defkey map "u" 'outline-up-heading))
+ (org-defkey map "/" 'org-occur)
+ (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
+ (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
+ (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
+ (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
+ (org-defkey map "\C-c\C-u" 'outline-up-heading)
+ map)))
+
+(defconst org-goto-help
+ "Browse buffer copy, to find location or copy text.%s
+RET=jump to location C-g=quit and return to previous location
+\[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
+
+(defvar org-goto-start-pos) ; dynamically scoped parameter
+
+(defun org-goto (&optional alternative-interface)
+ "Look up a different location in the current file, keeping current visibility.
+
+When you want look-up or go to a different location in a
+document, the fastest way is often to fold the entire buffer and
+then dive into the tree. This method has the disadvantage, that
+the previous location will be folded, which may not be what you
+want.
+
+This command works around this by showing a copy of the current
+buffer in an indirect buffer, in overview mode. You can dive
+into the tree in that copy, use org-occur and incremental search
+to find a location. When pressing RET or `Q', the command
+returns to the original buffer in which the visibility is still
+unchanged. After RET it will also jump to the location selected
+in the indirect buffer and expose the headline hierarchy above.
+
+With a prefix argument, use the alternative interface: e.g., if
+`org-goto-interface' is `outline' use `outline-path-completion'."
+ (interactive "P")
+ (org-goto-map)
+ (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
+ (org-refile-use-outline-path t)
+ (org-refile-target-verify-function nil)
+ (interface
+ (if (not alternative-interface)
+ org-goto-interface
+ (if (eq org-goto-interface 'outline)
+ 'outline-path-completion
+ 'outline)))
+ (org-goto-start-pos (point))
+ (selected-point
+ (if (eq interface 'outline)
+ (car (org-get-location (current-buffer) org-goto-help))
+ (let ((pa (org-refile-get-location "Goto")))
+ (org-refile-check-position pa)
+ (nth 3 pa)))))
+ (if selected-point
+ (progn
+ (org-mark-ring-push org-goto-start-pos)
+ (goto-char selected-point)
+ (when (or (org-invisible-p) (org-invisible-p2))
+ (org-show-context 'org-goto)))
+ (message "Quit"))))
+
+(defvar org-goto-selected-point nil) ; dynamically scoped parameter
+(defvar org-goto-exit-command nil) ; dynamically scoped parameter
+(defvar org-goto-local-auto-isearch-map) ; defined below
+
+(defun org-get-location (_buf help)
+ "Let the user select a location in current buffer.
+This function uses a recursive edit. It returns the selected position
+or nil."
+ (org-no-popups
+ (let ((isearch-mode-map org-goto-local-auto-isearch-map)
+ (isearch-hide-immediately nil)
+ (isearch-search-fun-function
+ (lambda () 'org-goto-local-search-headings))
+ (org-goto-selected-point org-goto-exit-command))
+ (save-excursion
+ (save-window-excursion
+ (delete-other-windows)
+ (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
+ (pop-to-buffer-same-window
+ (condition-case nil
+ (make-indirect-buffer (current-buffer) "*org-goto*")
+ (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
+ (with-output-to-temp-buffer "*Org Help*"
+ (princ (format help (if org-goto-auto-isearch
+ " Just type for auto-isearch."
+ " n/p/f/b/u to navigate, q to quit."))))
+ (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
+ (setq buffer-read-only nil)
+ (let ((org-startup-truncated t)
+ (org-startup-folded nil)
+ (org-startup-align-all-tables nil))
+ (org-mode)
+ (org-overview))
+ (setq buffer-read-only t)
+ (if (and (boundp 'org-goto-start-pos)
+ (integer-or-marker-p org-goto-start-pos))
+ (progn (goto-char org-goto-start-pos)
+ (when (org-invisible-p)
+ (org-show-set-visibility 'lineage)))
+ (goto-char (point-min)))
+ (let (org-special-ctrl-a/e) (org-beginning-of-line))
+ (message "Select location and press RET")
+ (use-local-map org-goto-map)
+ (recursive-edit)))
+ (kill-buffer "*org-goto*")
+ (cons org-goto-selected-point org-goto-exit-command))))
+
+(defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
+(set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
+;; `isearch-other-control-char' was removed in Emacs 24.4.
+(if (fboundp 'isearch-other-control-char)
+ (progn
+ (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
+ (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
+ (define-key org-goto-local-auto-isearch-map "\C-i" nil)
+ (define-key org-goto-local-auto-isearch-map "\C-m" nil)
+ (define-key org-goto-local-auto-isearch-map [return] nil))
+
+(defun org-goto-local-search-headings (string bound noerror)
+ "Search and make sure that any matches are in headlines."
+ (catch 'return
+ (while (if isearch-forward
+ (search-forward string bound noerror)
+ (search-backward string bound noerror))
+ (when (save-match-data
+ (and (save-excursion
+ (beginning-of-line)
+ (looking-at org-complex-heading-regexp))
+ (or (not (match-beginning 5))
+ (< (point) (match-beginning 5)))))
+ (throw 'return (point))))))
+
+(defun org-goto-local-auto-isearch ()
+ "Start isearch."
+ (interactive)
+ (goto-char (point-min))
+ (let ((keys (this-command-keys)))
+ (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
+ (isearch-mode t)
+ (isearch-process-search-char (string-to-char keys)))))
+
+(defun org-goto-ret (&optional _arg)
+ "Finish `org-goto' by going to the new location."
+ (interactive "P")
+ (setq org-goto-selected-point (point))
+ (setq org-goto-exit-command 'return)
+ (throw 'exit nil))
+
+(defun org-goto-left ()
+ "Finish `org-goto' by going to the new location."
+ (interactive)
+ (if (org-at-heading-p)
+ (progn
+ (beginning-of-line 1)
+ (setq org-goto-selected-point (point)
+ org-goto-exit-command 'left)
+ (throw 'exit nil))
+ (user-error "Not on a heading")))
+
+(defun org-goto-right ()
+ "Finish `org-goto' by going to the new location."
+ (interactive)
+ (if (org-at-heading-p)
+ (progn
+ (setq org-goto-selected-point (point)
+ org-goto-exit-command 'right)
+ (throw 'exit nil))
+ (user-error "Not on a heading")))
+
+(defun org-goto-quit ()
+ "Finish `org-goto' without cursor motion."
+ (interactive)
+ (setq org-goto-selected-point nil)
+ (setq org-goto-exit-command 'quit)
+ (throw 'exit nil))
+
+;;; Indirect buffer display of subtrees
+
+(defvar org-indirect-dedicated-frame nil
+ "This is the frame being used for indirect tree display.")
+(defvar org-last-indirect-buffer nil)
+
+(defun org-tree-to-indirect-buffer (&optional arg)
+ "Create indirect buffer and narrow it to current subtree.
+
+With a numerical prefix ARG, go up to this level and then take that tree.
+If ARG is negative, go up that many levels.
+
+If `org-indirect-buffer-display' is not `new-frame', the command removes the
+indirect buffer previously made with this command, to avoid proliferation of
+indirect buffers. However, when you call the command with a \
+`\\[universal-argument]' prefix, or
+when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
+so that you can work with several indirect buffers at the same time. If
+`org-indirect-buffer-display' is `dedicated-frame', the \
+`\\[universal-argument]' prefix also
+requests that a new frame be made for the new buffer, so that the dedicated
+frame is not changed."
+ (interactive "P")
+ (let ((cbuf (current-buffer))
+ (cwin (selected-window))
+ (pos (point))
+ beg end level heading ibuf)
+ (save-excursion
+ (org-back-to-heading t)
+ (when (numberp arg)
+ (setq level (org-outline-level))
+ (when (< arg 0) (setq arg (+ level arg)))
+ (while (> (setq level (org-outline-level)) arg)
+ (org-up-heading-safe)))
+ (setq beg (point)
+ heading (org-get-heading 'no-tags))
+ (org-end-of-subtree t t)
+ (when (org-at-heading-p) (backward-char 1))
+ (setq end (point)))
+ (when (and (buffer-live-p org-last-indirect-buffer)
+ (not (eq org-indirect-buffer-display 'new-frame))
+ (not arg))
+ (kill-buffer org-last-indirect-buffer))
+ (setq ibuf (org-get-indirect-buffer cbuf heading)
+ org-last-indirect-buffer ibuf)
+ (cond
+ ((or (eq org-indirect-buffer-display 'new-frame)
+ (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
+ (select-frame (make-frame))
+ (delete-other-windows)
+ (pop-to-buffer-same-window ibuf)
+ (org-set-frame-title heading))
+ ((eq org-indirect-buffer-display 'dedicated-frame)
+ (raise-frame
+ (select-frame (or (and org-indirect-dedicated-frame
+ (frame-live-p org-indirect-dedicated-frame)
+ org-indirect-dedicated-frame)
+ (setq org-indirect-dedicated-frame (make-frame)))))
+ (delete-other-windows)
+ (pop-to-buffer-same-window ibuf)
+ (org-set-frame-title (concat "Indirect: " heading)))
+ ((eq org-indirect-buffer-display 'current-window)
+ (pop-to-buffer-same-window ibuf))
+ ((eq org-indirect-buffer-display 'other-window)
+ (pop-to-buffer ibuf))
+ (t (error "Invalid value")))
+ (narrow-to-region beg end)
+ (outline-show-all)
+ (goto-char pos)
+ (run-hook-with-args 'org-cycle-hook 'all)
+ (and (window-live-p cwin) (select-window cwin))))
+
+(defun org-get-indirect-buffer (&optional buffer heading)
+ (setq buffer (or buffer (current-buffer)))
+ (let ((n 1) (base (buffer-name buffer)) bname)
+ (while (buffer-live-p
+ (get-buffer
+ (setq bname
+ (concat base "-"
+ (if heading (concat heading "-" (number-to-string n))
+ (number-to-string n))))))
+ (setq n (1+ n)))
+ (condition-case nil
+ (make-indirect-buffer buffer bname 'clone)
+ (error (make-indirect-buffer buffer bname)))))
+
+(defun org-set-frame-title (title)
+ "Set the title of the current frame to the string TITLE."
+ (modify-frame-parameters (selected-frame) (list (cons 'name title))))
+
+;;;; Structure editing
+
+;;; Inserting headlines
+
+(defun org--line-empty-p (n)
+ "Is the Nth next line empty?
+
+Counts the current line as N = 1 and the previous line as N = 0;
+see `beginning-of-line'."
+ (save-excursion
+ (and (not (bobp))
+ (or (beginning-of-line n) t)
+ (save-match-data
+ (looking-at "[ \t]*$")))))
+
+(defun org-previous-line-empty-p ()
+ "Is the previous line a blank line?
+When NEXT is non-nil, check the next line instead."
+ (org--line-empty-p 0))
+
+(defun org-next-line-empty-p ()
+ "Is the previous line a blank line?
+When NEXT is non-nil, check the next line instead."
+ (org--line-empty-p 2))
+
+(defun org-insert-heading (&optional arg invisible-ok top)
+ "Insert a new heading or an item with the same depth at point.
+
+If point is at the beginning of a heading or a list item, insert
+a new heading or a new item above the current one. When at the
+beginning of a regular line of text, turn it into a heading.
+
+If point is in the middle of a line, split it and create a new
+headline/item with the text in the current line after point (see
+`org-M-RET-may-split-line' on how to modify this behavior). As
+a special case, on a headline, splitting can only happen on the
+title itself. E.g., this excludes breaking stars or tags.
+
+With a `\\[universal-argument]' prefix, set \
+`org-insert-heading-respect-content' to
+a non-nil value for the duration of the command. This forces the
+insertion of a heading after the current subtree, independently
+on the location of point.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix, \
+insert the heading at the end of the tree
+above the current heading. For example, if point is within a
+2nd-level heading, then it will insert a 2nd-level heading at
+the end of the 1st-level parent subtree.
+
+When INVISIBLE-OK is set, stop at invisible headlines when going
+back. This is important for non-interactive uses of the
+command.
+
+When optional argument TOP is non-nil, insert a level 1 heading,
+unconditionally."
+ (interactive "P")
+ (let ((itemp (and (not top) (org-in-item-p)))
+ (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
+ (respect-content (or org-insert-heading-respect-content
+ (equal arg '(4))))
+ (initial-content ""))
+
+ (cond
+
+ ((or (= (buffer-size) 0)
+ (and (not (save-excursion
+ (and (ignore-errors (org-back-to-heading invisible-ok))
+ (org-at-heading-p))))
+ (or arg (not itemp))))
+ ;; At beginning of buffer or so high up that only a heading
+ ;; makes sense.
+ (cond ((and (bolp) (not respect-content)) (insert "* "))
+ ((not respect-content)
+ (unless may-split (end-of-line))
+ (insert "\n* "))
+ ((re-search-forward org-outline-regexp-bol nil t)
+ (beginning-of-line)
+ (insert "* \n")
+ (backward-char))
+ (t (goto-char (point-max))
+ (insert "\n* ")))
+ (run-hooks 'org-insert-heading-hook))
+
+ ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
+
+ (t
+ ;; Maybe move at the end of the subtree
+ (when (equal arg '(16))
+ (org-up-heading-safe)
+ (org-end-of-subtree t))
+ ;; Insert a heading
+ (save-restriction
+ (widen)
+ (let* ((level nil)
+ (on-heading (org-at-heading-p))
+ (empty-line-p (if on-heading
+ (org-previous-line-empty-p)
+ ;; We will decide later
+ nil))
+ ;; Get a level string to fall back on.
+ (fix-level
+ (if (org-before-first-heading-p) "*"
+ (save-excursion
+ (org-back-to-heading t)
+ (when (org-previous-line-empty-p) (setq empty-line-p t))
+ (looking-at org-outline-regexp)
+ (make-string (1- (length (match-string 0))) ?*))))
+ (stars
+ (save-excursion
+ (condition-case nil
+ (if top "* "
+ (org-back-to-heading invisible-ok)
+ (when (and (not on-heading)
+ (featurep 'org-inlinetask)
+ (integerp org-inlinetask-min-level)
+ (>= (length (match-string 0))
+ org-inlinetask-min-level))
+ ;; Find a heading level before the inline
+ ;; task.
+ (while (and (setq level (org-up-heading-safe))
+ (>= level org-inlinetask-min-level)))
+ (if (org-at-heading-p)
+ (org-back-to-heading invisible-ok)
+ (error "This should not happen")))
+ (unless (and (save-excursion
+ (save-match-data
+ (org-backward-heading-same-level
+ 1 invisible-ok))
+ (= (point) (match-beginning 0)))
+ (not (org-next-line-empty-p)))
+ (setq empty-line-p (or empty-line-p
+ (org-previous-line-empty-p))))
+ (match-string 0))
+ (error (or fix-level "* ")))))
+ (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
+ (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
+
+ ;; If we insert after content, move there and clean up
+ ;; whitespace.
+ (when respect-content
+ (if (not (org-before-first-heading-p))
+ (org-end-of-subtree nil t)
+ (re-search-forward org-outline-regexp-bol)
+ (beginning-of-line 0))
+ (skip-chars-backward " \r\t\n")
+ (and (not (looking-back "^\\*+" (line-beginning-position)))
+ (looking-at "[ \t]+") (replace-match ""))
+ (unless (eobp) (forward-char 1))
+ (when (looking-at "^\\*")
+ (unless (bobp) (backward-char 1))
+ (insert "\n")))
+
+ ;; If we are splitting, grab the text that should be moved
+ ;; to the new headline.
+ (when may-split
+ (if (org-at-heading-p)
+ ;; This is a heading: split intelligently (keeping
+ ;; tags).
+ (let ((pos (point)))
+ (beginning-of-line)
+ (let ((case-fold-search nil))
+ (unless (looking-at org-complex-heading-regexp)
+ (error "This should not happen")))
+ (when (and (match-beginning 4)
+ (> pos (match-beginning 4))
+ (< pos (match-end 4)))
+ (setq initial-content (buffer-substring pos (match-end 4)))
+ (goto-char pos)
+ (delete-region (point) (match-end 4))
+ (if (looking-at "[ \t]*$")
+ (replace-match "")
+ (insert (make-string (length initial-content) ?\s)))
+ (setq initial-content (org-trim initial-content)))
+ (goto-char pos))
+ ;; A normal line.
+ (setq initial-content
+ (org-trim
+ (delete-and-extract-region (point) (line-end-position))))))
+
+ ;; If we are at the beginning of the line, insert before it.
+ ;; Otherwise, after it.
+ (cond
+ ((and (bolp) (looking-at "[ \t]*$")))
+ ((bolp) (save-excursion (insert "\n")))
+ (t (end-of-line)
+ (insert "\n")))
+
+ ;; Insert the new heading
+ (insert stars)
+ (just-one-space)
+ (insert initial-content)
+ (unless (and blank (org-previous-line-empty-p))
+ (org-N-empty-lines-before-current (if blank 1 0)))
+ ;; Adjust visibility, which may be messed up if we removed
+ ;; blank lines while previous entry was hidden.
+ (let ((bol (line-beginning-position)))
+ (dolist (o (overlays-at (1- bol)))
+ (when (and (eq (overlay-get o 'invisible) 'outline)
+ (eq (overlay-end o) bol))
+ (move-overlay o (overlay-start o) (1- bol)))))
+ (run-hooks 'org-insert-heading-hook)))))))
+
+(defun org-N-empty-lines-before-current (N)
+ "Make the number of empty lines before current exactly N.
+So this will delete or add empty lines."
+ (save-excursion
+ (beginning-of-line)
+ (let ((p (point)))
+ (skip-chars-backward " \r\t\n")
+ (unless (bolp) (forward-line))
+ (delete-region (point) p))
+ (when (> N 0) (insert (make-string N ?\n)))))
+
+(defun org-get-heading (&optional no-tags no-todo)
+ "Return the heading of the current entry, without the stars.
+When NO-TAGS is non-nil, don't include tags.
+When NO-TODO is non-nil, don't include TODO keywords."
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((case-fold-search nil))
+ (cond
+ ((and no-tags no-todo)
+ (looking-at org-complex-heading-regexp)
+ ;; Return value has to be a string, but match group 4 is
+ ;; optional.
+ (or (match-string 4) ""))
+ (no-tags
+ (looking-at (concat org-outline-regexp
+ "\\(.*?\\)"
+ "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
+ (match-string 1))
+ (no-todo
+ (looking-at org-todo-line-regexp)
+ (match-string 3))
+ (t (looking-at org-heading-regexp)
+ (match-string 2))))))
+
+(defvar orgstruct-mode) ; defined below
+
+(defun org-heading-components ()
+ "Return the components of the current heading.
+This is a list with the following elements:
+- the level as an integer
+- the reduced level, different if `org-odd-levels-only' is set.
+- the TODO keyword, or nil
+- the priority character, like ?A, or nil if no priority is given
+- the headline text itself, or the tags string if no headline text
+- the tags string, or nil."
+ (save-excursion
+ (org-back-to-heading t)
+ (when (let (case-fold-search)
+ (looking-at
+ (if orgstruct-mode
+ org-heading-regexp
+ org-complex-heading-regexp)))
+ (if orgstruct-mode
+ (list (length (match-string 1))
+ (org-reduced-level (length (match-string 1)))
+ nil
+ nil
+ (match-string 2)
+ nil)
+ (list (length (match-string 1))
+ (org-reduced-level (length (match-string 1)))
+ (match-string-no-properties 2)
+ (and (match-end 3) (aref (match-string 3) 2))
+ (match-string-no-properties 4)
+ (match-string-no-properties 5))))))
+
+(defun org-get-entry ()
+ "Get the entry text, after heading, entire subtree."
+ (save-excursion
+ (org-back-to-heading t)
+ (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
+
+(defun org-edit-headline (&optional heading)
+ "Edit the current headline.
+Set it to HEADING when provided."
+ (interactive)
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (let ((case-fold-search nil))
+ (when (looking-at org-complex-heading-regexp)
+ (let* ((old (match-string-no-properties 4))
+ (new (save-match-data
+ (org-trim (or heading (read-string "Edit: " old))))))
+ (unless (equal old new)
+ (if old (replace-match new t t nil 4)
+ (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
+ (insert " " new))
+ (org-set-tags nil t)
+ (when (looking-at "[ \t]*$") (replace-match ""))))))))
+
+(defun org-insert-heading-after-current ()
+ "Insert a new heading with same level as current, after current subtree."
+ (interactive)
+ (org-back-to-heading)
+ (org-insert-heading)
+ (org-move-subtree-down)
+ (end-of-line 1))
+
+(defun org-insert-heading-respect-content (&optional invisible-ok)
+ "Insert heading with `org-insert-heading-respect-content' set to t."
+ (interactive)
+ (org-insert-heading '(4) invisible-ok))
+
+(defun org-insert-todo-heading-respect-content (&optional force-state)
+ "Insert TODO heading with `org-insert-heading-respect-content' set to t."
+ (interactive)
+ (org-insert-todo-heading force-state '(4)))
+
+(defun org-insert-todo-heading (arg &optional force-heading)
+ "Insert a new heading with the same level and TODO state as current heading.
+
+If the heading has no TODO state, or if the state is DONE, use
+the first state (TODO by default). Also with one prefix arg,
+force first state. With two prefix args, force inserting at the
+end of the parent subtree.
+
+When called at a plain list item, insert a new item with an
+unchecked check box."
+ (interactive "P")
+ (when (or force-heading (not (org-insert-item 'checkbox)))
+ (org-insert-heading (or (and (equal arg '(16)) '(16))
+ force-heading))
+ (save-excursion
+ (org-back-to-heading)
+ (outline-previous-heading)
+ (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
+ (let* ((new-mark-x
+ (if (or (equal arg '(4))
+ (not (match-beginning 2))
+ (member (match-string 2) org-done-keywords))
+ (car org-todo-keywords-1)
+ (match-string 2)))
+ (new-mark
+ (or
+ (run-hook-with-args-until-success
+ 'org-todo-get-default-hook new-mark-x nil)
+ new-mark-x)))
+ (beginning-of-line 1)
+ (and (looking-at org-outline-regexp) (goto-char (match-end 0))
+ (if org-treat-insert-todo-heading-as-state-change
+ (org-todo new-mark)
+ (insert new-mark " "))))
+ (when org-provide-todo-statistics
+ (org-update-parent-todo-statistics))))
+
+(defun org-insert-subheading (arg)
+ "Insert a new subheading and demote it.
+Works for outline headings and for plain lists alike."
+ (interactive "P")
+ (org-insert-heading arg)
+ (cond
+ ((org-at-heading-p) (org-do-demote))
+ ((org-at-item-p) (org-indent-item))))
+
+(defun org-insert-todo-subheading (arg)
+ "Insert a new subheading with TODO keyword or checkbox and demote it.
+Works for outline headings and for plain lists alike."
+ (interactive "P")
+ (org-insert-todo-heading arg)
+ (cond
+ ((org-at-heading-p) (org-do-demote))
+ ((org-at-item-p) (org-indent-item))))
+
+;;; Promotion and Demotion
+
+(defvar org-after-demote-entry-hook nil
+ "Hook run after an entry has been demoted.
+The cursor will be at the beginning of the entry.
+When a subtree is being demoted, the hook will be called for each node.")
+
+(defvar org-after-promote-entry-hook nil
+ "Hook run after an entry has been promoted.
+The cursor will be at the beginning of the entry.
+When a subtree is being promoted, the hook will be called for each node.")
+
+(defun org-promote-subtree ()
+ "Promote the entire subtree.
+See also `org-promote'."
+ (interactive)
+ (save-excursion
+ (org-with-limited-levels (org-map-tree 'org-promote)))
+ (org-fix-position-after-promote))
+
+(defun org-demote-subtree ()
+ "Demote the entire subtree.
+See `org-demote' and `org-promote'."
+ (interactive)
+ (save-excursion
+ (org-with-limited-levels (org-map-tree 'org-demote)))
+ (org-fix-position-after-promote))
+
+(defun org-do-promote ()
+ "Promote the current heading higher up the tree.
+If the region is active in `transient-mark-mode', promote all
+headings in the region."
+ (interactive)
+ (save-excursion
+ (if (org-region-active-p)
+ (org-map-region 'org-promote (region-beginning) (region-end))
+ (org-promote)))
+ (org-fix-position-after-promote))
+
+(defun org-do-demote ()
+ "Demote the current heading lower down the tree.
+If the region is active in `transient-mark-mode', demote all
+headings in the region."
+ (interactive)
+ (save-excursion
+ (if (org-region-active-p)
+ (org-map-region 'org-demote (region-beginning) (region-end))
+ (org-demote)))
+ (org-fix-position-after-promote))
+
+(defun org-fix-position-after-promote ()
+ "Fix cursor position and indentation after demoting/promoting."
+ (let ((pos (point)))
+ (when (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
+ (or (eq pos (match-end 1)) (eq pos (match-end 2))))
+ (cond ((eobp) (insert " "))
+ ((eolp) (insert " "))
+ ((equal (char-after) ?\s) (forward-char 1))))))
+
+(defun org-current-level ()
+ "Return the level of the current entry, or nil if before the first headline.
+The level is the number of stars at the beginning of the
+headline. Use `org-reduced-level' to remove the effect of
+`org-odd-levels'. Unlike to `org-outline-level', this function
+ignores inlinetasks."
+ (let ((level (org-with-limited-levels (org-outline-level))))
+ (and (> level 0) level)))
+
+(defun org-get-previous-line-level ()
+ "Return the outline depth of the last headline before the current line.
+Returns 0 for the first headline in the buffer, and nil if before the
+first headline."
+ (and (org-current-level)
+ (or (and (/= (line-beginning-position) (point-min))
+ (save-excursion (beginning-of-line 0) (org-current-level)))
+ 0)))
+
+(defun org-reduced-level (l)
+ "Compute the effective level of a heading.
+This takes into account the setting of `org-odd-levels-only'."
+ (cond
+ ((zerop l) 0)
+ (org-odd-levels-only (1+ (floor (/ l 2))))
+ (t l)))
+
+(defun org-level-increment ()
+ "Return the number of stars that will be added or removed at a
+time to headlines when structure editing, based on the value of
+`org-odd-levels-only'."
+ (if org-odd-levels-only 2 1))
+
+(defun org-get-valid-level (level &optional change)
+ "Rectify a level change under the influence of `org-odd-levels-only'
+LEVEL is a current level, CHANGE is by how much the level should be
+modified. Even if CHANGE is nil, LEVEL may be returned modified because
+even level numbers will become the next higher odd number."
+ (if org-odd-levels-only
+ (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
+ ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
+ ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
+ (max 1 (+ level (or change 0)))))
+
+(defun org-promote ()
+ "Promote the current heading higher up the tree."
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (let* ((after-change-functions (remq 'flyspell-after-change-function
+ after-change-functions))
+ (level (save-match-data (funcall outline-level)))
+ (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
+ (diff (abs (- level (length up-head) -1))))
+ (cond
+ ((and (= level 1) org-allow-promoting-top-level-subtree)
+ (replace-match "# " nil t))
+ ((= level 1)
+ (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
+ (t (replace-match up-head nil t)))
+ (unless (= level 1)
+ (when org-auto-align-tags (org-set-tags nil 'ignore-column))
+ (when org-adapt-indentation (org-fixup-indentation (- diff))))
+ (run-hooks 'org-after-promote-entry-hook))))
+
+(defun org-demote ()
+ "Demote the current heading lower down the tree."
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (let* ((after-change-functions (remq 'flyspell-after-change-function
+ after-change-functions))
+ (level (save-match-data (funcall outline-level)))
+ (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
+ (diff (abs (- level (length down-head) -1))))
+ (replace-match down-head nil t)
+ (when org-auto-align-tags (org-set-tags nil 'ignore-column))
+ (when org-adapt-indentation (org-fixup-indentation diff))
+ (run-hooks 'org-after-demote-entry-hook))))
+
+(defun org-cycle-level ()
+ "Cycle the level of an empty headline through possible states.
+This goes first to child, then to parent, level, then up the hierarchy.
+After top level, it switches back to sibling level."
+ (interactive)
+ (let ((org-adapt-indentation nil))
+ (when (org-point-at-end-of-empty-headline)
+ (setq this-command 'org-cycle-level) ; Only needed for caching
+ (let ((cur-level (org-current-level))
+ (prev-level (org-get-previous-line-level)))
+ (cond
+ ;; If first headline in file, promote to top-level.
+ ((= prev-level 0)
+ (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
+ do (org-do-promote)))
+ ;; If same level as prev, demote one.
+ ((= prev-level cur-level)
+ (org-do-demote))
+ ;; If parent is top-level, promote to top level if not already.
+ ((= prev-level 1)
+ (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
+ do (org-do-promote)))
+ ;; If top-level, return to prev-level.
+ ((= cur-level 1)
+ (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
+ do (org-do-demote)))
+ ;; If less than prev-level, promote one.
+ ((< cur-level prev-level)
+ (org-do-promote))
+ ;; If deeper than prev-level, promote until higher than
+ ;; prev-level.
+ ((> cur-level prev-level)
+ (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
+ do (org-do-promote))))
+ t))))
+
+(defun org-map-tree (fun)
+ "Call FUN for every heading underneath the current one."
+ (org-back-to-heading t)
+ (let ((level (funcall outline-level)))
+ (save-excursion
+ (funcall fun)
+ (while (and (progn
+ (outline-next-heading)
+ (> (funcall outline-level) level))
+ (not (eobp)))
+ (funcall fun)))))
+
+(defun org-map-region (fun beg end)
+ "Call FUN for every heading between BEG and END."
+ (let ((org-ignore-region t))
+ (save-excursion
+ (setq end (copy-marker end))
+ (goto-char beg)
+ (when (and (re-search-forward org-outline-regexp-bol nil t)
+ (< (point) end))
+ (funcall fun))
+ (while (and (progn
+ (outline-next-heading)
+ (< (point) end))
+ (not (eobp)))
+ (funcall fun)))))
+
+(defun org-fixup-indentation (diff)
+ "Change the indentation in the current entry by DIFF.
+
+DIFF is an integer. Indentation is done according to the
+following rules:
+
+ - Planning information and property drawers are always indented
+ according to the new level of the headline;
+
+ - Footnote definitions and their contents are ignored;
+
+ - Inlinetasks' boundaries are not shifted;
+
+ - Empty lines are ignored;
+
+ - Other lines' indentation are shifted by DIFF columns, unless
+ it would introduce a structural change in the document, in
+ which case no shifting is done at all.
+
+Assume point is at a heading or an inlinetask beginning."
+ (org-with-wide-buffer
+ (narrow-to-region (line-beginning-position)
+ (save-excursion
+ (if (org-with-limited-levels (org-at-heading-p))
+ (org-with-limited-levels (outline-next-heading))
+ (org-inlinetask-goto-end))
+ (point)))
+ (forward-line)
+ ;; Indent properly planning info and property drawer.
+ (when (looking-at-p org-planning-line-re)
+ (org-indent-line)
+ (forward-line))
+ (when (looking-at org-property-drawer-re)
+ (goto-char (match-end 0))
+ (forward-line)
+ (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
+ (catch 'no-shift
+ (when (zerop diff) (throw 'no-shift nil))
+ ;; If DIFF is negative, first check if a shift is possible at all
+ ;; (e.g., it doesn't break structure). This can only happen if
+ ;; some contents are not properly indented.
+ (let ((case-fold-search t))
+ (when (< diff 0)
+ (let ((diff (- diff))
+ (forbidden-re (concat org-outline-regexp
+ "\\|"
+ (substring org-footnote-definition-re 1))))
+ (save-excursion
+ (while (not (eobp))
+ (cond
+ ((looking-at-p "[ \t]*$") (forward-line))
+ ((and (looking-at-p org-footnote-definition-re)
+ (let ((e (org-element-at-point)))
+ (and (eq (org-element-type e) 'footnote-definition)
+ (goto-char (org-element-property :end e))))))
+ ((looking-at-p org-outline-regexp) (forward-line))
+ ;; Give up if shifting would move before column 0 or
+ ;; if it would introduce a headline or a footnote
+ ;; definition.
+ (t
+ (skip-chars-forward " \t")
+ (let ((ind (current-column)))
+ (when (or (< ind diff)
+ (and (= ind diff) (looking-at-p forbidden-re)))
+ (throw 'no-shift nil)))
+ ;; Ignore contents of example blocks and source
+ ;; blocks if their indentation is meant to be
+ ;; preserved. Jump to block's closing line.
+ (beginning-of-line)
+ (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
+ (let ((e (org-element-at-point)))
+ (and (memq (org-element-type e)
+ '(example-block src-block))
+ (or org-src-preserve-indentation
+ (org-element-property :preserve-indent e))
+ (goto-char (org-element-property :end e))
+ (progn (skip-chars-backward " \r\t\n")
+ (beginning-of-line)
+ t))))
+ (forward-line))))))))
+ ;; Shift lines but footnote definitions, inlinetasks boundaries
+ ;; by DIFF. Also skip contents of source or example blocks
+ ;; when indentation is meant to be preserved.
+ (while (not (eobp))
+ (cond
+ ((and (looking-at-p org-footnote-definition-re)
+ (let ((e (org-element-at-point)))
+ (and (eq (org-element-type e) 'footnote-definition)
+ (goto-char (org-element-property :end e))))))
+ ((looking-at-p org-outline-regexp) (forward-line))
+ ((looking-at-p "[ \t]*$") (forward-line))
+ (t
+ (indent-line-to (+ (org-get-indentation) diff))
+ (beginning-of-line)
+ (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
+ (let ((e (org-element-at-point)))
+ (and (memq (org-element-type e)
+ '(example-block src-block))
+ (or org-src-preserve-indentation
+ (org-element-property :preserve-indent e))
+ (goto-char (org-element-property :end e))
+ (progn (skip-chars-backward " \r\t\n")
+ (beginning-of-line)
+ t))))
+ (forward-line)))))))))
+
+(defun org-convert-to-odd-levels ()
+ "Convert an Org file with all levels allowed to one with odd levels.
+This will leave level 1 alone, convert level 2 to level 3, level 3 to
+level 5 etc."
+ (interactive)
+ (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
+ (let ((outline-level 'org-outline-level)
+ (org-odd-levels-only nil) n)
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "^\\*\\*+ " nil t)
+ (setq n (- (length (match-string 0)) 2))
+ (while (>= (setq n (1- n)) 0)
+ (org-demote))
+ (end-of-line 1))))))
+
+(defun org-convert-to-oddeven-levels ()
+ "Convert an Org file with only odd levels to one with odd/even levels.
+This promotes level 3 to level 2, level 5 to level 3 etc. If the
+file contains a section with an even level, conversion would
+destroy the structure of the file. An error is signaled in this
+case."
+ (interactive)
+ (goto-char (point-min))
+ ;; First check if there are no even levels
+ (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
+ (org-show-set-visibility 'canonical)
+ (error "Not all levels are odd in this file. Conversion not possible"))
+ (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
+ (let ((outline-regexp org-outline-regexp)
+ (outline-level 'org-outline-level)
+ (org-odd-levels-only nil) n)
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "^\\*\\*+ " nil t)
+ (setq n (/ (1- (length (match-string 0))) 2))
+ (while (>= (setq n (1- n)) 0)
+ (org-promote))
+ (end-of-line 1))))))
+
+(defun org-tr-level (n)
+ "Make N odd if required."
+ (if org-odd-levels-only (1+ (/ n 2)) n))
+
+;;; Vertical tree motion, cutting and pasting of subtrees
+
+(defun org-move-subtree-up (&optional arg)
+ "Move the current subtree up past ARG headlines of the same level."
+ (interactive "p")
+ (org-move-subtree-down (- (prefix-numeric-value arg))))
+
+(defun org-move-subtree-down (&optional arg)
+ "Move the current subtree down past ARG headlines of the same level."
+ (interactive "p")
+ (setq arg (prefix-numeric-value arg))
+ (let ((movfunc (if (> arg 0) 'org-get-next-sibling
+ 'org-get-last-sibling))
+ (ins-point (make-marker))
+ (cnt (abs arg))
+ (col (current-column))
+ beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
+ ;; Select the tree
+ (org-back-to-heading)
+ (setq beg0 (point))
+ (save-excursion
+ (setq ne-beg (org-back-over-empty-lines))
+ (setq beg (point)))
+ (save-match-data
+ (save-excursion (outline-end-of-heading)
+ (setq folded (org-invisible-p)))
+ (progn (org-end-of-subtree nil t)
+ (unless (eobp) (backward-char))))
+ (outline-next-heading)
+ (setq ne-end (org-back-over-empty-lines))
+ (setq end (point))
+ (goto-char beg0)
+ (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
+ ;; include less whitespace
+ (save-excursion
+ (goto-char beg)
+ (forward-line (- ne-beg ne-end))
+ (setq beg (point))))
+ ;; Find insertion point, with error handling
+ (while (> cnt 0)
+ (or (and (funcall movfunc) (looking-at org-outline-regexp))
+ (progn (goto-char beg0)
+ (user-error "Cannot move past superior level or buffer limit")))
+ (setq cnt (1- cnt)))
+ (when (> arg 0)
+ ;; Moving forward - still need to move over subtree
+ (org-end-of-subtree t t)
+ (save-excursion
+ (org-back-over-empty-lines)
+ (or (bolp) (newline))))
+ (setq ne-ins (org-back-over-empty-lines))
+ (move-marker ins-point (point))
+ (setq txt (buffer-substring beg end))
+ (org-save-markers-in-region beg end)
+ (delete-region beg end)
+ (org-remove-empty-overlays-at beg)
+ (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
+ (or (bobp) (outline-flag-region (1- (point)) (point) nil))
+ (and (not (bolp)) (looking-at "\n") (forward-char 1))
+ (let ((bbb (point)))
+ (insert-before-markers txt)
+ (org-reinstall-markers-in-region bbb)
+ (move-marker ins-point bbb))
+ (or (bolp) (insert "\n"))
+ (setq ins-end (point))
+ (goto-char ins-point)
+ (org-skip-whitespace)
+ (when (and (< arg 0)
+ (org-first-sibling-p)
+ (> ne-ins ne-beg))
+ ;; Move whitespace back to beginning
+ (save-excursion
+ (goto-char ins-end)
+ (let ((kill-whole-line t))
+ (kill-line (- ne-ins ne-beg)) (point)))
+ (insert (make-string (- ne-ins ne-beg) ?\n)))
+ (move-marker ins-point nil)
+ (if folded
+ (outline-hide-subtree)
+ (org-show-entry)
+ (org-show-children)
+ (org-cycle-hide-drawers 'children))
+ (org-clean-visibility-after-subtree-move)
+ ;; move back to the initial column we were at
+ (move-to-column col)))
+
+(defvar org-subtree-clip ""
+ "Clipboard for cut and paste of subtrees.
+This is actually only a copy of the kill, because we use the normal kill
+ring. We need it to check if the kill was created by `org-copy-subtree'.")
+
+(defvar org-subtree-clip-folded nil
+ "Was the last copied subtree folded?
+This is used to fold the tree back after pasting.")
+
+(defun org-cut-subtree (&optional n)
+ "Cut the current subtree into the clipboard.
+With prefix arg N, cut this many sequential subtrees.
+This is a short-hand for marking the subtree and then cutting it."
+ (interactive "p")
+ (org-copy-subtree n 'cut))
+
+(defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
+ "Copy the current subtree it in the clipboard.
+With prefix arg N, copy this many sequential subtrees.
+This is a short-hand for marking the subtree and then copying it.
+If CUT is non-nil, actually cut the subtree.
+If FORCE-STORE-MARKERS is non-nil, store the relative locations
+of some markers in the region, even if CUT is non-nil. This is
+useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
+ (interactive "p")
+ (let (beg end folded (beg0 (point)))
+ (if (called-interactively-p 'any)
+ (org-back-to-heading nil) ; take what looks like a subtree
+ (org-back-to-heading t)) ; take what is really there
+ (setq beg (point))
+ (skip-chars-forward " \t\r\n")
+ (save-match-data
+ (if nosubtrees
+ (outline-next-heading)
+ (save-excursion (outline-end-of-heading)
+ (setq folded (org-invisible-p)))
+ (ignore-errors (org-forward-heading-same-level (1- n) t))
+ (org-end-of-subtree t t)))
+ ;; Include the end of an inlinetask
+ (when (and (featurep 'org-inlinetask)
+ (looking-at-p (concat (org-inlinetask-outline-regexp)
+ "END[ \t]*$")))
+ (end-of-line))
+ (setq end (point))
+ (goto-char beg0)
+ (when (> end beg)
+ (setq org-subtree-clip-folded folded)
+ (when (or cut force-store-markers)
+ (org-save-markers-in-region beg end))
+ (if cut (kill-region beg end) (copy-region-as-kill beg end))
+ (setq org-subtree-clip (current-kill 0))
+ (message "%s: Subtree(s) with %d characters"
+ (if cut "Cut" "Copied")
+ (length org-subtree-clip)))))
+
+(defun org-paste-subtree (&optional level tree for-yank remove)
+ "Paste the clipboard as a subtree, with modification of headline level.
+The entire subtree is promoted or demoted in order to match a new headline
+level.
+
+If the cursor is at the beginning of a headline, the same level as
+that headline is used to paste the tree.
+
+If not, the new level is derived from the *visible* headings
+before and after the insertion point, and taken to be the inferior headline
+level of the two. So if the previous visible heading is level 3 and the
+next is level 4 (or vice versa), level 4 will be used for insertion.
+This makes sure that the subtree remains an independent subtree and does
+not swallow low level entries.
+
+You can also force a different level, either by using a numeric prefix
+argument, or by inserting the heading marker by hand. For example, if the
+cursor is after \"*****\", then the tree will be shifted to level 5.
+
+If optional TREE is given, use this text instead of the kill ring.
+
+When FOR-YANK is set, this is called by `org-yank'. In this case, do not
+move back over whitespace before inserting, and move point to the end of
+the inserted text when done.
+
+When REMOVE is non-nil, remove the subtree from the clipboard."
+ (interactive "P")
+ (setq tree (or tree (and kill-ring (current-kill 0))))
+ (unless (org-kill-is-subtree-p tree)
+ (user-error "%s"
+ (substitute-command-keys
+ "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
+ (org-with-limited-levels
+ (let* ((visp (not (org-invisible-p)))
+ (txt tree)
+ (^re_ "\\(\\*+\\)[ \t]*")
+ (old-level (if (string-match org-outline-regexp-bol txt)
+ (- (match-end 0) (match-beginning 0) 1)
+ -1))
+ (force-level (cond (level (prefix-numeric-value level))
+ ((and (looking-at "[ \t]*$")
+ (string-match
+ "^\\*+$" (buffer-substring
+ (point-at-bol) (point))))
+ (- (match-end 0) (match-beginning 0)))
+ ((and (bolp)
+ (looking-at org-outline-regexp))
+ (- (match-end 0) (point) 1))))
+ (previous-level (save-excursion
+ (condition-case nil
+ (progn
+ (outline-previous-visible-heading 1)
+ (if (looking-at ^re_)
+ (- (match-end 0) (match-beginning 0) 1)
+ 1))
+ (error 1))))
+ (next-level (save-excursion
+ (condition-case nil
+ (progn
+ (or (looking-at org-outline-regexp)
+ (outline-next-visible-heading 1))
+ (if (looking-at ^re_)
+ (- (match-end 0) (match-beginning 0) 1)
+ 1))
+ (error 1))))
+ (new-level (or force-level (max previous-level next-level)))
+ (shift (if (or (= old-level -1)
+ (= new-level -1)
+ (= old-level new-level))
+ 0
+ (- new-level old-level)))
+ (delta (if (> shift 0) -1 1))
+ (func (if (> shift 0) 'org-demote 'org-promote))
+ (org-odd-levels-only nil)
+ beg end newend)
+ ;; Remove the forced level indicator
+ (when force-level
+ (delete-region (point-at-bol) (point)))
+ ;; Paste
+ (beginning-of-line (if (bolp) 1 2))
+ (setq beg (point))
+ (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
+ (insert-before-markers txt)
+ (unless (string-suffix-p "\n" txt) (insert "\n"))
+ (setq newend (point))
+ (org-reinstall-markers-in-region beg)
+ (setq end (point))
+ (goto-char beg)
+ (skip-chars-forward " \t\n\r")
+ (setq beg (point))
+ (when (and (org-invisible-p) visp)
+ (save-excursion (outline-show-heading)))
+ ;; Shift if necessary
+ (unless (= shift 0)
+ (save-restriction
+ (narrow-to-region beg end)
+ (while (not (= shift 0))
+ (org-map-region func (point-min) (point-max))
+ (setq shift (+ delta shift)))
+ (goto-char (point-min))
+ (setq newend (point-max))))
+ (when (or (called-interactively-p 'interactive) for-yank)
+ (message "Clipboard pasted as level %d subtree" new-level))
+ (when (and (not for-yank) ; in this case, org-yank will decide about folding
+ kill-ring
+ (eq org-subtree-clip (current-kill 0))
+ org-subtree-clip-folded)
+ ;; The tree was folded before it was killed/copied
+ (outline-hide-subtree))
+ (and for-yank (goto-char newend))
+ (and remove (setq kill-ring (cdr kill-ring))))))
+
+(defun org-kill-is-subtree-p (&optional txt)
+ "Check if the current kill is an outline subtree, or a set of trees.
+Returns nil if kill does not start with a headline, or if the first
+headline level is not the largest headline level in the tree.
+So this will actually accept several entries of equal levels as well,
+which is OK for `org-paste-subtree'.
+If optional TXT is given, check this string instead of the current kill."
+ (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
+ (re (org-get-limited-outline-regexp))
+ (^re (concat "^" re))
+ (start-level (and kill
+ (string-match
+ (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
+ kill)
+ (- (match-end 2) (match-beginning 2) 1)))
+ (start (1+ (or (match-beginning 2) -1))))
+ (if (not start-level)
+ (progn
+ nil) ;; does not even start with a heading
+ (catch 'exit
+ (while (setq start (string-match ^re kill (1+ start)))
+ (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
+ (throw 'exit nil)))
+ t))))
+
+(defvar org-markers-to-move nil
+ "Markers that should be moved with a cut-and-paste operation.
+Those markers are stored together with their positions relative to
+the start of the region.")
+
+(defun org-save-markers-in-region (beg end)
+ "Check markers in region.
+If these markers are between BEG and END, record their position relative
+to BEG, so that after moving the block of text, we can put the markers back
+into place.
+This function gets called just before an entry or tree gets cut from the
+buffer. After re-insertion, `org-reinstall-markers-in-region' must be
+called immediately, to move the markers with the entries."
+ (setq org-markers-to-move nil)
+ (when (featurep 'org-clock)
+ (org-clock-save-markers-for-cut-and-paste beg end))
+ (when (featurep 'org-agenda)
+ (org-agenda-save-markers-for-cut-and-paste beg end)))
+
+(defun org-check-and-save-marker (marker beg end)
+ "Check if MARKER is between BEG and END.
+If yes, remember the marker and the distance to BEG."
+ (when (and (marker-buffer marker)
+ (equal (marker-buffer marker) (current-buffer))
+ (>= marker beg) (< marker end))
+ (push (cons marker (- marker beg)) org-markers-to-move)))
+
+(defun org-reinstall-markers-in-region (beg)
+ "Move all remembered markers to their position relative to BEG."
+ (dolist (x org-markers-to-move)
+ (move-marker (car x) (+ beg (cdr x))))
+ (setq org-markers-to-move nil))
+
+(defun org-narrow-to-subtree ()
+ "Narrow buffer to the current subtree."
+ (interactive)
+ (save-excursion
+ (save-match-data
+ (org-with-limited-levels
+ (narrow-to-region
+ (progn (org-back-to-heading t) (point))
+ (progn (org-end-of-subtree t t)
+ (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
+ (point)))))))
+
+(defun org-narrow-to-block ()
+ "Narrow buffer to the current block."
+ (interactive)
+ (let* ((case-fold-search t)
+ (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
+ "^[ \t]*#\\+end_.*")))
+ (if blockp
+ (narrow-to-region (car blockp) (cdr blockp))
+ (user-error "Not in a block"))))
+
+(defun org-clone-subtree-with-time-shift (n &optional shift)
+ "Clone the task (subtree) at point N times.
+The clones will be inserted as siblings.
+
+In interactive use, the user will be prompted for the number of
+clones to be produced. If the entry has a timestamp, the user
+will also be prompted for a time shift, which may be a repeater
+as used in time stamps, for example `+3d'. To disable this,
+you can call the function with a universal prefix argument.
+
+When a valid repeater is given and the entry contains any time
+stamps, the clones will become a sequence in time, with time
+stamps in the subtree shifted for each clone produced. If SHIFT
+is nil or the empty string, time stamps will be left alone. The
+ID property of the original subtree is removed.
+
+In each clone, all the CLOCK entries will be removed. This
+prevents Org from considering that the clocked times overlap.
+
+If the original subtree did contain time stamps with a repeater,
+the following will happen:
+- the repeater will be removed in each clone
+- an additional clone will be produced, with the current, unshifted
+ date(s) in the entry.
+- the original entry will be placed *after* all the clones, with
+ repeater intact.
+- the start days in the repeater in the original entry will be shifted
+ to past the last clone.
+In this way you can spell out a number of instances of a repeating task,
+and still retain the repeater to cover future instances of the task.
+
+As described above, N+1 clones are produced when the original
+subtree has a repeater. Setting N to 0, then, can be used to
+remove the repeater from a subtree and create a shifted clone
+with the original repeater."
+ (interactive "nNumber of clones to produce: ")
+ (unless (wholenump n) (user-error "Invalid number of replications %s" n))
+ (when (org-before-first-heading-p) (user-error "No subtree to clone"))
+ (let* ((beg (save-excursion (org-back-to-heading t) (point)))
+ (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
+ (shift
+ (or shift
+ (if (and (not (equal current-prefix-arg '(4)))
+ (save-excursion
+ (goto-char beg)
+ (re-search-forward org-ts-regexp-both end-of-tree t)))
+ (read-from-minibuffer
+ "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
+ ""))) ;No time shift
+ (doshift
+ (and (org-string-nw-p shift)
+ (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
+ shift)
+ (user-error "Invalid shift specification %s" shift)))))
+ (goto-char end-of-tree)
+ (unless (bolp) (insert "\n"))
+ (let* ((end (point))
+ (template (buffer-substring beg end))
+ (shift-n (and doshift (string-to-number (match-string 1 shift))))
+ (shift-what (pcase (and doshift (match-string 2 shift))
+ (`nil nil)
+ ("d" 'day)
+ ("w" (setq shift-n (* 7 shift-n)) 'day)
+ ("m" 'month)
+ ("y" 'year)
+ (_ (error "Unsupported time unit"))))
+ (nmin 1)
+ (nmax n)
+ (n-no-remove -1)
+ (idprop (org-entry-get nil "ID")))
+ (when (and doshift
+ (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
+ template))
+ (delete-region beg end)
+ (setq end beg)
+ (setq nmin 0)
+ (setq nmax (1+ nmax))
+ (setq n-no-remove nmax))
+ (goto-char end)
+ (cl-loop for n from nmin to nmax do
+ (insert
+ ;; Prepare clone.
+ (with-temp-buffer
+ (insert template)
+ (org-mode)
+ (goto-char (point-min))
+ (org-show-subtree)
+ (and idprop (if org-clone-delete-id
+ (org-entry-delete nil "ID")
+ (org-id-get-create t)))
+ (unless (= n 0)
+ (while (re-search-forward org-clock-line-re nil t)
+ (delete-region (line-beginning-position)
+ (line-beginning-position 2)))
+ (goto-char (point-min))
+ (while (re-search-forward org-drawer-regexp nil t)
+ (org-remove-empty-drawer-at (point))))
+ (goto-char (point-min))
+ (when doshift
+ (while (re-search-forward org-ts-regexp-both nil t)
+ (org-timestamp-change (* n shift-n) shift-what))
+ (unless (= n n-no-remove)
+ (goto-char (point-min))
+ (while (re-search-forward org-ts-regexp nil t)
+ (save-excursion
+ (goto-char (match-beginning 0))
+ (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
+ (delete-region (match-beginning 1) (match-end 1)))))))
+ (buffer-string)))))
+ (goto-char beg)))
+
+;;; Outline Sorting
+
+(defun org-sort (with-case)
+ "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
+Optional argument WITH-CASE means sort case-sensitively."
+ (interactive "P")
+ (cond
+ ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
+ ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
+ (t
+ (org-call-with-arg 'org-sort-entries with-case))))
+
+(defun org-sort-remove-invisible (s)
+ "Remove invisible links from string S."
+ (remove-text-properties 0 (length s) org-rm-props s)
+ (while (string-match org-bracket-link-regexp s)
+ (setq s (replace-match (if (match-end 2)
+ (match-string 3 s)
+ (match-string 1 s))
+ t t s)))
+ (let ((st (format " %s " s)))
+ (while (string-match org-emph-re st)
+ (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
+ (setq s (substring st 1 -1)))
+ s)
+
+(defvar org-priority-regexp) ; defined later in the file
+
+(defvar org-after-sorting-entries-or-items-hook nil
+ "Hook that is run after a bunch of entries or items have been sorted.
+When children are sorted, the cursor is in the parent line when this
+hook gets called. When a region or a plain list is sorted, the cursor
+will be in the first entry of the sorted region/list.")
+
+(defun org-sort-entries
+ (&optional with-case sorting-type getkey-func compare-func property
+ interactive?)
+ "Sort entries on a certain level of an outline tree.
+If there is an active region, the entries in the region are sorted.
+Else, if the cursor is before the first entry, sort the top-level items.
+Else, the children of the entry at point are sorted.
+
+Sorting can be alphabetically, numerically, by date/time as given by
+a time stamp, by a property, by priority order, or by a custom function.
+
+The command prompts for the sorting type unless it has been given to the
+function through the SORTING-TYPE argument, which needs to be a character,
+\(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
+the precise meaning of each character:
+
+a Alphabetically, ignoring the TODO keyword and the priority, if any.
+c By creation time, which is assumed to be the first inactive time stamp
+ at the beginning of a line.
+d By deadline date/time.
+k By clocking time.
+n Numerically, by converting the beginning of the entry/item to a number.
+o By order of TODO keywords.
+p By priority according to the cookie.
+r By the value of a property.
+s By scheduled date/time.
+t By date/time, either the first active time stamp in the entry, or, if
+ none exist, by the first inactive one.
+
+Capital letters will reverse the sort order.
+
+If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
+called with point at the beginning of the record. It must return a
+value that is compatible with COMPARE-FUNC, the function used to
+compare entries.
+
+Comparing entries ignores case by default. However, with an optional argument
+WITH-CASE, the sorting considers case as well.
+
+Sorting is done against the visible part of the headlines, it ignores hidden
+links.
+
+When sorting is done, call `org-after-sorting-entries-or-items-hook'.
+
+A non-nil value for INTERACTIVE? is used to signal that this
+function is being called interactively."
+ (interactive (list current-prefix-arg nil nil nil nil t))
+ (let ((case-func (if with-case 'identity 'downcase))
+ (cmstr
+ ;; The clock marker is lost when using `sort-subr', let's
+ ;; store the clocking string.
+ (when (equal (marker-buffer org-clock-marker) (current-buffer))
+ (save-excursion
+ (goto-char org-clock-marker)
+ (buffer-substring-no-properties (line-beginning-position)
+ (point)))))
+ start beg end stars re re2
+ txt what tmp)
+ ;; Find beginning and end of region to sort
+ (cond
+ ((org-region-active-p)
+ ;; we will sort the region
+ (setq end (region-end)
+ what "region")
+ (goto-char (region-beginning))
+ (unless (org-at-heading-p) (outline-next-heading))
+ (setq start (point)))
+ ((or (org-at-heading-p)
+ (ignore-errors (progn (org-back-to-heading) t)))
+ ;; we will sort the children of the current headline
+ (org-back-to-heading)
+ (setq start (point)
+ end (progn (org-end-of-subtree t t)
+ (or (bolp) (insert "\n"))
+ (when (>= (org-back-over-empty-lines) 1)
+ (forward-line 1))
+ (point))
+ what "children")
+ (goto-char start)
+ (outline-show-subtree)
+ (outline-next-heading))
+ (t
+ ;; we will sort the top-level entries in this file
+ (goto-char (point-min))
+ (or (org-at-heading-p) (outline-next-heading))
+ (setq start (point))
+ (goto-char (point-max))
+ (beginning-of-line 1)
+ (when (looking-at ".*?\\S-")
+ ;; File ends in a non-white line
+ (end-of-line 1)
+ (insert "\n"))
+ (setq end (point-max))
+ (setq what "top-level")
+ (goto-char start)
+ (outline-show-all)))
+
+ (setq beg (point))
+ (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
+
+ (looking-at "\\(\\*+\\)")
+ (setq stars (match-string 1)
+ re (concat "^" (regexp-quote stars) " +")
+ re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
+ txt (buffer-substring beg end))
+ (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
+ (when (and (not (equal stars "*")) (string-match re2 txt))
+ (user-error "Region to sort contains a level above the first entry"))
+
+ (unless sorting-type
+ (message
+ "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
+ [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
+ A/N/P/R/O/F/T/S/D/C/K means reversed:"
+ what)
+ (setq sorting-type (read-char-exclusive)))
+
+ (unless getkey-func
+ (and (= (downcase sorting-type) ?f)
+ (setq getkey-func
+ (or (and interactive?
+ (org-read-function
+ "Function for extracting keys: "))
+ (error "Missing key extractor")))))
+
+ (and (= (downcase sorting-type) ?r)
+ (not property)
+ (setq property
+ (completing-read "Property: "
+ (mapcar #'list (org-buffer-property-keys t))
+ nil t)))
+
+ (when (member sorting-type '(?k ?K)) (org-clock-sum))
+ (message "Sorting entries...")
+
+ (save-restriction
+ (narrow-to-region start end)
+ (let ((dcst (downcase sorting-type))
+ (case-fold-search nil)
+ (now (current-time)))
+ (sort-subr
+ (/= dcst sorting-type)
+ ;; This function moves to the beginning character of the "record" to
+ ;; be sorted.
+ (lambda nil
+ (if (re-search-forward re nil t)
+ (goto-char (match-beginning 0))
+ (goto-char (point-max))))
+ ;; This function moves to the last character of the "record" being
+ ;; sorted.
+ (lambda nil
+ (save-match-data
+ (condition-case nil
+ (outline-forward-same-level 1)
+ (error
+ (goto-char (point-max))))))
+ ;; This function returns the value that gets sorted against.
+ (lambda nil
+ (cond
+ ((= dcst ?n)
+ (if (looking-at org-complex-heading-regexp)
+ (string-to-number (org-sort-remove-invisible (match-string 4)))
+ nil))
+ ((= dcst ?a)
+ (if (looking-at org-complex-heading-regexp)
+ (funcall case-func (org-sort-remove-invisible (match-string 4)))
+ nil))
+ ((= dcst ?k)
+ (or (get-text-property (point) :org-clock-minutes) 0))
+ ((= dcst ?t)
+ (let ((end (save-excursion (outline-next-heading) (point))))
+ (if (or (re-search-forward org-ts-regexp end t)
+ (re-search-forward org-ts-regexp-both end t))
+ (org-time-string-to-seconds (match-string 0))
+ (float-time now))))
+ ((= dcst ?c)
+ (let ((end (save-excursion (outline-next-heading) (point))))
+ (if (re-search-forward
+ (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
+ end t)
+ (org-time-string-to-seconds (match-string 0))
+ (float-time now))))
+ ((= dcst ?s)
+ (let ((end (save-excursion (outline-next-heading) (point))))
+ (if (re-search-forward org-scheduled-time-regexp end t)
+ (org-time-string-to-seconds (match-string 1))
+ (float-time now))))
+ ((= dcst ?d)
+ (let ((end (save-excursion (outline-next-heading) (point))))
+ (if (re-search-forward org-deadline-time-regexp end t)
+ (org-time-string-to-seconds (match-string 1))
+ (float-time now))))
+ ((= dcst ?p)
+ (if (re-search-forward org-priority-regexp (point-at-eol) t)
+ (string-to-char (match-string 2))
+ org-default-priority))
+ ((= dcst ?r)
+ (or (org-entry-get nil property) ""))
+ ((= dcst ?o)
+ (when (looking-at org-complex-heading-regexp)
+ (let* ((m (match-string 2))
+ (s (if (member m org-done-keywords) '- '+)))
+ (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
+ ((= dcst ?f)
+ (if getkey-func
+ (progn
+ (setq tmp (funcall getkey-func))
+ (when (stringp tmp) (setq tmp (funcall case-func tmp)))
+ tmp)
+ (error "Invalid key function `%s'" getkey-func)))
+ (t (error "Invalid sorting type `%c'" sorting-type))))
+ nil
+ (cond
+ ((= dcst ?a) 'string<)
+ ((= dcst ?f)
+ (or compare-func
+ (and interactive?
+ (org-read-function
+ (concat "Function for comparing keys "
+ "(empty for default `sort-subr' predicate): ")
+ 'allow-empty))))
+ ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
+ (run-hooks 'org-after-sorting-entries-or-items-hook)
+ ;; Reset the clock marker if needed
+ (when cmstr
+ (save-excursion
+ (goto-char start)
+ (search-forward cmstr nil t)
+ (move-marker org-clock-marker (point))))
+ (message "Sorting entries...done")))
+
+;;; The orgstruct minor mode
+
+;; Define a minor mode which can be used in other modes in order to
+;; integrate the Org mode structure editing commands.
+
+;; This is really a hack, because the Org mode structure commands use
+;; keys which normally belong to the major mode. Here is how it
+;; works: The minor mode defines all the keys necessary to operate the
+;; structure commands, but wraps the commands into a function which
+;; tests if the cursor is currently at a headline or a plain list
+;; item. If that is the case, the structure command is used,
+;; temporarily setting many Org mode variables like regular
+;; expressions for filling etc. However, when any of those keys is
+;; used at a different location, function uses `key-binding' to look
+;; up if the key has an associated command in another currently active
+;; keymap (minor modes, major mode, global), and executes that
+;; command. There might be problems if any of the keys is otherwise
+;; used as a prefix key.
+
+(defcustom orgstruct-heading-prefix-regexp ""
+ "Regexp that matches the custom prefix of Org headlines in
+orgstruct(++)-mode."
+ :group 'org
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'regexp)
+;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
+
+(defcustom orgstruct-setup-hook nil
+ "Hook run after orgstruct-mode-map is filled."
+ :group 'org
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'hook)
+
+(defvar orgstruct-initialized nil)
+
+(defvar org-local-vars nil
+ "List of local variables, for use by `orgstruct-mode'.")
+
+;;;###autoload
+(define-minor-mode orgstruct-mode
+ "Toggle the minor mode `orgstruct-mode'.
+This mode is for using Org mode structure commands in other
+modes. The following keys behave as if Org mode were active, if
+the cursor is on a headline, or on a plain list item (both as
+defined by Org mode)."
+ nil " OrgStruct" (make-sparse-keymap)
+ (funcall (if orgstruct-mode
+ 'add-to-invisibility-spec
+ 'remove-from-invisibility-spec)
+ '(outline . t))
+ (when orgstruct-mode
+ (org-load-modules-maybe)
+ (unless orgstruct-initialized
+ (orgstruct-setup)
+ (setq orgstruct-initialized t))))
+
+;;;###autoload
+(defun turn-on-orgstruct ()
+ "Unconditionally turn on `orgstruct-mode'."
+ (orgstruct-mode 1))
+
+(defvar-local orgstruct-is-++ nil
+ "Is `orgstruct-mode' in ++ version in the current-buffer?")
+(defvar-local org-fb-vars nil)
+(defun orgstruct++-mode (&optional arg)
+ "Toggle `orgstruct-mode', the enhanced version of it.
+In addition to setting orgstruct-mode, this also exports all
+indentation and autofilling variables from Org mode into the
+buffer. It will also recognize item context in multiline items."
+ (interactive "P")
+ (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
+ (if (< arg 1)
+ (progn (orgstruct-mode -1)
+ (dolist (v org-fb-vars)
+ (set (make-local-variable (car v))
+ (if (eq (car-safe (cadr v)) 'quote)
+ (cl-cadadr v)
+ (nth 1 v)))))
+ (orgstruct-mode 1)
+ (setq org-fb-vars nil)
+ (unless org-local-vars
+ (setq org-local-vars (org-get-local-variables)))
+ (let (var val)
+ (dolist (x org-local-vars)
+ (when (string-match
+ "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
+\\|fill-prefix\\|indent-\\)"
+ (symbol-name (car x)))
+ (setq var (car x) val (nth 1 x))
+ (push (list var `(quote ,(eval var))) org-fb-vars)
+ (set (make-local-variable var)
+ (if (eq (car-safe val) 'quote) (nth 1 val) val))))
+ (setq-local orgstruct-is-++ t))))
+
+;;;###autoload
+(defun turn-on-orgstruct++ ()
+ "Unconditionally turn on `orgstruct++-mode'."
+ (orgstruct++-mode 1))
+
+(defun orgstruct-error ()
+ "Error when there is no default binding for a structure key."
+ (interactive)
+ (funcall (if (fboundp 'user-error)
+ 'user-error
+ 'error)
+ "This key has no function outside structure elements"))
+
+(defun orgstruct-setup ()
+ "Setup orgstruct keymap."
+ (dolist (cell '((org-demote . t)
+ (org-metaleft . t)
+ (org-metaright . t)
+ (org-promote . t)
+ (org-shiftmetaleft . t)
+ (org-shiftmetaright . t)
+ org-backward-element
+ org-backward-heading-same-level
+ org-ctrl-c-ret
+ org-ctrl-c-minus
+ org-ctrl-c-star
+ org-cycle
+ org-force-cycle-archived
+ org-forward-heading-same-level
+ org-insert-heading
+ org-insert-heading-respect-content
+ org-kill-note-or-show-branches
+ org-mark-subtree
+ org-meta-return
+ org-metadown
+ org-metaup
+ org-narrow-to-subtree
+ org-promote-subtree
+ org-reveal
+ org-shiftdown
+ org-shiftleft
+ org-shiftmetadown
+ org-shiftmetaup
+ org-shiftright
+ org-shifttab
+ org-shifttab
+ org-shiftup
+ org-show-children
+ org-show-subtree
+ org-sort
+ org-up-element
+ outline-demote
+ outline-next-visible-heading
+ outline-previous-visible-heading
+ outline-promote
+ outline-up-heading))
+ (let ((f (or (car-safe cell) cell))
+ (disable-when-heading-prefix (cdr-safe cell)))
+ (when (fboundp f)
+ (let ((new-bindings))
+ (dolist (binding (nconc (where-is-internal f org-mode-map)
+ (where-is-internal f outline-mode-map)))
+ (push binding new-bindings)
+ ;; TODO use local-function-key-map
+ (dolist (rep '(("<tab>" . "TAB")
+ ("<return>" . "RET")
+ ("<escape>" . "ESC")
+ ("<delete>" . "DEL")))
+ (setq binding (read-kbd-macro
+ (let ((case-fold-search))
+ (replace-regexp-in-string
+ (regexp-quote (cdr rep))
+ (car rep)
+ (key-description binding)))))
+ (cl-pushnew binding new-bindings :test 'equal)))
+ (dolist (binding new-bindings)
+ (let ((key (lookup-key orgstruct-mode-map binding)))
+ (when (or (not key) (numberp key))
+ (ignore-errors
+ (org-defkey orgstruct-mode-map
+ binding
+ (orgstruct-make-binding
+ f binding disable-when-heading-prefix))))))))))
+ (run-hooks 'orgstruct-setup-hook))
+
+(defun orgstruct-make-binding (fun key disable-when-heading-prefix)
+ "Create a function for binding in the structure minor mode.
+FUN is the command to call inside a table. KEY is the key that
+should be checked in for a command to execute outside of tables.
+Non-nil `disable-when-heading-prefix' means to disable the command
+if `orgstruct-heading-prefix-regexp' is not empty."
+ (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
+ (let ((nname name)
+ (i 0))
+ (while (fboundp (intern nname))
+ (setq nname (format "%s-%d" name (setq i (1+ i)))))
+ (setq name (intern nname)))
+ (eval
+ (let ((bindings '((org-heading-regexp
+ (concat "^"
+ orgstruct-heading-prefix-regexp
+ "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
+ (org-outline-regexp
+ (concat orgstruct-heading-prefix-regexp "\\*+ "))
+ (org-outline-regexp-bol
+ (concat "^" org-outline-regexp))
+ (outline-regexp org-outline-regexp)
+ (outline-heading-end-regexp "\n")
+ (outline-level 'org-outline-level)
+ (outline-heading-alist))))
+ `(defun ,name (arg)
+ ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
+ "Outside of structure, run the binding of `"
+ (key-description key) "'."
+ (when disable-when-heading-prefix
+ (concat
+ "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
+ "back to the default binding due to limitations of Org's implementation of\n"
+ "`" (symbol-name fun) "'.")))
+ (interactive "p")
+ (let* ((disable
+ ,(and disable-when-heading-prefix
+ '(not (string= orgstruct-heading-prefix-regexp ""))))
+ (fallback
+ (or disable
+ (not
+ (let* ,bindings
+ (org-context-p 'headline 'item
+ ,(when (memq fun
+ '(org-insert-heading
+ org-insert-heading-respect-content
+ org-meta-return))
+ '(when orgstruct-is-++
+ 'item-body))))))))
+ (if fallback
+ (let* ((orgstruct-mode)
+ (binding
+ (let ((key ,key))
+ (catch 'exit
+ (dolist
+ (rep
+ '(nil
+ ("<\\([^>]*\\)tab>" . "\\1TAB")
+ ("<\\([^>]*\\)return>" . "\\1RET")
+ ("<\\([^>]*\\)escape>" . "\\1ESC")
+ ("<\\([^>]*\\)delete>" . "\\1DEL"))
+ nil)
+ (when rep
+ (setq key (read-kbd-macro
+ (let ((case-fold-search))
+ (replace-regexp-in-string
+ (car rep)
+ (cdr rep)
+ (key-description key))))))
+ (when (key-binding key)
+ (throw 'exit (key-binding key))))))))
+ (if (keymapp binding)
+ (org-set-transient-map binding)
+ (let ((func (or binding
+ (unless disable
+ 'orgstruct-error))))
+ (when func
+ (call-interactively func)))))
+ (org-run-like-in-org-mode
+ (lambda ()
+ (interactive)
+ (let* ,bindings
+ (call-interactively ',fun)))))))))
+ name))
+
+(defun org-contextualize-keys (alist contexts)
+ "Return valid elements in ALIST depending on CONTEXTS.
+
+`org-agenda-custom-commands' or `org-capture-templates' are the
+values used for ALIST, and `org-agenda-custom-commands-contexts'
+or `org-capture-templates-contexts' are the associated contexts
+definitions."
+ (let ((contexts
+ ;; normalize contexts
+ (mapcar
+ (lambda(c) (cond ((listp (cadr c))
+ (list (car c) (car c) (nth 1 c)))
+ ((string= "" (cadr c))
+ (list (car c) (car c) (nth 2 c)))
+ (t c)))
+ contexts))
+ (a alist) r s)
+ ;; loop over all commands or templates
+ (dolist (c a)
+ (let (vrules repl)
+ (cond
+ ((not (assoc (car c) contexts))
+ (push c r))
+ ((and (assoc (car c) contexts)
+ (setq vrules (org-contextualize-validate-key
+ (car c) contexts)))
+ (mapc (lambda (vr)
+ (unless (equal (car vr) (cadr vr))
+ (setq repl vr)))
+ vrules)
+ (if (not repl) (push c r)
+ (push (cadr repl) s)
+ (push
+ (cons (car c)
+ (cdr (or (assoc (cadr repl) alist)
+ (error "Undefined key `%s' as contextual replacement for `%s'"
+ (cadr repl) (car c)))))
+ r))))))
+ ;; Return limited ALIST, possibly with keys modified, and deduplicated
+ (delq
+ nil
+ (delete-dups
+ (mapcar (lambda (x)
+ (let ((tpl (car x)))
+ (unless (delq
+ nil
+ (mapcar (lambda (y)
+ (equal y tpl))
+ s))
+ x)))
+ (reverse r))))))
+
+(defun org-contextualize-validate-key (key contexts)
+ "Check CONTEXTS for agenda or capture KEY."
+ (let (res)
+ (dolist (r contexts)
+ (dolist (rr (car (last r)))
+ (when
+ (and (equal key (car r))
+ (if (functionp rr) (funcall rr)
+ (or (and (eq (car rr) 'in-file)
+ (buffer-file-name)
+ (string-match (cdr rr) (buffer-file-name)))
+ (and (eq (car rr) 'in-mode)
+ (string-match (cdr rr) (symbol-name major-mode)))
+ (and (eq (car rr) 'in-buffer)
+ (string-match (cdr rr) (buffer-name)))
+ (when (and (eq (car rr) 'not-in-file)
+ (buffer-file-name))
+ (not (string-match (cdr rr) (buffer-file-name))))
+ (when (eq (car rr) 'not-in-mode)
+ (not (string-match (cdr rr) (symbol-name major-mode))))
+ (when (eq (car rr) 'not-in-buffer)
+ (not (string-match (cdr rr) (buffer-name)))))))
+ (push r res))))
+ (delete-dups (delq nil res))))
+
+(defun org-context-p (&rest contexts)
+ "Check if local context is any of CONTEXTS.
+Possible values in the list of contexts are `table', `headline', and `item'."
+ (let ((pos (point)))
+ (goto-char (point-at-bol))
+ (prog1 (or (and (memq 'table contexts)
+ (looking-at "[ \t]*|"))
+ (and (memq 'headline contexts)
+ (looking-at org-outline-regexp))
+ (and (memq 'item contexts)
+ (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
+ (and (memq 'item-body contexts)
+ (org-in-item-p)))
+ (goto-char pos))))
+
+(defconst org-unique-local-variables
+ '(org-element--cache
+ org-element--cache-objects
+ org-element--cache-sync-keys
+ org-element--cache-sync-requests
+ org-element--cache-sync-timer)
+ "List of local variables that cannot be transferred to another buffer.")
+
+(defun org-get-local-variables ()
+ "Return a list of all local variables in an Org mode buffer."
+ (delq nil
+ (mapcar
+ (lambda (x)
+ (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
+ (name (car binding)))
+ (and (not (get name 'org-state))
+ (not (memq name org-unique-local-variables))
+ (string-match-p
+ "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
+auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
+ (symbol-name name))
+ binding)))
+ (with-temp-buffer
+ (org-mode)
+ (buffer-local-variables)))))
+
+(defun org-clone-local-variables (from-buffer &optional regexp)
+ "Clone local variables from FROM-BUFFER.
+Optional argument REGEXP selects variables to clone."
+ (dolist (pair (buffer-local-variables from-buffer))
+ (pcase pair
+ (`(,name . ,value) ;ignore unbound variables
+ (when (and (not (memq name org-unique-local-variables))
+ (or (null regexp) (string-match-p regexp (symbol-name name))))
+ (set (make-local-variable name) value))))))
+
+;;;###autoload
+(defun org-run-like-in-org-mode (cmd)
+ "Run a command, pretending that the current buffer is in Org mode.
+This will temporarily bind local variables that are typically bound in
+Org mode to the values they have in Org mode, and then interactively
+call CMD."
+ (org-load-modules-maybe)
+ (unless org-local-vars
+ (setq org-local-vars (org-get-local-variables)))
+ (let (binds)
+ (dolist (var org-local-vars)
+ (when (or (not (boundp (car var)))
+ (eq (symbol-value (car var))
+ (default-value (car var))))
+ (push (list (car var) `(quote ,(cadr var))) binds)))
+ (eval `(let ,binds
+ (call-interactively (quote ,cmd))))))
+
+(defun org-get-category (&optional pos force-refresh)
+ "Get the category applying to position POS."
+ (save-match-data
+ (when force-refresh (org-refresh-category-properties))
+ (let ((pos (or pos (point))))
+ (or (get-text-property pos 'org-category)
+ (progn (org-refresh-category-properties)
+ (get-text-property pos 'org-category))))))
+
+;;; Refresh properties
+
+(defun org-refresh-properties (dprop tprop)
+ "Refresh buffer text properties.
+DPROP is the drawer property and TPROP is either the
+corresponding text property to set, or an alist with each element
+being a text property (as a symbol) and a function to apply to
+the value of the drawer property."
+ (let* ((case-fold-search t)
+ (inhibit-read-only t)
+ (inherit? (org-property-inherit-p dprop))
+ (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
+ (global (and inherit? (org--property-global-value dprop nil))))
+ (org-with-silent-modifications
+ (org-with-point-at 1
+ ;; Set global values (e.g., values defined through
+ ;; "#+PROPERTY:" keywords) to the whole buffer.
+ (when global (put-text-property (point-min) (point-max) tprop global))
+ ;; Set local values.
+ (while (re-search-forward property-re nil t)
+ (when (org-at-property-p)
+ (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
+ (outline-next-heading))))))
+
+(defun org-refresh-property (tprop p &optional inherit)
+ "Refresh the buffer text property TPROP from the drawer property P.
+The refresh happens only for the current headline, or the whole
+sub-tree if optional argument INHERIT is non-nil."
+ (unless (org-before-first-heading-p)
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((start (point))
+ (end (save-excursion
+ (if inherit (org-end-of-subtree t t)
+ (or (outline-next-heading) (point-max))))))
+ (if (symbolp tprop)
+ ;; TPROP is a text property symbol.
+ (put-text-property start end tprop p)
+ ;; TPROP is an alist with (property . function) elements.
+ (pcase-dolist (`(,prop . ,f) tprop)
+ (put-text-property start end prop (funcall f p))))))))
+
+(defun org-refresh-category-properties ()
+ "Refresh category text properties in the buffer."
+ (let ((case-fold-search t)
+ (inhibit-read-only t)
+ (default-category
+ (cond ((null org-category)
+ (if buffer-file-name
+ (file-name-sans-extension
+ (file-name-nondirectory buffer-file-name))
+ "???"))
+ ((symbolp org-category) (symbol-name org-category))
+ (t org-category))))
+ (org-with-silent-modifications
+ (org-with-wide-buffer
+ ;; Set buffer-wide category. Search last #+CATEGORY keyword.
+ ;; This is the default category for the buffer. If none is
+ ;; found, fall-back to `org-category' or buffer file name.
+ (put-text-property
+ (point-min) (point-max)
+ 'org-category
+ (catch 'buffer-category
+ (goto-char (point-max))
+ (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (throw 'buffer-category
+ (org-element-property :value element)))))
+ default-category))
+ ;; Set sub-tree specific categories.
+ (goto-char (point-min))
+ (let ((regexp (org-re-property "CATEGORY")))
+ (while (re-search-forward regexp nil t)
+ (let ((value (match-string-no-properties 3)))
+ (when (org-at-property-p)
+ (put-text-property
+ (save-excursion (org-back-to-heading t) (point))
+ (save-excursion (org-end-of-subtree t t) (point))
+ 'org-category
+ value)))))))))
+
+(defun org-refresh-stats-properties ()
+ "Refresh stats text properties in the buffer."
+ (org-with-silent-modifications
+ (org-with-point-at 1
+ (let ((regexp (concat org-outline-regexp-bol
+ ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
+ (while (re-search-forward regexp nil t)
+ (let* ((numerator (string-to-number (match-string 1)))
+ (denominator (and (match-end 2)
+ (string-to-number (match-string 2))))
+ (stats (cond ((not denominator) numerator) ;percent
+ ((= denominator 0) 0)
+ (t (/ (* numerator 100) denominator)))))
+ (put-text-property (point) (progn (org-end-of-subtree t t) (point))
+ 'org-stats stats)))))))
+
+(defun org-refresh-effort-properties ()
+ "Refresh effort properties"
+ (org-refresh-properties
+ org-effort-property
+ '((effort . identity)
+ (effort-minutes . org-duration-string-to-minutes))))
+
+;;;; Link Stuff
+
+;;; Link abbreviations
+
+(defun org-link-expand-abbrev (link)
+ "Apply replacements as defined in `org-link-abbrev-alist'."
+ (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
+ (let* ((key (match-string 1 link))
+ (as (or (assoc key org-link-abbrev-alist-local)
+ (assoc key org-link-abbrev-alist)))
+ (tag (and (match-end 2) (match-string 3 link)))
+ rpl)
+ (if (not as)
+ link
+ (setq rpl (cdr as))
+ (cond
+ ((symbolp rpl) (funcall rpl tag))
+ ((string-match "%(\\([^)]+\\))" rpl)
+ (replace-match
+ (save-match-data
+ (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
+ ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
+ ((string-match "%h" rpl)
+ (replace-match (url-hexify-string (or tag "")) t t rpl))
+ (t (concat rpl tag)))))
+ link))
+
+;;; Storing and inserting links
+
+(defvar org-insert-link-history nil
+ "Minibuffer history for links inserted with `org-insert-link'.")
+
+(defvar org-stored-links nil
+ "Contains the links stored with `org-store-link'.")
+
+(defvar org-store-link-plist nil
+ "Plist with info about the most recently link created with `org-store-link'.")
+
+(defun org-store-link-functions ()
+ "Return a list of functions that are called to create and store a link.
+The functions defined in the :store property of
+`org-link-parameters'.
+
+Each function will be called in turn until one returns a non-nil
+value. Each function should check if it is responsible for
+creating this link (for example by looking at the major mode).
+If not, it must exit and return nil. If yes, it should return
+a non-nil value after calling `org-store-link-props' with a list
+of properties and values. Special properties are:
+
+:type The link prefix, like \"http\". This must be given.
+:link The link, like \"http://www.astro.uva.nl/~dominik\".
+ This is obligatory as well.
+:description Optional default description for the second pair
+ of brackets in an Org mode link. The user can still change
+ this when inserting this link into an Org mode buffer.
+
+In addition to these, any additional properties can be specified
+and then used in capture templates."
+ (cl-loop for link in org-link-parameters
+ with store-func
+ do (setq store-func (org-link-get-parameter (car link) :store))
+ if store-func
+ collect store-func))
+
+(defvar org-agenda-buffer-name) ; Defined in org-agenda.el
+(defvar org-id-link-to-org-use-id) ; Defined in org-id.el
+
+;;;###autoload
+(defun org-store-link (arg)
+ "Store an org-link to the current location.
+\\<org-mode-map>
+This link is added to `org-stored-links' and can later be inserted
+into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
+
+For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
+A single
+`\\[universal-argument]' negates `org-context-in-file-links' for file links or
+`org-gnus-prefer-web-links' for links to Usenet articles.
+
+A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
+skipping storing functions that are not
+part of Org core.
+
+A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
+prefix ARG forces storing a link for each line in the
+active region."
+ (interactive "P")
+ (org-load-modules-maybe)
+ (if (and (equal arg '(64)) (org-region-active-p))
+ (save-excursion
+ (let ((end (region-end)))
+ (goto-char (region-beginning))
+ (set-mark (point))
+ (while (< (point-at-eol) end)
+ (move-end-of-line 1) (activate-mark)
+ (let (current-prefix-arg)
+ (call-interactively 'org-store-link))
+ (move-beginning-of-line 2)
+ (set-mark (point)))))
+ (setq org-store-link-plist nil)
+ (let (link cpltxt desc description search
+ txt custom-id agenda-link sfuns sfunsn)
+ (cond
+
+ ;; Store a link using an external link type
+ ((and (not (equal arg '(16)))
+ (setq sfuns
+ (delq
+ nil (mapcar (lambda (f)
+ (let (fs) (if (funcall f) (push f fs))))
+ (org-store-link-functions)))
+ sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
+ (or (and (cdr sfuns)
+ (funcall (intern
+ (completing-read
+ "Which function for creating the link? "
+ sfunsn nil t (car sfunsn)))))
+ (funcall (caar sfuns)))
+ (setq link (plist-get org-store-link-plist :link)
+ desc (or (plist-get org-store-link-plist
+ :description)
+ link))))
+
+ ;; Store a link from a source code buffer.
+ ((org-src-edit-buffer-p)
+ (let ((coderef-format (org-src-coderef-format)))
+ (cond ((save-excursion
+ (beginning-of-line)
+ (looking-at (org-src-coderef-regexp coderef-format)))
+ (setq link (format "(%s)" (match-string-no-properties 3))))
+ ((called-interactively-p 'any)
+ (let ((label (read-string "Code line label: ")))
+ (end-of-line)
+ (setq link (format coderef-format label))
+ (let ((gc (- 79 (length link))))
+ (if (< (current-column) gc)
+ (org-move-to-column gc t)
+ (insert " ")))
+ (insert link)
+ (setq link (concat "(" label ")"))
+ (setq desc nil)))
+ (t (setq link nil)))))
+
+ ;; We are in the agenda, link to referenced location
+ ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
+ (let ((m (or (get-text-property (point) 'org-hd-marker)
+ (get-text-property (point) 'org-marker))))
+ (when m
+ (org-with-point-at m
+ (setq agenda-link
+ (if (called-interactively-p 'any)
+ (call-interactively 'org-store-link)
+ (org-store-link nil)))))))
+
+ ((eq major-mode 'calendar-mode)
+ (let ((cd (calendar-cursor-to-date)))
+ (setq link
+ (format-time-string
+ (car org-time-stamp-formats)
+ (apply 'encode-time
+ (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
+ nil nil nil))))
+ (org-store-link-props :type "calendar" :date cd)))
+
+ ((eq major-mode 'help-mode)
+ (setq link (concat "help:" (save-excursion
+ (goto-char (point-min))
+ (looking-at "^[^ ]+")
+ (match-string 0))))
+ (org-store-link-props :type "help"))
+
+ ((eq major-mode 'w3-mode)
+ (setq cpltxt (if (and (buffer-name)
+ (not (string-match "Untitled" (buffer-name))))
+ (buffer-name)
+ (url-view-url t))
+ link (url-view-url t))
+ (org-store-link-props :type "w3" :url (url-view-url t)))
+
+ ((eq major-mode 'image-mode)
+ (setq cpltxt (concat "file:"
+ (abbreviate-file-name buffer-file-name))
+ link cpltxt)
+ (org-store-link-props :type "image" :file buffer-file-name))
+
+ ;; In dired, store a link to the file of the current line
+ ((derived-mode-p 'dired-mode)
+ (let ((file (dired-get-filename nil t)))
+ (setq file (if file
+ (abbreviate-file-name
+ (expand-file-name (dired-get-filename nil t)))
+ ;; otherwise, no file so use current directory.
+ default-directory))
+ (setq cpltxt (concat "file:" file)
+ link cpltxt)))
+
+ ((setq search (run-hook-with-args-until-success
+ 'org-create-file-search-functions))
+ (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
+ "::" search))
+ (setq cpltxt (or description link)))
+
+ ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
+ (org-with-limited-levels
+ (setq custom-id (org-entry-get nil "CUSTOM_ID"))
+ (cond
+ ;; Store a link using the target at point
+ ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
+ (setq cpltxt
+ (concat "file:"
+ (abbreviate-file-name
+ (buffer-file-name (buffer-base-buffer)))
+ "::" (match-string 1))
+ link cpltxt))
+ ((and (featurep 'org-id)
+ (or (eq org-id-link-to-org-use-id t)
+ (and (called-interactively-p 'any)
+ (or (eq org-id-link-to-org-use-id 'create-if-interactive)
+ (and (eq org-id-link-to-org-use-id
+ 'create-if-interactive-and-no-custom-id)
+ (not custom-id))))
+ (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
+ ;; Store a link using the ID at point
+ (setq link (condition-case nil
+ (prog1 (org-id-store-link)
+ (setq desc (or (plist-get org-store-link-plist
+ :description)
+ "")))
+ (error
+ ;; Probably before first headline, link only to file
+ (concat "file:"
+ (abbreviate-file-name
+ (buffer-file-name (buffer-base-buffer))))))))
+ (t
+ ;; Just link to current headline
+ (setq cpltxt (concat "file:"
+ (abbreviate-file-name
+ (buffer-file-name (buffer-base-buffer)))))
+ ;; Add a context search string
+ (when (org-xor org-context-in-file-links
+ (equal arg '(4)))
+ (let* ((element (org-element-at-point))
+ (name (org-element-property :name element)))
+ (setq txt (cond
+ ((org-at-heading-p) nil)
+ (name)
+ ((org-region-active-p)
+ (buffer-substring (region-beginning) (region-end)))))
+ (when (or (null txt) (string-match "\\S-" txt))
+ (setq cpltxt
+ (concat cpltxt "::"
+ (condition-case nil
+ (org-make-org-heading-search-string txt)
+ (error "")))
+ desc (or name
+ (nth 4 (ignore-errors (org-heading-components)))
+ "NONE")))))
+ (when (string-match "::\\'" cpltxt)
+ (setq cpltxt (substring cpltxt 0 -2)))
+ (setq link cpltxt)))))
+
+ ((buffer-file-name (buffer-base-buffer))
+ ;; Just link to this file here.
+ (setq cpltxt (concat "file:"
+ (abbreviate-file-name
+ (buffer-file-name (buffer-base-buffer)))))
+ ;; Add a context string.
+ (when (org-xor org-context-in-file-links
+ (equal arg '(4)))
+ (setq txt (if (org-region-active-p)
+ (buffer-substring (region-beginning) (region-end))
+ (buffer-substring (point-at-bol) (point-at-eol))))
+ ;; Only use search option if there is some text.
+ (when (string-match "\\S-" txt)
+ (setq cpltxt
+ (concat cpltxt "::" (org-make-org-heading-search-string txt))
+ desc "NONE")))
+ (setq link cpltxt))
+
+ ((called-interactively-p 'interactive)
+ (user-error "No method for storing a link from this buffer"))
+
+ (t (setq link nil)))
+
+ ;; We're done setting link and desc, clean up
+ (when (consp link) (setq cpltxt (car link) link (cdr link)))
+ (setq link (or link cpltxt)
+ desc (or desc cpltxt))
+ (cond ((not desc))
+ ((equal desc "NONE") (setq desc nil))
+ (t (setq desc
+ (replace-regexp-in-string
+ org-bracket-link-analytic-regexp
+ (lambda (m) (or (match-string 5 m) (match-string 3 m)))
+ desc))))
+ ;; Return the link
+ (if (not (and (or (called-interactively-p 'any)
+ executing-kbd-macro)
+ link))
+ (or agenda-link (and link (org-make-link-string link desc)))
+ (push (list link desc) org-stored-links)
+ (message "Stored: %s" (or desc link))
+ (when custom-id
+ (setq link (concat "file:" (abbreviate-file-name
+ (buffer-file-name)) "::#" custom-id))
+ (push (list link desc) org-stored-links))
+ (car org-stored-links)))))
+
+(defun org-store-link-props (&rest plist)
+ "Store link properties, extract names, addresses and dates."
+ (let ((x (plist-get plist :from)))
+ (when x
+ (let ((adr (mail-extract-address-components x)))
+ (setq plist (plist-put plist :fromname (car adr)))
+ (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
+ (let ((x (plist-get plist :to)))
+ (when x
+ (let ((adr (mail-extract-address-components x)))
+ (setq plist (plist-put plist :toname (car adr)))
+ (setq plist (plist-put plist :toaddress (nth 1 adr))))))
+ (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
+ (when x
+ (setq plist (plist-put plist :date-timestamp
+ (format-time-string
+ (org-time-stamp-format t) x)))
+ (setq plist (plist-put plist :date-timestamp-inactive
+ (format-time-string
+ (org-time-stamp-format t t) x)))))
+ (let ((from (plist-get plist :from))
+ (to (plist-get plist :to)))
+ (when (and from to org-from-is-user-regexp)
+ (setq plist
+ (plist-put plist :fromto
+ (if (string-match org-from-is-user-regexp from)
+ (concat "to %t")
+ (concat "from %f"))))))
+ (setq org-store-link-plist plist))
+
+(defun org-add-link-props (&rest plist)
+ "Add these properties to the link property list."
+ (let (key value)
+ (while plist
+ (setq key (pop plist) value (pop plist))
+ (setq org-store-link-plist
+ (plist-put org-store-link-plist key value)))))
+
+(defun org-email-link-description (&optional fmt)
+ "Return the description part of an email link.
+This takes information from `org-store-link-plist' and formats it
+according to FMT (default from `org-email-link-description-format')."
+ (setq fmt (or fmt org-email-link-description-format))
+ (let* ((p org-store-link-plist)
+ (to (plist-get p :toaddress))
+ (from (plist-get p :fromaddress))
+ (table
+ (list
+ (cons "%c" (plist-get p :fromto))
+ (cons "%F" (plist-get p :from))
+ (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
+ (cons "%T" (plist-get p :to))
+ (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
+ (cons "%s" (plist-get p :subject))
+ (cons "%d" (plist-get p :date))
+ (cons "%m" (plist-get p :message-id)))))
+ (when (string-match "%c" fmt)
+ ;; Check if the user wrote this message
+ (if (and org-from-is-user-regexp from to
+ (save-match-data (string-match org-from-is-user-regexp from)))
+ (setq fmt (replace-match "to %t" t t fmt))
+ (setq fmt (replace-match "from %f" t t fmt))))
+ (org-replace-escapes fmt table)))
+
+(defun org-make-org-heading-search-string (&optional string)
+ "Make search string for the current headline or STRING."
+ (let ((s (or string
+ (and (derived-mode-p 'org-mode)
+ (save-excursion
+ (org-back-to-heading t)
+ (org-element-property :raw-value (org-element-at-point))))))
+ (lines org-context-in-file-links))
+ (or string (setq s (concat "*" s))) ; Add * for headlines
+ (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
+ (when (and string (integerp lines) (> lines 0))
+ (let ((slines (org-split-string s "\n")))
+ (when (< lines (length slines))
+ (setq s (mapconcat
+ 'identity
+ (reverse (nthcdr (- (length slines) lines)
+ (reverse slines))) "\n")))))
+ (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
+
+(defun org-make-link-string (link &optional description)
+ "Make a link with brackets, consisting of LINK and DESCRIPTION."
+ (unless (org-string-nw-p link) (error "Empty link"))
+ (let ((uri (cond ((string-match org-link-types-re link)
+ (concat (match-string 1 link)
+ (org-link-escape (substring link (match-end 1)))))
+ ;; For readability, url-encode internal links only
+ ;; when absolutely needed (i.e, when they contain
+ ;; square brackets). File links however, are
+ ;; encoded since, e.g., spaces are significant.
+ ((or (file-name-absolute-p link)
+ (string-match-p "\\`\\.\\.?/\\|[][]" link))
+ (org-link-escape link))
+ (t link)))
+ (description
+ (and (org-string-nw-p description)
+ ;; Remove brackets from description, as they are fatal.
+ (replace-regexp-in-string
+ "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
+ (org-trim description)))))
+ (format "[[%s]%s]"
+ uri
+ (if description (format "[%s]" description) ""))))
+
+(defconst org-link-escape-chars
+ ;;%20 %5B %5D %25
+ '(?\s ?\[ ?\] ?%)
+ "List of characters that should be escaped in a link when stored to Org.
+This is the list that is used for internal purposes.")
+
+(defun org-link-escape (text &optional table merge)
+ "Return percent escaped representation of TEXT.
+TEXT is a string with the text to escape.
+Optional argument TABLE is a list with characters that should be
+escaped. When nil, `org-link-escape-chars' is used.
+If optional argument MERGE is set, merge TABLE into
+`org-link-escape-chars'."
+ (let ((characters-to-encode
+ (cond ((null table) org-link-escape-chars)
+ (merge (append org-link-escape-chars table))
+ (t table))))
+ (mapconcat
+ (lambda (c)
+ (if (or (memq c characters-to-encode)
+ (and org-url-hexify-p (or (< c 32) (> c 126))))
+ (mapconcat (lambda (e) (format "%%%.2X" e))
+ (or (encode-coding-char c 'utf-8)
+ (error "Unable to percent escape character: %c" c))
+ "")
+ (char-to-string c)))
+ text "")))
+
+(defun org-link-unescape (str)
+ "Unhex hexified Unicode parts in string STR.
+E.g. `%C3%B6' becomes the german o-Umlaut. This is the
+reciprocal of `org-link-escape', which see."
+ (if (org-string-nw-p str)
+ (replace-regexp-in-string
+ "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
+ str))
+
+(defun org-link-unescape-compound (hex)
+ "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
+Note: this function also decodes single byte encodings like
+`%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
+ (save-match-data
+ (let* ((bytes (cdr (split-string hex "%")))
+ (ret "")
+ (eat 0)
+ (sum 0))
+ (while bytes
+ (let* ((val (string-to-number (pop bytes) 16))
+ (shift-xor
+ (if (= 0 eat)
+ (cond
+ ((>= val 252) (cons 6 252))
+ ((>= val 248) (cons 5 248))
+ ((>= val 240) (cons 4 240))
+ ((>= val 224) (cons 3 224))
+ ((>= val 192) (cons 2 192))
+ (t (cons 0 0)))
+ (cons 6 128))))
+ (when (>= val 192) (setq eat (car shift-xor)))
+ (setq val (logxor val (cdr shift-xor)))
+ (setq sum (+ (lsh sum (car shift-xor)) val))
+ (when (> eat 0) (setq eat (- eat 1)))
+ (cond
+ ((= 0 eat) ;multi byte
+ (setq ret (concat ret (char-to-string sum)))
+ (setq sum 0))
+ ((not bytes) ; single byte(s)
+ (setq ret (org-link-unescape-single-byte-sequence hex))))))
+ ret)))
+
+(defun org-link-unescape-single-byte-sequence (hex)
+ "Unhexify hex-encoded single byte character sequences."
+ (mapconcat (lambda (byte)
+ (char-to-string (string-to-number byte 16)))
+ (cdr (split-string hex "%")) ""))
+
+(defun org-xor (a b)
+ "Exclusive or."
+ (if a (not b) b))
+
+(defun org-fixup-message-id-for-http (s)
+ "Replace special characters in a message id, so it can be used in an http query."
+ (when (string-match "%" s)
+ (setq s (mapconcat (lambda (c)
+ (if (eq c ?%)
+ "%25"
+ (char-to-string c)))
+ s "")))
+ (while (string-match "<" s)
+ (setq s (replace-match "%3C" t t s)))
+ (while (string-match ">" s)
+ (setq s (replace-match "%3E" t t s)))
+ (while (string-match "@" s)
+ (setq s (replace-match "%40" t t s)))
+ s)
+
+(defun org-link-prettify (link)
+ "Return a human-readable representation of LINK.
+The car of LINK must be a raw link.
+The cdr of LINK must be either a link description or nil."
+ (let ((desc (or (cadr link) "<no description>")))
+ (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
+ "<" (car link) ">")))
+
+;;;###autoload
+(defun org-insert-link-global ()
+ "Insert a link like Org mode does.
+This command can be called in any mode to insert a link in Org syntax."
+ (interactive)
+ (org-load-modules-maybe)
+ (org-run-like-in-org-mode 'org-insert-link))
+
+(defun org-insert-all-links (arg &optional pre post)
+ "Insert all links in `org-stored-links'.
+When a universal prefix, do not delete the links from `org-stored-links'.
+When `ARG' is a number, insert the last N link(s).
+`PRE' and `POST' are optional arguments to define a string to
+prepend or to append."
+ (interactive "P")
+ (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
+ (links (copy-sequence org-stored-links))
+ (pr (or pre "- "))
+ (po (or post "\n"))
+ (cnt 1) l)
+ (if (null org-stored-links)
+ (message "No link to insert")
+ (while (and (or (listp arg) (>= arg cnt))
+ (setq l (if (listp arg)
+ (pop links)
+ (pop org-stored-links))))
+ (setq cnt (1+ cnt))
+ (insert pr)
+ (org-insert-link nil (car l) (or (cadr l) "<no description>"))
+ (insert po)))))
+
+(defun org-insert-last-stored-link (arg)
+ "Insert the last link stored in `org-stored-links'."
+ (interactive "p")
+ (org-insert-all-links arg "" "\n"))
+
+(defun org-link-fontify-links-to-this-file ()
+ "Fontify links to the current file in `org-stored-links'."
+ (let ((f (buffer-file-name)) a b)
+ (setq a (mapcar (lambda(l)
+ (let ((ll (car l)))
+ (when (and (string-match "^file:\\(.+\\)::" ll)
+ (equal f (expand-file-name (match-string 1 ll))))
+ ll)))
+ org-stored-links))
+ (when (featurep 'org-id)
+ (setq b (mapcar (lambda(l)
+ (let ((ll (car l)))
+ (when (and (string-match "^id:\\(.+\\)$" ll)
+ (equal f (expand-file-name
+ (or (org-id-find-id-file
+ (match-string 1 ll)) ""))))
+ ll)))
+ org-stored-links)))
+ (mapcar (lambda(l)
+ (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
+ (delq nil (append a b)))))
+
+(defvar org--links-history nil)
+(defun org-insert-link (&optional complete-file link-location default-description)
+ "Insert a link. At the prompt, enter the link.
+
+Completion can be used to insert any of the link protocol prefixes in use.
+
+The history can be used to select a link previously stored with
+`org-store-link'. When the empty string is entered (i.e. if you just
+press `RET' at the prompt), the link defaults to the most recently
+stored link. As `SPC' triggers completion in the minibuffer, you need to
+use `M-SPC' or `C-q SPC' to force the insertion of a space character.
+
+You will also be prompted for a description, and if one is given, it will
+be displayed in the buffer instead of the link.
+
+If there is already a link at point, this command will allow you to edit
+link and description parts.
+
+With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
+file name can be
+selected using completion. The path to the file will be relative to the
+current directory if the file is in the current directory or a subdirectory.
+Otherwise, the link will be the absolute path as completed in the minibuffer
+\(i.e. normally ~/path/to/file). You can configure this behavior using the
+option `org-link-file-path-type'.
+
+With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
+absolute path even if the file is in
+the current directory or below.
+
+A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
+prefix negates `org-keep-stored-link-after-insertion'.
+
+If `org-make-link-description-function' is non-nil, this function will be
+called with the link target, and the result will be the default
+link description.
+
+If the LINK-LOCATION parameter is non-nil, this value will be used as
+the link location instead of reading one interactively.
+
+If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
+as the default description."
+ (interactive "P")
+ (let* ((wcf (current-window-configuration))
+ (origbuf (current-buffer))
+ (region (when (org-region-active-p)
+ (buffer-substring (region-beginning) (region-end))))
+ (remove (and region (list (region-beginning) (region-end))))
+ (desc region)
+ (link link-location)
+ (abbrevs org-link-abbrev-alist-local)
+ entry all-prefixes auto-desc)
+ (cond
+ (link-location) ; specified by arg, just use it.
+ ((org-in-regexp org-bracket-link-regexp 1)
+ ;; We do have a link at point, and we are going to edit it.
+ (setq remove (list (match-beginning 0) (match-end 0)))
+ (setq desc (when (match-end 3) (match-string-no-properties 3)))
+ (setq link (read-string "Link: "
+ (org-link-unescape
+ (match-string-no-properties 1)))))
+ ((or (org-in-regexp org-angle-link-re)
+ (org-in-regexp org-plain-link-re))
+ ;; Convert to bracket link
+ (setq remove (list (match-beginning 0) (match-end 0))
+ link (read-string "Link: "
+ (org-unbracket-string "<" ">" (match-string 0)))))
+ ((member complete-file '((4) (16)))
+ ;; Completing read for file names.
+ (setq link (org-file-complete-link complete-file)))
+ (t
+ ;; Read link, with completion for stored links.
+ (org-link-fontify-links-to-this-file)
+ (org-switch-to-buffer-other-window "*Org Links*")
+ (with-current-buffer "*Org Links*"
+ (erase-buffer)
+ (insert "Insert a link.
+Use TAB to complete link prefixes, then RET for type-specific completion support\n")
+ (when org-stored-links
+ (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
+ (insert (mapconcat 'org-link-prettify
+ (reverse org-stored-links) "\n")))
+ (goto-char (point-min)))
+ (let ((cw (selected-window)))
+ (select-window (get-buffer-window "*Org Links*" 'visible))
+ (with-current-buffer "*Org Links*" (setq truncate-lines t))
+ (unless (pos-visible-in-window-p (point-max))
+ (org-fit-window-to-buffer))
+ (and (window-live-p cw) (select-window cw)))
+ (setq all-prefixes (append (mapcar 'car abbrevs)
+ (mapcar 'car org-link-abbrev-alist)
+ (org-link-types)))
+ (unwind-protect
+ ;; Fake a link history, containing the stored links.
+ (let ((org--links-history
+ (append (mapcar #'car org-stored-links)
+ org-insert-link-history)))
+ (setq link
+ (org-completing-read
+ "Link: "
+ (append
+ (mapcar (lambda (x) (concat x ":")) all-prefixes)
+ (mapcar #'car org-stored-links))
+ nil nil nil
+ 'org--links-history
+ (caar org-stored-links)))
+ (unless (org-string-nw-p link) (user-error "No link selected"))
+ (dolist (l org-stored-links)
+ (when (equal link (cadr l))
+ (setq link (car l))
+ (setq auto-desc t)))
+ (when (or (member link all-prefixes)
+ (and (equal ":" (substring link -1))
+ (member (substring link 0 -1) all-prefixes)
+ (setq link (substring link 0 -1))))
+ (setq link (with-current-buffer origbuf
+ (org-link-try-special-completion link)))))
+ (set-window-configuration wcf)
+ (kill-buffer "*Org Links*"))
+ (setq entry (assoc link org-stored-links))
+ (or entry (push link org-insert-link-history))
+ (setq desc (or desc (nth 1 entry)))))
+
+ (when (funcall (if (equal complete-file '(64)) 'not 'identity)
+ (not org-keep-stored-link-after-insertion))
+ (setq org-stored-links (delq (assoc link org-stored-links)
+ org-stored-links)))
+
+ (when (and (string-match org-plain-link-re link)
+ (not (string-match org-ts-regexp link)))
+ ;; URL-like link, normalize the use of angular brackets.
+ (setq link (org-unbracket-string "<" ">" link)))
+
+ ;; Check if we are linking to the current file with a search
+ ;; option If yes, simplify the link by using only the search
+ ;; option.
+ (when (and buffer-file-name
+ (let ((case-fold-search nil))
+ (string-match "\\`file:\\(.+?\\)::" link)))
+ (let ((path (match-string-no-properties 1 link))
+ (search (substring-no-properties link (match-end 0))))
+ (save-match-data
+ (when (equal (file-truename buffer-file-name) (file-truename path))
+ ;; We are linking to this same file, with a search option
+ (setq link search)))))
+
+ ;; Check if we can/should use a relative path. If yes, simplify the link
+ (let ((case-fold-search nil))
+ (when (string-match "\\`\\(file\\|docview\\):" link)
+ (let* ((type (match-string-no-properties 0 link))
+ (path (substring-no-properties link (match-end 0)))
+ (origpath path))
+ (cond
+ ((or (eq org-link-file-path-type 'absolute)
+ (equal complete-file '(16)))
+ (setq path (abbreviate-file-name (expand-file-name path))))
+ ((eq org-link-file-path-type 'noabbrev)
+ (setq path (expand-file-name path)))
+ ((eq org-link-file-path-type 'relative)
+ (setq path (file-relative-name path)))
+ (t
+ (save-match-data
+ (if (string-match (concat "^" (regexp-quote
+ (expand-file-name
+ (file-name-as-directory
+ default-directory))))
+ (expand-file-name path))
+ ;; We are linking a file with relative path name.
+ (setq path (substring (expand-file-name path)
+ (match-end 0)))
+ (setq path (abbreviate-file-name (expand-file-name path)))))))
+ (setq link (concat type path))
+ (when (equal desc origpath)
+ (setq desc path)))))
+
+ (if org-make-link-description-function
+ (setq desc
+ (or (condition-case nil
+ (funcall org-make-link-description-function link desc)
+ (error (progn (message "Can't get link description from `%s'"
+ (symbol-name org-make-link-description-function))
+ (sit-for 2) nil)))
+ (read-string "Description: " default-description)))
+ (if default-description (setq desc default-description)
+ (setq desc (or (and auto-desc desc)
+ (read-string "Description: " desc)))))
+
+ (unless (string-match "\\S-" desc) (setq desc nil))
+ (when remove (apply 'delete-region remove))
+ (insert (org-make-link-string link desc))
+ ;; Redisplay so as the new link has proper invisible characters.
+ (sit-for 0)))
+
+(defun org-link-try-special-completion (type)
+ "If there is completion support for link type TYPE, offer it."
+ (let ((fun (org-link-get-parameter type :complete)))
+ (if (functionp fun)
+ (funcall fun)
+ (read-string "Link (no completion support): " (concat type ":")))))
+
+(defun org-file-complete-link (&optional arg)
+ "Create a file link using completion."
+ (let ((file (read-file-name "File: "))
+ (pwd (file-name-as-directory (expand-file-name ".")))
+ (pwd1 (file-name-as-directory (abbreviate-file-name
+ (expand-file-name ".")))))
+ (cond ((equal arg '(16))
+ (concat "file:"
+ (abbreviate-file-name (expand-file-name file))))
+ ((string-match
+ (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
+ (concat "file:" (match-string 1 file)))
+ ((string-match
+ (concat "^" (regexp-quote pwd) "\\(.+\\)")
+ (expand-file-name file))
+ (concat "file:"
+ (match-string 1 (expand-file-name file))))
+ (t (concat "file:" file)))))
+
+(defun org-completing-read (&rest args)
+ "Completing-read with SPACE being a normal character."
+ (let ((enable-recursive-minibuffers t)
+ (minibuffer-local-completion-map
+ (copy-keymap minibuffer-local-completion-map)))
+ (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
+ (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
+ (org-defkey minibuffer-local-completion-map (kbd "C-c !")
+ 'org-time-stamp-inactive)
+ (apply #'completing-read args)))
+
+;;; Opening/following a link
+
+(defvar org-link-search-failed nil)
+
+(defvar org-open-link-functions nil
+ "Hook for functions finding a plain text link.
+These functions must take a single argument, the link content.
+They will be called for links that look like [[link text][description]]
+when LINK TEXT does not have a protocol like \"http:\" and does not look
+like a filename (e.g. \"./blue.png\").
+
+These functions will be called *before* Org attempts to resolve the
+link by doing text searches in the current buffer - so if you want a
+link \"[[target]]\" to still find \"<<target>>\", your function should
+handle this as a special case.
+
+When the function does handle the link, it must return a non-nil value.
+If it decides that it is not responsible for this link, it must return
+nil to indicate that that Org can continue with other options like
+exact and fuzzy text search.")
+
+(defun org-next-link (&optional search-backward)
+ "Move forward to the next link.
+If the link is in hidden text, expose it."
+ (interactive "P")
+ (when (and org-link-search-failed (eq this-command last-command))
+ (goto-char (point-min))
+ (message "Link search wrapped back to beginning of buffer"))
+ (setq org-link-search-failed nil)
+ (let* ((pos (point))
+ (ct (org-context))
+ (a (assq :link ct))
+ (srch-fun (if search-backward 're-search-backward 're-search-forward)))
+ (cond (a (goto-char (nth (if search-backward 1 2) a)))
+ ((looking-at org-any-link-re)
+ ;; Don't stay stuck at link without an org-link face
+ (forward-char (if search-backward -1 1))))
+ (if (funcall srch-fun org-any-link-re nil t)
+ (progn
+ (goto-char (match-beginning 0))
+ (when (org-invisible-p) (org-show-context)))
+ (goto-char pos)
+ (setq org-link-search-failed t)
+ (message "No further link found"))))
+
+(defun org-previous-link ()
+ "Move backward to the previous link.
+If the link is in hidden text, expose it."
+ (interactive)
+ (funcall 'org-next-link t))
+
+(defun org-translate-link (s)
+ "Translate a link string if a translation function has been defined."
+ (with-temp-buffer
+ (insert (org-trim s))
+ (org-trim (org-element-interpret-data (org-element-context)))))
+
+(defun org-translate-link-from-planner (type path)
+ "Translate a link from Emacs Planner syntax so that Org can follow it.
+This is still an experimental function, your mileage may vary."
+ (cond
+ ((member type '("http" "https" "news" "ftp"))
+ ;; standard Internet links are the same.
+ nil)
+ ((and (equal type "irc") (string-match "^//" path))
+ ;; Planner has two / at the beginning of an irc link, we have 1.
+ ;; We should have zero, actually....
+ (setq path (substring path 1)))
+ ((and (equal type "lisp") (string-match "^/" path))
+ ;; Planner has a slash, we do not.
+ (setq type "elisp" path (substring path 1)))
+ ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
+ ;; A typical message link. Planner has the id after the final slash,
+ ;; we separate it with a hash mark
+ (setq path (concat (match-string 1 path) "#"
+ (org-unbracket-string "<" ">" (match-string 2 path))))))
+ (cons type path))
+
+(defun org-find-file-at-mouse (ev)
+ "Open file link or URL at mouse."
+ (interactive "e")
+ (mouse-set-point ev)
+ (org-open-at-point 'in-emacs))
+
+(defun org-open-at-mouse (ev)
+ "Open file link or URL at mouse.
+See the docstring of `org-open-file' for details."
+ (interactive "e")
+ (mouse-set-point ev)
+ (when (eq major-mode 'org-agenda-mode)
+ (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
+ (org-open-at-point))
+
+(defvar org-window-config-before-follow-link nil
+ "The window configuration before following a link.
+This is saved in case the need arises to restore it.")
+
+;;;###autoload
+(defun org-open-at-point-global ()
+ "Follow a link or time-stamp like Org mode does.
+This command can be called in any mode to follow an external link
+or a time-stamp that has Org mode syntax. Its behavior is
+undefined when called on internal links (e.g., fuzzy links).
+Raise an error when there is nothing to follow. "
+ (interactive)
+ (cond ((org-in-regexp org-any-link-re)
+ (org-open-link-from-string (match-string-no-properties 0)))
+ ((or (org-in-regexp org-ts-regexp-both nil t)
+ (org-in-regexp org-tsr-regexp-both nil t))
+ (org-follow-timestamp-link))
+ (t (user-error "No link found"))))
+
+;;;###autoload
+(defun org-open-link-from-string (s &optional arg reference-buffer)
+ "Open a link in the string S, as if it was in Org mode."
+ (interactive "sLink: \nP")
+ (let ((reference-buffer (or reference-buffer (current-buffer))))
+ (with-temp-buffer
+ (let ((org-inhibit-startup (not reference-buffer)))
+ (org-mode)
+ (insert s)
+ (goto-char (point-min))
+ (when reference-buffer
+ (setq org-link-abbrev-alist-local
+ (with-current-buffer reference-buffer
+ org-link-abbrev-alist-local)))
+ (org-open-at-point arg reference-buffer)))))
+
+(defvar org-open-at-point-functions nil
+ "Hook that is run when following a link at point.
+
+Functions in this hook must return t if they identify and follow
+a link at point. If they don't find anything interesting at point,
+they must return nil.")
+
+(defvar org-link-search-inhibit-query nil)
+(defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
+(defun org--open-doi-link (path)
+ "Open a \"doi\" type link.
+PATH is a the path to search for, as a string."
+ (browse-url (url-encode-url (concat org-doi-server-url path))))
+
+(defun org--open-elisp-link (path)
+ "Open a \"elisp\" type link.
+PATH is the sexp to evaluate, as a string."
+ (let ((cmd path))
+ (if (or (and (org-string-nw-p
+ org-confirm-elisp-link-not-regexp)
+ (string-match-p org-confirm-elisp-link-not-regexp cmd))
+ (not org-confirm-elisp-link-function)
+ (funcall org-confirm-elisp-link-function
+ (format "Execute \"%s\" as elisp? "
+ (org-add-props cmd nil 'face 'org-warning))))
+ (message "%s => %s" cmd
+ (if (eq (string-to-char cmd) ?\()
+ (eval (read cmd))
+ (call-interactively (read cmd))))
+ (user-error "Abort"))))
+
+(defun org--open-help-link (path)
+ "Open a \"help\" type link.
+PATH is a symbol name, as a string."
+ (pcase (intern path)
+ ((and (pred fboundp) variable) (describe-function variable))
+ ((and (pred boundp) function) (describe-variable function))
+ (name (user-error "Unknown function or variable: %s" name))))
+
+(defun org--open-shell-link (path)
+ "Open a \"shell\" type link.
+PATH is the command to execute, as a string."
+ (let ((buf (generate-new-buffer "*Org Shell Output*"))
+ (cmd path))
+ (if (or (and (org-string-nw-p
+ org-confirm-shell-link-not-regexp)
+ (string-match
+ org-confirm-shell-link-not-regexp cmd))
+ (not org-confirm-shell-link-function)
+ (funcall org-confirm-shell-link-function
+ (format "Execute \"%s\" in shell? "
+ (org-add-props cmd nil
+ 'face 'org-warning))))
+ (progn
+ (message "Executing %s" cmd)
+ (shell-command cmd buf)
+ (when (featurep 'midnight)
+ (setq clean-buffer-list-kill-buffer-names
+ (cons (buffer-name buf)
+ clean-buffer-list-kill-buffer-names))))
+ (user-error "Abort"))))
+
+(defun org-open-at-point (&optional arg reference-buffer)
+ "Open link, timestamp, footnote or tags at point.
+
+When point is on a link, follow it. Normally, files will be
+opened by an appropriate application. If the optional prefix
+argument ARG is non-nil, Emacs will visit the file. With
+a double prefix argument, try to open outside of Emacs, in the
+application the system uses for this file type.
+
+When point is on a timestamp, open the agenda at the day
+specified.
+
+When point is a footnote definition, move to the first reference
+found. If it is on a reference, move to the associated
+definition.
+
+When point is on a headline, display a list of every link in the
+entry, so it is possible to pick one, or all, of them. If point
+is on a tag, call `org-tags-view' instead.
+
+When optional argument REFERENCE-BUFFER is non-nil, it should
+specify a buffer from where the link search should happen. This
+is used internally by `org-open-link-from-string'.
+
+On top of syntactically correct links, this function will open
+the link at point in comments or comment blocks and the first
+link in a property drawer line."
+ (interactive "P")
+ ;; On a code block, open block's results.
+ (unless (call-interactively 'org-babel-open-src-block-result)
+ (org-load-modules-maybe)
+ (setq org-window-config-before-follow-link (current-window-configuration))
+ (org-remove-occur-highlights nil nil t)
+ (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
+ (let* ((context
+ ;; Only consider supported types, even if they are not
+ ;; the closest one.
+ (org-element-lineage
+ (org-element-context)
+ '(clock comment comment-block footnote-definition
+ footnote-reference headline inlinetask keyword link
+ node-property timestamp)
+ t))
+ (type (org-element-type context))
+ (value (org-element-property :value context)))
+ (cond
+ ((not context) (user-error "No link found"))
+ ;; Exception: open timestamps and links in properties
+ ;; drawers, keywords and comments.
+ ((memq type '(comment comment-block keyword node-property))
+ (call-interactively #'org-open-at-point-global))
+ ;; On a headline or an inlinetask, but not on a timestamp,
+ ;; a link, a footnote reference or on tags.
+ ((and (memq type '(headline inlinetask))
+ ;; Not on tags.
+ (let ((case-fold-search nil))
+ (save-excursion
+ (beginning-of-line)
+ (looking-at org-complex-heading-regexp))
+ (or (not (match-beginning 5))
+ (< (point) (match-beginning 5)))))
+ (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
+ (links (car data))
+ (links-end (cdr data)))
+ (if links
+ (dolist (link (if (stringp links) (list links) links))
+ (search-forward link nil links-end)
+ (goto-char (match-beginning 0))
+ (org-open-at-point))
+ (require 'org-attach)
+ (org-attach-reveal 'if-exists))))
+ ;; On a clock line, make sure point is on the timestamp
+ ;; before opening it.
+ ((and (eq type 'clock)
+ value
+ (>= (point) (org-element-property :begin value))
+ (<= (point) (org-element-property :end value)))
+ (org-follow-timestamp-link))
+ ;; Do nothing on white spaces after an object.
+ ((>= (point)
+ (save-excursion
+ (goto-char (org-element-property :end context))
+ (skip-chars-backward " \t")
+ (point)))
+ (user-error "No link found"))
+ ((eq type 'timestamp) (org-follow-timestamp-link))
+ ;; On tags within a headline or an inlinetask.
+ ((and (memq type '(headline inlinetask))
+ (let ((case-fold-search nil))
+ (save-excursion (beginning-of-line)
+ (looking-at org-complex-heading-regexp))
+ (and (match-beginning 5)
+ (>= (point) (match-beginning 5)))))
+ (org-tags-view arg (substring (match-string 5) 0 -1)))
+ ((eq type 'link)
+ ;; When link is located within the description of another
+ ;; link (e.g., an inline image), always open the parent
+ ;; link.
+ (let* ((link (let ((up (org-element-property :parent context)))
+ (if (eq (org-element-type up) 'link) up context)))
+ (type (org-element-property :type link))
+ (path (org-link-unescape (org-element-property :path link))))
+ ;; Switch back to REFERENCE-BUFFER needed when called in
+ ;; a temporary buffer through `org-open-link-from-string'.
+ (with-current-buffer (or reference-buffer (current-buffer))
+ (cond
+ ((equal type "file")
+ (if (string-match "[*?{]" (file-name-nondirectory path))
+ (dired path)
+ ;; Look into `org-link-parameters' in order to find
+ ;; a DEDICATED-FUNCTION to open file. The function
+ ;; will be applied on raw link instead of parsed
+ ;; link due to the limitation in `org-add-link-type'
+ ;; ("open" function called with a single argument).
+ ;; If no such function is found, fallback to
+ ;; `org-open-file'.
+ (let* ((option (org-element-property :search-option link))
+ (app (org-element-property :application link))
+ (dedicated-function
+ (org-link-get-parameter
+ (if app (concat type "+" app) type)
+ :follow)))
+ (if dedicated-function
+ (funcall dedicated-function
+ (concat path
+ (and option (concat "::" option))))
+ (apply #'org-open-file
+ path
+ (cond (arg)
+ ((equal app "emacs") 'emacs)
+ ((equal app "sys") 'system))
+ (cond ((not option) nil)
+ ((string-match-p "\\`[0-9]+\\'" option)
+ (list (string-to-number option)))
+ (t (list nil
+ (org-link-unescape option)))))))))
+ ((functionp (org-link-get-parameter type :follow))
+ (funcall (org-link-get-parameter type :follow) path))
+ ((member type '("coderef" "custom-id" "fuzzy" "radio"))
+ (unless (run-hook-with-args-until-success
+ 'org-open-link-functions path)
+ (if (not arg) (org-mark-ring-push)
+ (switch-to-buffer-other-window
+ (org-get-buffer-for-internal-link (current-buffer))))
+ (let ((destination
+ (org-with-wide-buffer
+ (if (equal type "radio")
+ (org-search-radio-target
+ (org-element-property :path link))
+ (org-link-search
+ (if (member type '("custom-id" "coderef"))
+ (org-element-property :raw-link link)
+ path)
+ ;; Prevent fuzzy links from matching
+ ;; themselves.
+ (and (equal type "fuzzy")
+ (+ 2 (org-element-property :begin link)))))
+ (point))))
+ (unless (and (<= (point-min) destination)
+ (>= (point-max) destination))
+ (widen))
+ (goto-char destination))))
+ (t (browse-url-at-point))))))
+ ;; On a footnote reference or at a footnote definition's label.
+ ((or (eq type 'footnote-reference)
+ (and (eq type 'footnote-definition)
+ (save-excursion
+ ;; Do not validate action when point is on the
+ ;; spaces right after the footnote label, in
+ ;; order to be on par with behaviour on links.
+ (skip-chars-forward " \t")
+ (let ((begin
+ (org-element-property :contents-begin context)))
+ (if begin (< (point) begin)
+ (= (org-element-property :post-affiliated context)
+ (line-beginning-position)))))))
+ (org-footnote-action))
+ (t (user-error "No link found")))))
+ (run-hook-with-args 'org-follow-link-hook)))
+
+(defun org-offer-links-in-entry (buffer marker &optional nth zero)
+ "Offer links in the current entry and return the selected link.
+If there is only one link, return it.
+If NTH is an integer, return the NTH link found.
+If ZERO is a string, check also this string for a link, and if
+there is one, return it."
+ (with-current-buffer buffer
+ (org-with-wide-buffer
+ (goto-char marker)
+ (let ((cnt ?0)
+ have-zero end links link c)
+ (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
+ (push (match-string 0 zero) links)
+ (setq cnt (1- cnt) have-zero t))
+ (save-excursion
+ (org-back-to-heading t)
+ (setq end (save-excursion (outline-next-heading) (point)))
+ (while (re-search-forward org-any-link-re end t)
+ (push (match-string 0) links))
+ (setq links (org-uniquify (reverse links))))
+ (cond
+ ((null links)
+ (message "No links"))
+ ((equal (length links) 1)
+ (setq link (car links)))
+ ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
+ (setq link (nth (if have-zero nth (1- nth)) links)))
+ (t ; we have to select a link
+ (save-excursion
+ (save-window-excursion
+ (delete-other-windows)
+ (with-output-to-temp-buffer "*Select Link*"
+ (dolist (l links)
+ (cond
+ ((not (string-match org-bracket-link-regexp l))
+ (princ (format "[%c] %s\n" (cl-incf cnt)
+ (org-unbracket-string "<" ">" l))))
+ ((match-end 3)
+ (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
+ (match-string 3 l) (match-string 1 l))))
+ (t (princ (format "[%c] %s\n" (cl-incf cnt)
+ (match-string 1 l)))))))
+ (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
+ (message "Select link to open, RET to open all:")
+ (setq c (read-char-exclusive))
+ (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
+ (when (equal c ?q) (user-error "Abort"))
+ (if (equal c ?\C-m)
+ (setq link links)
+ (setq nth (- c ?0))
+ (when have-zero (setq nth (1+ nth)))
+ (unless (and (integerp nth) (>= (length links) nth))
+ (user-error "Invalid link selection"))
+ (setq link (nth (1- nth) links)))))
+ (cons link end)))))
+
+;; TODO: These functions are deprecated since `org-open-at-point'
+;; hard-codes behaviour for "file+emacs" and "file+sys" types.
+(defun org-open-file-with-system (path)
+ "Open file at PATH using the system way of opening it."
+ (org-open-file path 'system))
+(defun org-open-file-with-emacs (path)
+ "Open file at PATH in Emacs."
+ (org-open-file path 'emacs))
+
+
+;;; File search
+
+(defvar org-create-file-search-functions nil
+ "List of functions to construct the right search string for a file link.
+These functions are called in turn with point at the location to
+which the link should point.
+
+A function in the hook should first test if it would like to
+handle this file type, for example by checking the `major-mode'
+or the file extension. If it decides not to handle this file, it
+should just return nil to give other functions a chance. If it
+does handle the file, it must return the search string to be used
+when following the link. The search string will be part of the
+file link, given after a double colon, and `org-open-at-point'
+will automatically search for it. If special measures must be
+taken to make the search successful, another function should be
+added to the companion hook `org-execute-file-search-functions',
+which see.
+
+A function in this hook may also use `setq' to set the variable
+`description' to provide a suggestion for the descriptive text to
+be used for this link when it gets inserted into an Org buffer
+with \\[org-insert-link].")
+
+(defvar org-execute-file-search-functions nil
+ "List of functions to execute a file search triggered by a link.
+
+Functions added to this hook must accept a single argument, the
+search string that was part of the file link, the part after the
+double colon. The function must first check if it would like to
+handle this search, for example by checking the `major-mode' or
+the file extension. If it decides not to handle this search, it
+should just return nil to give other functions a chance. If it
+does handle the search, it must return a non-nil value to keep
+other functions from trying.
+
+Each function can access the current prefix argument through the
+variable `current-prefix-arg'. Note that a single prefix is used
+to force opening a link in Emacs, so it may be good to only use a
+numeric or double prefix to guide the search function.
+
+In case this is needed, a function in this hook can also restore
+the window configuration before `org-open-at-point' was called using:
+
+ (set-window-configuration org-window-config-before-follow-link)")
+
+(defun org-search-radio-target (target)
+ "Search a radio target matching TARGET in current buffer.
+White spaces are not significant."
+ (let ((re (format "<<<%s>>>"
+ (mapconcat #'regexp-quote
+ (org-split-string target "[ \t\n]+")
+ "[ \t]+\\(?:\n[ \t]*\\)?")))
+ (origin (point)))
+ (goto-char (point-min))
+ (catch :radio-match
+ (while (re-search-forward re nil t)
+ (backward-char)
+ (let ((object (org-element-context)))
+ (when (eq (org-element-type object) 'radio-target)
+ (goto-char (org-element-property :begin object))
+ (org-show-context 'link-search)
+ (throw :radio-match nil))))
+ (goto-char origin)
+ (user-error "No match for radio target: %s" target))))
+
+(defun org-link-search (s &optional avoid-pos stealth)
+ "Search for a search string S.
+
+If S starts with \"#\", it triggers a custom ID search.
+
+If S is enclosed within parenthesis, it initiates a coderef
+search.
+
+If S is surrounded by forward slashes, it is interpreted as
+a regular expression. In Org mode files, this will create an
+`org-occur' sparse tree. In ordinary files, `occur' will be used
+to list matches. If the current buffer is in `dired-mode', grep
+will be used to search in all files.
+
+When AVOID-POS is given, ignore matches near that position.
+
+When optional argument STEALTH is non-nil, do not modify
+visibility around point, thus ignoring `org-show-context-detail'
+variable.
+
+Search is case-insensitive and ignores white spaces. Return type
+of matched result, which is either `dedicated' or `fuzzy'."
+ (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
+ (let* ((case-fold-search t)
+ (origin (point))
+ (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
+ (starred (eq (string-to-char normalized) ?*))
+ (words (split-string (if starred (substring s 1) s)))
+ (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
+ (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
+ type)
+ (cond
+ ;; Check if there are any special search functions.
+ ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
+ ((eq (string-to-char s) ?#)
+ ;; Look for a custom ID S if S starts with "#".
+ (let* ((id (substring normalized 1))
+ (match (org-find-property "CUSTOM_ID" id)))
+ (if match (progn (goto-char match) (setf type 'dedicated))
+ (error "No match for custom ID: %s" id))))
+ ((string-match "\\`(\\(.*\\))\\'" normalized)
+ ;; Look for coderef targets if S is enclosed within parenthesis.
+ (let ((coderef (match-string-no-properties 1 normalized))
+ (re (substring s-single-re 1 -1)))
+ (goto-char (point-min))
+ (catch :coderef-match
+ (while (re-search-forward re nil t)
+ (let ((element (org-element-at-point)))
+ (when (and (memq (org-element-type element)
+ '(example-block src-block))
+ ;; Build proper regexp according to current
+ ;; block's label format.
+ (let ((label-fmt
+ (regexp-quote
+ (or (org-element-property :label-fmt element)
+ org-coderef-label-format))))
+ (save-excursion
+ (beginning-of-line)
+ (looking-at (format ".*?\\(%s\\)[ \t]*$"
+ (format label-fmt coderef))))))
+ (setq type 'dedicated)
+ (goto-char (match-beginning 1))
+ (throw :coderef-match nil))))
+ (goto-char origin)
+ (error "No match for coderef: %s" coderef))))
+ ((string-match "\\`/\\(.*\\)/\\'" normalized)
+ ;; Look for a regular expression.
+ (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
+ (match-string 1 s)))
+ ;; From here, we handle fuzzy links.
+ ;;
+ ;; Look for targets, only if not in a headline search.
+ ((and (not starred)
+ (let ((target (format "<<%s>>" s-multi-re)))
+ (catch :target-match
+ (goto-char (point-min))
+ (while (re-search-forward target nil t)
+ (backward-char)
+ (let ((context (org-element-context)))
+ (when (eq (org-element-type context) 'target)
+ (setq type 'dedicated)
+ (goto-char (org-element-property :begin context))
+ (throw :target-match t))))
+ nil))))
+ ;; Look for elements named after S, only if not in a headline
+ ;; search.
+ ((and (not starred)
+ (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
+ (catch :name-match
+ (goto-char (point-min))
+ (while (re-search-forward name nil t)
+ (let ((element (org-element-at-point)))
+ (when (equal words
+ (split-string
+ (org-element-property :name element)))
+ (setq type 'dedicated)
+ (beginning-of-line)
+ (throw :name-match t))))
+ nil))))
+ ;; Regular text search. Prefer headlines in Org mode buffers.
+ ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
+ ;; statistics cookies and tags.
+ ((and (derived-mode-p 'org-mode)
+ (let ((title-re
+ (format "%s.*\\(?:%s[ \t]\\)?.*%s"
+ org-outline-regexp-bol
+ org-comment-string
+ (mapconcat #'regexp-quote words ".+")))
+ (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
+ (comment-re (format "\\`%s[ \t]+" org-comment-string)))
+ (goto-char (point-min))
+ (catch :found
+ (while (re-search-forward title-re nil t)
+ (when (equal words
+ (split-string
+ (replace-regexp-in-string
+ cookie-re ""
+ (replace-regexp-in-string
+ comment-re "" (org-get-heading t t)))))
+ (throw :found t)))
+ nil)))
+ (beginning-of-line)
+ (setq type 'dedicated))
+ ;; Offer to create non-existent headline depending on
+ ;; `org-link-search-must-match-exact-headline'.
+ ((and (derived-mode-p 'org-mode)
+ (not org-link-search-inhibit-query)
+ (eq org-link-search-must-match-exact-headline 'query-to-create)
+ (yes-or-no-p "No match - create this as a new heading? "))
+ (goto-char (point-max))
+ (unless (bolp) (newline))
+ (org-insert-heading nil t t)
+ (insert s "\n")
+ (beginning-of-line 0))
+ ;; Only headlines are looked after. No need to process
+ ;; further: throw an error.
+ ((and (derived-mode-p 'org-mode)
+ (or starred org-link-search-must-match-exact-headline))
+ (goto-char origin)
+ (error "No match for fuzzy expression: %s" normalized))
+ ;; Regular text search.
+ ((catch :fuzzy-match
+ (goto-char (point-min))
+ (while (re-search-forward s-multi-re nil t)
+ ;; Skip match if it contains AVOID-POS or it is included in
+ ;; a link with a description but outside the description.
+ (unless (or (and avoid-pos
+ (<= (match-beginning 0) avoid-pos)
+ (> (match-end 0) avoid-pos))
+ (and (save-match-data
+ (org-in-regexp org-bracket-link-regexp))
+ (match-beginning 3)
+ (or (> (match-beginning 3) (point))
+ (<= (match-end 3) (point)))
+ (org-element-lineage
+ (save-match-data (org-element-context))
+ '(link) t)))
+ (goto-char (match-beginning 0))
+ (setq type 'fuzzy)
+ (throw :fuzzy-match t)))
+ nil))
+ ;; All failed. Throw an error.
+ (t (goto-char origin)
+ (error "No match for fuzzy expression: %s" normalized)))
+ ;; Disclose surroundings of match, if appropriate.
+ (when (and (derived-mode-p 'org-mode) (not stealth))
+ (org-show-context 'link-search))
+ type))
+
+(defun org-get-buffer-for-internal-link (buffer)
+ "Return a buffer to be used for displaying the link target of internal links."
+ (cond
+ ((not org-display-internal-link-with-indirect-buffer)
+ buffer)
+ ((string-suffix-p "(Clone)" (buffer-name buffer))
+ (message "Buffer is already a clone, not making another one")
+ ;; we also do not modify visibility in this case
+ buffer)
+ (t ; make a new indirect buffer for displaying the link
+ (let* ((bn (buffer-name buffer))
+ (ibn (concat bn "(Clone)"))
+ (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
+ (with-current-buffer ib (org-overview))
+ ib))))
+
+(defun org-do-occur (regexp &optional cleanup)
+ "Call the Emacs command `occur'.
+If CLEANUP is non-nil, remove the printout of the regular expression
+in the *Occur* buffer. This is useful if the regex is long and not useful
+to read."
+ (occur regexp)
+ (when cleanup
+ (let ((cwin (selected-window)) win beg end)
+ (when (setq win (get-buffer-window "*Occur*"))
+ (select-window win))
+ (goto-char (point-min))
+ (when (re-search-forward "match[a-z]+" nil t)
+ (setq beg (match-end 0))
+ (when (re-search-forward "^[ \t]*[0-9]+" nil t)
+ (setq end (1- (match-beginning 0)))))
+ (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
+ (goto-char (point-min))
+ (select-window cwin))))
+
+;;; The mark ring for links jumps
+
+(defvar org-mark-ring nil
+ "Mark ring for positions before jumps in Org mode.")
+(defvar org-mark-ring-last-goto nil
+ "Last position in the mark ring used to go back.")
+;; Fill and close the ring
+(setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
+(dotimes (_ org-mark-ring-length)
+ (push (make-marker) org-mark-ring))
+(setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
+ org-mark-ring)
+
+(defun org-mark-ring-push (&optional pos buffer)
+ "Put the current position or POS into the mark ring and rotate it."
+ (interactive)
+ (setq pos (or pos (point)))
+ (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
+ (move-marker (car org-mark-ring)
+ (or pos (point))
+ (or buffer (current-buffer)))
+ (message "%s"
+ (substitute-command-keys
+ "Position saved to mark ring, go back with \
+`\\[org-mark-ring-goto]'.")))
+
+(defun org-mark-ring-goto (&optional n)
+ "Jump to the previous position in the mark ring.
+With prefix arg N, jump back that many stored positions. When
+called several times in succession, walk through the entire ring.
+Org mode commands jumping to a different position in the current file,
+or to another Org file, automatically push the old position onto the ring."
+ (interactive "p")
+ (let (p m)
+ (if (eq last-command this-command)
+ (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
+ (setq p org-mark-ring))
+ (setq org-mark-ring-last-goto p)
+ (setq m (car p))
+ (pop-to-buffer-same-window (marker-buffer m))
+ (goto-char m)
+ (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
+
+(defun org-add-angle-brackets (s)
+ (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
+ (unless (equal (substring s -1) ">") (setq s (concat s ">")))
+ s)
+
+;;; Following specific links
+
+(defvar org-agenda-buffer-tmp-name)
+(defvar org-agenda-start-on-weekday)
+(defun org-follow-timestamp-link ()
+ "Open an agenda view for the time-stamp date/range at point."
+ (cond
+ ((org-at-date-range-p t)
+ (let ((org-agenda-start-on-weekday)
+ (t1 (match-string 1))
+ (t2 (match-string 2)) tt1 tt2)
+ (setq tt1 (time-to-days (org-time-string-to-time t1))
+ tt2 (time-to-days (org-time-string-to-time t2)))
+ (let ((org-agenda-buffer-tmp-name
+ (format "*Org Agenda(a:%s)"
+ (concat (substring t1 0 10) "--" (substring t2 0 10)))))
+ (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
+ ((org-at-timestamp-p t)
+ (let ((org-agenda-buffer-tmp-name
+ (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
+ (org-agenda-list nil (time-to-days (org-time-string-to-time
+ (substring (match-string 1) 0 10)))
+ 1)))
+ (t (error "This should not happen"))))
+
+
+;;; Following file links
+(declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
+(declare-function mailcap-extension-to-mime "mailcap" (extn))
+(declare-function mailcap-mime-info
+ "mailcap" (string &optional request no-decode))
+(defvar org-wait nil)
+(defun org-open-file (path &optional in-emacs line search)
+ "Open the file at PATH.
+First, this expands any special file name abbreviations. Then the
+configuration variable `org-file-apps' is checked if it contains an
+entry for this file type, and if yes, the corresponding command is launched.
+
+If no application is found, Emacs simply visits the file.
+
+With optional prefix argument IN-EMACS, Emacs will visit the file.
+With a double \\[universal-argument] \\[universal-argument] \
+prefix arg, Org tries to avoid opening in Emacs
+and to use an external application to visit the file.
+
+Optional LINE specifies a line to go to, optional SEARCH a string
+to search for. If LINE or SEARCH is given, the file will be
+opened in Emacs, unless an entry from org-file-apps that makes
+use of groups in a regexp matches.
+
+If you want to change the way frames are used when following a
+link, please customize `org-link-frame-setup'.
+
+If the file does not exist, an error is thrown."
+ (let* ((file (if (equal path "")
+ buffer-file-name
+ (substitute-in-file-name (expand-file-name path))))
+ (file-apps (append org-file-apps (org-default-apps)))
+ (apps (cl-remove-if
+ 'org-file-apps-entry-match-against-dlink-p file-apps))
+ (apps-dlink (cl-remove-if-not
+ 'org-file-apps-entry-match-against-dlink-p file-apps))
+ (remp (and (assq 'remote apps) (org-file-remote-p file)))
+ (dirp (unless remp (file-directory-p file)))
+ (file (if (and dirp org-open-directory-means-index-dot-org)
+ (concat (file-name-as-directory file) "index.org")
+ file))
+ (a-m-a-p (assq 'auto-mode apps))
+ (dfile (downcase file))
+ ;; Reconstruct the original link from the PATH, LINE and
+ ;; SEARCH args.
+ (link (cond (line (concat file "::" (number-to-string line)))
+ (search (concat file "::" search))
+ (t file)))
+ (dlink (downcase link))
+ (old-buffer (current-buffer))
+ (old-pos (point))
+ (old-mode major-mode)
+ (ext
+ (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
+ (match-string 1 dfile)))
+ cmd link-match-data)
+ (cond
+ ((member in-emacs '((16) system))
+ (setq cmd (cdr (assq 'system apps))))
+ (in-emacs (setq cmd 'emacs))
+ (t
+ (setq cmd (or (and remp (cdr (assq 'remote apps)))
+ (and dirp (cdr (assq 'directory apps)))
+ ;; First, try matching against apps-dlink if we
+ ;; get a match here, store the match data for
+ ;; later.
+ (let ((match (assoc-default dlink apps-dlink
+ 'string-match)))
+ (if match
+ (progn (setq link-match-data (match-data))
+ match)
+ (progn (setq in-emacs (or in-emacs line search))
+ nil))) ; if we have no match in apps-dlink,
+ ; always open the file in emacs if line or search
+ ; is given (for backwards compatibility)
+ (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
+ 'string-match)
+ (cdr (assoc ext apps))
+ (cdr (assq t apps))))))
+ (when (eq cmd 'system)
+ (setq cmd (cdr (assq 'system apps))))
+ (when (eq cmd 'default)
+ (setq cmd (cdr (assoc t apps))))
+ (when (eq cmd 'mailcap)
+ (require 'mailcap)
+ (mailcap-parse-mailcaps)
+ (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
+ (command (mailcap-mime-info mime-type)))
+ (if (stringp command)
+ (setq cmd command)
+ (setq cmd 'emacs))))
+ (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
+ (not (file-exists-p file))
+ (not org-open-non-existing-files))
+ (user-error "No such file: %s" file))
+ (cond
+ ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
+ ;; Remove quotes around the file name - we'll use shell-quote-argument.
+ (while (string-match "['\"]%s['\"]" cmd)
+ (setq cmd (replace-match "%s" t t cmd)))
+ (setq cmd (replace-regexp-in-string
+ "%s"
+ (shell-quote-argument (convert-standard-filename file))
+ cmd
+ nil t))
+
+ ;; Replace "%1", "%2" etc. in command with group matches from regex
+ (save-match-data
+ (let ((match-index 1)
+ (number-of-groups (- (/ (length link-match-data) 2) 1)))
+ (set-match-data link-match-data)
+ (while (<= match-index number-of-groups)
+ (let ((regex (concat "%" (number-to-string match-index)))
+ (replace-with (match-string match-index dlink)))
+ (while (string-match regex cmd)
+ (setq cmd (replace-match replace-with t t cmd))))
+ (setq match-index (+ match-index 1)))))
+
+ (save-window-excursion
+ (message "Running %s...done" cmd)
+ (start-process-shell-command cmd nil cmd)
+ (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
+ ((or (stringp cmd)
+ (eq cmd 'emacs))
+ (funcall (cdr (assq 'file org-link-frame-setup)) file)
+ (widen)
+ (cond (line (org-goto-line line)
+ (when (derived-mode-p 'org-mode) (org-reveal)))
+ (search (org-link-search search))))
+ ((functionp cmd)
+ (save-match-data
+ (set-match-data link-match-data)
+ (condition-case nil
+ (funcall cmd file link)
+ ;; FIXME: Remove this check when most default installations
+ ;; of Emacs have at least Org 9.0.
+ ((debug wrong-number-of-arguments wrong-type-argument
+ invalid-function)
+ (user-error "Please see Org News for version 9.0 about \
+`org-file-apps'--Lisp error: %S" cmd)))))
+ ((consp cmd)
+ ;; FIXME: Remove this check when most default installations of
+ ;; Emacs have at least Org 9.0.
+ ;; Heads-up instead of silently fall back to
+ ;; `org-link-frame-setup' for an old usage of `org-file-apps'
+ ;; with sexp instead of a function for `cmd'.
+ (user-error "Please see Org News for version 9.0 about \
+`org-file-apps'--Error: Deprecated usage of %S" cmd))
+ (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
+ (and (derived-mode-p 'org-mode)
+ (eq old-mode 'org-mode)
+ (or (not (eq old-buffer (current-buffer)))
+ (not (eq old-pos (point))))
+ (org-mark-ring-push old-pos old-buffer))))
+
+(defun org-file-apps-entry-match-against-dlink-p (entry)
+ "This function returns non-nil if `entry' uses a regular
+expression which should be matched against the whole link by
+org-open-file.
+
+It assumes that is the case when the entry uses a regular
+expression which has at least one grouping construct and the
+action is either a lisp form or a command string containing
+`%1', i.e. using at least one subexpression match as a
+parameter."
+ (let ((selector (car entry))
+ (action (cdr entry)))
+ (if (stringp selector)
+ (and (> (regexp-opt-depth selector) 0)
+ (or (and (stringp action)
+ (string-match "%[0-9]" action))
+ (consp action)))
+ nil)))
+
+(defun org-default-apps ()
+ "Return the default applications for this operating system."
+ (cond
+ ((eq system-type 'darwin)
+ org-file-apps-defaults-macosx)
+ ((eq system-type 'windows-nt)
+ org-file-apps-defaults-windowsnt)
+ (t org-file-apps-defaults-gnu)))
+
+(defun org-apps-regexp-alist (list &optional add-auto-mode)
+ "Convert extensions to regular expressions in the cars of LIST.
+Also, weed out any non-string entries, because the return value is used
+only for regexp matching.
+When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
+point to the symbol `emacs', indicating that the file should
+be opened in Emacs."
+ (append
+ (delq nil
+ (mapcar (lambda (x)
+ (unless (not (stringp (car x)))
+ (if (string-match "\\W" (car x))
+ x
+ (cons (concat "\\." (car x) "\\'") (cdr x)))))
+ list))
+ (when add-auto-mode
+ (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
+
+(defvar ange-ftp-name-format)
+(defun org-file-remote-p (file)
+ "Test whether FILE specifies a location on a remote system.
+Return non-nil if the location is indeed remote.
+
+For example, the filename \"/user@host:/foo\" specifies a location
+on the system \"/user@host:\"."
+ (cond ((fboundp 'file-remote-p)
+ (file-remote-p file))
+ ((fboundp 'tramp-handle-file-remote-p)
+ (tramp-handle-file-remote-p file))
+ ((and (boundp 'ange-ftp-name-format)
+ (string-match (car ange-ftp-name-format) file))
+ t)))
+
+
+;;;; Refiling
+
+(defun org-get-org-file ()
+ "Read a filename, with default directory `org-directory'."
+ (let ((default (or org-default-notes-file remember-data-file)))
+ (read-file-name (format "File name [%s]: " default)
+ (file-name-as-directory org-directory)
+ default)))
+
+(defun org-notes-order-reversed-p ()
+ "Check if the current file should receive notes in reversed order."
+ (cond
+ ((not org-reverse-note-order) nil)
+ ((eq t org-reverse-note-order) t)
+ ((not (listp org-reverse-note-order)) nil)
+ (t (catch 'exit
+ (dolist (entry org-reverse-note-order)
+ (when (string-match (car entry) buffer-file-name)
+ (throw 'exit (cdr entry))))))))
+
+(defvar org-refile-target-table nil
+ "The list of refile targets, created by `org-refile'.")
+
+(defvar org-agenda-new-buffers nil
+ "Buffers created to visit agenda files.")
+
+(defvar org-refile-cache nil
+ "Cache for refile targets.")
+
+(defvar org-refile-markers nil
+ "All the markers used for caching refile locations.")
+
+(defun org-refile-marker (pos)
+ "Get a new refile marker, but only if caching is in use."
+ (if (not org-refile-use-cache)
+ pos
+ (let ((m (make-marker)))
+ (move-marker m pos)
+ (push m org-refile-markers)
+ m)))
+
+(defun org-refile-cache-clear ()
+ "Clear the refile cache and disable all the markers."
+ (dolist (m org-refile-markers) (move-marker m nil))
+ (setq org-refile-markers nil)
+ (setq org-refile-cache nil)
+ (message "Refile cache has been cleared"))
+
+(defun org-refile-cache-check-set (set)
+ "Check if all the markers in the cache still have live buffers."
+ (let (marker)
+ (catch 'exit
+ (while (and set (setq marker (nth 3 (pop set))))
+ ;; If `org-refile-use-outline-path' is 'file, marker may be nil
+ (when (and marker (null (marker-buffer marker)))
+ (message "Please regenerate the refile cache with `C-0 C-c C-w'")
+ (sit-for 3)
+ (throw 'exit nil)))
+ t)))
+
+(defun org-refile-cache-put (set &rest identifiers)
+ "Push the refile targets SET into the cache, under IDENTIFIERS."
+ (let* ((key (sha1 (prin1-to-string identifiers)))
+ (entry (assoc key org-refile-cache)))
+ (if entry
+ (setcdr entry set)
+ (push (cons key set) org-refile-cache))))
+
+(defun org-refile-cache-get (&rest identifiers)
+ "Retrieve the cached value for refile targets given by IDENTIFIERS."
+ (cond
+ ((not org-refile-cache) nil)
+ ((not org-refile-use-cache) (org-refile-cache-clear) nil)
+ (t
+ (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
+ org-refile-cache))))
+ (and set (org-refile-cache-check-set set) set)))))
+
+(defvar org-outline-path-cache nil
+ "Alist between buffer positions and outline paths.
+It value is an alist (POSITION . PATH) where POSITION is the
+buffer position at the beginning of an entry and PATH is a list
+of strings describing the outline path for that entry, in reverse
+order.")
+
+(defun org-refile-get-targets (&optional default-buffer)
+ "Produce a table with refile targets."
+ (let ((case-fold-search nil)
+ ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
+ (entries (or org-refile-targets '((nil . (:level . 1)))))
+ targets tgs files desc descre)
+ (message "Getting targets...")
+ (with-current-buffer (or default-buffer (current-buffer))
+ (dolist (entry entries)
+ (setq files (car entry) desc (cdr entry))
+ (cond
+ ((null files) (setq files (list (current-buffer))))
+ ((eq files 'org-agenda-files)
+ (setq files (org-agenda-files 'unrestricted)))
+ ((and (symbolp files) (fboundp files))
+ (setq files (funcall files)))
+ ((and (symbolp files) (boundp files))
+ (setq files (symbol-value files))))
+ (when (stringp files) (setq files (list files)))
+ (cond
+ ((eq (car desc) :tag)
+ (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
+ ((eq (car desc) :todo)
+ (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
+ ((eq (car desc) :regexp)
+ (setq descre (cdr desc)))
+ ((eq (car desc) :level)
+ (setq descre (concat "^\\*\\{" (number-to-string
+ (if org-odd-levels-only
+ (1- (* 2 (cdr desc)))
+ (cdr desc)))
+ "\\}[ \t]")))
+ ((eq (car desc) :maxlevel)
+ (setq descre (concat "^\\*\\{1," (number-to-string
+ (if org-odd-levels-only
+ (1- (* 2 (cdr desc)))
+ (cdr desc)))
+ "\\}[ \t]")))
+ (t (error "Bad refiling target description %s" desc)))
+ (dolist (f files)
+ (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
+ (or
+ (setq tgs (org-refile-cache-get (buffer-file-name) descre))
+ (progn
+ (when (bufferp f)
+ (setq f (buffer-file-name (buffer-base-buffer f))))
+ (setq f (and f (expand-file-name f)))
+ (when (eq org-refile-use-outline-path 'file)
+ (push (list (file-name-nondirectory f) f nil nil) tgs))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (setq org-outline-path-cache nil)
+ (while (re-search-forward descre nil t)
+ (beginning-of-line)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ (let ((begin (point))
+ (heading (match-string-no-properties 4)))
+ (unless (or (and
+ org-refile-target-verify-function
+ (not
+ (funcall org-refile-target-verify-function)))
+ (not heading))
+ (let ((re (format org-complex-heading-regexp-format
+ (regexp-quote heading)))
+ (target
+ (if (not org-refile-use-outline-path) heading
+ (mapconcat
+ #'org-protect-slash
+ (append
+ (pcase org-refile-use-outline-path
+ (`file (list (file-name-nondirectory
+ (buffer-file-name
+ (buffer-base-buffer)))))
+ (`full-file-path
+ (list (buffer-file-name
+ (buffer-base-buffer))))
+ (_ nil))
+ (org-get-outline-path t t))
+ "/"))))
+ (push (list target f re (org-refile-marker (point)))
+ tgs)))
+ (when (= (point) begin)
+ ;; Verification function has not moved point.
+ (end-of-line)))))))
+ (when org-refile-use-cache
+ (org-refile-cache-put tgs (buffer-file-name) descre))
+ (setq targets (append tgs targets))))))
+ (message "Getting targets...done")
+ (delete-dups (nreverse targets))))
+
+(defun org-protect-slash (s)
+ (replace-regexp-in-string "/" "\\/" s nil t))
+
+(defun org--get-outline-path-1 (&optional use-cache)
+ "Return outline path to current headline.
+
+Outline path is a list of strings, in reverse order. When
+optional argument USE-CACHE is non-nil, make use of a cache. See
+`org-get-outline-path' for details.
+
+Assume buffer is widened and point is on a headline."
+ (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
+ (let ((p (point))
+ (heading (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp)
+ (if (not (match-end 4)) ""
+ ;; Remove statistics cookies.
+ (org-trim
+ (org-link-display-format
+ (replace-regexp-in-string
+ "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
+ (match-string-no-properties 4))))))))
+ (if (org-up-heading-safe)
+ (let ((path (cons heading (org--get-outline-path-1 use-cache))))
+ (when use-cache
+ (push (cons p path) org-outline-path-cache))
+ path)
+ ;; This is a new root node. Since we assume we are moving
+ ;; forward, we can drop previous cache so as to limit number
+ ;; of associations there.
+ (let ((path (list heading)))
+ (when use-cache (setq org-outline-path-cache (list (cons p path))))
+ path)))))
+
+(defun org-get-outline-path (&optional with-self use-cache)
+ "Return the outline path to the current entry.
+
+An outline path is a list of ancestors for current headline, as
+a list of strings. Statistics cookies are removed and links are
+replaced with their description, if any, or their path otherwise.
+
+When optional argument WITH-SELF is non-nil, the path also
+includes the current headline.
+
+When optional argument USE-CACHE is non-nil, cache outline paths
+between calls to this function so as to avoid backtracking. This
+argument is useful when planning to find more than one outline
+path in the same document. In that case, there are two
+conditions to satisfy:
+ - `org-outline-path-cache' is set to nil before starting the
+ process;
+ - outline paths are computed by increasing buffer positions."
+ (org-with-wide-buffer
+ (and (or (and with-self (org-back-to-heading t))
+ (org-up-heading-safe))
+ (reverse (org--get-outline-path-1 use-cache)))))
+
+(defun org-format-outline-path (path &optional width prefix separator)
+ "Format the outline path PATH for display.
+WIDTH is the maximum number of characters that is available.
+PREFIX is a prefix to be included in the returned string,
+such as the file name.
+SEPARATOR is inserted between the different parts of the path,
+the default is \"/\"."
+ (setq width (or width 79))
+ (setq path (delq nil path))
+ (unless (> width 0)
+ (user-error "Argument `width' must be positive"))
+ (setq separator (or separator "/"))
+ (let* ((org-odd-levels-only nil)
+ (fpath (concat
+ prefix (and prefix path separator)
+ (mapconcat
+ (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
+ (cl-loop for head in path
+ for n from 0
+ collect (org-add-props
+ head nil 'face
+ (nth (% n org-n-level-faces) org-level-faces)))
+ separator))))
+ (when (> (length fpath) width)
+ (if (< width 7)
+ ;; It's unlikely that `width' will be this small, but don't
+ ;; waste characters by adding ".." if it is.
+ (setq fpath (substring fpath 0 width))
+ (setf (substring fpath (- width 2)) "..")))
+ fpath))
+
+(defun org-display-outline-path (&optional file current separator just-return-string)
+ "Display the current outline path in the echo area.
+
+If FILE is non-nil, prepend the output with the file name.
+If CURRENT is non-nil, append the current heading to the output.
+SEPARATOR is passed through to `org-format-outline-path'. It separates
+the different parts of the path and defaults to \"/\".
+If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
+ (interactive "P")
+ (let* (case-fold-search
+ (bfn (buffer-file-name (buffer-base-buffer)))
+ (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
+ res)
+ (when current (setq path (append path
+ (save-excursion
+ (org-back-to-heading t)
+ (when (looking-at org-complex-heading-regexp)
+ (list (match-string 4)))))))
+ (setq res
+ (org-format-outline-path
+ path
+ (1- (frame-width))
+ (and file bfn (concat (file-name-nondirectory bfn) separator))
+ separator))
+ (if just-return-string
+ (org-no-properties res)
+ (org-unlogged-message "%s" res))))
+
+(defvar org-refile-history nil
+ "History for refiling operations.")
+
+(defvar org-after-refile-insert-hook nil
+ "Hook run after `org-refile' has inserted its stuff at the new location.
+Note that this is still *before* the stuff will be removed from
+the *old* location.")
+
+(defvar org-capture-last-stored-marker)
+(defvar org-refile-keep nil
+ "Non-nil means `org-refile' will copy instead of refile.")
+
+(defun org-copy ()
+ "Like `org-refile', but copy."
+ (interactive)
+ (let ((org-refile-keep t))
+ (funcall 'org-refile nil nil nil "Copy")))
+
+(defun org-refile (&optional arg default-buffer rfloc msg)
+ "Move the entry or entries at point to another heading.
+
+The list of target headings is compiled using the information in
+`org-refile-targets', which see.
+
+At the target location, the entry is filed as a subitem of the
+target heading. Depending on `org-reverse-note-order', the new
+subitem will either be the first or the last subitem.
+
+If there is an active region, all entries in that region will be
+refiled. However, the region must fulfill the requirement that
+the first heading sets the top-level of the moved text.
+
+With a `\\[universal-argument]' ARG, the command will only visit the target \
+location
+and not actually move anything.
+
+With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
+location where the last
+refiling operation has put the subtree.
+
+With a numeric prefix argument of `2', refile to the running clock.
+
+With a numeric prefix argument of `3', emulate `org-refile-keep'
+being set to t and copy to the target location, don't move it.
+Beware that keeping refiled entries may result in duplicated ID
+properties.
+
+RFLOC can be a refile location obtained in a different way.
+
+MSG is a string to replace \"Refile\" in the default prompt with
+another verb. E.g. `org-copy' sets this parameter to \"Copy\".
+
+See also `org-refile-use-outline-path'.
+
+If you are using target caching (see `org-refile-use-cache'), you
+have to clear the target cache in order to find new targets.
+This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
+prefix argument (`C-u C-u C-u C-c C-w')."
+ (interactive "P")
+ (if (member arg '(0 (64)))
+ (org-refile-cache-clear)
+ (let* ((actionmsg (cond (msg msg)
+ ((equal arg 3) "Refile (and keep)")
+ (t "Refile")))
+ (regionp (org-region-active-p))
+ (region-start (and regionp (region-beginning)))
+ (region-end (and regionp (region-end)))
+ (org-refile-keep (if (equal arg 3) t org-refile-keep))
+ pos it nbuf file level reversed)
+ (setq last-command nil)
+ (when regionp
+ (goto-char region-start)
+ (or (bolp) (goto-char (point-at-bol)))
+ (setq region-start (point))
+ (unless (or (org-kill-is-subtree-p
+ (buffer-substring region-start region-end))
+ (prog1 org-refile-active-region-within-subtree
+ (let ((s (point-at-eol)))
+ (org-toggle-heading)
+ (setq region-end (+ (- (point-at-eol) s) region-end)))))
+ (user-error "The region is not a (sequence of) subtree(s)")))
+ (if (equal arg '(16))
+ (org-refile-goto-last-stored)
+ (when (or
+ (and (equal arg 2)
+ org-clock-hd-marker (marker-buffer org-clock-hd-marker)
+ (prog1
+ (setq it (list (or org-clock-heading "running clock")
+ (buffer-file-name
+ (marker-buffer org-clock-hd-marker))
+ ""
+ (marker-position org-clock-hd-marker)))
+ (setq arg nil)))
+ (setq it
+ (or rfloc
+ (let (heading-text)
+ (save-excursion
+ (unless (and arg (listp arg))
+ (org-back-to-heading t)
+ (setq heading-text
+ (replace-regexp-in-string
+ org-bracket-link-regexp
+ "\\3"
+ (or (nth 4 (org-heading-components))
+ ""))))
+ (org-refile-get-location
+ (cond ((and arg (listp arg)) "Goto")
+ (regionp (concat actionmsg " region to"))
+ (t (concat actionmsg " subtree \""
+ heading-text "\" to")))
+ default-buffer
+ (and (not (equal '(4) arg))
+ org-refile-allow-creating-parent-nodes)))))))
+ (setq file (nth 1 it)
+ pos (nth 3 it))
+ (when (and (not arg)
+ pos
+ (equal (buffer-file-name) file)
+ (if regionp
+ (and (>= pos region-start)
+ (<= pos region-end))
+ (and (>= pos (point))
+ (< pos (save-excursion
+ (org-end-of-subtree t t))))))
+ (error "Cannot refile to position inside the tree or region"))
+ (setq nbuf (or (find-buffer-visiting file)
+ (find-file-noselect file)))
+ (if (and arg (not (equal arg 3)))
+ (progn
+ (pop-to-buffer-same-window nbuf)
+ (goto-char pos)
+ (org-show-context 'org-goto))
+ (if regionp
+ (progn
+ (org-kill-new (buffer-substring region-start region-end))
+ (org-save-markers-in-region region-start region-end))
+ (org-copy-subtree 1 nil t))
+ (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
+ (find-file-noselect file)))
+ (setq reversed (org-notes-order-reversed-p))
+ (org-with-wide-buffer
+ (if pos
+ (progn
+ (goto-char pos)
+ (looking-at org-outline-regexp)
+ (setq level (org-get-valid-level (funcall outline-level) 1))
+ (goto-char
+ (if reversed
+ (or (outline-next-heading) (point-max))
+ (or (save-excursion (org-get-next-sibling))
+ (org-end-of-subtree t t)
+ (point-max)))))
+ (setq level 1)
+ (if (not reversed)
+ (goto-char (point-max))
+ (goto-char (point-min))
+ (or (outline-next-heading) (goto-char (point-max)))))
+ (unless (bolp) (newline))
+ (org-paste-subtree level nil nil t)
+ (when org-log-refile
+ (org-add-log-setup 'refile nil nil org-log-refile)
+ (unless (eq org-log-refile 'note)
+ (save-excursion (org-add-log-note))))
+ (and org-auto-align-tags
+ (let ((org-loop-over-headlines-in-active-region nil))
+ (org-set-tags nil t)))
+ (let ((bookmark-name (plist-get org-bookmark-names-plist
+ :last-refile)))
+ (when bookmark-name
+ (with-demoted-errors
+ (bookmark-set bookmark-name))))
+ ;; If we are refiling for capture, make sure that the
+ ;; last-capture pointers point here
+ (when (bound-and-true-p org-capture-is-refiling)
+ (let ((bookmark-name (plist-get org-bookmark-names-plist
+ :last-capture-marker)))
+ (when bookmark-name
+ (with-demoted-errors
+ (bookmark-set bookmark-name))))
+ (move-marker org-capture-last-stored-marker (point)))
+ (when (fboundp 'deactivate-mark) (deactivate-mark))
+ (run-hooks 'org-after-refile-insert-hook)))
+ (unless org-refile-keep
+ (if regionp
+ (delete-region (point) (+ (point) (- region-end region-start)))
+ (delete-region
+ (and (org-back-to-heading t) (point))
+ (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
+ (when (featurep 'org-inlinetask)
+ (org-inlinetask-remove-END-maybe))
+ (setq org-markers-to-move nil)
+ (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
+
+(defun org-refile-goto-last-stored ()
+ "Go to the location where the last refile was stored."
+ (interactive)
+ (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
+ (message "This is the location of the last refile"))
+
+(defun org-refile--get-location (refloc tbl)
+ "When user refile to REFLOC, find the associated target in TBL.
+Also check `org-refile-target-table'."
+ (car (delq
+ nil
+ (mapcar
+ (lambda (r) (or (assoc r tbl)
+ (assoc r org-refile-target-table)))
+ (list (replace-regexp-in-string "/$" "" refloc)
+ (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
+
+(defun org-refile-get-location (&optional prompt default-buffer new-nodes)
+ "Prompt the user for a refile location, using PROMPT.
+PROMPT should not be suffixed with a colon and a space, because
+this function appends the default value from
+`org-refile-history' automatically, if that is not empty."
+ (let ((org-refile-targets org-refile-targets)
+ (org-refile-use-outline-path org-refile-use-outline-path))
+ (setq org-refile-target-table (org-refile-get-targets default-buffer)))
+ (unless org-refile-target-table
+ (user-error "No refile targets"))
+ (let* ((cbuf (current-buffer))
+ (cfn (buffer-file-name (buffer-base-buffer cbuf)))
+ (cfunc (if (and org-refile-use-outline-path
+ org-outline-path-complete-in-steps)
+ #'org-olpath-completing-read
+ #'completing-read))
+ (extra (if org-refile-use-outline-path "/" ""))
+ (cbnex (concat (buffer-name) extra))
+ (filename (and cfn (expand-file-name cfn)))
+ (tbl (mapcar
+ (lambda (x)
+ (if (and (not (member org-refile-use-outline-path
+ '(file full-file-path)))
+ (not (equal filename (nth 1 x))))
+ (cons (concat (car x) extra " ("
+ (file-name-nondirectory (nth 1 x)) ")")
+ (cdr x))
+ (cons (concat (car x) extra) (cdr x))))
+ org-refile-target-table))
+ (completion-ignore-case t)
+ cdef
+ (prompt (concat prompt
+ (or (and (car org-refile-history)
+ (concat " (default " (car org-refile-history) ")"))
+ (and (assoc cbnex tbl) (setq cdef cbnex)
+ (concat " (default " cbnex ")"))) ": "))
+ pa answ parent-target child parent old-hist)
+ (setq old-hist org-refile-history)
+ (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
+ nil 'org-refile-history (or cdef (car org-refile-history))))
+ (if (setq pa (org-refile--get-location answ tbl))
+ (progn
+ (org-refile-check-position pa)
+ (when (or (not org-refile-history)
+ (not (eq old-hist org-refile-history))
+ (not (equal (car pa) (car org-refile-history))))
+ (setq org-refile-history
+ (cons (car pa) (if (assoc (car org-refile-history) tbl)
+ org-refile-history
+ (cdr org-refile-history))))
+ (when (equal (car org-refile-history) (nth 1 org-refile-history))
+ (pop org-refile-history)))
+ pa)
+ (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
+ (progn
+ (setq parent (match-string 1 answ)
+ child (match-string 2 answ))
+ (setq parent-target (org-refile--get-location parent tbl))
+ (when (and parent-target
+ (or (eq new-nodes t)
+ (and (eq new-nodes 'confirm)
+ (y-or-n-p (format "Create new node \"%s\"? "
+ child)))))
+ (org-refile-new-child parent-target child)))
+ (user-error "Invalid target location")))))
+
+(declare-function org-string-nw-p "org-macs" (s))
+(defun org-refile-check-position (refile-pointer)
+ "Check if the refile pointer matches the headline to which it points."
+ (let* ((file (nth 1 refile-pointer))
+ (re (nth 2 refile-pointer))
+ (pos (nth 3 refile-pointer))
+ buffer)
+ (if (and (not (markerp pos)) (not file))
+ (user-error "Please indicate a target file in the refile path")
+ (when (org-string-nw-p re)
+ (setq buffer (if (markerp pos)
+ (marker-buffer pos)
+ (or (find-buffer-visiting file)
+ (find-file-noselect file))))
+ (with-current-buffer buffer
+ (org-with-wide-buffer
+ (goto-char pos)
+ (beginning-of-line 1)
+ (unless (looking-at-p re)
+ (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
+
+(defun org-refile-new-child (parent-target child)
+ "Use refile target PARENT-TARGET to add new CHILD below it."
+ (unless parent-target
+ (error "Cannot find parent for new node"))
+ (let ((file (nth 1 parent-target))
+ (pos (nth 3 parent-target))
+ level)
+ (with-current-buffer (or (find-buffer-visiting file)
+ (find-file-noselect file))
+ (org-with-wide-buffer
+ (if pos
+ (goto-char pos)
+ (goto-char (point-max))
+ (unless (bolp) (newline)))
+ (when (looking-at org-outline-regexp)
+ (setq level (funcall outline-level))
+ (org-end-of-subtree t t))
+ (org-back-over-empty-lines)
+ (insert "\n" (make-string
+ (if pos (org-get-valid-level level 1) 1) ?*)
+ " " child "\n")
+ (beginning-of-line 0)
+ (list (concat (car parent-target) "/" child) file "" (point))))))
+
+(defun org-olpath-completing-read (prompt collection &rest args)
+ "Read an outline path like a file name."
+ (let ((thetable collection))
+ (apply #'completing-read
+ prompt
+ (lambda (string predicate &optional flag)
+ (cond
+ ((eq flag nil) (try-completion string thetable))
+ ((eq flag t)
+ (let ((l (length string)))
+ (mapcar (lambda (x)
+ (let ((r (substring x l))
+ (f (if (string-match " ([^)]*)$" x)
+ (match-string 0 x)
+ "")))
+ (if (string-match "/" r)
+ (concat string (substring r 0 (match-end 0)) f)
+ x)))
+ (all-completions string thetable predicate))))
+ ;; Exact match?
+ ((eq flag 'lambda) (assoc string thetable))))
+ args)))
+
+;;;; Dynamic blocks
+
+(defun org-find-dblock (name)
+ "Find the first dynamic block with name NAME in the buffer.
+If not found, stay at current position and return nil."
+ (let ((case-fold-search t) pos)
+ (save-excursion
+ (goto-char (point-min))
+ (setq pos (and (re-search-forward
+ (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
+ (match-beginning 0))))
+ (when pos (goto-char pos))
+ pos))
+
+(defun org-create-dblock (plist)
+ "Create a dynamic block section, with parameters taken from PLIST.
+PLIST must contain a :name entry which is used as the name of the block."
+ (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
+ (end-of-line 1)
+ (newline))
+ (let ((col (current-column))
+ (name (plist-get plist :name)))
+ (insert "#+BEGIN: " name)
+ (while plist
+ (if (eq (car plist) :name)
+ (setq plist (cddr plist))
+ (insert " " (prin1-to-string (pop plist)))))
+ (insert "\n\n" (make-string col ?\ ) "#+END:\n")
+ (beginning-of-line -2)))
+
+(defun org-prepare-dblock ()
+ "Prepare dynamic block for refresh.
+This empties the block, puts the cursor at the insert position and returns
+the property list including an extra property :name with the block name."
+ (unless (looking-at org-dblock-start-re)
+ (user-error "Not at a dynamic block"))
+ (let* ((begdel (1+ (match-end 0)))
+ (name (org-no-properties (match-string 1)))
+ (params (append (list :name name)
+ (read (concat "(" (match-string 3) ")")))))
+ (save-excursion
+ (beginning-of-line 1)
+ (skip-chars-forward " \t")
+ (setq params (plist-put params :indentation-column (current-column))))
+ (unless (re-search-forward org-dblock-end-re nil t)
+ (error "Dynamic block not terminated"))
+ (setq params
+ (append params
+ (list :content (buffer-substring
+ begdel (match-beginning 0)))))
+ (delete-region begdel (match-beginning 0))
+ (goto-char begdel)
+ (open-line 1)
+ params))
+
+(defun org-map-dblocks (&optional command)
+ "Apply COMMAND to all dynamic blocks in the current buffer.
+If COMMAND is not given, use `org-update-dblock'."
+ (let ((cmd (or command 'org-update-dblock)))
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward org-dblock-start-re nil t)
+ (goto-char (match-beginning 0))
+ (save-excursion
+ (condition-case nil
+ (funcall cmd)
+ (error (message "Error during update of dynamic block"))))
+ (unless (re-search-forward org-dblock-end-re nil t)
+ (error "Dynamic block not terminated"))))))
+
+(defun org-dblock-update (&optional arg)
+ "User command for updating dynamic blocks.
+Update the dynamic block at point. With prefix ARG, update all dynamic
+blocks in the buffer."
+ (interactive "P")
+ (if arg
+ (org-update-all-dblocks)
+ (or (looking-at org-dblock-start-re)
+ (org-beginning-of-dblock))
+ (org-update-dblock)))
+
+(defun org-update-dblock ()
+ "Update the dynamic block at point.
+This means to empty the block, parse for parameters and then call
+the correct writing function."
+ (interactive)
+ (save-excursion
+ (let* ((win (selected-window))
+ (pos (point))
+ (line (org-current-line))
+ (params (org-prepare-dblock))
+ (name (plist-get params :name))
+ (indent (plist-get params :indentation-column))
+ (cmd (intern (concat "org-dblock-write:" name))))
+ (message "Updating dynamic block `%s' at line %d..." name line)
+ (funcall cmd params)
+ (message "Updating dynamic block `%s' at line %d...done" name line)
+ (goto-char pos)
+ (when (and indent (> indent 0))
+ (setq indent (make-string indent ?\ ))
+ (save-excursion
+ (select-window win)
+ (org-beginning-of-dblock)
+ (forward-line 1)
+ (while (not (looking-at org-dblock-end-re))
+ (insert indent)
+ (beginning-of-line 2))
+ (when (looking-at org-dblock-end-re)
+ (and (looking-at "[ \t]+")
+ (replace-match ""))
+ (insert indent)))))))
+
+(defun org-beginning-of-dblock ()
+ "Find the beginning of the dynamic block at point.
+Error if there is no such block at point."
+ (let ((pos (point))
+ beg)
+ (end-of-line 1)
+ (if (and (re-search-backward org-dblock-start-re nil t)
+ (setq beg (match-beginning 0))
+ (re-search-forward org-dblock-end-re nil t)
+ (> (match-end 0) pos))
+ (goto-char beg)
+ (goto-char pos)
+ (error "Not in a dynamic block"))))
+
+(defun org-update-all-dblocks ()
+ "Update all dynamic blocks in the buffer.
+This function can be used in a hook."
+ (interactive)
+ (when (derived-mode-p 'org-mode)
+ (org-map-dblocks 'org-update-dblock)))
+
+
+;;;; Completion
+
+(declare-function org-export-backend-options "ox" (cl-x) t)
+(defun org-get-export-keywords ()
+ "Return a list of all currently understood export keywords.
+Export keywords include options, block names, attributes and
+keywords relative to each registered export back-end."
+ (let (keywords)
+ (dolist (backend
+ (bound-and-true-p org-export-registered-backends)
+ (delq nil keywords))
+ ;; Back-end name (for keywords, like #+LATEX:)
+ (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
+ (dolist (option-entry (org-export-backend-options backend))
+ ;; Back-end options.
+ (push (nth 1 option-entry) keywords)))))
+
+(defconst org-options-keywords
+ '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
+ "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
+ "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
+ "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
+ "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
+
+(defcustom org-structure-template-alist
+ '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
+ ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
+ ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
+ ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
+ ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
+ ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
+ ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
+ ("L" "#+LaTeX: ")
+ ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
+ ("H" "#+HTML: ")
+ ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
+ ("A" "#+ASCII: ")
+ ("i" "#+INDEX: ?")
+ ("I" "#+INCLUDE: %file ?"))
+ "Structure completion elements.
+This is a list of abbreviation keys and values. The value gets inserted
+if you type `<' followed by the key and then press the completion key,
+usually `TAB'. %file will be replaced by a file name after prompting
+for the file using completion. The cursor will be placed at the position
+of the `?' in the template.
+There are two templates for each key, the first uses the original Org syntax,
+the second uses Emacs Muse-like syntax tags. These Muse-like tags become
+the default when the /org-mtags.el/ module has been loaded. See also the
+variable `org-mtags-prefer-muse-templates'."
+ :group 'org-completion
+ :type '(repeat
+ (list
+ (string :tag "Key")
+ (string :tag "Template")))
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+(defun org-try-structure-completion ()
+ "Try to complete a structure template before point.
+This looks for strings like \"<e\" on an otherwise empty line and
+expands them."
+ (let ((l (buffer-substring (point-at-bol) (point)))
+ a)
+ (when (and (looking-at "[ \t]*$")
+ (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
+ (setq a (assoc (match-string 1 l) org-structure-template-alist)))
+ (org-complete-expand-structure-template (+ -1 (point-at-bol)
+ (match-beginning 1)) a)
+ t)))
+
+(defun org-complete-expand-structure-template (start cell)
+ "Expand a structure template."
+ (let ((rpl (nth 1 cell))
+ (ind ""))
+ (delete-region start (point))
+ (when (string-match "\\`[ \t]*#\\+" rpl)
+ (cond
+ ((bolp))
+ ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
+ (setq ind (buffer-substring (point-at-bol) (point))))
+ (t (newline))))
+ (setq start (point))
+ (when (string-match "%file" rpl)
+ (setq rpl (replace-match
+ (concat
+ "\""
+ (save-match-data
+ (abbreviate-file-name (read-file-name "Include file: ")))
+ "\"")
+ t t rpl)))
+ (setq rpl (mapconcat 'identity (split-string rpl "\n")
+ (concat "\n" ind)))
+ (insert rpl)
+ (when (re-search-backward "\\?" start t) (delete-char 1))))
+
+;;;; TODO, DEADLINE, Comments
+
+(defun org-toggle-comment ()
+ "Change the COMMENT state of an entry."
+ (interactive)
+ (save-excursion
+ (org-back-to-heading)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
+ (skip-chars-forward " \t")
+ (unless (memq (char-before) '(?\s ?\t)) (insert " "))
+ (if (org-in-commented-heading-p t)
+ (delete-region (point)
+ (progn (search-forward " " (line-end-position) 'move)
+ (skip-chars-forward " \t")
+ (point)))
+ (insert org-comment-string)
+ (unless (eolp) (insert " ")))))
+
+(defvar org-last-todo-state-is-todo nil
+ "This is non-nil when the last TODO state change led to a TODO state.
+If the last change removed the TODO tag or switched to DONE, then
+this is nil.")
+
+(defvar org-setting-tags nil) ; dynamically skipped
+
+(defvar org-todo-setup-filter-hook nil
+ "Hook for functions that pre-filter todo specs.
+Each function takes a todo spec and returns either nil or the spec
+transformed into canonical form." )
+
+(defvar org-todo-get-default-hook nil
+ "Hook for functions that get a default item for todo.
+Each function takes arguments (NEW-MARK OLD-MARK) and returns either
+nil or a string to be used for the todo mark." )
+
+(defvar org-agenda-headline-snapshot-before-repeat)
+
+(defun org-current-effective-time ()
+ "Return current time adjusted for `org-extend-today-until' variable."
+ (let* ((ct (org-current-time))
+ (dct (decode-time ct))
+ (ct1
+ (cond
+ (org-use-last-clock-out-time-as-effective-time
+ (or (org-clock-get-last-clock-out-time) ct))
+ ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
+ (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
+ (t ct))))
+ ct1))
+
+(defun org-todo-yesterday (&optional arg)
+ "Like `org-todo' but the time of change will be 23:59 of yesterday."
+ (interactive "P")
+ (if (eq major-mode 'org-agenda-mode)
+ (apply 'org-agenda-todo-yesterday arg)
+ (let* ((org-use-effective-time t)
+ (hour (nth 2 (decode-time (org-current-time))))
+ (org-extend-today-until (1+ hour)))
+ (org-todo arg))))
+
+(defvar org-block-entry-blocking ""
+ "First entry preventing the TODO state change.")
+
+(defun org-cancel-repeater ()
+ "Cancel a repeater by setting its numeric value to zero."
+ (interactive)
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((bound1 (point))
+ (bound0 (save-excursion (outline-next-heading) (point))))
+ (when (and (re-search-forward
+ (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
+ org-deadline-time-regexp "\\)\\|\\("
+ org-ts-regexp "\\)")
+ bound0 t)
+ (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
+ bound1 t))
+ (replace-match "0" t nil nil 1)))))
+
+(defvar org-state)
+(defvar org-blocked-by-checkboxes)
+(defun org-todo (&optional arg)
+ "Change the TODO state of an item.
+
+The state of an item is given by a keyword at the start of the heading,
+like
+ *** TODO Write paper
+ *** DONE Call mom
+
+The different keywords are specified in the variable `org-todo-keywords'.
+By default the available states are \"TODO\" and \"DONE\". So, for this
+example: when the item starts with TODO, it is changed to DONE.
+When it starts with DONE, the DONE is removed. And when neither TODO nor
+DONE are present, add TODO at the beginning of the heading.
+
+With `\\[universal-argument]' prefix ARG, use completion to determine the new \
+state.
+With numeric prefix ARG, switch to that state.
+With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
+next set of TODO \
+keywords (nextset).
+With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
+prefix, circumvent any state blocking.
+With a numeric prefix arg of 0, inhibit note taking for the change.
+With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
+
+When called through ELisp, arg is also interpreted in the following way:
+`none' -> empty state
+\"\" -> switch to empty state
+`done' -> switch to DONE
+`nextset' -> switch to the next set of keywords
+`previousset' -> switch to the previous set of keywords
+\"WAITING\" -> switch to the specified keyword, but only if it
+ really is a member of `org-todo-keywords'."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ `(org-todo ,arg)
+ org-loop-over-headlines-in-active-region
+ cl (when (org-invisible-p) (org-end-of-subtree nil t))))
+ (when (equal arg '(16)) (setq arg 'nextset))
+ (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
+ (let ((org-blocker-hook org-blocker-hook)
+ commentp
+ case-fold-search)
+ (when (equal arg '(64))
+ (setq arg nil org-blocker-hook nil))
+ (when (and org-blocker-hook
+ (or org-inhibit-blocking
+ (org-entry-get nil "NOBLOCKING")))
+ (setq org-blocker-hook nil))
+ (save-excursion
+ (catch 'exit
+ (org-back-to-heading t)
+ (when (org-in-commented-heading-p t)
+ (org-toggle-comment)
+ (setq commentp t))
+ (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
+ (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
+ (looking-at "\\(?: *\\|[ \t]*$\\)"))
+ (let* ((match-data (match-data))
+ (startpos (point-at-bol))
+ (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
+ (org-log-done org-log-done)
+ (org-log-repeat org-log-repeat)
+ (org-todo-log-states org-todo-log-states)
+ (org-inhibit-logging
+ (if (equal arg 0)
+ (progn (setq arg nil) 'note) org-inhibit-logging))
+ (this (match-string 1))
+ (hl-pos (match-beginning 0))
+ (head (org-get-todo-sequence-head this))
+ (ass (assoc head org-todo-kwd-alist))
+ (interpret (nth 1 ass))
+ (done-word (nth 3 ass))
+ (final-done-word (nth 4 ass))
+ (org-last-state (or this ""))
+ (completion-ignore-case t)
+ (member (member this org-todo-keywords-1))
+ (tail (cdr member))
+ (org-state (cond
+ ((and org-todo-key-trigger
+ (or (and (equal arg '(4))
+ (eq org-use-fast-todo-selection 'prefix))
+ (and (not arg) org-use-fast-todo-selection
+ (not (eq org-use-fast-todo-selection
+ 'prefix)))))
+ ;; Use fast selection.
+ (org-fast-todo-selection))
+ ((and (equal arg '(4))
+ (or (not org-use-fast-todo-selection)
+ (not org-todo-key-trigger)))
+ ;; Read a state with completion.
+ (completing-read
+ "State: " (mapcar #'list org-todo-keywords-1)
+ nil t))
+ ((eq arg 'right)
+ (if this
+ (if tail (car tail) nil)
+ (car org-todo-keywords-1)))
+ ((eq arg 'left)
+ (unless (equal member org-todo-keywords-1)
+ (if this
+ (nth (- (length org-todo-keywords-1)
+ (length tail) 2)
+ org-todo-keywords-1)
+ (org-last org-todo-keywords-1))))
+ ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
+ (setq arg nil))) ;hack to fall back to cycling
+ (arg
+ ;; User or caller requests a specific state.
+ (cond
+ ((equal arg "") nil)
+ ((eq arg 'none) nil)
+ ((eq arg 'done) (or done-word (car org-done-keywords)))
+ ((eq arg 'nextset)
+ (or (car (cdr (member head org-todo-heads)))
+ (car org-todo-heads)))
+ ((eq arg 'previousset)
+ (let ((org-todo-heads (reverse org-todo-heads)))
+ (or (car (cdr (member head org-todo-heads)))
+ (car org-todo-heads))))
+ ((car (member arg org-todo-keywords-1)))
+ ((stringp arg)
+ (user-error "State `%s' not valid in this file" arg))
+ ((nth (1- (prefix-numeric-value arg))
+ org-todo-keywords-1))))
+ ((null member) (or head (car org-todo-keywords-1)))
+ ((equal this final-done-word) nil) ;-> make empty
+ ((null tail) nil) ;-> first entry
+ ((memq interpret '(type priority))
+ (if (eq this-command last-command)
+ (car tail)
+ (if (> (length tail) 0)
+ (or done-word (car org-done-keywords))
+ nil)))
+ (t
+ (car tail))))
+ (org-state (or
+ (run-hook-with-args-until-success
+ 'org-todo-get-default-hook org-state org-last-state)
+ org-state))
+ (next (if org-state (concat " " org-state " ") " "))
+ (change-plist (list :type 'todo-state-change :from this :to org-state
+ :position startpos))
+ dolog now-done-p)
+ (when org-blocker-hook
+ (let (org-blocked-by-checkboxes block-reason)
+ (setq org-last-todo-state-is-todo
+ (not (member this org-done-keywords)))
+ (unless (save-excursion
+ (save-match-data
+ (org-with-wide-buffer
+ (run-hook-with-args-until-failure
+ 'org-blocker-hook change-plist))))
+ (setq block-reason (if org-blocked-by-checkboxes
+ "contained checkboxes"
+ (format "\"%s\"" org-block-entry-blocking)))
+ (if (called-interactively-p 'interactive)
+ (user-error "TODO state change from %s to %s blocked (by %s)"
+ this org-state block-reason)
+ ;; Fail silently.
+ (message "TODO state change from %s to %s blocked (by %s)"
+ this org-state block-reason)
+ (throw 'exit nil)))))
+ (store-match-data match-data)
+ (replace-match next t t)
+ (cond ((equal this org-state)
+ (message "TODO state was already %s" (org-trim next)))
+ ((pos-visible-in-window-p hl-pos)
+ (message "TODO state changed to %s" (org-trim next))))
+ (unless head
+ (setq head (org-get-todo-sequence-head org-state)
+ ass (assoc head org-todo-kwd-alist)
+ interpret (nth 1 ass)
+ done-word (nth 3 ass)
+ final-done-word (nth 4 ass)))
+ (when (memq arg '(nextset previousset))
+ (message "Keyword-Set %d/%d: %s"
+ (- (length org-todo-sets) -1
+ (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
+ (length org-todo-sets)
+ (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
+ (setq org-last-todo-state-is-todo
+ (not (member org-state org-done-keywords)))
+ (setq now-done-p (and (member org-state org-done-keywords)
+ (not (member this org-done-keywords))))
+ (and logging (org-local-logging logging))
+ (when (and (or org-todo-log-states org-log-done)
+ (not (eq org-inhibit-logging t))
+ (not (memq arg '(nextset previousset))))
+ ;; We need to look at recording a time and note.
+ (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
+ (nth 2 (assoc this org-todo-log-states))))
+ (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
+ (setq dolog 'time))
+ (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
+ (and org-state
+ (member org-state org-not-done-keywords)
+ (not (member this org-not-done-keywords))))
+ ;; This is now a todo state and was not one before
+ ;; If there was a CLOSED time stamp, get rid of it.
+ (org-add-planning-info nil nil 'closed))
+ (when (and now-done-p org-log-done)
+ ;; It is now done, and it was not done before.
+ (org-add-planning-info 'closed (org-current-effective-time))
+ (when (and (not dolog) (eq 'note org-log-done))
+ (org-add-log-setup 'done org-state this 'note)))
+ (when (and org-state dolog)
+ ;; This is a non-nil state, and we need to log it.
+ (org-add-log-setup 'state org-state this dolog)))
+ ;; Fixup tag positioning.
+ (org-todo-trigger-tag-changes org-state)
+ (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
+ (when org-provide-todo-statistics
+ (org-update-parent-todo-statistics))
+ (run-hooks 'org-after-todo-state-change-hook)
+ (when (and arg (not (member org-state org-done-keywords)))
+ (setq head (org-get-todo-sequence-head org-state)))
+ (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
+ ;; Do we need to trigger a repeat?
+ (when now-done-p
+ (when (boundp 'org-agenda-headline-snapshot-before-repeat)
+ ;; This is for the agenda, take a snapshot of the headline.
+ (save-match-data
+ (setq org-agenda-headline-snapshot-before-repeat
+ (org-get-heading))))
+ (org-auto-repeat-maybe org-state))
+ ;; Fixup cursor location if close to the keyword.
+ (when (and (outline-on-heading-p)
+ (not (bolp))
+ (save-excursion (beginning-of-line 1)
+ (looking-at org-todo-line-regexp))
+ (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
+ (goto-char (or (match-end 2) (match-end 1)))
+ (and (looking-at " ") (just-one-space)))
+ (when org-trigger-hook
+ (save-excursion
+ (run-hook-with-args 'org-trigger-hook change-plist)))
+ (when commentp (org-toggle-comment))))))))
+
+(defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
+ "Block turning an entry into a TODO, using the hierarchy.
+This checks whether the current task should be blocked from state
+changes. Such blocking occurs when:
+
+ 1. The task has children which are not all in a completed state.
+
+ 2. A task has a parent with the property :ORDERED:, and there
+ are siblings prior to the current task with incomplete
+ status.
+
+ 3. The parent of the task is blocked because it has siblings that should
+ be done first, or is child of a block grandparent TODO entry."
+
+ (if (not org-enforce-todo-dependencies)
+ t ; if locally turned off don't block
+ (catch 'dont-block
+ ;; If this is not a todo state change, or if this entry is already DONE,
+ ;; do not block
+ (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
+ (member (plist-get change-plist :from)
+ (cons 'done org-done-keywords))
+ (member (plist-get change-plist :to)
+ (cons 'todo org-not-done-keywords))
+ (not (plist-get change-plist :to)))
+ (throw 'dont-block t))
+ ;; If this task has children, and any are undone, it's blocked
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((this-level (funcall outline-level)))
+ (outline-next-heading)
+ (let ((child-level (funcall outline-level)))
+ (while (and (not (eobp))
+ (> child-level this-level))
+ ;; this todo has children, check whether they are all
+ ;; completed
+ (when (and (not (org-entry-is-done-p))
+ (org-entry-is-todo-p))
+ (setq org-block-entry-blocking (org-get-heading))
+ (throw 'dont-block nil))
+ (outline-next-heading)
+ (setq child-level (funcall outline-level))))))
+ ;; Otherwise, if the task's parent has the :ORDERED: property, and
+ ;; any previous siblings are undone, it's blocked
+ (save-excursion
+ (org-back-to-heading t)
+ (let* ((pos (point))
+ (parent-pos (and (org-up-heading-safe) (point)))
+ (case-fold-search nil))
+ (unless parent-pos (throw 'dont-block t)) ; no parent
+ (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
+ (forward-line 1)
+ (re-search-forward org-not-done-heading-regexp pos t))
+ (setq org-block-entry-blocking (match-string 0))
+ (throw 'dont-block nil)) ; block, there is an older sibling not done.
+ ;; Search further up the hierarchy, to see if an ancestor is blocked
+ (while t
+ (goto-char parent-pos)
+ (unless (looking-at org-not-done-heading-regexp)
+ (throw 'dont-block t)) ; do not block, parent is not a TODO
+ (setq pos (point))
+ (setq parent-pos (and (org-up-heading-safe) (point)))
+ (unless parent-pos (throw 'dont-block t)) ; no parent
+ (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
+ (forward-line 1)
+ (re-search-forward org-not-done-heading-regexp pos t)
+ (setq org-block-entry-blocking (org-get-heading)))
+ (throw 'dont-block nil)))))))) ; block, older sibling not done.
+
+(defcustom org-track-ordered-property-with-tag nil
+ "Should the ORDERED property also be shown as a tag?
+The ORDERED property decides if an entry should require subtasks to be
+completed in sequence. Since a property is not very visible, setting
+this option means that toggling the ORDERED property with the command
+`org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
+not relevant for the behavior, but it makes things more visible.
+
+Note that toggling the tag with tags commands will not change the property
+and therefore not influence behavior!
+
+This can be t, meaning the tag ORDERED should be used, It can also be a
+string to select a different tag for this task."
+ :group 'org-todo
+ :type '(choice
+ (const :tag "No tracking" nil)
+ (const :tag "Track with ORDERED tag" t)
+ (string :tag "Use other tag")))
+
+(defun org-toggle-ordered-property ()
+ "Toggle the ORDERED property of the current entry.
+For better visibility, you can track the value of this property with a tag.
+See variable `org-track-ordered-property-with-tag'."
+ (interactive)
+ (let* ((t1 org-track-ordered-property-with-tag)
+ (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
+ (save-excursion
+ (org-back-to-heading)
+ (if (org-entry-get nil "ORDERED")
+ (progn
+ (org-delete-property "ORDERED")
+ (and tag (org-toggle-tag tag 'off))
+ (message "Subtasks can be completed in arbitrary order"))
+ (org-entry-put nil "ORDERED" "t")
+ (and tag (org-toggle-tag tag 'on))
+ (message "Subtasks must be completed in sequence")))))
+
+(defun org-block-todo-from-checkboxes (change-plist)
+ "Block turning an entry into a TODO, using checkboxes.
+This checks whether the current task should be blocked from state
+changes because there are unchecked boxes in this entry."
+ (if (not org-enforce-todo-checkbox-dependencies)
+ t ; if locally turned off don't block
+ (catch 'dont-block
+ ;; If this is not a todo state change, or if this entry is already DONE,
+ ;; do not block
+ (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
+ (member (plist-get change-plist :from)
+ (cons 'done org-done-keywords))
+ (member (plist-get change-plist :to)
+ (cons 'todo org-not-done-keywords))
+ (not (plist-get change-plist :to)))
+ (throw 'dont-block t))
+ ;; If this task has checkboxes that are not checked, it's blocked
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((beg (point)) end)
+ (outline-next-heading)
+ (setq end (point))
+ (goto-char beg)
+ (when (org-list-search-forward
+ (concat (org-item-beginning-re)
+ "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
+ "\\[[- ]\\]")
+ end t)
+ (when (boundp 'org-blocked-by-checkboxes)
+ (setq org-blocked-by-checkboxes t))
+ (throw 'dont-block nil))))
+ t))) ; do not block
+
+(defun org-entry-blocked-p ()
+ "Non-nil if entry at point is blocked."
+ (and (not (org-entry-get nil "NOBLOCKING"))
+ (member (org-entry-get nil "TODO") org-not-done-keywords)
+ (not (run-hook-with-args-until-failure
+ 'org-blocker-hook
+ (list :type 'todo-state-change
+ :position (point)
+ :from 'todo
+ :to 'done)))))
+
+(defun org-update-statistics-cookies (all)
+ "Update the statistics cookie, either from TODO or from checkboxes.
+This should be called with the cursor in a line with a statistics
+cookie. When called with a \\[universal-argument] prefix, update
+all statistics cookies in the buffer."
+ (interactive "P")
+ (if all
+ (progn
+ (org-update-checkbox-count 'all)
+ (org-map-entries 'org-update-parent-todo-statistics))
+ (if (not (org-at-heading-p))
+ (org-update-checkbox-count)
+ (let ((pos (point-marker))
+ end l1 l2)
+ (ignore-errors (org-back-to-heading t))
+ (if (not (org-at-heading-p))
+ (org-update-checkbox-count)
+ (setq l1 (org-outline-level))
+ (setq end (save-excursion
+ (outline-next-heading)
+ (when (org-at-heading-p) (setq l2 (org-outline-level)))
+ (point)))
+ (if (and (save-excursion
+ (re-search-forward
+ "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
+ (not (save-excursion (re-search-forward
+ ":COOKIE_DATA:.*\\<todo\\>" end t))))
+ (org-update-checkbox-count)
+ (if (and l2 (> l2 l1))
+ (progn
+ (goto-char end)
+ (org-update-parent-todo-statistics))
+ (goto-char pos)
+ (beginning-of-line 1)
+ (while (re-search-forward
+ "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
+ (point-at-eol) t)
+ (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
+ (goto-char pos)
+ (move-marker pos nil)))))
+
+(defvar org-entry-property-inherited-from) ;; defined below
+(defun org-update-parent-todo-statistics ()
+ "Update any statistics cookie in the parent of the current headline.
+When `org-hierarchical-todo-statistics' is nil, statistics will cover
+the entire subtree and this will travel up the hierarchy and update
+statistics everywhere."
+ (let* ((prop (save-excursion (org-up-heading-safe)
+ (org-entry-get nil "COOKIE_DATA" 'inherit)))
+ (recursive (or (not org-hierarchical-todo-statistics)
+ (and prop (string-match "\\<recursive\\>" prop))))
+ (lim (or (and prop (marker-position org-entry-property-inherited-from))
+ 0))
+ (first t)
+ (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
+ level ltoggle l1 new ndel
+ (cnt-all 0) (cnt-done 0) is-percent kwd
+ checkbox-beg cookie-present)
+ (catch 'exit
+ (save-excursion
+ (beginning-of-line 1)
+ (setq ltoggle (funcall outline-level))
+ ;; Three situations are to consider:
+
+ ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
+ ;; to the top-level ancestor on the headline;
+
+ ;; 2. If parent has "recursive" property, repeat up to the
+ ;; headline setting that property, taking inheritance into
+ ;; account;
+
+ ;; 3. Else, move up to direct parent and proceed only once.
+ (while (and (setq level (org-up-heading-safe))
+ (or recursive first)
+ (>= (point) lim))
+ (setq first nil cookie-present nil)
+ (unless (and level
+ (not (string-match
+ "\\<checkbox\\>"
+ (downcase (or (org-entry-get nil "COOKIE_DATA")
+ "")))))
+ (throw 'exit nil))
+ (while (re-search-forward box-re (point-at-eol) t)
+ (setq cnt-all 0 cnt-done 0 cookie-present t)
+ (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
+ (save-match-data
+ (unless (outline-next-heading) (throw 'exit nil))
+ (while (and (looking-at org-complex-heading-regexp)
+ (> (setq l1 (length (match-string 1))) level))
+ (setq kwd (and (or recursive (= l1 ltoggle))
+ (match-string 2)))
+ (if (or (eq org-provide-todo-statistics 'all-headlines)
+ (and (eq org-provide-todo-statistics t)
+ (or (member kwd org-done-keywords)))
+ (and (listp org-provide-todo-statistics)
+ (stringp (car org-provide-todo-statistics))
+ (or (member kwd org-provide-todo-statistics)
+ (member kwd org-done-keywords)))
+ (and (listp org-provide-todo-statistics)
+ (listp (car org-provide-todo-statistics))
+ (or (member kwd (car org-provide-todo-statistics))
+ (and (member kwd org-done-keywords)
+ (member kwd (cadr org-provide-todo-statistics))))))
+ (setq cnt-all (1+ cnt-all))
+ (and (eq org-provide-todo-statistics t)
+ kwd
+ (setq cnt-all (1+ cnt-all))))
+ (when (or (and (member org-provide-todo-statistics '(t all-headlines))
+ (member kwd org-done-keywords))
+ (and (listp org-provide-todo-statistics)
+ (listp (car org-provide-todo-statistics))
+ (member kwd org-done-keywords)
+ (member kwd (cadr org-provide-todo-statistics)))
+ (and (listp org-provide-todo-statistics)
+ (stringp (car org-provide-todo-statistics))
+ (member kwd org-done-keywords)))
+ (setq cnt-done (1+ cnt-done)))
+ (outline-next-heading)))
+ (setq new
+ (if is-percent
+ (format "[%d%%]" (floor (* 100.0 cnt-done)
+ (max 1 cnt-all)))
+ (format "[%d/%d]" cnt-done cnt-all))
+ ndel (- (match-end 0) checkbox-beg))
+ (goto-char checkbox-beg)
+ (insert new)
+ (delete-region (point) (+ (point) ndel))
+ (when org-auto-align-tags (org-fix-tags-on-the-fly)))
+ (when cookie-present
+ (run-hook-with-args 'org-after-todo-statistics-hook
+ cnt-done (- cnt-all cnt-done))))))
+ (run-hooks 'org-todo-statistics-hook)))
+
+(defvar org-after-todo-statistics-hook nil
+ "Hook that is called after a TODO statistics cookie has been updated.
+Each function is called with two arguments: the number of not-done entries
+and the number of done entries.
+
+For example, the following function, when added to this hook, will switch
+an entry to DONE when all children are done, and back to TODO when new
+entries are set to a TODO status. Note that this hook is only called
+when there is a statistics cookie in the headline!
+
+ (defun org-summary-todo (n-done n-not-done)
+ \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
+ (let (org-log-done org-log-states) ; turn off logging
+ (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
+")
+
+(defvar org-todo-statistics-hook nil
+ "Hook that is run whenever Org thinks TODO statistics should be updated.
+This hook runs even if there is no statistics cookie present, in which case
+`org-after-todo-statistics-hook' would not run.")
+
+(defun org-todo-trigger-tag-changes (state)
+ "Apply the changes defined in `org-todo-state-tags-triggers'."
+ (let ((l org-todo-state-tags-triggers)
+ changes)
+ (when (or (not state) (equal state ""))
+ (setq changes (append changes (cdr (assoc "" l)))))
+ (when (and (stringp state) (> (length state) 0))
+ (setq changes (append changes (cdr (assoc state l)))))
+ (when (member state org-not-done-keywords)
+ (setq changes (append changes (cdr (assq 'todo l)))))
+ (when (member state org-done-keywords)
+ (setq changes (append changes (cdr (assq 'done l)))))
+ (dolist (c changes)
+ (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
+
+(defun org-local-logging (value)
+ "Get logging settings from a property VALUE."
+ ;; Directly set the variables, they are already local.
+ (setq org-log-done nil
+ org-log-repeat nil
+ org-todo-log-states nil)
+ (dolist (w (org-split-string value))
+ (let (a)
+ (cond
+ ((setq a (assoc w org-startup-options))
+ (and (member (nth 1 a) '(org-log-done org-log-repeat))
+ (set (nth 1 a) (nth 2 a))))
+ ((setq a (org-extract-log-state-settings w))
+ (and (member (car a) org-todo-keywords-1)
+ (push a org-todo-log-states)))))))
+
+(defun org-get-todo-sequence-head (kwd)
+ "Return the head of the TODO sequence to which KWD belongs.
+If KWD is not set, check if there is a text property remembering the
+right sequence."
+ (let (p)
+ (cond
+ ((not kwd)
+ (or (get-text-property (point-at-bol) 'org-todo-head)
+ (progn
+ (setq p (next-single-property-change (point-at-bol) 'org-todo-head
+ nil (point-at-eol)))
+ (get-text-property p 'org-todo-head))))
+ ((not (member kwd org-todo-keywords-1))
+ (car org-todo-keywords-1))
+ (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
+
+(defun org-fast-todo-selection ()
+ "Fast TODO keyword selection with single keys.
+Returns the new TODO keyword, or nil if no state change should occur."
+ (let* ((fulltable org-todo-key-alist)
+ (done-keywords org-done-keywords) ;; needed for the faces.
+ (maxlen (apply 'max (mapcar
+ (lambda (x)
+ (if (stringp (car x)) (string-width (car x)) 0))
+ fulltable)))
+ (expert nil)
+ (fwidth (+ maxlen 3 1 3))
+ (ncol (/ (- (window-width) 4) fwidth))
+ tg cnt e c tbl
+ groups ingroup)
+ (save-excursion
+ (save-window-excursion
+ (if expert
+ (set-buffer (get-buffer-create " *Org todo*"))
+ (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
+ (erase-buffer)
+ (setq-local org-done-keywords done-keywords)
+ (setq tbl fulltable cnt 0)
+ (while (setq e (pop tbl))
+ (cond
+ ((equal e '(:startgroup))
+ (push '() groups) (setq ingroup t)
+ (unless (= cnt 0)
+ (setq cnt 0)
+ (insert "\n"))
+ (insert "{ "))
+ ((equal e '(:endgroup))
+ (setq ingroup nil cnt 0)
+ (insert "}\n"))
+ ((equal e '(:newline))
+ (unless (= cnt 0)
+ (setq cnt 0)
+ (insert "\n")
+ (setq e (car tbl))
+ (while (equal (car tbl) '(:newline))
+ (insert "\n")
+ (setq tbl (cdr tbl)))))
+ (t
+ (setq tg (car e) c (cdr e))
+ (when ingroup (push tg (car groups)))
+ (setq tg (org-add-props tg nil 'face
+ (org-get-todo-face tg)))
+ (when (and (= cnt 0) (not ingroup)) (insert " "))
+ (insert "[" c "] " tg (make-string
+ (- fwidth 4 (length tg)) ?\ ))
+ (when (= (setq cnt (1+ cnt)) ncol)
+ (insert "\n")
+ (when ingroup (insert " "))
+ (setq cnt 0)))))
+ (insert "\n")
+ (goto-char (point-min))
+ (unless expert (org-fit-window-to-buffer))
+ (message "[a-z..]:Set [SPC]:clear")
+ (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
+ (cond
+ ((or (= c ?\C-g)
+ (and (= c ?q) (not (rassoc c fulltable))))
+ (setq quit-flag t))
+ ((= c ?\ ) nil)
+ ((setq e (rassoc c fulltable) tg (car e))
+ tg)
+ (t (setq quit-flag t)))))))
+
+(defun org-entry-is-todo-p ()
+ (member (org-get-todo-state) org-not-done-keywords))
+
+(defun org-entry-is-done-p ()
+ (member (org-get-todo-state) org-done-keywords))
+
+(defun org-get-todo-state ()
+ "Return the TODO keyword of the current subtree."
+ (save-excursion
+ (org-back-to-heading t)
+ (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
+ (match-end 2)
+ (match-string 2))))
+
+(defun org-at-date-range-p (&optional inactive-ok)
+ "Non-nil if point is inside a date range.
+
+When optional argument INACTIVE-OK is non-nil, also consider
+inactive time ranges.
+
+When this function returns a non-nil value, match data is set
+according to `org-tr-regexp-both' or `org-tr-regexp', depending
+on INACTIVE-OK."
+ (interactive)
+ (save-excursion
+ (catch 'exit
+ (let ((pos (point)))
+ (skip-chars-backward "^[<\r\n")
+ (skip-chars-backward "<[")
+ (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
+ (>= (match-end 0) pos)
+ (throw 'exit t))
+ (skip-chars-backward "^<[\r\n")
+ (skip-chars-backward "<[")
+ (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
+ (>= (match-end 0) pos)
+ (throw 'exit t)))
+ nil)))
+
+(defun org-get-repeat (&optional tagline)
+ "Check if there is a deadline/schedule with repeater in this entry."
+ (save-match-data
+ (save-excursion
+ (org-back-to-heading t)
+ (and (re-search-forward (if tagline
+ (concat tagline "\\s-*" org-repeat-re)
+ org-repeat-re)
+ (org-entry-end-position) t)
+ (match-string-no-properties 1)))))
+
+(defvar org-last-changed-timestamp)
+(defvar org-last-inserted-timestamp)
+(defvar org-log-post-message)
+(defvar org-log-note-purpose)
+(defvar org-log-note-how nil)
+(defvar org-log-note-extra)
+(defun org-auto-repeat-maybe (done-word)
+ "Check if the current headline contains a repeated time-stamp.
+
+If yes, set TODO state back to what it was and change the base date
+of repeating deadline/scheduled time stamps to new date.
+
+This function is run automatically after each state change to a DONE state."
+ (let* ((repeat (org-get-repeat))
+ (aa (assoc org-last-state org-todo-kwd-alist))
+ (interpret (nth 1 aa))
+ (head (nth 2 aa))
+ (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
+ (msg "Entry repeats: ")
+ (org-log-done nil)
+ (org-todo-log-states nil))
+ (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
+ (when (eq org-log-repeat t) (setq org-log-repeat 'state))
+ (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
+ org-todo-repeat-to-state)))
+ (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
+ to-state)
+ ((eq interpret 'type) org-last-state)
+ (head)
+ (t 'none))))
+ (when (or org-log-repeat (org-entry-get nil "CLOCK"))
+ (org-entry-put nil "LAST_REPEAT" (format-time-string
+ (org-time-stamp-format t t))))
+ (when org-log-repeat
+ (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
+ (memq 'org-add-log-note post-command-hook))
+ ;; We are already setup for some record.
+ (when (eq org-log-repeat 'note)
+ ;; Make sure we take a note, not only a time stamp.
+ (setq org-log-note-how 'note))
+ ;; Set up for taking a record.
+ (org-add-log-setup 'state
+ (or done-word (car org-done-keywords))
+ org-last-state
+ org-log-repeat)))
+ (org-back-to-heading t)
+ (org-add-planning-info nil nil 'closed)
+ (let ((end (save-excursion (outline-next-heading) (point)))
+ (planning-re (regexp-opt
+ (list org-scheduled-string org-deadline-string))))
+ (while (re-search-forward org-ts-regexp end t)
+ (let* ((ts (match-string 0))
+ (planning? (org-at-planning-p))
+ (type (if (not planning?) "Plain:"
+ (save-excursion
+ (re-search-backward
+ planning-re (line-beginning-position) t)
+ (match-string 0)))))
+ (cond
+ ;; Ignore fake time-stamps (e.g., within comments).
+ ((and (not planning?)
+ (not (org-at-property-p))
+ (not (eq 'timestamp
+ (org-element-type (save-excursion
+ (backward-char)
+ (org-element-context)))))))
+ ;; Time-stamps without a repeater are usually skipped.
+ ;; However, a SCHEDULED time-stamp without one is
+ ;; removed, as it is considered as no longer relevant.
+ ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
+ (when (equal type org-scheduled-string)
+ (org-remove-timestamp-with-keyword type)))
+ (t
+ (let ((n (string-to-number (match-string 2 ts)))
+ (what (match-string 3 ts)))
+ (when (equal what "w") (setq n (* n 7) what "d"))
+ (when (and (equal what "h")
+ (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
+ ts)))
+ (user-error
+ "Cannot repeat in Repeat in %d hour(s) because no hour \
+has been set"
+ n))
+ ;; Preparation, see if we need to modify the start
+ ;; date for the change.
+ (when (match-end 1)
+ (let ((time (save-match-data (org-time-string-to-time ts))))
+ (cond
+ ((equal (match-string 1 ts) ".")
+ ;; Shift starting date to today
+ (org-timestamp-change
+ (- (org-today) (time-to-days time))
+ 'day))
+ ((equal (match-string 1 ts) "+")
+ (let ((nshiftmax 10)
+ (nshift 0))
+ (while (or (= nshift 0)
+ (not (time-less-p (current-time) time)))
+ (when (= (cl-incf nshift) nshiftmax)
+ (or (y-or-n-p
+ (format "%d repeater intervals were not \
+enough to shift date past today. Continue? "
+ nshift))
+ (user-error "Abort")))
+ (org-timestamp-change n (cdr (assoc what whata)))
+ (org-at-timestamp-p t)
+ (setq ts (match-string 1))
+ (setq time
+ (save-match-data
+ (org-time-string-to-time ts)))))
+ (org-timestamp-change (- n) (cdr (assoc what whata)))
+ ;; Rematch, so that we have everything in place
+ ;; for the real shift.
+ (org-at-timestamp-p t)
+ (setq ts (match-string 1))
+ (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
+ ts)))))
+ (save-excursion
+ (org-timestamp-change n (cdr (assoc what whata)) nil t))
+ (setq msg
+ (concat
+ msg type " " org-last-changed-timestamp " "))))))))
+ (setq org-log-post-message msg)
+ (message "%s" msg))))
+
+(defun org-show-todo-tree (arg)
+ "Make a compact tree which shows all headlines marked with TODO.
+The tree will show the lines where the regexp matches, and all higher
+headlines above the match.
+With a `\\[universal-argument]' prefix, prompt for a regexp to match.
+With a numeric prefix N, construct a sparse tree for the Nth element
+of `org-todo-keywords-1'."
+ (interactive "P")
+ (let ((case-fold-search nil)
+ (kwd-re
+ (cond ((null arg) org-not-done-regexp)
+ ((equal arg '(4))
+ (let ((kwd
+ (completing-read "Keyword (or KWD1|KWD2|...): "
+ (mapcar #'list org-todo-keywords-1))))
+ (concat "\\("
+ (mapconcat 'identity (org-split-string kwd "|") "\\|")
+ "\\)\\>")))
+ ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
+ (regexp-quote (nth (1- (prefix-numeric-value arg))
+ org-todo-keywords-1)))
+ (t (user-error "Invalid prefix argument: %s" arg)))))
+ (message "%d TODO entries found"
+ (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
+
+(defun org--deadline-or-schedule (arg type time)
+ "Insert DEADLINE or SCHEDULE information in current entry.
+TYPE is either `deadline' or `scheduled'. See `org-deadline' or
+`org-schedule' for information about ARG and TIME arguments."
+ (let* ((deadline? (eq type 'deadline))
+ (keyword (if deadline? org-deadline-string org-scheduled-string))
+ (log (if deadline? org-log-redeadline org-log-reschedule))
+ (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
+ (old-date-time (and old-date (org-time-string-to-time old-date)))
+ ;; Save repeater cookie from either TIME or current scheduled
+ ;; time stamp. We are going to insert it back at the end of
+ ;; the process.
+ (repeater (or (and (org-string-nw-p time)
+ ;; We use `org-repeat-re' because we need
+ ;; to tell the difference between a real
+ ;; repeater and a time delta, e.g. "+2d".
+ (string-match org-repeat-re time)
+ (match-string 1 time))
+ (and (org-string-nw-p old-date)
+ (string-match "\\([.+-]+[0-9]+[hdwmy]\
+\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
+ old-date)
+ (match-string 1 old-date)))))
+ (pcase arg
+ (`(4)
+ (when (and old-date log)
+ (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
+ nil old-date log))
+ (org-remove-timestamp-with-keyword keyword)
+ (message (if deadline? "Item no longer has a deadline."
+ "Item is no longer scheduled.")))
+ (`(16)
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((regexp (if deadline? org-deadline-time-regexp
+ org-scheduled-time-regexp)))
+ (if (not (re-search-forward regexp (line-end-position 2) t))
+ (user-error (if deadline? "No deadline information to update"
+ "No scheduled information to update"))
+ (let* ((rpl0 (match-string 1))
+ (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
+ (msg (if deadline? "Warn starting from" "Delay until")))
+ (replace-match
+ (concat keyword
+ " <" rpl
+ (format " -%dd"
+ (abs (- (time-to-days
+ (save-match-data
+ (org-read-date
+ nil t nil msg old-date-time)))
+ (time-to-days old-date-time))))
+ ">") t t))))))
+ (_
+ (org-add-planning-info type time 'closed)
+ (when (and old-date
+ log
+ (not (equal old-date org-last-inserted-timestamp)))
+ (org-add-log-setup (if deadline? 'redeadline 'reschedule)
+ org-last-inserted-timestamp
+ old-date
+ log))
+ (when repeater
+ (save-excursion
+ (org-back-to-heading t)
+ (when (re-search-forward
+ (concat keyword " " org-last-inserted-timestamp)
+ (line-end-position 2)
+ t)
+ (goto-char (1- (match-end 0)))
+ (insert " " repeater)
+ (setq org-last-inserted-timestamp
+ (concat (substring org-last-inserted-timestamp 0 -1)
+ " " repeater
+ (substring org-last-inserted-timestamp -1))))))
+ (message (if deadline? "Deadline on %s" "Scheduled to %s")
+ org-last-inserted-timestamp)))))
+
+(defun org-deadline (arg &optional time)
+ "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
+With one universal prefix argument, remove any deadline from the item.
+With two universal prefix arguments, prompt for a warning delay.
+With argument TIME, set the deadline at the corresponding date. TIME
+can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ (lambda () (org--deadline-or-schedule arg 'deadline time))
+ nil
+ (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level
+ 'region)
+ (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
+ (org--deadline-or-schedule arg 'deadline time)))
+
+(defun org-schedule (arg &optional time)
+ "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
+With one universal prefix argument, remove any scheduling date from the item.
+With two universal prefix arguments, prompt for a delay cookie.
+With argument TIME, scheduled at the corresponding date. TIME can
+either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ (lambda () (org--deadline-or-schedule arg 'scheduled time))
+ nil
+ (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level
+ 'region)
+ (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
+ (org--deadline-or-schedule arg 'scheduled time)))
+
+(defun org-get-scheduled-time (pom &optional inherit)
+ "Get the scheduled time as a time tuple, of a format suitable
+for calling org-schedule with, or if there is no scheduling,
+returns nil."
+ (let ((time (org-entry-get pom "SCHEDULED" inherit)))
+ (when time
+ (apply 'encode-time (org-parse-time-string time)))))
+
+(defun org-get-deadline-time (pom &optional inherit)
+ "Get the deadline as a time tuple, of a format suitable for
+calling org-deadline with, or if there is no scheduling, returns
+nil."
+ (let ((time (org-entry-get pom "DEADLINE" inherit)))
+ (when time
+ (apply 'encode-time (org-parse-time-string time)))))
+
+(defun org-remove-timestamp-with-keyword (keyword)
+ "Remove all time stamps with KEYWORD in the current entry."
+ (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
+ beg)
+ (save-excursion
+ (org-back-to-heading t)
+ (setq beg (point))
+ (outline-next-heading)
+ (while (re-search-backward re beg t)
+ (replace-match "")
+ (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
+ (equal (char-before) ?\ ))
+ (backward-delete-char 1)
+ (when (string-match "^[ \t]*$" (buffer-substring
+ (point-at-bol) (point-at-eol)))
+ (delete-region (point-at-bol)
+ (min (point-max) (1+ (point-at-eol))))))))))
+
+(defvar org-time-was-given) ; dynamically scoped parameter
+(defvar org-end-time-was-given) ; dynamically scoped parameter
+
+(defun org-at-planning-p ()
+ "Non-nil when point is on a planning info line."
+ ;; This is as accurate and faster than `org-element-at-point' since
+ ;; planning info location is fixed in the section.
+ (org-with-wide-buffer
+ (beginning-of-line)
+ (and (looking-at-p org-planning-line-re)
+ (eq (point)
+ (ignore-errors
+ (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
+ (org-back-to-heading t)
+ (org-with-limited-levels (org-back-to-heading t)))
+ (line-beginning-position 2))))))
+
+(defun org-add-planning-info (what &optional time &rest remove)
+ "Insert new timestamp with keyword in the planning line.
+WHAT indicates what kind of time stamp to add. It is a symbol
+among `closed', `deadline', `scheduled' and nil. TIME indicates
+the time to use. If none is given, the user is prompted for
+a date. REMOVE indicates what kind of entries to remove. An old
+WHAT entry will also be removed."
+ (let (org-time-was-given org-end-time-was-given default-time default-input)
+ (catch 'exit
+ (when (and (memq what '(scheduled deadline))
+ (or (not time)
+ (and (stringp time)
+ (string-match "^[-+]+[0-9]" time))))
+ ;; Try to get a default date/time from existing timestamp
+ (save-excursion
+ (org-back-to-heading t)
+ (let ((end (save-excursion (outline-next-heading) (point))) ts)
+ (when (re-search-forward (if (eq what 'scheduled)
+ org-scheduled-time-regexp
+ org-deadline-time-regexp)
+ end t)
+ (setq ts (match-string 1)
+ default-time (apply 'encode-time (org-parse-time-string ts))
+ default-input (and ts (org-get-compact-tod ts)))))))
+ (when what
+ (setq time
+ (if (stringp time)
+ ;; This is a string (relative or absolute), set
+ ;; proper date.
+ (apply #'encode-time
+ (org-read-date-analyze
+ time default-time (decode-time default-time)))
+ ;; If necessary, get the time from the user
+ (or time (org-read-date nil 'to-time nil nil
+ default-time default-input)))))
+
+ (org-with-wide-buffer
+ (org-back-to-heading t)
+ (forward-line)
+ (unless (bolp) (insert "\n"))
+ (cond ((looking-at-p org-planning-line-re)
+ ;; Move to current indentation.
+ (skip-chars-forward " \t")
+ ;; Check if we have to remove something.
+ (dolist (type (if what (cons what remove) remove))
+ (save-excursion
+ (when (re-search-forward
+ (cl-case type
+ (closed org-closed-time-regexp)
+ (deadline org-deadline-time-regexp)
+ (scheduled org-scheduled-time-regexp)
+ (otherwise
+ (error "Invalid planning type: %s" type)))
+ (line-end-position) t)
+ ;; Delete until next keyword or end of line.
+ (delete-region
+ (match-beginning 0)
+ (if (re-search-forward org-keyword-time-not-clock-regexp
+ (line-end-position)
+ t)
+ (match-beginning 0)
+ (line-end-position))))))
+ ;; If there is nothing more to add and no more keyword
+ ;; is left, remove the line completely.
+ (if (and (looking-at-p "[ \t]*$") (not what))
+ (delete-region (line-beginning-position)
+ (line-beginning-position 2))
+ ;; If we removed last keyword, do not leave trailing
+ ;; white space at the end of line.
+ (let ((p (point)))
+ (save-excursion
+ (end-of-line)
+ (unless (= (skip-chars-backward " \t" p) 0)
+ (delete-region (point) (line-end-position)))))))
+ ((not what) (throw 'exit nil)) ; Nothing to do.
+ (t (insert-before-markers "\n")
+ (backward-char 1)
+ (when org-adapt-indentation
+ (indent-to-column (1+ (org-outline-level))))))
+ (when what
+ ;; Insert planning keyword.
+ (insert (cl-case what
+ (closed org-closed-string)
+ (deadline org-deadline-string)
+ (scheduled org-scheduled-string)
+ (otherwise (error "Invalid planning type: %s" what)))
+ " ")
+ ;; Insert associated timestamp.
+ (let ((ts (org-insert-time-stamp
+ time
+ (or org-time-was-given
+ (and (eq what 'closed) org-log-done-with-time))
+ (eq what 'closed)
+ nil nil (list org-end-time-was-given))))
+ (unless (eolp) (insert " "))
+ ts))))))
+
+(defvar org-log-note-marker (make-marker)
+ "Marker pointing at the entry where the note is to be inserted.")
+(defvar org-log-note-purpose nil)
+(defvar org-log-note-state nil)
+(defvar org-log-note-previous-state nil)
+(defvar org-log-note-extra nil)
+(defvar org-log-note-window-configuration nil)
+(defvar org-log-note-return-to (make-marker))
+(defvar org-log-note-effective-time nil
+ "Remembered current time so that dynamically scoped
+`org-extend-today-until' affects timestamps in state change log")
+
+(defvar org-log-post-message nil
+ "Message to be displayed after a log note has been stored.
+The auto-repeater uses this.")
+
+(defun org-add-note ()
+ "Add a note to the current entry.
+This is done in the same way as adding a state change note."
+ (interactive)
+ (org-add-log-setup 'note))
+
+(defun org-log-beginning (&optional create)
+ "Return expected start of log notes in current entry.
+When optional argument CREATE is non-nil, the function creates
+a drawer to store notes, if necessary. Returned position ignores
+narrowing."
+ (org-with-wide-buffer
+ (let ((drawer (org-log-into-drawer)))
+ (cond
+ (drawer
+ (org-end-of-meta-data)
+ (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
+ (end (if (org-at-heading-p) (point)
+ (save-excursion (outline-next-heading) (point))))
+ (case-fold-search t))
+ (catch 'exit
+ ;; Try to find existing drawer.
+ (while (re-search-forward regexp end t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'drawer)
+ (let ((cend (org-element-property :contents-end element)))
+ (when (and (not org-log-states-order-reversed) cend)
+ (goto-char cend)))
+ (throw 'exit nil))))
+ ;; No drawer found. Create one, if permitted.
+ (when create
+ (unless (bolp) (insert "\n"))
+ (let ((beg (point)))
+ (insert ":" drawer ":\n:END:\n")
+ (org-indent-region beg (point)))
+ (end-of-line -1)))))
+ (t
+ (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
+ (skip-chars-forward " \t\n")
+ (beginning-of-line)
+ (unless org-log-states-order-reversed
+ (org-skip-over-state-notes)
+ (skip-chars-backward " \t\n")
+ (forward-line)))))
+ (if (bolp) (point) (line-beginning-position 2))))
+
+(defun org-add-log-setup (&optional purpose state prev-state how extra)
+ "Set up the post command hook to take a note.
+If this is about to TODO state change, the new state is expected in STATE.
+HOW is an indicator what kind of note should be created.
+EXTRA is additional text that will be inserted into the notes buffer."
+ (move-marker org-log-note-marker (point))
+ (setq org-log-note-purpose purpose
+ org-log-note-state state
+ org-log-note-previous-state prev-state
+ org-log-note-how how
+ org-log-note-extra extra
+ org-log-note-effective-time (org-current-effective-time))
+ (add-hook 'post-command-hook 'org-add-log-note 'append))
+
+(defun org-skip-over-state-notes ()
+ "Skip past the list of State notes in an entry."
+ (when (ignore-errors (goto-char (org-in-item-p)))
+ (let* ((struct (org-list-struct))
+ (prevs (org-list-prevs-alist struct))
+ (regexp
+ (concat "[ \t]*- +"
+ (replace-regexp-in-string
+ " +" " +"
+ (org-replace-escapes
+ (regexp-quote (cdr (assq 'state org-log-note-headings)))
+ `(("%d" . ,org-ts-regexp-inactive)
+ ("%D" . ,org-ts-regexp)
+ ("%s" . "\"\\S-+\"")
+ ("%S" . "\"\\S-+\"")
+ ("%t" . ,org-ts-regexp-inactive)
+ ("%T" . ,org-ts-regexp)
+ ("%u" . ".*?")
+ ("%U" . ".*?")))))))
+ (while (looking-at-p regexp)
+ (goto-char (or (org-list-get-next-item (point) struct prevs)
+ (org-list-get-item-end (point) struct)))))))
+
+(defun org-add-log-note (&optional _purpose)
+ "Pop up a window for taking a note, and add this note later."
+ (remove-hook 'post-command-hook 'org-add-log-note)
+ (setq org-log-note-window-configuration (current-window-configuration))
+ (delete-other-windows)
+ (move-marker org-log-note-return-to (point))
+ (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
+ (goto-char org-log-note-marker)
+ (org-switch-to-buffer-other-window "*Org Note*")
+ (erase-buffer)
+ (if (memq org-log-note-how '(time state))
+ (let (current-prefix-arg) (org-store-log-note))
+ (let ((org-inhibit-startup t)) (org-mode))
+ (insert (format "# Insert note for %s.
+# Finish with C-c C-c, or cancel with C-c C-k.\n\n"
+ (cond
+ ((eq org-log-note-purpose 'clock-out) "stopped clock")
+ ((eq org-log-note-purpose 'done) "closed todo item")
+ ((eq org-log-note-purpose 'state)
+ (format "state change from \"%s\" to \"%s\""
+ (or org-log-note-previous-state "")
+ (or org-log-note-state "")))
+ ((eq org-log-note-purpose 'reschedule)
+ "rescheduling")
+ ((eq org-log-note-purpose 'delschedule)
+ "no longer scheduled")
+ ((eq org-log-note-purpose 'redeadline)
+ "changing deadline")
+ ((eq org-log-note-purpose 'deldeadline)
+ "removing deadline")
+ ((eq org-log-note-purpose 'refile)
+ "refiling")
+ ((eq org-log-note-purpose 'note)
+ "this entry")
+ (t (error "This should not happen")))))
+ (when org-log-note-extra (insert org-log-note-extra))
+ (setq-local org-finish-function 'org-store-log-note)
+ (run-hooks 'org-log-buffer-setup-hook)))
+
+(defvar org-note-abort nil) ; dynamically scoped
+(defun org-store-log-note ()
+ "Finish taking a log note, and insert it to where it belongs."
+ (let ((txt (prog1 (buffer-string)
+ (kill-buffer)))
+ (note (cdr (assq org-log-note-purpose org-log-note-headings)))
+ lines)
+ (while (string-match "\\`# .*\n[ \t\n]*" txt)
+ (setq txt (replace-match "" t t txt)))
+ (when (string-match "\\s-+\\'" txt)
+ (setq txt (replace-match "" t t txt)))
+ (setq lines (org-split-string txt "\n"))
+ (when (org-string-nw-p note)
+ (setq note
+ (org-replace-escapes
+ note
+ (list (cons "%u" (user-login-name))
+ (cons "%U" user-full-name)
+ (cons "%t" (format-time-string
+ (org-time-stamp-format 'long 'inactive)
+ org-log-note-effective-time))
+ (cons "%T" (format-time-string
+ (org-time-stamp-format 'long nil)
+ org-log-note-effective-time))
+ (cons "%d" (format-time-string
+ (org-time-stamp-format nil 'inactive)
+ org-log-note-effective-time))
+ (cons "%D" (format-time-string
+ (org-time-stamp-format nil nil)
+ org-log-note-effective-time))
+ (cons "%s" (cond
+ ((not org-log-note-state) "")
+ ((string-match-p org-ts-regexp
+ org-log-note-state)
+ (format "\"[%s]\""
+ (substring org-log-note-state 1 -1)))
+ (t (format "\"%s\"" org-log-note-state))))
+ (cons "%S"
+ (cond
+ ((not org-log-note-previous-state) "")
+ ((string-match-p org-ts-regexp
+ org-log-note-previous-state)
+ (format "\"[%s]\""
+ (substring
+ org-log-note-previous-state 1 -1)))
+ (t (format "\"%s\""
+ org-log-note-previous-state)))))))
+ (when lines (setq note (concat note " \\\\")))
+ (push note lines))
+ (when (and lines (not (or current-prefix-arg org-note-abort)))
+ (with-current-buffer (marker-buffer org-log-note-marker)
+ (org-with-wide-buffer
+ ;; Find location for the new note.
+ (goto-char org-log-note-marker)
+ (set-marker org-log-note-marker nil)
+ ;; Note associated to a clock is to be located right after
+ ;; the clock. Do not move point.
+ (unless (eq org-log-note-purpose 'clock-out)
+ (goto-char (org-log-beginning t)))
+ ;; Make sure point is at the beginning of an empty line.
+ (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
+ ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
+ ;; In an existing list, add a new item at the top level.
+ ;; Otherwise, indent line like a regular one.
+ (let ((itemp (org-in-item-p)))
+ (if itemp
+ (indent-line-to
+ (let ((struct (save-excursion
+ (goto-char itemp) (org-list-struct))))
+ (org-list-get-ind (org-list-get-top-point struct) struct)))
+ (org-indent-line)))
+ (insert (org-list-bullet-string "-") (pop lines))
+ (let ((ind (org-list-item-body-column (line-beginning-position))))
+ (dolist (line lines)
+ (insert "\n")
+ (indent-line-to ind)
+ (insert line)))
+ (message "Note stored")
+ (org-back-to-heading t)
+ (org-cycle-hide-drawers 'children))
+ ;; Fix `buffer-undo-list' when `org-store-log-note' is called
+ ;; from within `org-add-log-note' because `buffer-undo-list'
+ ;; is then modified outside of `org-with-remote-undo'.
+ (when (eq this-command 'org-agenda-todo)
+ (setcdr buffer-undo-list (cddr buffer-undo-list))))))
+ ;; Don't add undo information when called from `org-agenda-todo'.
+ (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
+ (set-window-configuration org-log-note-window-configuration)
+ (with-current-buffer (marker-buffer org-log-note-return-to)
+ (goto-char org-log-note-return-to))
+ (move-marker org-log-note-return-to nil)
+ (when org-log-post-message (message "%s" org-log-post-message))))
+
+(defun org-remove-empty-drawer-at (pos)
+ "Remove an empty drawer at position POS.
+POS may also be a marker."
+ (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
+ (org-with-wide-buffer
+ (goto-char pos)
+ (let ((drawer (org-element-at-point)))
+ (when (and (memq (org-element-type drawer) '(drawer property-drawer))
+ (not (org-element-property :contents-begin drawer)))
+ (delete-region (org-element-property :begin drawer)
+ (progn (goto-char (org-element-property :end drawer))
+ (skip-chars-backward " \r\t\n")
+ (forward-line)
+ (point))))))))
+
+(defvar org-ts-type nil)
+(defun org-sparse-tree (&optional arg type)
+ "Create a sparse tree, prompt for the details.
+This command can create sparse trees. You first need to select the type
+of match used to create the tree:
+
+t Show all TODO entries.
+T Show entries with a specific TODO keyword.
+m Show entries selected by a tags/property match.
+p Enter a property name and its value (both with completion on existing
+ names/values) and show entries with that property.
+r Show entries matching a regular expression (`/' can be used as well).
+b Show deadlines and scheduled items before a date.
+a Show deadlines and scheduled items after a date.
+d Show deadlines due within `org-deadline-warning-days'.
+D Show deadlines and scheduled items between a date range."
+ (interactive "P")
+ (setq type (or type org-sparse-tree-default-date-type))
+ (setq org-ts-type type)
+ (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
+ \[d]eadlines [b]efore-date [a]fter-date [D]ates range
+ \[c]ycle through date types: %s"
+ (cl-case type
+ (all "all timestamps")
+ (scheduled "only scheduled")
+ (deadline "only deadline")
+ (active "only active timestamps")
+ (inactive "only inactive timestamps")
+ (closed "with a closed time-stamp")
+ (otherwise "scheduled/deadline")))
+ (let ((answer (read-char-exclusive)))
+ (cl-case answer
+ (?c
+ (org-sparse-tree
+ arg
+ (cadr
+ (memq type '(nil all scheduled deadline active inactive closed)))))
+ (?d (call-interactively 'org-check-deadlines))
+ (?b (call-interactively 'org-check-before-date))
+ (?a (call-interactively 'org-check-after-date))
+ (?D (call-interactively 'org-check-dates-range))
+ (?t (call-interactively 'org-show-todo-tree))
+ (?T (org-show-todo-tree '(4)))
+ (?m (call-interactively 'org-match-sparse-tree))
+ ((?p ?P)
+ (let* ((kwd (completing-read
+ "Property: " (mapcar #'list (org-buffer-property-keys))))
+ (value (completing-read
+ "Value: " (mapcar #'list (org-property-values kwd)))))
+ (unless (string-match "\\`{.*}\\'" value)
+ (setq value (concat "\"" value "\"")))
+ (org-match-sparse-tree arg (concat kwd "=" value))))
+ ((?r ?R ?/) (call-interactively 'org-occur))
+ (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
+
+(defvar-local org-occur-highlights nil
+ "List of overlays used for occur matches.")
+(defvar-local org-occur-parameters nil
+ "Parameters of the active org-occur calls.
+This is a list, each call to org-occur pushes as cons cell,
+containing the regular expression and the callback, onto the list.
+The list can contain several entries if `org-occur' has been called
+several time with the KEEP-PREVIOUS argument. Otherwise, this list
+will only contain one set of parameters. When the highlights are
+removed (for example with `C-c C-c', or with the next edit (depending
+on `org-remove-highlights-with-change'), this variable is emptied
+as well.")
+
+(defun org-occur (regexp &optional keep-previous callback)
+ "Make a compact tree which shows all matches of REGEXP.
+
+The tree will show the lines where the regexp matches, and any other context
+defined in `org-show-context-detail', which see.
+
+When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
+done by a previous call to `org-occur' will be kept, to allow stacking of
+calls to this command.
+
+Optional argument CALLBACK can be a function of no argument. In this case,
+it is called with point at the end of the match, match data being set
+accordingly. Current match is shown only if the return value is non-nil.
+The function must neither move point nor alter narrowing."
+ (interactive "sRegexp: \nP")
+ (when (equal regexp "")
+ (user-error "Regexp cannot be empty"))
+ (unless keep-previous
+ (org-remove-occur-highlights nil nil t))
+ (push (cons regexp callback) org-occur-parameters)
+ (let ((cnt 0))
+ (save-excursion
+ (goto-char (point-min))
+ (when (or (not keep-previous) ; do not want to keep
+ (not org-occur-highlights)) ; no previous matches
+ ;; hide everything
+ (org-overview))
+ (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
+ (isearch-no-upper-case-p regexp t)
+ org-occur-case-fold-search)))
+ (while (re-search-forward regexp nil t)
+ (when (or (not callback)
+ (save-match-data (funcall callback)))
+ (setq cnt (1+ cnt))
+ (when org-highlight-sparse-tree-matches
+ (org-highlight-new-match (match-beginning 0) (match-end 0)))
+ (org-show-context 'occur-tree)))))
+ (when org-remove-highlights-with-change
+ (add-hook 'before-change-functions 'org-remove-occur-highlights
+ nil 'local))
+ (unless org-sparse-tree-open-archived-trees
+ (org-hide-archived-subtrees (point-min) (point-max)))
+ (run-hooks 'org-occur-hook)
+ (when (called-interactively-p 'interactive)
+ (message "%d match(es) for regexp %s" cnt regexp))
+ cnt))
+
+(defun org-occur-next-match (&optional n _reset)
+ "Function for `next-error-function' to find sparse tree matches.
+N is the number of matches to move, when negative move backwards.
+This function always goes back to the starting point when no
+match is found."
+ (let* ((limit (if (< n 0) (point-min) (point-max)))
+ (search-func (if (< n 0)
+ 'previous-single-char-property-change
+ 'next-single-char-property-change))
+ (n (abs n))
+ (pos (point))
+ p1)
+ (catch 'exit
+ (while (setq p1 (funcall search-func (point) 'org-type))
+ (when (equal p1 limit)
+ (goto-char pos)
+ (user-error "No more matches"))
+ (when (equal (get-char-property p1 'org-type) 'org-occur)
+ (setq n (1- n))
+ (when (= n 0)
+ (goto-char p1)
+ (throw 'exit (point))))
+ (goto-char p1))
+ (goto-char p1)
+ (user-error "No more matches"))))
+
+(defun org-show-context (&optional key)
+ "Make sure point and context are visible.
+Optional argument KEY, when non-nil, is a symbol. See
+`org-show-context-detail' for allowed values and how much is to
+be shown."
+ (org-show-set-visibility
+ (cond ((symbolp org-show-context-detail) org-show-context-detail)
+ ((cdr (assq key org-show-context-detail)))
+ (t (cdr (assq 'default org-show-context-detail))))))
+
+(defun org-show-set-visibility (detail)
+ "Set visibility around point according to DETAIL.
+DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
+`tree', `canonical' or t. See `org-show-context-detail' for more
+information."
+ ;; Show current heading and possibly its entry, following headline
+ ;; or all children.
+ (if (and (org-at-heading-p) (not (eq detail 'local)))
+ (org-flag-heading nil)
+ (org-show-entry)
+ ;; If point is hidden within a drawer or a block, make sure to
+ ;; expose it.
+ (dolist (o (overlays-at (point)))
+ (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
+ (delete-overlay o)))
+ (unless (org-before-first-heading-p)
+ (org-with-limited-levels
+ (cl-case detail
+ ((tree canonical t) (org-show-children))
+ ((nil minimal ancestors))
+ (t (save-excursion
+ (outline-next-heading)
+ (org-flag-heading nil)))))))
+ ;; Show all siblings.
+ (when (eq detail 'lineage) (org-show-siblings))
+ ;; Show ancestors, possibly with their children.
+ (when (memq detail '(ancestors lineage tree canonical t))
+ (save-excursion
+ (while (org-up-heading-safe)
+ (org-flag-heading nil)
+ (when (memq detail '(canonical t)) (org-show-entry))
+ (when (memq detail '(tree canonical t)) (org-show-children))))))
+
+(defvar org-reveal-start-hook nil
+ "Hook run before revealing a location.")
+
+(defun org-reveal (&optional siblings)
+ "Show current entry, hierarchy above it, and the following headline.
+
+This can be used to show a consistent set of context around
+locations exposed with `org-show-context'.
+
+With optional argument SIBLINGS, on each level of the hierarchy all
+siblings are shown. This repairs the tree structure to what it would
+look like when opened with hierarchical calls to `org-cycle'.
+
+With a \\[universal-argument] \\[universal-argument] prefix, \
+go to the parent and show the entire tree."
+ (interactive "P")
+ (run-hooks 'org-reveal-start-hook)
+ (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
+ ((equal siblings '(16))
+ (save-excursion
+ (when (org-up-heading-safe)
+ (org-show-subtree)
+ (run-hook-with-args 'org-cycle-hook 'subtree))))
+ (t (org-show-set-visibility 'lineage))))
+
+(defun org-highlight-new-match (beg end)
+ "Highlight from BEG to END and mark the highlight is an occur headline."
+ (let ((ov (make-overlay beg end)))
+ (overlay-put ov 'face 'secondary-selection)
+ (overlay-put ov 'org-type 'org-occur)
+ (push ov org-occur-highlights)))
+
+(defun org-remove-occur-highlights (&optional _beg _end noremove)
+ "Remove the occur highlights from the buffer.
+BEG and END are ignored. If NOREMOVE is nil, remove this function
+from the `before-change-functions' in the current buffer."
+ (interactive)
+ (unless org-inhibit-highlight-removal
+ (mapc #'delete-overlay org-occur-highlights)
+ (setq org-occur-highlights nil)
+ (setq org-occur-parameters nil)
+ (unless noremove
+ (remove-hook 'before-change-functions
+ 'org-remove-occur-highlights 'local))))
+
+;;;; Priorities
+
+(defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
+ "Regular expression matching the priority indicator.")
+
+(defvar org-remove-priority-next-time nil)
+
+(defun org-priority-up ()
+ "Increase the priority of the current item."
+ (interactive)
+ (org-priority 'up))
+
+(defun org-priority-down ()
+ "Decrease the priority of the current item."
+ (interactive)
+ (org-priority 'down))
+
+(defun org-priority (&optional action _show)
+ "Change the priority of an item.
+ACTION can be `set', `up', `down', or a character."
+ (interactive "P")
+ (if (equal action '(4))
+ (org-show-priority)
+ (unless org-enable-priority-commands
+ (user-error "Priority commands are disabled"))
+ (setq action (or action 'set))
+ (let (current new news have remove)
+ (save-excursion
+ (org-back-to-heading t)
+ (when (looking-at org-priority-regexp)
+ (setq current (string-to-char (match-string 2))
+ have t))
+ (cond
+ ((eq action 'remove)
+ (setq remove t new ?\ ))
+ ((or (eq action 'set)
+ (integerp action))
+ (if (not (eq action 'set))
+ (setq new action)
+ (message "Priority %c-%c, SPC to remove: "
+ org-highest-priority org-lowest-priority)
+ (save-match-data
+ (setq new (read-char-exclusive))))
+ (when (and (= (upcase org-highest-priority) org-highest-priority)
+ (= (upcase org-lowest-priority) org-lowest-priority))
+ (setq new (upcase new)))
+ (cond ((equal new ?\ ) (setq remove t))
+ ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
+ (user-error "Priority must be between `%c' and `%c'"
+ org-highest-priority org-lowest-priority))))
+ ((eq action 'up)
+ (setq new (if have
+ (1- current) ; normal cycling
+ ;; last priority was empty
+ (if (eq last-command this-command)
+ org-lowest-priority ; wrap around empty to lowest
+ ;; default
+ (if org-priority-start-cycle-with-default
+ org-default-priority
+ (1- org-default-priority))))))
+ ((eq action 'down)
+ (setq new (if have
+ (1+ current) ; normal cycling
+ ;; last priority was empty
+ (if (eq last-command this-command)
+ org-highest-priority ; wrap around empty to highest
+ ;; default
+ (if org-priority-start-cycle-with-default
+ org-default-priority
+ (1+ org-default-priority))))))
+ (t (user-error "Invalid action")))
+ (when (or (< (upcase new) org-highest-priority)
+ (> (upcase new) org-lowest-priority))
+ (if (and (memq action '(up down))
+ (not have) (not (eq last-command this-command)))
+ ;; `new' is from default priority
+ (error
+ "The default can not be set, see `org-default-priority' why")
+ ;; normal cycling: `new' is beyond highest/lowest priority
+ ;; and is wrapped around to the empty priority
+ (setq remove t)))
+ (setq news (format "%c" new))
+ (if have
+ (if remove
+ (replace-match "" t t nil 1)
+ (replace-match news t t nil 2))
+ (if remove
+ (user-error "No priority cookie found in line")
+ (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
+ (if (match-end 2)
+ (progn
+ (goto-char (match-end 2))
+ (insert " [#" news "]"))
+ (goto-char (match-beginning 3))
+ (insert "[#" news "] "))))
+ (org-set-tags nil 'align))
+ (if remove
+ (message "Priority removed")
+ (message "Priority of current item set to %s" news)))))
+
+(defun org-show-priority ()
+ "Show the priority of the current item.
+This priority is composed of the main priority given with the [#A] cookies,
+and by additional input from the age of a schedules or deadline entry."
+ (interactive)
+ (let ((pri (if (eq major-mode 'org-agenda-mode)
+ (org-get-at-bol 'priority)
+ (save-excursion
+ (save-match-data
+ (beginning-of-line)
+ (and (looking-at org-heading-regexp)
+ (org-get-priority (match-string 0))))))))
+ (message "Priority is %d" (if pri pri -1000))))
+
+(defun org-get-priority (s)
+ "Find priority cookie and return priority."
+ (save-match-data
+ (if (functionp org-get-priority-function)
+ (funcall org-get-priority-function)
+ (if (not (string-match org-priority-regexp s))
+ (* 1000 (- org-lowest-priority org-default-priority))
+ (* 1000 (- org-lowest-priority
+ (string-to-char (match-string 2 s))))))))
+
+;;;; Tags
+
+(defvar org-agenda-archives-mode)
+(defvar org-map-continue-from nil
+ "Position from where mapping should continue.
+Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
+
+(defvar org-scanner-tags nil
+ "The current tag list while the tags scanner is running.")
+
+(defvar org-trust-scanner-tags nil
+ "Should `org-get-tags-at' use the tags for the scanner.
+This is for internal dynamical scoping only.
+When this is non-nil, the function `org-get-tags-at' will return the value
+of `org-scanner-tags' instead of building the list by itself. This
+can lead to large speed-ups when the tags scanner is used in a file with
+many entries, and when the list of tags is retrieved, for example to
+obtain a list of properties. Building the tags list for each entry in such
+a file becomes an N^2 operation - but with this variable set, it scales
+as N.")
+
+(defvar org--matcher-tags-todo-only nil)
+
+(defun org-scan-tags (action matcher todo-only &optional start-level)
+ "Scan headline tags with inheritance and produce output ACTION.
+
+ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
+or `agenda' to produce an entry list for an agenda view. It can also be
+a Lisp form or a function that should be called at each matched headline, in
+this case the return value is a list of all return values from these calls.
+
+MATCHER is a function accepting three arguments, returning
+a non-nil value whenever a given set of tags qualifies a headline
+for inclusion. See `org-make-tags-matcher' for more information.
+As a special case, it can also be set to t (respectively nil) in
+order to match all (respectively none) headline.
+
+When TODO-ONLY is non-nil, only lines with a not-done TODO
+keyword are included in the output.
+
+START-LEVEL can be a string with asterisks, reducing the scope to
+headlines matching this string."
+ (require 'org-agenda)
+ (let* ((re (concat "^"
+ (if start-level
+ ;; Get the correct level to match
+ (concat "\\*\\{" (number-to-string start-level) "\\} ")
+ org-outline-regexp)
+ " *\\(\\<\\("
+ (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
+ "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
+ (props (list 'face 'default
+ 'done-face 'org-agenda-done
+ 'undone-face 'default
+ 'mouse-face 'highlight
+ 'org-not-done-regexp org-not-done-regexp
+ 'org-todo-regexp org-todo-regexp
+ 'org-complex-heading-regexp org-complex-heading-regexp
+ 'help-echo
+ (format "mouse-2 or RET jump to org file %s"
+ (abbreviate-file-name
+ (or (buffer-file-name (buffer-base-buffer))
+ (buffer-name (buffer-base-buffer)))))))
+ (org-map-continue-from nil)
+ lspos tags tags-list
+ (tags-alist (list (cons 0 org-file-tags)))
+ (llast 0) rtn rtn1 level category i txt
+ todo marker entry priority
+ ts-date ts-date-type ts-date-pair)
+ (unless (or (member action '(agenda sparse-tree)) (functionp action))
+ (setq action (list 'lambda nil action)))
+ (save-excursion
+ (goto-char (point-min))
+ (when (eq action 'sparse-tree)
+ (org-overview)
+ (org-remove-occur-highlights))
+ (while (let (case-fold-search)
+ (re-search-forward re nil t))
+ (setq org-map-continue-from nil)
+ (catch :skip
+ (setq todo
+ ;; TODO: is the 1-2 difference a bug?
+ (when (match-end 1) (match-string-no-properties 2))
+ tags (when (match-end 4) (match-string-no-properties 4)))
+ (goto-char (setq lspos (match-beginning 0)))
+ (setq level (org-reduced-level (org-outline-level))
+ category (org-get-category))
+ (when (eq action 'agenda)
+ (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
+ ts-date (car ts-date-pair)
+ ts-date-type (cdr ts-date-pair)))
+ (setq i llast llast level)
+ ;; remove tag lists from same and sublevels
+ (while (>= i level)
+ (when (setq entry (assoc i tags-alist))
+ (setq tags-alist (delete entry tags-alist)))
+ (setq i (1- i)))
+ ;; add the next tags
+ (when tags
+ (setq tags (org-split-string tags ":")
+ tags-alist
+ (cons (cons level tags) tags-alist)))
+ ;; compile tags for current headline
+ (setq tags-list
+ (if org-use-tag-inheritance
+ (apply 'append (mapcar 'cdr (reverse tags-alist)))
+ tags)
+ org-scanner-tags tags-list)
+ (when org-use-tag-inheritance
+ (setcdr (car tags-alist)
+ (mapcar (lambda (x)
+ (setq x (copy-sequence x))
+ (org-add-prop-inherited x))
+ (cdar tags-alist))))
+ (when (and tags org-use-tag-inheritance
+ (or (not (eq t org-use-tag-inheritance))
+ org-tags-exclude-from-inheritance))
+ ;; Selective inheritance, remove uninherited ones.
+ (setcdr (car tags-alist)
+ (org-remove-uninherited-tags (cdar tags-alist))))
+ (when (and
+
+ ;; eval matcher only when the todo condition is OK
+ (and (or (not todo-only) (member todo org-not-done-keywords))
+ (if (functionp matcher)
+ (let ((case-fold-search t) (org-trust-scanner-tags t))
+ (funcall matcher todo tags-list level))
+ matcher))
+
+ ;; Call the skipper, but return t if it does not
+ ;; skip, so that the `and' form continues evaluating.
+ (progn
+ (unless (eq action 'sparse-tree) (org-agenda-skip))
+ t)
+
+ ;; Check if timestamps are deselecting this entry
+ (or (not todo-only)
+ (and (member todo org-not-done-keywords)
+ (or (not org-agenda-tags-todo-honor-ignore-options)
+ (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
+
+ ;; select this headline
+ (cond
+ ((eq action 'sparse-tree)
+ (and org-highlight-sparse-tree-matches
+ (org-get-heading) (match-end 0)
+ (org-highlight-new-match
+ (match-beginning 1) (match-end 1)))
+ (org-show-context 'tags-tree))
+ ((eq action 'agenda)
+ (setq txt (org-agenda-format-item
+ ""
+ (concat
+ (if (eq org-tags-match-list-sublevels 'indented)
+ (make-string (1- level) ?.) "")
+ (org-get-heading))
+ (make-string level ?\s)
+ category
+ tags-list)
+ priority (org-get-priority txt))
+ (goto-char lspos)
+ (setq marker (org-agenda-new-marker))
+ (org-add-props txt props
+ 'org-marker marker 'org-hd-marker marker 'org-category category
+ 'todo-state todo
+ 'ts-date ts-date
+ 'priority priority
+ 'type (concat "tagsmatch" ts-date-type))
+ (push txt rtn))
+ ((functionp action)
+ (setq org-map-continue-from nil)
+ (save-excursion
+ (setq rtn1 (funcall action))
+ (push rtn1 rtn)))
+ (t (user-error "Invalid action")))
+
+ ;; if we are to skip sublevels, jump to end of subtree
+ (unless org-tags-match-list-sublevels
+ (org-end-of-subtree t)
+ (backward-char 1))))
+ ;; Get the correct position from where to continue
+ (if org-map-continue-from
+ (goto-char org-map-continue-from)
+ (and (= (point) lspos) (end-of-line 1)))))
+ (when (and (eq action 'sparse-tree)
+ (not org-sparse-tree-open-archived-trees))
+ (org-hide-archived-subtrees (point-min) (point-max)))
+ (nreverse rtn)))
+
+(defun org-remove-uninherited-tags (tags)
+ "Remove all tags that are not inherited from the list TAGS."
+ (cond
+ ((eq org-use-tag-inheritance t)
+ (if org-tags-exclude-from-inheritance
+ (org-delete-all org-tags-exclude-from-inheritance tags)
+ tags))
+ ((not org-use-tag-inheritance) nil)
+ ((stringp org-use-tag-inheritance)
+ (delq nil (mapcar
+ (lambda (x)
+ (if (and (string-match org-use-tag-inheritance x)
+ (not (member x org-tags-exclude-from-inheritance)))
+ x nil))
+ tags)))
+ ((listp org-use-tag-inheritance)
+ (delq nil (mapcar
+ (lambda (x)
+ (if (member x org-use-tag-inheritance) x nil))
+ tags)))))
+
+(defun org-match-sparse-tree (&optional todo-only match)
+ "Create a sparse tree according to tags string MATCH.
+
+MATCH is a string with match syntax. It can contain a selection
+of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
+TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
+those. See the manual for details.
+
+If optional argument TODO-ONLY is non-nil, only select lines that
+are also TODO tasks."
+ (interactive "P")
+ (org-agenda-prepare-buffers (list (current-buffer)))
+ (let ((org--matcher-tags-todo-only todo-only))
+ (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
+ org--matcher-tags-todo-only)))
+
+(defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
+
+(defvar org-cached-props nil)
+(defun org-cached-entry-get (pom property)
+ (if (or (eq t org-use-property-inheritance)
+ (and (stringp org-use-property-inheritance)
+ (let ((case-fold-search t))
+ (string-match-p org-use-property-inheritance property)))
+ (and (listp org-use-property-inheritance)
+ (member-ignore-case property org-use-property-inheritance)))
+ ;; Caching is not possible, check it directly.
+ (org-entry-get pom property 'inherit)
+ ;; Get all properties, so we can do complicated checks easily.
+ (cdr (assoc-string property
+ (or org-cached-props
+ (setq org-cached-props (org-entry-properties pom)))
+ t))))
+
+(defun org-global-tags-completion-table (&optional files)
+ "Return the list of all tags in all agenda buffer/files.
+Optional FILES argument is a list of files which can be used
+instead of the agenda files."
+ (save-excursion
+ (org-uniquify
+ (delq nil
+ (apply #'append
+ (mapcar
+ (lambda (file)
+ (set-buffer (find-file-noselect file))
+ (mapcar (lambda (x)
+ (and (stringp (car-safe x))
+ (list (car-safe x))))
+ (or org-current-tag-alist (org-get-buffer-tags))))
+ (if (car-safe files) files
+ (org-agenda-files))))))))
+
+(defun org-make-tags-matcher (match)
+ "Create the TAGS/TODO matcher form for the selection string MATCH.
+
+Returns a cons of the selection string MATCH and a function
+implementing the matcher.
+
+The matcher is to be called at an Org entry, with point on the
+headline, and returns non-nil if the entry matches the selection
+string MATCH. It must be called with three arguments: the TODO
+keyword at the entry (or nil if none), the list of all tags at
+the entry including inherited ones and the reduced level of the
+headline. Additionally, the category of the entry, if any, must
+be specified as the text property `org-category' on the headline.
+
+This function sets the variable `org--matcher-tags-todo-only' to
+a non-nil value if the matcher restricts matching to TODO
+entries, otherwise it is not touched.
+
+See also `org-scan-tags'."
+ (unless match
+ ;; Get a new match request, with completion against the global
+ ;; tags table and the local tags in current buffer.
+ (let ((org-last-tags-completion-table
+ (org-uniquify
+ (delq nil (append (org-get-buffer-tags)
+ (org-global-tags-completion-table))))))
+ (setq match
+ (completing-read
+ "Match: "
+ 'org-tags-completion-function nil nil nil 'org-tags-history))))
+
+ (let ((match0 match)
+ (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
+ (start 0)
+ tagsmatch todomatch tagsmatcher todomatcher)
+
+ ;; Expand group tags.
+ (setq match (org-tags-expand match))
+
+ ;; Check if there is a TODO part of this match, which would be the
+ ;; part after a "/". To make sure that this slash is not part of
+ ;; a property value to be matched against, we also check that
+ ;; there is no / after that slash. First, find the last slash.
+ (let ((s 0))
+ (while (string-match "/+" match s)
+ (setq start (match-beginning 0))
+ (setq s (match-end 0))))
+ (if (and (string-match "/+" match start)
+ (not (string-match-p "\"" match start)))
+ ;; Match contains also a TODO-matching request.
+ (progn
+ (setq tagsmatch (substring match 0 (match-beginning 0)))
+ (setq todomatch (substring match (match-end 0)))
+ (when (string-prefix-p "!" todomatch)
+ (setq org--matcher-tags-todo-only t)
+ (setq todomatch (substring todomatch 1)))
+ (when (string-match "\\`\\s-*\\'" todomatch)
+ (setq todomatch nil)))
+ ;; Only matching tags.
+ (setq tagsmatch match)
+ (setq todomatch nil))
+
+ ;; Make the tags matcher.
+ (when (org-string-nw-p tagsmatch)
+ (let ((orlist nil)
+ (orterms (org-split-string tagsmatch "|"))
+ term)
+ (while (setq term (pop orterms))
+ (while (and (equal (substring term -1) "\\") orterms)
+ (setq term (concat term "|" (pop orterms)))) ;repair bad split.
+ (while (string-match re term)
+ (let* ((rest (substring term (match-end 0)))
+ (minus (and (match-end 1)
+ (equal (match-string 1 term) "-")))
+ (tag (save-match-data
+ (replace-regexp-in-string
+ "\\\\-" "-" (match-string 2 term))))
+ (regexp (eq (string-to-char tag) ?{))
+ (levelp (match-end 4))
+ (propp (match-end 5))
+ (mm
+ (cond
+ (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
+ (levelp
+ `(,(org-op-to-function (match-string 3 term))
+ level
+ ,(string-to-number (match-string 4 term))))
+ (propp
+ (let* ((gv (pcase (upcase (match-string 5 term))
+ ("CATEGORY"
+ '(get-text-property (point) 'org-category))
+ ("TODO" 'todo)
+ (p `(org-cached-entry-get nil ,p))))
+ (pv (match-string 7 term))
+ (regexp (eq (string-to-char pv) ?{))
+ (strp (eq (string-to-char pv) ?\"))
+ (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
+ (po (org-op-to-function (match-string 6 term)
+ (if timep 'time strp))))
+ (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
+ (when timep (setq pv (org-matcher-time pv)))
+ (cond ((and regexp (eq po 'org<>))
+ `(not (string-match ,pv (or ,gv ""))))
+ (regexp `(string-match ,pv (or ,gv "")))
+ (strp `(,po (or ,gv "") ,pv))
+ (t
+ `(,po
+ (string-to-number (or ,gv ""))
+ ,(string-to-number pv))))))
+ (t `(member ,tag tags-list)))))
+ (push (if minus `(not ,mm) mm) tagsmatcher)
+ (setq term rest)))
+ (push `(and ,@tagsmatcher) orlist)
+ (setq tagsmatcher nil))
+ (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
+
+ ;; Make the TODO matcher.
+ (when (org-string-nw-p todomatch)
+ (let ((orlist nil))
+ (dolist (term (org-split-string todomatch "|"))
+ (while (string-match re term)
+ (let* ((minus (and (match-end 1)
+ (equal (match-string 1 term) "-")))
+ (kwd (match-string 2 term))
+ (regexp (eq (string-to-char kwd) ?{))
+ (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
+ `(equal todo ,kwd))))
+ (push (if minus `(not ,mm) mm) todomatcher))
+ (setq term (substring term (match-end 0))))
+ (push (if (> (length todomatcher) 1)
+ (cons 'and todomatcher)
+ (car todomatcher))
+ orlist)
+ (setq todomatcher nil))
+ (setq todomatcher (cons 'or orlist))))
+
+ ;; Return the string and function of the matcher. If no
+ ;; tags-specific or todo-specific matcher exists, match
+ ;; everything.
+ (let ((matcher (if (and tagsmatcher todomatcher)
+ `(and ,tagsmatcher ,todomatcher)
+ (or tagsmatcher todomatcher t))))
+ (when org--matcher-tags-todo-only
+ (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
+ (cons match0 `(lambda (todo tags-list level) ,matcher)))))
+
+(defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
+ "Expand group tags in MATCH.
+
+This replaces every group tag in MATCH with a regexp tag search.
+For example, a group tag \"Work\" defined as { Work : Lab Conf }
+will be replaced like this:
+
+ Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
+ +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
+ -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
+
+Replacing by a regexp preserves the structure of the match.
+E.g., this expansion
+
+ Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
+
+will match anything tagged with \"Lab\" and \"Home\", or tagged
+with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
+
+A group tag in MATCH can contain regular expressions of its own.
+For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
+will be replaced like this:
+
+ Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
+
+When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
+assumed to be a single group tag, and the function will return
+the list of tags in this group.
+
+When DOWNCASE is non-nil, expand downcased TAGS."
+ (if org-group-tags
+ (let* ((case-fold-search t)
+ (stable org-mode-syntax-table)
+ (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
+ (taggroups (if downcased
+ (mapcar (lambda (tg) (mapcar #'downcase tg))
+ taggroups)
+ taggroups))
+ (taggroups-keys (mapcar #'car taggroups))
+ (return-match (if downcased (downcase match) match))
+ (count 0)
+ (work-already-expanded tags-already-expanded)
+ regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
+ ;; @ and _ are allowed as word-components in tags.
+ (modify-syntax-entry ?@ "w" stable)
+ (modify-syntax-entry ?_ "w" stable)
+ ;; Temporarily replace regexp-expressions in the match-expression.
+ (while (string-match "{.+?}" return-match)
+ (cl-incf count)
+ (push (match-string 0 return-match) regexps-in-match)
+ (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
+ (while (and taggroups-keys
+ (with-syntax-table stable
+ (string-match
+ (concat "\\(?1:[+-]?\\)\\(?2:\\<"
+ (regexp-opt taggroups-keys) "\\>\\)")
+ return-match)))
+ (let* ((dir (match-string 1 return-match))
+ (tag (match-string 2 return-match))
+ (tag (if downcased (downcase tag) tag)))
+ (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
+ (member tag work-already-expanded))
+ (setq tags-in-group (assoc tag taggroups))
+ (push tag work-already-expanded)
+ ;; Recursively expand each tag in the group, if the tag hasn't
+ ;; already been expanded. Restore the match-data after all recursive calls.
+ (save-match-data
+ (let (tags-expanded)
+ (dolist (x (cdr tags-in-group))
+ (if (and (member x taggroups-keys)
+ (not (member x work-already-expanded)))
+ (setq tags-expanded
+ (delete-dups
+ (append
+ (org-tags-expand x t downcased
+ work-already-expanded)
+ tags-expanded)))
+ (setq tags-expanded
+ (append (list x) tags-expanded)))
+ (setq work-already-expanded
+ (delete-dups
+ (append tags-expanded
+ work-already-expanded))))
+ (setq tags-in-group
+ (delete-dups (cons (car tags-in-group)
+ tags-expanded)))))
+ ;; Filter tag-regexps from tags.
+ (setq regexp-in-group-escaped
+ (delq nil (mapcar (lambda (x)
+ (if (stringp x)
+ (and (equal "{" (substring x 0 1))
+ (equal "}" (substring x -1))
+ x)
+ x))
+ tags-in-group))
+ regexp-in-group
+ (mapcar (lambda (x)
+ (substring x 1 -1))
+ regexp-in-group-escaped)
+ tags-in-group
+ (delq nil (mapcar (lambda (x)
+ (if (stringp x)
+ (and (not (equal "{" (substring x 0 1)))
+ (not (equal "}" (substring x -1)))
+ x)
+ x))
+ tags-in-group)))
+ ;; If single-as-list, do no more in the while-loop.
+ (if (not single-as-list)
+ (progn
+ (when regexp-in-group
+ (setq regexp-in-group
+ (concat "\\|"
+ (mapconcat 'identity regexp-in-group
+ "\\|"))))
+ (setq tags-in-group
+ (concat dir
+ "{\\<"
+ (regexp-opt tags-in-group)
+ "\\>"
+ regexp-in-group
+ "}"))
+ (when (stringp tags-in-group)
+ (org-add-props tags-in-group '(grouptag t)))
+ (setq return-match
+ (replace-match tags-in-group t t return-match)))
+ (setq tags-in-group
+ (append regexp-in-group-escaped tags-in-group))))
+ (setq taggroups-keys (delete tag taggroups-keys))))
+ ;; Add the regular expressions back into the match-expression again.
+ (while regexps-in-match
+ (setq return-match (replace-regexp-in-string (format "<%d>" count)
+ (pop regexps-in-match)
+ return-match t t))
+ (cl-decf count))
+ (if single-as-list
+ (if tags-in-group tags-in-group (list return-match))
+ return-match))
+ (if single-as-list
+ (list (if downcased (downcase match) match))
+ match)))
+
+(defun org-op-to-function (op &optional stringp)
+ "Turn an operator into the appropriate function."
+ (setq op
+ (cond
+ ((equal op "<" ) '(< string< org-time<))
+ ((equal op ">" ) '(> org-string> org-time>))
+ ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
+ ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
+ ((member op '("=" "==")) '(= string= org-time=))
+ ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
+ (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
+
+(defun org<> (a b) (not (= a b)))
+(defun org-string<= (a b) (or (string= a b) (string< a b)))
+(defun org-string>= (a b) (not (string< a b)))
+(defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
+(defun org-string<> (a b) (not (string= a b)))
+(defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
+(defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
+(defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
+(defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
+(defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
+(defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
+(defun org-2ft (s)
+ "Convert S to a floating point time.
+If S is already a number, just return it. If it is a string, parse
+it as a time string and apply `float-time' to it. If S is nil, just return 0."
+ (cond
+ ((numberp s) s)
+ ((stringp s)
+ (condition-case nil
+ (float-time (apply 'encode-time (org-parse-time-string s)))
+ (error 0.)))
+ (t 0.)))
+
+(defun org-time-today ()
+ "Time in seconds today at 0:00.
+Returns the float number of seconds since the beginning of the
+epoch to the beginning of today (00:00)."
+ (float-time (apply 'encode-time
+ (append '(0 0 0) (nthcdr 3 (decode-time))))))
+
+(defun org-matcher-time (s)
+ "Interpret a time comparison value."
+ (save-match-data
+ (cond
+ ((string= s "<now>") (float-time))
+ ((string= s "<today>") (org-time-today))
+ ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
+ ((string= s "<yesterday>") (- (org-time-today) 86400.0))
+ ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
+ (+ (org-time-today)
+ (* (string-to-number (match-string 1 s))
+ (cdr (assoc (match-string 2 s)
+ '(("d" . 86400.0) ("w" . 604800.0)
+ ("m" . 2678400.0) ("y" . 31557600.0)))))))
+ (t (org-2ft s)))))
+
+(defun org-match-any-p (re list)
+ "Does re match any element of list?"
+ (setq list (mapcar (lambda (x) (string-match re x)) list))
+ (delq nil list))
+
+(defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
+(defvar org-tags-overlay (make-overlay 1 1))
+(delete-overlay org-tags-overlay)
+
+(defun org-get-local-tags-at (&optional pos)
+ "Get a list of tags defined in the current headline."
+ (org-get-tags-at pos 'local))
+
+(defun org-get-local-tags ()
+ "Get a list of tags defined in the current headline."
+ (org-get-tags-at nil 'local))
+
+(defun org-get-tags-at (&optional pos local)
+ "Get a list of all headline tags applicable at POS.
+POS defaults to point. If tags are inherited, the list contains
+the targets in the same sequence as the headlines appear, i.e.
+the tags of the current headline come last.
+When LOCAL is non-nil, only return tags from the current headline,
+ignore inherited ones."
+ (interactive)
+ (if (and org-trust-scanner-tags
+ (or (not pos) (equal pos (point)))
+ (not local))
+ org-scanner-tags
+ (let (tags ltags lastpos parent)
+ (save-excursion
+ (save-restriction
+ (widen)
+ (goto-char (or pos (point)))
+ (save-match-data
+ (catch 'done
+ (condition-case nil
+ (progn
+ (org-back-to-heading t)
+ (while (not (equal lastpos (point)))
+ (setq lastpos (point))
+ (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
+ (setq ltags (org-split-string
+ (match-string-no-properties 1) ":"))
+ (when parent
+ (setq ltags (mapcar 'org-add-prop-inherited ltags)))
+ (setq tags (append
+ (if parent
+ (org-remove-uninherited-tags ltags)
+ ltags)
+ tags)))
+ (or org-use-tag-inheritance (throw 'done t))
+ (when local (throw 'done t))
+ (or (org-up-heading-safe) (error nil))
+ (setq parent t)))
+ (error nil)))))
+ (if local
+ tags
+ (reverse (delete-dups
+ (reverse (append
+ (org-remove-uninherited-tags
+ org-file-tags)
+ tags)))))))))
+
+(defun org-add-prop-inherited (s)
+ (add-text-properties 0 (length s) '(inherited t) s)
+ s)
+
+(defun org-toggle-tag (tag &optional onoff)
+ "Toggle the tag TAG for the current line.
+If ONOFF is `on' or `off', don't toggle but set to this state."
+ (let (res current)
+ (save-excursion
+ (org-back-to-heading t)
+ (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
+ (point-at-eol) t)
+ (progn
+ (setq current (match-string 1))
+ (replace-match ""))
+ (setq current ""))
+ (setq current (nreverse (org-split-string current ":")))
+ (cond
+ ((eq onoff 'on)
+ (setq res t)
+ (or (member tag current) (push tag current)))
+ ((eq onoff 'off)
+ (or (not (member tag current)) (setq current (delete tag current))))
+ (t (if (member tag current)
+ (setq current (delete tag current))
+ (setq res t)
+ (push tag current))))
+ (end-of-line 1)
+ (if current
+ (progn
+ (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
+ (org-set-tags nil t))
+ (delete-horizontal-space))
+ (run-hooks 'org-after-tags-change-hook))
+ res))
+
+(defun org--align-tags-here (to-col)
+ "Align tags on the current headline to TO-COL.
+Assume point is on a headline."
+ (let ((pos (point)))
+ (beginning-of-line)
+ (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
+ (>= pos (match-beginning 2)))
+ ;; No tags or point within tags: do not align.
+ (goto-char pos)
+ (goto-char (match-beginning 1))
+ (let ((shift (max (- (if (>= to-col 0) to-col
+ (- (abs to-col) (string-width (match-string 2))))
+ (current-column))
+ 1)))
+ (replace-match (make-string shift ?\s) nil nil nil 1)
+ ;; Preserve initial position, if possible. In any case, stop
+ ;; before tags.
+ (when (< pos (point)) (goto-char pos))))))
+
+(defun org-set-tags-command (&optional arg just-align)
+ "Call the set-tags command for the current entry."
+ (interactive "P")
+ (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
+ (org-set-tags arg just-align)
+ (save-excursion
+ (unless (and (org-region-active-p)
+ org-loop-over-headlines-in-active-region)
+ (org-back-to-heading t))
+ (org-set-tags arg just-align))))
+
+(defun org-set-tags-to (data)
+ "Set the tags of the current entry to DATA, replacing the current tags.
+DATA may be a tags string like :aa:bb:cc:, or a list of tags.
+If DATA is nil or the empty string, any tags will be removed."
+ (interactive "sTags: ")
+ (setq data
+ (cond
+ ((eq data nil) "")
+ ((equal data "") "")
+ ((stringp data)
+ (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
+ ":"))
+ ((listp data)
+ (concat ":" (mapconcat 'identity data ":") ":"))))
+ (when data
+ (save-excursion
+ (org-back-to-heading t)
+ (when (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ (if (match-end 5)
+ (progn
+ (goto-char (match-beginning 5))
+ (insert data)
+ (delete-region (point) (point-at-eol))
+ (org-set-tags nil 'align))
+ (goto-char (point-at-eol))
+ (insert " " data)
+ (org-set-tags nil 'align)))
+ (beginning-of-line 1)
+ (when (looking-at ".*?\\([ \t]+\\)$")
+ (delete-region (match-beginning 1) (match-end 1))))))
+
+(defun org-align-all-tags ()
+ "Align the tags in all headings."
+ (interactive)
+ (save-excursion
+ (or (ignore-errors (org-back-to-heading t))
+ (outline-next-heading))
+ (if (org-at-heading-p)
+ (org-set-tags t)
+ (message "No headings"))))
+
+(defvar org-indent-indentation-per-level)
+(defun org-set-tags (&optional arg just-align)
+ "Set the tags for the current headline.
+With prefix ARG, realign all tags in headings in the current buffer.
+When JUST-ALIGN is non-nil, only align tags."
+ (interactive "P")
+ (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
+ (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
+ 'region-start-level
+ 'region))
+ org-loop-over-headlines-in-active-region)
+ (org-map-entries
+ ;; We don't use ARG and JUST-ALIGN here because these args
+ ;; are not useful when looping over headlines.
+ #'org-set-tags
+ org-loop-over-headlines-in-active-region
+ cl
+ '(when (org-invisible-p) (org-end-of-subtree nil t))))
+ (let ((org-setting-tags t))
+ (if arg
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward org-outline-regexp-bol nil t)
+ (org-set-tags nil t)
+ (end-of-line))
+ (message "All tags realigned to column %d" org-tags-column))
+ (let* ((current (org-get-tags-string))
+ (tags
+ (if just-align current
+ ;; Get a new set of tags from the user.
+ (save-excursion
+ (let* ((seen)
+ (table
+ (setq
+ org-last-tags-completion-table
+ ;; Uniquify tags in alists, yet preserve
+ ;; structure (i.e., keywords).
+ (delq nil
+ (mapcar
+ (lambda (pair)
+ (let ((head (car pair)))
+ (cond ((symbolp head) pair)
+ ((member head seen) nil)
+ (t (push head seen)
+ pair))))
+ (append
+ (or org-current-tag-alist
+ (org-get-buffer-tags))
+ (and
+ org-complete-tags-always-offer-all-agenda-tags
+ (org-global-tags-completion-table
+ (org-agenda-files))))))))
+ (current-tags (org-split-string current ":"))
+ (inherited-tags
+ (nreverse (nthcdr (length current-tags)
+ (nreverse (org-get-tags-at))))))
+ (replace-regexp-in-string
+ "\\([-+&]+\\|,\\)"
+ ":"
+ (if (or (eq t org-use-fast-tag-selection)
+ (and org-use-fast-tag-selection
+ (delq nil (mapcar #'cdr table))))
+ (org-fast-tag-selection
+ current-tags inherited-tags table
+ (and org-fast-tag-selection-include-todo
+ org-todo-key-alist))
+ (let ((org-add-colon-after-tag-completion
+ (< 1 (length table))))
+ (org-trim
+ (completing-read
+ "Tags: "
+ #'org-tags-completion-function
+ nil nil current 'org-tags-history))))))))))
+
+ (when org-tags-sort-function
+ (setq tags
+ (mapconcat
+ #'identity
+ (sort (org-split-string tags "[^[:alnum:]_@#%]+")
+ org-tags-sort-function)
+ ":")))
+
+ (if (or (string= ":" tags)
+ (string= "::" tags))
+ (setq tags ""))
+ (if (not (org-string-nw-p tags)) (setq tags "")
+ (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
+ (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
+
+ ;; Insert new tags at the correct column.
+ (unless (equal current tags)
+ (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))
+ ;; Remove current tags, if any.
+ (when (match-end 5) (replace-match "" nil nil nil 5))
+ ;; Insert new tags, if any. Otherwise, remove trailing
+ ;; white spaces.
+ (end-of-line)
+ (if (not (equal tags ""))
+ ;; When text is being inserted on an invisible
+ ;; region boundary, it can be inadvertently sucked
+ ;; into invisibility.
+ (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
+ (skip-chars-backward " \t")
+ (delete-region (point) (line-end-position)))))
+ ;; Align tags, if any. Fix tags column if `org-indent-mode'
+ ;; is on.
+ (unless (equal tags "")
+ (let* ((level (save-excursion
+ (beginning-of-line)
+ (skip-chars-forward "\\*")))
+ (offset (if (bound-and-true-p org-indent-mode)
+ (* (1- org-indent-indentation-per-level)
+ (1- level))
+ 0))
+ (tags-column
+ (+ org-tags-column
+ (if (> org-tags-column 0) (- offset) offset))))
+ (org--align-tags-here tags-column))))
+ (unless just-align (run-hooks 'org-after-tags-change-hook))))))
+
+(defun org-change-tag-in-region (beg end tag off)
+ "Add or remove TAG for each entry in the region.
+This works in the agenda, and also in an Org buffer."
+ (interactive
+ (list (region-beginning) (region-end)
+ (let ((org-last-tags-completion-table
+ (if (derived-mode-p 'org-mode)
+ (org-uniquify
+ (delq nil (append (org-get-buffer-tags)
+ (org-global-tags-completion-table))))
+ (org-global-tags-completion-table))))
+ (completing-read
+ "Tag: " 'org-tags-completion-function nil nil nil
+ 'org-tags-history))
+ (progn
+ (message "[s]et or [r]emove? ")
+ (equal (read-char-exclusive) ?r))))
+ (when (fboundp 'deactivate-mark) (deactivate-mark))
+ (let ((agendap (equal major-mode 'org-agenda-mode))
+ l1 l2 m buf pos newhead (cnt 0))
+ (goto-char end)
+ (setq l2 (1- (org-current-line)))
+ (goto-char beg)
+ (setq l1 (org-current-line))
+ (cl-loop for l from l1 to l2 do
+ (org-goto-line l)
+ (setq m (get-text-property (point) 'org-hd-marker))
+ (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
+ (and agendap m))
+ (setq buf (if agendap (marker-buffer m) (current-buffer))
+ pos (if agendap m (point)))
+ (with-current-buffer buf
+ (save-excursion
+ (save-restriction
+ (goto-char pos)
+ (setq cnt (1+ cnt))
+ (org-toggle-tag tag (if off 'off 'on))
+ (setq newhead (org-get-heading)))))
+ (and agendap (org-agenda-change-all-lines newhead m))))
+ (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
+
+(defun org-tags-completion-function (string _predicate &optional flag)
+ (let (s1 s2 rtn (ctable org-last-tags-completion-table)
+ (confirm (lambda (x) (stringp (car x)))))
+ (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
+ (setq s1 (match-string 1 string)
+ s2 (match-string 2 string))
+ (setq s1 "" s2 string))
+ (cond
+ ((eq flag nil)
+ ;; try completion
+ (setq rtn (try-completion s2 ctable confirm))
+ (when (stringp rtn)
+ (setq rtn
+ (concat s1 s2 (substring rtn (length s2))
+ (if (and org-add-colon-after-tag-completion
+ (assoc rtn ctable))
+ ":" ""))))
+ rtn)
+ ((eq flag t)
+ ;; all-completions
+ (all-completions s2 ctable confirm))
+ ((eq flag 'lambda)
+ ;; exact match?
+ (assoc s2 ctable)))))
+
+(defun org-fast-tag-insert (kwd tags face &optional end)
+ "Insert KDW, and the TAGS, the latter with face FACE.
+Also insert END."
+ (insert (format "%-12s" (concat kwd ":"))
+ (org-add-props (mapconcat 'identity tags " ") nil 'face face)
+ (or end "")))
+
+(defun org-fast-tag-show-exit (flag)
+ (save-excursion
+ (org-goto-line 3)
+ (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
+ (replace-match ""))
+ (when flag
+ (end-of-line 1)
+ (org-move-to-column (- (window-width) 19) t)
+ (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
+
+(defun org-set-current-tags-overlay (current prefix)
+ "Add an overlay to CURRENT tag with PREFIX."
+ (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
+ (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
+ (org-overlay-display org-tags-overlay (concat prefix s))))
+
+(defvar org-last-tag-selection-key nil)
+(defun org-fast-tag-selection (current inherited table &optional todo-table)
+ "Fast tag selection with single keys.
+CURRENT is the current list of tags in the headline, INHERITED is the
+list of inherited tags, and TABLE is an alist of tags and corresponding keys,
+possibly with grouping information. TODO-TABLE is a similar table with
+TODO keywords, should these have keys assigned to them.
+If the keys are nil, a-z are automatically assigned.
+Returns the new tags string, or nil to not change the current settings."
+ (let* ((fulltable (append table todo-table))
+ (maxlen (apply 'max (mapcar
+ (lambda (x)
+ (if (stringp (car x)) (string-width (car x)) 0))
+ fulltable)))
+ (buf (current-buffer))
+ (expert (eq org-fast-tag-selection-single-key 'expert))
+ (buffer-tags nil)
+ (fwidth (+ maxlen 3 1 3))
+ (ncol (/ (- (window-width) 4) fwidth))
+ (i-face 'org-done)
+ (c-face 'org-todo)
+ tg cnt e c char c1 c2 ntable tbl rtn
+ ov-start ov-end ov-prefix
+ (exit-after-next org-fast-tag-selection-single-key)
+ (done-keywords org-done-keywords)
+ groups ingroup intaggroup)
+ (save-excursion
+ (beginning-of-line 1)
+ (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
+ (setq ov-start (match-beginning 1)
+ ov-end (match-end 1)
+ ov-prefix "")
+ (setq ov-start (1- (point-at-eol))
+ ov-end (1+ ov-start))
+ (skip-chars-forward "^\n\r")
+ (setq ov-prefix
+ (concat
+ (buffer-substring (1- (point)) (point))
+ (if (> (current-column) org-tags-column)
+ " "
+ (make-string (- org-tags-column (current-column)) ?\ ))))))
+ (move-overlay org-tags-overlay ov-start ov-end)
+ (save-window-excursion
+ (if expert
+ (set-buffer (get-buffer-create " *Org tags*"))
+ (delete-other-windows)
+ (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
+ (org-switch-to-buffer-other-window " *Org tags*"))
+ (erase-buffer)
+ (setq-local org-done-keywords done-keywords)
+ (org-fast-tag-insert "Inherited" inherited i-face "\n")
+ (org-fast-tag-insert "Current" current c-face "\n\n")
+ (org-fast-tag-show-exit exit-after-next)
+ (org-set-current-tags-overlay current ov-prefix)
+ (setq tbl fulltable char ?a cnt 0)
+ (while (setq e (pop tbl))
+ (cond
+ ((eq (car e) :startgroup)
+ (push '() groups) (setq ingroup t)
+ (unless (zerop cnt)
+ (setq cnt 0)
+ (insert "\n"))
+ (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
+ ((eq (car e) :endgroup)
+ (setq ingroup nil cnt 0)
+ (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
+ ((eq (car e) :startgrouptag)
+ (setq intaggroup t)
+ (unless (zerop cnt)
+ (setq cnt 0)
+ (insert "\n"))
+ (insert "[ "))
+ ((eq (car e) :endgrouptag)
+ (setq intaggroup nil cnt 0)
+ (insert "]\n"))
+ ((equal e '(:newline))
+ (unless (zerop cnt)
+ (setq cnt 0)
+ (insert "\n")
+ (setq e (car tbl))
+ (while (equal (car tbl) '(:newline))
+ (insert "\n")
+ (setq tbl (cdr tbl)))))
+ ((equal e '(:grouptags)) (insert " : "))
+ (t
+ (setq tg (copy-sequence (car e)) c2 nil)
+ (if (cdr e)
+ (setq c (cdr e))
+ ;; automatically assign a character.
+ (setq c1 (string-to-char
+ (downcase (substring
+ tg (if (= (string-to-char tg) ?@) 1 0)))))
+ (if (or (rassoc c1 ntable) (rassoc c1 table))
+ (while (or (rassoc char ntable) (rassoc char table))
+ (setq char (1+ char)))
+ (setq c2 c1))
+ (setq c (or c2 char)))
+ (when ingroup (push tg (car groups)))
+ (setq tg (org-add-props tg nil 'face
+ (cond
+ ((not (assoc tg table))
+ (org-get-todo-face tg))
+ ((member tg current) c-face)
+ ((member tg inherited) i-face))))
+ (when (equal (caar tbl) :grouptags)
+ (org-add-props tg nil 'face 'org-tag-group))
+ (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
+ (insert "[" c "] " tg (make-string
+ (- fwidth 4 (length tg)) ?\ ))
+ (push (cons tg c) ntable)
+ (when (= (cl-incf cnt) ncol)
+ (insert "\n")
+ (when (or ingroup intaggroup) (insert " "))
+ (setq cnt 0)))))
+ (setq ntable (nreverse ntable))
+ (insert "\n")
+ (goto-char (point-min))
+ (unless expert (org-fit-window-to-buffer))
+ (setq rtn
+ (catch 'exit
+ (while t
+ (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
+ (if (not groups) "no " "")
+ (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
+ (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
+ (setq org-last-tag-selection-key c)
+ (cond
+ ((= c ?\r) (throw 'exit t))
+ ((= c ?!)
+ (setq groups (not groups))
+ (goto-char (point-min))
+ (while (re-search-forward "[{}]" nil t) (replace-match " ")))
+ ((= c ?\C-c)
+ (if (not expert)
+ (org-fast-tag-show-exit
+ (setq exit-after-next (not exit-after-next)))
+ (setq expert nil)
+ (delete-other-windows)
+ (set-window-buffer (split-window-vertically) " *Org tags*")
+ (org-switch-to-buffer-other-window " *Org tags*")
+ (org-fit-window-to-buffer)))
+ ((or (= c ?\C-g)
+ (and (= c ?q) (not (rassoc c ntable))))
+ (delete-overlay org-tags-overlay)
+ (setq quit-flag t))
+ ((= c ?\ )
+ (setq current nil)
+ (when exit-after-next (setq exit-after-next 'now)))
+ ((= c ?\t)
+ (condition-case nil
+ (setq tg (completing-read
+ "Tag: "
+ (or buffer-tags
+ (with-current-buffer buf
+ (setq buffer-tags
+ (org-get-buffer-tags))))))
+ (quit (setq tg "")))
+ (when (string-match "\\S-" tg)
+ (cl-pushnew (list tg) buffer-tags :test #'equal)
+ (if (member tg current)
+ (setq current (delete tg current))
+ (push tg current)))
+ (when exit-after-next (setq exit-after-next 'now)))
+ ((setq e (rassoc c todo-table) tg (car e))
+ (with-current-buffer buf
+ (save-excursion (org-todo tg)))
+ (when exit-after-next (setq exit-after-next 'now)))
+ ((setq e (rassoc c ntable) tg (car e))
+ (if (member tg current)
+ (setq current (delete tg current))
+ (cl-loop for g in groups do
+ (when (member tg g)
+ (dolist (x g) (setq current (delete x current)))))
+ (push tg current))
+ (when exit-after-next (setq exit-after-next 'now))))
+
+ ;; Create a sorted list
+ (setq current
+ (sort current
+ (lambda (a b)
+ (assoc b (cdr (memq (assoc a ntable) ntable))))))
+ (when (eq exit-after-next 'now) (throw 'exit t))
+ (goto-char (point-min))
+ (beginning-of-line 2)
+ (delete-region (point) (point-at-eol))
+ (org-fast-tag-insert "Current" current c-face)
+ (org-set-current-tags-overlay current ov-prefix)
+ (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
+ (setq tg (match-string 1))
+ (add-text-properties
+ (match-beginning 1) (match-end 1)
+ (list 'face
+ (cond
+ ((member tg current) c-face)
+ ((member tg inherited) i-face)
+ (t (get-text-property (match-beginning 1) 'face))))))
+ (goto-char (point-min)))))
+ (delete-overlay org-tags-overlay)
+ (if rtn
+ (mapconcat 'identity current ":")
+ nil))))
+
+(defun org-get-tags-string ()
+ "Get the TAGS string in the current headline."
+ (unless (org-at-heading-p t)
+ (user-error "Not on a heading"))
+ (save-excursion
+ (beginning-of-line 1)
+ (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
+ (match-string-no-properties 1)
+ "")))
+
+(defun org-get-tags ()
+ "Get the list of tags specified in the current headline."
+ (org-split-string (org-get-tags-string) ":"))
+
+(defun org-get-buffer-tags ()
+ "Get a table of all tags used in the buffer, for completion."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((tag-re (concat org-outline-regexp-bol
+ "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
+ tags)
+ (while (re-search-forward tag-re nil t)
+ (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
+ (push tag tags)))
+ (mapcar #'list (append org-file-tags (org-uniquify tags))))))
+
+;;;; The mapping API
+
+(defvar org-agenda-skip-comment-trees)
+(defvar org-agenda-skip-function)
+(defun org-map-entries (func &optional match scope &rest skip)
+ "Call FUNC at each headline selected by MATCH in SCOPE.
+
+FUNC is a function or a lisp form. The function will be called without
+arguments, with the cursor positioned at the beginning of the headline.
+The return values of all calls to the function will be collected and
+returned as a list.
+
+The call to FUNC will be wrapped into a save-excursion form, so FUNC
+does not need to preserve point. After evaluation, the cursor will be
+moved to the end of the line (presumably of the headline of the
+processed entry) and search continues from there. Under some
+circumstances, this may not produce the wanted results. For example,
+if you have removed (e.g. archived) the current (sub)tree it could
+mean that the next entry will be skipped entirely. In such cases, you
+can specify the position from where search should continue by making
+FUNC set the variable `org-map-continue-from' to the desired buffer
+position.
+
+MATCH is a tags/property/todo match as it is used in the agenda tags view.
+Only headlines that are matched by this query will be considered during
+the iteration. When MATCH is nil or t, all headlines will be
+visited by the iteration.
+
+SCOPE determines the scope of this command. It can be any of:
+
+nil The current buffer, respecting the restriction if any
+tree The subtree started with the entry at point
+region The entries within the active region, if any
+region-start-level
+ The entries within the active region, but only those at
+ the same level than the first one.
+file The current buffer, without restriction
+file-with-archives
+ The current buffer, and any archives associated with it
+agenda All agenda files
+agenda-with-archives
+ All agenda files with any archive files associated with them
+\(file1 file2 ...)
+ If this is a list, all files in the list will be scanned
+
+The remaining args are treated as settings for the skipping facilities of
+the scanner. The following items can be given here:
+
+ archive skip trees with the archive tag
+ comment skip trees with the COMMENT keyword
+ function or Emacs Lisp form:
+ will be used as value for `org-agenda-skip-function', so
+ whenever the function returns a position, FUNC will not be
+ called for that entry and search will continue from the
+ position returned
+
+If your function needs to retrieve the tags including inherited tags
+at the *current* entry, you can use the value of the variable
+`org-scanner-tags' which will be much faster than getting the value
+with `org-get-tags-at'. If your function gets properties with
+`org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
+to t around the call to `org-entry-properties' to get the same speedup.
+Note that if your function moves around to retrieve tags and properties at
+a *different* entry, you cannot use these techniques."
+ (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
+ (not (org-region-active-p)))
+ (let* ((org-agenda-archives-mode nil) ; just to make sure
+ (org-agenda-skip-archived-trees (memq 'archive skip))
+ (org-agenda-skip-comment-trees (memq 'comment skip))
+ (org-agenda-skip-function
+ (car (org-delete-all '(comment archive) skip)))
+ (org-tags-match-list-sublevels t)
+ (start-level (eq scope 'region-start-level))
+ matcher res
+ org-todo-keywords-for-agenda
+ org-done-keywords-for-agenda
+ org-todo-keyword-alist-for-agenda
+ org-tag-alist-for-agenda
+ org--matcher-tags-todo-only)
+
+ (cond
+ ((eq match t) (setq matcher t))
+ ((eq match nil) (setq matcher t))
+ (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
+
+ (save-excursion
+ (save-restriction
+ (cond ((eq scope 'tree)
+ (org-back-to-heading t)
+ (org-narrow-to-subtree)
+ (setq scope nil))
+ ((and (or (eq scope 'region) (eq scope 'region-start-level))
+ (org-region-active-p))
+ ;; If needed, set start-level to a string like "2"
+ (when start-level
+ (save-excursion
+ (goto-char (region-beginning))
+ (unless (org-at-heading-p) (outline-next-heading))
+ (setq start-level (org-current-level))))
+ (narrow-to-region (region-beginning)
+ (save-excursion
+ (goto-char (region-end))
+ (unless (and (bolp) (org-at-heading-p))
+ (outline-next-heading))
+ (point)))
+ (setq scope nil)))
+
+ (if (not scope)
+ (progn
+ (org-agenda-prepare-buffers
+ (and buffer-file-name (list buffer-file-name)))
+ (setq res
+ (org-scan-tags
+ func matcher org--matcher-tags-todo-only start-level)))
+ ;; Get the right scope
+ (cond
+ ((and scope (listp scope) (symbolp (car scope)))
+ (setq scope (eval scope)))
+ ((eq scope 'agenda)
+ (setq scope (org-agenda-files t)))
+ ((eq scope 'agenda-with-archives)
+ (setq scope (org-agenda-files t))
+ (setq scope (org-add-archive-files scope)))
+ ((eq scope 'file)
+ (setq scope (and buffer-file-name (list buffer-file-name))))
+ ((eq scope 'file-with-archives)
+ (setq scope (org-add-archive-files (list (buffer-file-name))))))
+ (org-agenda-prepare-buffers scope)
+ (dolist (file scope)
+ (with-current-buffer (org-find-base-buffer-visiting file)
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (setq res
+ (append
+ res
+ (org-scan-tags
+ func matcher org--matcher-tags-todo-only)))))))))
+ res)))
+
+;;; Properties API
+
+(defconst org-special-properties
+ '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
+ "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
+ "The special properties valid in Org mode.
+These are properties that are not defined in the property drawer,
+but in some other way.")
+
+(defconst org-default-properties
+ '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
+ "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
+ "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
+ "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
+ "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
+ "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
+ "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
+ "Some properties that are used by Org mode for various purposes.
+Being in this list makes sure that they are offered for completion.")
+
+(defun org--valid-property-p (property)
+ "Non nil when string PROPERTY is a valid property name."
+ (not
+ (or (equal property "")
+ (string-match-p "\\s-" property))))
+
+(defun org--update-property-plist (key val props)
+ "Associate KEY to VAL in alist PROPS.
+Modifications are made by side-effect. Return new alist."
+ (let* ((appending (string= (substring key -1) "+"))
+ (key (if appending (substring key 0 -1) key))
+ (old (assoc-string key props t)))
+ (if (not old) (cons (cons key val) props)
+ (setcdr old (if appending (concat (cdr old) " " val) val))
+ props)))
+
+(defun org-get-property-block (&optional beg force)
+ "Return the (beg . end) range of the body of the property drawer.
+BEG is the beginning of the current subtree, or of the part
+before the first headline. If it is not given, it will be found.
+If the drawer does not exist, create it if FORCE is non-nil, or
+return nil."
+ (org-with-wide-buffer
+ (when beg (goto-char beg))
+ (unless (org-before-first-heading-p)
+ (let ((beg (cond (beg)
+ ((or (not (featurep 'org-inlinetask))
+ (org-inlinetask-in-task-p))
+ (org-back-to-heading t))
+ (t (org-with-limited-levels (org-back-to-heading t))))))
+ (forward-line)
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (cond ((looking-at org-property-drawer-re)
+ (forward-line)
+ (cons (point) (progn (goto-char (match-end 0))
+ (line-beginning-position))))
+ (force
+ (goto-char beg)
+ (org-insert-property-drawer)
+ (let ((pos (save-excursion (search-forward ":END:")
+ (line-beginning-position))))
+ (cons pos pos))))))))
+
+(defun org-at-property-p ()
+ "Non-nil when point is inside a property drawer.
+See `org-property-re' for match data, if applicable."
+ (save-excursion
+ (beginning-of-line)
+ (and (looking-at org-property-re)
+ (let ((property-drawer (save-match-data (org-get-property-block))))
+ (and property-drawer
+ (>= (point) (car property-drawer))
+ (< (point) (cdr property-drawer)))))))
+
+(defun org-property-action ()
+ "Do an action on properties."
+ (interactive)
+ (unless (org-at-property-p) (user-error "Not at a property"))
+ (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
+ (let ((c (read-char-exclusive)))
+ (cl-case c
+ (?s (call-interactively #'org-set-property))
+ (?d (call-interactively #'org-delete-property))
+ (?D (call-interactively #'org-delete-property-globally))
+ (?c (call-interactively #'org-compute-property-at-point))
+ (otherwise (user-error "No such property action %c" c)))))
+
+(defun org-inc-effort ()
+ "Increment the value of the effort property in the current entry."
+ (interactive)
+ (org-set-effort nil t))
+
+(defvar org-clock-effort) ; Defined in org-clock.el.
+(defvar org-clock-current-task) ; Defined in org-clock.el.
+(defun org-set-effort (&optional value increment)
+ "Set the effort property of the current entry.
+With numerical prefix arg, use the nth allowed value, 0 stands for the
+10th allowed value.
+
+When INCREMENT is non-nil, set the property to the next allowed value."
+ (interactive "P")
+ (when (equal value 0) (setq value 10))
+ (let* ((completion-ignore-case t)
+ (prop org-effort-property)
+ (cur (org-entry-get nil prop))
+ (allowed (org-property-get-allowed-values nil prop 'table))
+ (existing (mapcar 'list (org-property-values prop)))
+ (heading (nth 4 (org-heading-components)))
+ rpl
+ (val (cond
+ ((stringp value) value)
+ ((and allowed (integerp value))
+ (or (car (nth (1- value) allowed))
+ (car (org-last allowed))))
+ ((and allowed increment)
+ (or (cl-caadr (member (list cur) allowed))
+ (user-error "Allowed effort values are not set")))
+ (allowed
+ (message "Select 1-9,0, [RET%s]: %s"
+ (if cur (concat "=" cur) "")
+ (mapconcat 'car allowed " "))
+ (setq rpl (read-char-exclusive))
+ (if (equal rpl ?\r)
+ cur
+ (setq rpl (- rpl ?0))
+ (when (equal rpl 0) (setq rpl 10))
+ (if (and (> rpl 0) (<= rpl (length allowed)))
+ (car (nth (1- rpl) allowed))
+ (org-completing-read "Effort: " allowed nil))))
+ (t
+ (org-completing-read
+ (concat "Effort" (and cur (string-match "\\S-" cur)
+ (concat " [" cur "]"))
+ ": ")
+ existing nil nil "" nil cur)))))
+ (unless (equal (org-entry-get nil prop) val)
+ (org-entry-put nil prop val))
+ (org-refresh-property
+ '((effort . identity)
+ (effort-minutes . org-duration-string-to-minutes))
+ val)
+ (when (equal heading (bound-and-true-p org-clock-current-task))
+ (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
+ (org-clock-update-mode-line))
+ (message "%s is now %s" prop val)))
+
+(defun org-entry-properties (&optional pom which)
+ "Get all properties of the current entry.
+
+When POM is a buffer position, get all properties from the entry
+there instead.
+
+This includes the TODO keyword, the tags, time strings for
+deadline, scheduled, and clocking, and any additional properties
+defined in the entry.
+
+If WHICH is nil or `all', get all properties. If WHICH is
+`special' or `standard', only get that subclass. If WHICH is
+a string, only get that property.
+
+Return value is an alist. Keys are properties, as upcased
+strings."
+ (org-with-point-at pom
+ (when (and (derived-mode-p 'org-mode)
+ (ignore-errors (org-back-to-heading t)))
+ (catch 'exit
+ (let* ((beg (point))
+ (specific (and (stringp which) (upcase which)))
+ (which (cond ((not specific) which)
+ ((member specific org-special-properties) 'special)
+ (t 'standard)))
+ props)
+ ;; Get the special properties, like TODO and TAGS.
+ (when (memq which '(nil all special))
+ (when (or (not specific) (string= specific "CLOCKSUM"))
+ (let ((clocksum (get-text-property (point) :org-clock-minutes)))
+ (when clocksum
+ (push (cons "CLOCKSUM"
+ (org-minutes-to-clocksum-string clocksum))
+ props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "CLOCKSUM_T"))
+ (let ((clocksumt (get-text-property (point)
+ :org-clock-minutes-today)))
+ (when clocksumt
+ (push (cons "CLOCKSUM_T"
+ (org-minutes-to-clocksum-string clocksumt))
+ props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "ITEM"))
+ (let ((case-fold-search nil))
+ (when (looking-at org-complex-heading-regexp)
+ (push (cons "ITEM"
+ (let ((title (match-string-no-properties 4)))
+ (if (org-string-nw-p title)
+ (org-remove-tabs title)
+ "")))
+ props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "TODO"))
+ (let ((case-fold-search nil))
+ (when (and (looking-at org-todo-line-regexp) (match-end 2))
+ (push (cons "TODO" (match-string-no-properties 2)) props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "PRIORITY"))
+ (push (cons "PRIORITY"
+ (if (looking-at org-priority-regexp)
+ (match-string-no-properties 2)
+ (char-to-string org-default-priority)))
+ props)
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "FILE"))
+ (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
+ props)
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "TAGS"))
+ (let ((value (org-string-nw-p (org-get-tags-string))))
+ (when value (push (cons "TAGS" value) props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "ALLTAGS"))
+ (let ((value (org-get-tags-at)))
+ (when value
+ (push (cons "ALLTAGS"
+ (format ":%s:" (mapconcat #'identity value ":")))
+ props)))
+ (when specific (throw 'exit props)))
+ (when (or (not specific) (string= specific "BLOCKED"))
+ (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
+ (when specific (throw 'exit props)))
+ (when (or (not specific)
+ (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
+ (forward-line)
+ (when (looking-at-p org-planning-line-re)
+ (end-of-line)
+ (let ((bol (line-beginning-position))
+ ;; Backward compatibility: time keywords used to
+ ;; be configurable (before 8.3). Make sure we
+ ;; get the correct keyword.
+ (key-assoc `(("CLOSED" . ,org-closed-string)
+ ("DEADLINE" . ,org-deadline-string)
+ ("SCHEDULED" . ,org-scheduled-string))))
+ (dolist (pair (if specific (list (assoc specific key-assoc))
+ key-assoc))
+ (save-excursion
+ (when (search-backward (cdr pair) bol t)
+ (goto-char (match-end 0))
+ (skip-chars-forward " \t")
+ (and (looking-at org-ts-regexp-both)
+ (push (cons (car pair)
+ (match-string-no-properties 0))
+ props)))))))
+ (when specific (throw 'exit props)))
+ (when (or (not specific)
+ (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
+ (let ((find-ts
+ (lambda (end ts)
+ ;; Fix next time-stamp before END. TS is the
+ ;; list of time-stamps found so far.
+ (let ((ts ts)
+ (regexp (cond
+ ((string= specific "TIMESTAMP")
+ org-ts-regexp)
+ ((string= specific "TIMESTAMP_IA")
+ org-ts-regexp-inactive)
+ ((assoc "TIMESTAMP_IA" ts)
+ org-ts-regexp)
+ ((assoc "TIMESTAMP" ts)
+ org-ts-regexp-inactive)
+ (t org-ts-regexp-both))))
+ (catch 'next
+ (while (re-search-forward regexp end t)
+ (backward-char)
+ (let ((object (org-element-context)))
+ ;; Accept to match timestamps in node
+ ;; properties, too.
+ (when (memq (org-element-type object)
+ '(node-property timestamp))
+ (let ((type
+ (org-element-property :type object)))
+ (cond
+ ((and (memq type '(active active-range))
+ (not (equal specific "TIMESTAMP_IA")))
+ (unless (assoc "TIMESTAMP" ts)
+ (push (cons "TIMESTAMP"
+ (org-element-property
+ :raw-value object))
+ ts)
+ (when specific (throw 'exit ts))))
+ ((and (memq type '(inactive inactive-range))
+ (not (string= specific "TIMESTAMP")))
+ (unless (assoc "TIMESTAMP_IA" ts)
+ (push (cons "TIMESTAMP_IA"
+ (org-element-property
+ :raw-value object))
+ ts)
+ (when specific (throw 'exit ts))))))
+ ;; Both timestamp types are found,
+ ;; move to next part.
+ (when (= (length ts) 2) (throw 'next ts)))))
+ ts)))))
+ (goto-char beg)
+ ;; First look for timestamps within headline.
+ (let ((ts (funcall find-ts (line-end-position) nil)))
+ (if (= (length ts) 2) (setq props (nconc ts props))
+ ;; Then find timestamps in the section, skipping
+ ;; planning line.
+ (let ((end (save-excursion (outline-next-heading))))
+ (forward-line)
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (setq props (nconc (funcall find-ts end ts) props))))))))
+ ;; Get the standard properties, like :PROP:.
+ (when (memq which '(nil all standard))
+ ;; If we are looking after a specific property, delegate
+ ;; to `org-entry-get', which is faster. However, make an
+ ;; exception for "CATEGORY", since it can be also set
+ ;; through keywords (i.e. #+CATEGORY).
+ (if (and specific (not (equal specific "CATEGORY")))
+ (let ((value (org-entry-get beg specific nil t)))
+ (throw 'exit (and value (list (cons specific value)))))
+ (let ((range (org-get-property-block beg)))
+ (when range
+ (let ((end (cdr range)) seen-base)
+ (goto-char (car range))
+ ;; Unlike to `org--update-property-plist', we
+ ;; handle the case where base values is found
+ ;; after its extension. We also forbid standard
+ ;; properties to be named as special properties.
+ (while (re-search-forward org-property-re end t)
+ (let* ((key (upcase (match-string-no-properties 2)))
+ (extendp (string-match-p "\\+\\'" key))
+ (key-base (if extendp (substring key 0 -1) key))
+ (value (match-string-no-properties 3)))
+ (cond
+ ((member-ignore-case key-base org-special-properties))
+ (extendp
+ (setq props
+ (org--update-property-plist key value props)))
+ ((member key seen-base))
+ (t (push key seen-base)
+ (let ((p (assoc-string key props t)))
+ (if p (setcdr p (concat value " " (cdr p)))
+ (push (cons key value) props))))))))))))
+ (unless (assoc "CATEGORY" props)
+ (push (cons "CATEGORY" (org-get-category beg)) props)
+ (when (string= specific "CATEGORY") (throw 'exit props)))
+ ;; Return value.
+ props)))))
+
+(defun org--property-local-values (property literal-nil)
+ "Return value for PROPERTY in current entry.
+Value is a list whose car is the base value for PROPERTY and cdr
+a list of accumulated values. Return nil if neither is found in
+the entry. Also return nil when PROPERTY is set to \"nil\",
+unless LITERAL-NIL is non-nil."
+ (let ((range (org-get-property-block)))
+ (when range
+ (goto-char (car range))
+ (let* ((case-fold-search t)
+ (end (cdr range))
+ (value
+ ;; Base value.
+ (save-excursion
+ (let ((v (and (re-search-forward
+ (org-re-property property nil t) end t)
+ (match-string-no-properties 3))))
+ (list (if literal-nil v (org-not-nil v)))))))
+ ;; Find additional values.
+ (let* ((property+ (org-re-property (concat property "+") nil t)))
+ (while (re-search-forward property+ end t)
+ (push (match-string-no-properties 3) value)))
+ ;; Return final values.
+ (and (not (equal value '(nil))) (nreverse value))))))
+
+(defun org--property-global-value (property literal-nil)
+ "Return value for PROPERTY in current buffer.
+Return value is a string. Return nil if property is not set
+globally. Also return nil when PROPERTY is set to \"nil\",
+unless LITERAL-NIL is non-nil."
+ (let ((global
+ (cdr (or (assoc-string property org-file-properties t)
+ (assoc-string property org-global-properties t)
+ (assoc-string property org-global-properties-fixed t)))))
+ (if literal-nil global (org-not-nil global))))
+
+(defun org-entry-get (pom property &optional inherit literal-nil)
+ "Get value of PROPERTY for entry or content at point-or-marker POM.
+
+If INHERIT is non-nil and the entry does not have the property,
+then also check higher levels of the hierarchy. If INHERIT is
+the symbol `selective', use inheritance only if the setting in
+`org-use-property-inheritance' selects PROPERTY for inheritance.
+
+If the property is present but empty, the return value is the
+empty string. If the property is not present at all, nil is
+returned. In any other case, return the value as a string.
+Search is case-insensitive.
+
+If LITERAL-NIL is set, return the string value \"nil\" as
+a string, do not interpret it as the list atom nil. This is used
+for inheritance when a \"nil\" value can supersede a non-nil
+value higher up the hierarchy."
+ (org-with-point-at pom
+ (cond
+ ((member-ignore-case property (cons "CATEGORY" org-special-properties))
+ ;; We need a special property. Use `org-entry-properties' to
+ ;; retrieve it, but specify the wanted property.
+ (cdr (assoc-string property (org-entry-properties nil property))))
+ ((and inherit
+ (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
+ (org-entry-get-with-inheritance property literal-nil))
+ (t
+ (let* ((local (org--property-local-values property literal-nil))
+ (value (and local (mapconcat #'identity (delq nil local) " "))))
+ (if literal-nil value (org-not-nil value)))))))
+
+(defun org-property-or-variable-value (var &optional inherit)
+ "Check if there is a property fixing the value of VAR.
+If yes, return this value. If not, return the current value of the variable."
+ (let ((prop (org-entry-get nil (symbol-name var) inherit)))
+ (if (and prop (stringp prop) (string-match "\\S-" prop))
+ (read prop)
+ (symbol-value var))))
+
+(defun org-entry-delete (pom property)
+ "Delete PROPERTY from entry at point-or-marker POM.
+Accumulated properties, i.e. PROPERTY+, are also removed. Return
+non-nil when a property was removed."
+ (org-with-point-at pom
+ (pcase (org-get-property-block)
+ (`(,begin . ,origin)
+ (let* ((end (copy-marker origin))
+ (re (org-re-property
+ (concat (regexp-quote property) "\\+?") t t)))
+ (goto-char begin)
+ (while (re-search-forward re end t)
+ (delete-region (match-beginning 0) (line-beginning-position 2)))
+ ;; If drawer is empty, remove it altogether.
+ (when (= begin end)
+ (delete-region (line-beginning-position 0)
+ (line-beginning-position 2)))
+ ;; Return non-nil if some property was removed.
+ (prog1 (/= end origin) (set-marker end nil))))
+ (_ nil))))
+
+;; Multi-values properties are properties that contain multiple values
+;; These values are assumed to be single words, separated by whitespace.
+(defun org-entry-add-to-multivalued-property (pom property value)
+ "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
+ (let* ((old (org-entry-get pom property))
+ (values (and old (org-split-string old "[ \t]"))))
+ (setq value (org-entry-protect-space value))
+ (unless (member value values)
+ (setq values (append values (list value)))
+ (org-entry-put pom property
+ (mapconcat 'identity values " ")))))
+
+(defun org-entry-remove-from-multivalued-property (pom property value)
+ "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
+ (let* ((old (org-entry-get pom property))
+ (values (and old (org-split-string old "[ \t]"))))
+ (setq value (org-entry-protect-space value))
+ (when (member value values)
+ (setq values (delete value values))
+ (org-entry-put pom property
+ (mapconcat 'identity values " ")))))
+
+(defun org-entry-member-in-multivalued-property (pom property value)
+ "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
+ (let* ((old (org-entry-get pom property))
+ (values (and old (org-split-string old "[ \t]"))))
+ (setq value (org-entry-protect-space value))
+ (member value values)))
+
+(defun org-entry-get-multivalued-property (pom property)
+ "Return a list of values in a multivalued property."
+ (let* ((value (org-entry-get pom property))
+ (values (and value (org-split-string value "[ \t]"))))
+ (mapcar 'org-entry-restore-space values)))
+
+(defun org-entry-put-multivalued-property (pom property &rest values)
+ "Set multivalued PROPERTY at point-or-marker POM to VALUES.
+VALUES should be a list of strings. Spaces will be protected."
+ (org-entry-put pom property
+ (mapconcat 'org-entry-protect-space values " "))
+ (let* ((value (org-entry-get pom property))
+ (values (and value (org-split-string value "[ \t]"))))
+ (mapcar 'org-entry-restore-space values)))
+
+(defun org-entry-protect-space (s)
+ "Protect spaces and newline in string S."
+ (while (string-match " " s)
+ (setq s (replace-match "%20" t t s)))
+ (while (string-match "\n" s)
+ (setq s (replace-match "%0A" t t s)))
+ s)
+
+(defun org-entry-restore-space (s)
+ "Restore spaces and newline in string S."
+ (while (string-match "%20" s)
+ (setq s (replace-match " " t t s)))
+ (while (string-match "%0A" s)
+ (setq s (replace-match "\n" t t s)))
+ s)
+
+(defvar org-entry-property-inherited-from (make-marker)
+ "Marker pointing to the entry from where a property was inherited.
+Each call to `org-entry-get-with-inheritance' will set this marker to the
+location of the entry where the inheritance search matched. If there was
+no match, the marker will point nowhere.
+Note that also `org-entry-get' calls this function, if the INHERIT flag
+is set.")
+
+(defun org-entry-get-with-inheritance (property &optional literal-nil)
+ "Get PROPERTY of entry or content at point, search higher levels if needed.
+The search will stop at the first ancestor which has the property defined.
+If the value found is \"nil\", return nil to show that the property
+should be considered as undefined (this is the meaning of nil here).
+However, if LITERAL-NIL is set, return the string value \"nil\" instead."
+ (move-marker org-entry-property-inherited-from nil)
+ (org-with-wide-buffer
+ (let (value)
+ (catch 'exit
+ (while t
+ (let ((v (org--property-local-values property literal-nil)))
+ (when v
+ (setq value
+ (concat (mapconcat #'identity (delq nil v) " ")
+ (and value " ")
+ value)))
+ (cond
+ ((car v)
+ (org-back-to-heading t)
+ (move-marker org-entry-property-inherited-from (point))
+ (throw 'exit nil))
+ ((org-up-heading-safe))
+ (t
+ (let ((global (org--property-global-value property literal-nil)))
+ (cond ((not global))
+ (value (setq value (concat global " " value)))
+ (t (setq value global))))
+ (throw 'exit nil))))))
+ (if literal-nil value (org-not-nil value)))))
+
+(defvar org-property-changed-functions nil
+ "Hook called when the value of a property has changed.
+Each hook function should accept two arguments, the name of the property
+and the new value.")
+
+(defun org-entry-put (pom property value)
+ "Set PROPERTY to VALUE for entry at point-or-marker POM.
+
+If the value is nil, it is converted to the empty string. If it
+is not a string, an error is raised. Also raise an error on
+invalid property names.
+
+PROPERTY can be any regular property (see
+`org-special-properties'). It can also be \"TODO\",
+\"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
+
+For the last two properties, VALUE may have any of the special
+values \"earlier\" and \"later\". The function then increases or
+decreases scheduled or deadline date by one day."
+ (cond ((null value) (setq value ""))
+ ((not (stringp value)) (error "Properties values should be strings"))
+ ((not (org--valid-property-p property))
+ (user-error "Invalid property name: \"%s\"" property)))
+ (org-with-point-at pom
+ (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
+ (org-back-to-heading t)
+ (org-with-limited-levels (org-back-to-heading t)))
+ (let ((beg (point)))
+ (cond
+ ((equal property "TODO")
+ (cond ((not (org-string-nw-p value)) (setq value 'none))
+ ((not (member value org-todo-keywords-1))
+ (user-error "\"%s\" is not a valid TODO state" value)))
+ (org-todo value)
+ (org-set-tags nil 'align))
+ ((equal property "PRIORITY")
+ (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
+ (org-set-tags nil 'align))
+ ((equal property "SCHEDULED")
+ (forward-line)
+ (if (and (looking-at-p org-planning-line-re)
+ (re-search-forward
+ org-scheduled-time-regexp (line-end-position) t))
+ (cond ((string= value "earlier") (org-timestamp-change -1 'day))
+ ((string= value "later") (org-timestamp-change 1 'day))
+ ((string= value "") (org-schedule '(4)))
+ (t (org-schedule nil value)))
+ (if (member value '("earlier" "later" ""))
+ (call-interactively #'org-schedule)
+ (org-schedule nil value))))
+ ((equal property "DEADLINE")
+ (forward-line)
+ (if (and (looking-at-p org-planning-line-re)
+ (re-search-forward
+ org-deadline-time-regexp (line-end-position) t))
+ (cond ((string= value "earlier") (org-timestamp-change -1 'day))
+ ((string= value "later") (org-timestamp-change 1 'day))
+ ((string= value "") (org-deadline '(4)))
+ (t (org-deadline nil value)))
+ (if (member value '("earlier" "later" ""))
+ (call-interactively #'org-deadline)
+ (org-deadline nil value))))
+ ((member property org-special-properties)
+ (error "The %s property cannot be set with `org-entry-put'" property))
+ (t
+ (let* ((range (org-get-property-block beg 'force))
+ (end (cdr range))
+ (case-fold-search t))
+ (goto-char (car range))
+ (if (re-search-forward (org-re-property property nil t) end t)
+ (progn (delete-region (match-beginning 0) (match-end 0))
+ (goto-char (match-beginning 0)))
+ (goto-char end)
+ (insert "\n")
+ (backward-char))
+ (insert ":" property ":")
+ (when value (insert " " value))
+ (org-indent-line)))))
+ (run-hook-with-args 'org-property-changed-functions property value)))
+
+(defun org-buffer-property-keys
+ (&optional specials defaults columns ignore-malformed)
+ "Get all property keys in the current buffer.
+
+When SPECIALS is non-nil, also list the special properties that
+reflect things like tags and TODO state.
+
+When DEFAULTS is non-nil, also include properties that has
+special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
+DESCRIPTION, LOCATION, and LOGGING and others.
+
+When COLUMNS in non-nil, also include property names given in
+COLUMN formats in the current buffer.
+
+When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
+automatically performed, such drawers will be silently ignored."
+ (let ((case-fold-search t)
+ (props (append
+ (and specials org-special-properties)
+ (and defaults (cons org-effort-property org-default-properties))
+ nil)))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward org-property-start-re nil t)
+ (let ((range (org-get-property-block)))
+ (catch 'skip
+ (unless range
+ (when (and (not ignore-malformed)
+ (not (org-before-first-heading-p))
+ (y-or-n-p (format "Malformed drawer at %d, repair?"
+ (line-beginning-position))))
+ (org-get-property-block nil t))
+ (throw 'skip nil))
+ (goto-char (car range))
+ (let ((begin (car range))
+ (end (cdr range)))
+ ;; Make sure that found property block is not located
+ ;; before current point, as it would generate an infloop.
+ ;; It can happen, for example, in the following
+ ;; situation:
+ ;;
+ ;; * Headline
+ ;; :PROPERTIES:
+ ;; ...
+ ;; :END:
+ ;; *************** Inlinetask
+ ;; #+BEGIN_EXAMPLE
+ ;; :PROPERTIES:
+ ;; #+END_EXAMPLE
+ ;;
+ (if (< begin (point)) (throw 'skip nil) (goto-char begin))
+ (while (< (point) end)
+ (let ((p (progn (looking-at org-property-re)
+ (match-string-no-properties 2))))
+ ;; Only add true property name, not extension symbol.
+ (push (if (not (string-match-p "\\+\\'" p)) p
+ (substring p 0 -1))
+ props))
+ (forward-line))))
+ (outline-next-heading)))
+ (when columns
+ (goto-char (point-min))
+ (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
+ (let ((element (org-element-at-point)))
+ (when (memq (org-element-type element) '(keyword node-property))
+ (let ((value (org-element-property :value element))
+ (start 0))
+ (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
+ (setq start (match-end 0))
+ (let ((p (match-string-no-properties 1 value)))
+ (unless (member-ignore-case p org-special-properties)
+ (push p props))))))))))
+ (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
+
+(defun org-property-values (key)
+ "List all non-nil values of property KEY in current buffer."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((case-fold-search t)
+ (re (org-re-property key))
+ values)
+ (while (re-search-forward re nil t)
+ (push (org-entry-get (point) key) values))
+ (delete-dups values))))
+
+(defun org-insert-property-drawer ()
+ "Insert a property drawer into the current entry."
+ (org-with-wide-buffer
+ (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
+ (org-back-to-heading t)
+ (org-with-limited-levels (org-back-to-heading t)))
+ (forward-line)
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (unless (looking-at-p org-property-drawer-re)
+ ;; Make sure we start editing a line from current entry, not from
+ ;; next one. It prevents extending text properties or overlays
+ ;; belonging to the latter.
+ (when (bolp) (backward-char))
+ (let ((begin (1+ (point)))
+ (inhibit-read-only t))
+ (insert "\n:PROPERTIES:\n:END:")
+ (when (eobp) (insert "\n"))
+ (org-indent-region begin (point))))))
+
+(defun org-insert-drawer (&optional arg drawer)
+ "Insert a drawer at point.
+
+When optional argument ARG is non-nil, insert a property drawer.
+
+Optional argument DRAWER, when non-nil, is a string representing
+drawer's name. Otherwise, the user is prompted for a name.
+
+If a region is active, insert the drawer around that region
+instead.
+
+Point is left between drawer's boundaries."
+ (interactive "P")
+ (let* ((drawer (if arg "PROPERTIES"
+ (or drawer (read-from-minibuffer "Drawer: ")))))
+ (cond
+ ;; With C-u, fall back on `org-insert-property-drawer'
+ (arg (org-insert-property-drawer))
+ ;; Check validity of suggested drawer's name.
+ ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
+ (user-error "Invalid drawer name"))
+ ;; With an active region, insert a drawer at point.
+ ((not (org-region-active-p))
+ (progn
+ (unless (bolp) (insert "\n"))
+ (insert (format ":%s:\n\n:END:\n" drawer))
+ (forward-line -2)))
+ ;; Otherwise, insert the drawer at point
+ (t
+ (let ((rbeg (region-beginning))
+ (rend (copy-marker (region-end))))
+ (unwind-protect
+ (progn
+ (goto-char rbeg)
+ (beginning-of-line)
+ (when (save-excursion
+ (re-search-forward org-outline-regexp-bol rend t))
+ (user-error "Drawers cannot contain headlines"))
+ ;; Position point at the beginning of the first
+ ;; non-blank line in region. Insert drawer's opening
+ ;; there, then indent it.
+ (org-skip-whitespace)
+ (beginning-of-line)
+ (insert ":" drawer ":\n")
+ (forward-line -1)
+ (indent-for-tab-command)
+ ;; Move point to the beginning of the first blank line
+ ;; after the last non-blank line in region. Insert
+ ;; drawer's closing, then indent it.
+ (goto-char rend)
+ (skip-chars-backward " \r\t\n")
+ (insert "\n:END:")
+ (deactivate-mark t)
+ (indent-for-tab-command)
+ (unless (eolp) (insert "\n")))
+ ;; Clear marker, whatever the outcome of insertion is.
+ (set-marker rend nil)))))))
+
+(defvar org-property-set-functions-alist nil
+ "Property set function alist.
+Each entry should have the following format:
+
+ (PROPERTY . READ-FUNCTION)
+
+The read function will be called with the same argument as
+`org-completing-read'.")
+
+(defun org-set-property-function (property)
+ "Get the function that should be used to set PROPERTY.
+This is computed according to `org-property-set-functions-alist'."
+ (or (cdr (assoc property org-property-set-functions-alist))
+ 'org-completing-read))
+
+(defun org-read-property-value (property)
+ "Read PROPERTY value from user."
+ (let* ((completion-ignore-case t)
+ (allowed (org-property-get-allowed-values nil property 'table))
+ (cur (org-entry-get nil property))
+ (prompt (concat property " value"
+ (if (and cur (string-match "\\S-" cur))
+ (concat " [" cur "]") "") ": "))
+ (set-function (org-set-property-function property))
+ (val (if allowed
+ (funcall set-function prompt allowed nil
+ (not (get-text-property 0 'org-unrestricted
+ (caar allowed))))
+ (funcall set-function prompt
+ (mapcar 'list (org-property-values property))
+ nil nil "" nil cur))))
+ (org-trim val)))
+
+(defvar org-last-set-property nil)
+(defvar org-last-set-property-value nil)
+(defun org-read-property-name ()
+ "Read a property name."
+ (let ((completion-ignore-case t)
+ (default-prop (or (and (org-at-property-p)
+ (match-string-no-properties 2))
+ org-last-set-property)))
+ (org-completing-read
+ (concat "Property"
+ (if default-prop (concat " [" default-prop "]") "")
+ ": ")
+ (mapcar #'list (org-buffer-property-keys nil t t))
+ nil nil nil nil default-prop)))
+
+(defun org-set-property-and-value (use-last)
+ "Allow to set [PROPERTY]: [value] direction from prompt.
+When use-default, don't even ask, just use the last
+\"[PROPERTY]: [value]\" string from the history."
+ (interactive "P")
+ (let* ((completion-ignore-case t)
+ (pv (or (and use-last org-last-set-property-value)
+ (org-completing-read
+ "Enter a \"[Property]: [value]\" pair: "
+ nil nil nil nil nil
+ org-last-set-property-value)))
+ prop val)
+ (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
+ (setq prop (match-string 1 pv)
+ val (match-string 2 pv))
+ (org-set-property prop val))))
+
+(defun org-set-property (property value)
+ "In the current entry, set PROPERTY to VALUE.
+
+When called interactively, this will prompt for a property name, offering
+completion on existing and default properties. And then it will prompt
+for a value, offering completion either on allowed values (via an inherited
+xxx_ALL property) or on existing values in other instances of this property
+in the current file.
+
+Throw an error when trying to set a property with an invalid name."
+ (interactive (list nil nil))
+ (let ((property (or property (org-read-property-name))))
+ ;; `org-entry-put' also makes the following check, but this one
+ ;; avoids polluting `org-last-set-property' and
+ ;; `org-last-set-property-value' needlessly.
+ (unless (org--valid-property-p property)
+ (user-error "Invalid property name: \"%s\"" property))
+ (let ((value (or value (org-read-property-value property)))
+ (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
+ (setq org-last-set-property property)
+ (setq org-last-set-property-value (concat property ": " value))
+ ;; Possibly postprocess the inserted value:
+ (when fn (setq value (funcall fn value)))
+ (unless (equal (org-entry-get nil property) value)
+ (org-entry-put nil property value)))))
+
+(defun org-find-property (property &optional value)
+ "Find first entry in buffer that sets PROPERTY.
+
+When optional argument VALUE is non-nil, only consider an entry
+if it contains PROPERTY set to this value. If PROPERTY should be
+explicitly set to nil, use string \"nil\" for VALUE.
+
+Return position where the entry begins, or nil if there is no
+such entry. If narrowing is in effect, only search the visible
+part of the buffer."
+ (save-excursion
+ (goto-char (point-min))
+ (let ((case-fold-search t)
+ (re (org-re-property property nil (not value) value)))
+ (catch 'exit
+ (while (re-search-forward re nil t)
+ (when (if value (org-at-property-p)
+ (org-entry-get (point) property nil t))
+ (throw 'exit (progn (org-back-to-heading t) (point)))))))))
+
+(defun org-delete-property (property)
+ "In the current entry, delete PROPERTY."
+ (interactive
+ (let* ((completion-ignore-case t)
+ (cat (org-entry-get (point) "CATEGORY"))
+ (props0 (org-entry-properties nil 'standard))
+ (props (if cat props0
+ (delete `("CATEGORY" . ,(org-get-category)) props0)))
+ (prop (if (< 1 (length props))
+ (completing-read "Property: " props nil t)
+ (caar props))))
+ (list prop)))
+ (if (not property)
+ (message "No property to delete in this entry")
+ (org-entry-delete nil property)
+ (message "Property \"%s\" deleted" property)))
+
+(defun org-delete-property-globally (property)
+ "Remove PROPERTY globally, from all entries.
+This function ignores narrowing, if any."
+ (interactive
+ (let* ((completion-ignore-case t)
+ (prop (completing-read
+ "Globally remove property: "
+ (mapcar #'list (org-buffer-property-keys)))))
+ (list prop)))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let ((count 0)
+ (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
+ (while (re-search-forward re nil t)
+ (when (org-entry-delete (point) property) (cl-incf count)))
+ (message "Property \"%s\" removed from %d entries" property count))))
+
+(defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
+
+(defun org-compute-property-at-point ()
+ "Compute the property at point.
+This looks for an enclosing column format, extracts the operator and
+then applies it to the property in the column format's scope."
+ (interactive)
+ (unless (org-at-property-p)
+ (user-error "Not at a property"))
+ (let ((prop (match-string-no-properties 2)))
+ (org-columns-get-format-and-top-level)
+ (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
+ (user-error "No operator defined for property %s" prop))
+ (org-columns-compute prop)))
+
+(defvar org-property-allowed-value-functions nil
+ "Hook for functions supplying allowed values for a specific property.
+The functions must take a single argument, the name of the property, and
+return a flat list of allowed values. If \":ETC\" is one of
+the values, this means that these values are intended as defaults for
+completion, but that other values should be allowed too.
+The functions must return nil if they are not responsible for this
+property.")
+
+(defun org-property-get-allowed-values (pom property &optional table)
+ "Get allowed values for the property PROPERTY.
+When TABLE is non-nil, return an alist that can directly be used for
+completion."
+ (let (vals)
+ (cond
+ ((equal property "TODO")
+ (setq vals (org-with-point-at pom
+ (append org-todo-keywords-1 '("")))))
+ ((equal property "PRIORITY")
+ (let ((n org-lowest-priority))
+ (while (>= n org-highest-priority)
+ (push (char-to-string n) vals)
+ (setq n (1- n)))))
+ ((equal property "CATEGORY"))
+ ((member property org-special-properties))
+ ((setq vals (run-hook-with-args-until-success
+ 'org-property-allowed-value-functions property)))
+ (t
+ (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
+ (when (and vals (string-match "\\S-" vals))
+ (setq vals (car (read-from-string (concat "(" vals ")"))))
+ (setq vals (mapcar (lambda (x)
+ (cond ((stringp x) x)
+ ((numberp x) (number-to-string x))
+ ((symbolp x) (symbol-name x))
+ (t "???")))
+ vals)))))
+ (when (member ":ETC" vals)
+ (setq vals (remove ":ETC" vals))
+ (org-add-props (car vals) '(org-unrestricted t)))
+ (if table (mapcar 'list vals) vals)))
+
+(defun org-property-previous-allowed-value (&optional _previous)
+ "Switch to the next allowed value for this property."
+ (interactive)
+ (org-property-next-allowed-value t))
+
+(defun org-property-next-allowed-value (&optional previous)
+ "Switch to the next allowed value for this property."
+ (interactive)
+ (unless (org-at-property-p)
+ (user-error "Not at a property"))
+ (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
+ (key (match-string 2))
+ (value (match-string 3))
+ (allowed (or (org-property-get-allowed-values (point) key)
+ (and (member value '("[ ]" "[-]" "[X]"))
+ '("[ ]" "[X]"))))
+ (heading (save-match-data (nth 4 (org-heading-components))))
+ nval)
+ (unless allowed
+ (user-error "Allowed values for this property have not been defined"))
+ (when previous (setq allowed (reverse allowed)))
+ (when (member value allowed)
+ (setq nval (car (cdr (member value allowed)))))
+ (setq nval (or nval (car allowed)))
+ (when (equal nval value)
+ (user-error "Only one allowed value for this property"))
+ (org-at-property-p)
+ (replace-match (concat " :" key ": " nval) t t)
+ (org-indent-line)
+ (beginning-of-line 1)
+ (skip-chars-forward " \t")
+ (when (equal prop org-effort-property)
+ (org-refresh-property
+ '((effort . identity)
+ (effort-minutes . org-duration-string-to-minutes))
+ nval)
+ (when (string= org-clock-current-task heading)
+ (setq org-clock-effort nval)
+ (org-clock-update-mode-line)))
+ (run-hook-with-args 'org-property-changed-functions key nval)))
+
+(defun org-find-olp (path &optional this-buffer)
+ "Return a marker pointing to the entry at outline path OLP.
+If anything goes wrong, throw an error.
+You can wrap this call to catch the error like this:
+
+ (condition-case msg
+ (org-mobile-locate-entry (match-string 4))
+ (error (nth 1 msg)))
+
+The return value will then be either a string with the error message,
+or a marker if everything is OK.
+
+If THIS-BUFFER is set, the outline path does not contain a file,
+only headings."
+ (let* ((file (if this-buffer buffer-file-name (pop path)))
+ (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
+ (level 1)
+ (lmin 1)
+ (lmax 1)
+ end found flevel)
+ (unless buffer (error "File not found :%s" file))
+ (with-current-buffer buffer
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (dolist (heading path)
+ (let ((re (format org-complex-heading-regexp-format
+ (regexp-quote heading)))
+ (cnt 0))
+ (while (re-search-forward re end t)
+ (setq level (- (match-end 1) (match-beginning 1)))
+ (when (and (>= level lmin) (<= level lmax))
+ (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
+ (when (= cnt 0)
+ (error "Heading not found on level %d: %s" lmax heading))
+ (when (> cnt 1)
+ (error "Heading not unique on level %d: %s" lmax heading))
+ (goto-char found)
+ (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
+ (setq end (save-excursion (org-end-of-subtree t t)))))
+ (when (org-at-heading-p)
+ (point-marker))))))
+
+(defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
+ "Find node HEADING in BUFFER.
+Return a marker to the heading if it was found, or nil if not.
+If POS-ONLY is set, return just the position instead of a marker.
+
+The heading text must match exact, but it may have a TODO keyword,
+a priority cookie and tags in the standard locations."
+ (with-current-buffer (or buffer (current-buffer))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let (case-fold-search)
+ (when (re-search-forward
+ (format org-complex-heading-regexp-format
+ (regexp-quote heading)) nil t)
+ (if pos-only
+ (match-beginning 0)
+ (move-marker (make-marker) (match-beginning 0))))))))
+
+(defun org-find-exact-heading-in-directory (heading &optional dir)
+ "Find Org node headline HEADING in all .org files in directory DIR.
+When the target headline is found, return a marker to this location."
+ (let ((files (directory-files (or dir default-directory)
+ t "\\`[^.#].*\\.org\\'"))
+ visiting m buffer)
+ (catch 'found
+ (dolist (file files)
+ (message "trying %s" file)
+ (setq visiting (org-find-base-buffer-visiting file))
+ (setq buffer (or visiting (find-file-noselect file)))
+ (setq m (org-find-exact-headline-in-buffer
+ heading buffer))
+ (when (and (not m) (not visiting)) (kill-buffer buffer))
+ (and m (throw 'found m))))))
+
+(defun org-find-entry-with-id (ident)
+ "Locate the entry that contains the ID property with exact value IDENT.
+IDENT can be a string, a symbol or a number, this function will search for
+the string representation of it.
+Return the position where this entry starts, or nil if there is no such entry."
+ (interactive "sID: ")
+ (let ((id (cond
+ ((stringp ident) ident)
+ ((symbolp ident) (symbol-name ident))
+ ((numberp ident) (number-to-string ident))
+ (t (error "IDENT %s must be a string, symbol or number" ident)))))
+ (org-with-wide-buffer (org-find-property "ID" id))))
+
+;;;; Timestamps
+
+(defvar org-last-changed-timestamp nil)
+(defvar org-last-inserted-timestamp nil
+ "The last time stamp inserted with `org-insert-time-stamp'.")
+(defvar org-ts-what) ; dynamically scoped parameter
+
+(defun org-time-stamp (arg &optional inactive)
+ "Prompt for a date/time and insert a time stamp.
+
+If the user specifies a time like HH:MM or if this command is
+called with at least one prefix argument, the time stamp contains
+the date and the time. Otherwise, only the date is included.
+
+All parts of a date not specified by the user are filled in from
+the timestamp at point, if any, or the current date/time
+otherwise.
+
+If there is already a timestamp at the cursor, it is replaced.
+
+With two universal prefix arguments, insert an active timestamp
+with the current time without prompting the user.
+
+When called from lisp, the timestamp is inactive if INACTIVE is
+non-nil."
+ (interactive "P")
+ (let* ((ts (cond
+ ((org-at-date-range-p t)
+ (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
+ ((org-at-timestamp-p t) (match-string 0))))
+ ;; Default time is either the timestamp at point or today.
+ ;; When entering a range, only the range start is considered.
+ (default-time (if (not ts) (current-time)
+ (apply #'encode-time (org-parse-time-string ts))))
+ (default-input (and ts (org-get-compact-tod ts)))
+ (repeater (and ts
+ (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
+ (match-string 0 ts)))
+ org-time-was-given
+ org-end-time-was-given
+ (time
+ (and (if (equal arg '(16)) (current-time)
+ ;; Preserve `this-command' and `last-command'.
+ (let ((this-command this-command)
+ (last-command last-command))
+ (org-read-date
+ arg 'totime nil nil default-time default-input
+ inactive))))))
+ (cond
+ ((and ts
+ (memq last-command '(org-time-stamp org-time-stamp-inactive))
+ (memq this-command '(org-time-stamp org-time-stamp-inactive)))
+ (insert "--")
+ (org-insert-time-stamp time (or org-time-was-given arg) inactive))
+ (ts
+ ;; Make sure we're on a timestamp. When in the middle of a date
+ ;; range, move arbitrarily to range end.
+ (unless (org-at-timestamp-p t)
+ (skip-chars-forward "-")
+ (org-at-timestamp-p t))
+ (replace-match "")
+ (setq org-last-changed-timestamp
+ (org-insert-time-stamp
+ time (or org-time-was-given arg)
+ inactive nil nil (list org-end-time-was-given)))
+ (when repeater
+ (backward-char)
+ (insert " " repeater)
+ (setq org-last-changed-timestamp
+ (concat (substring org-last-inserted-timestamp 0 -1)
+ " " repeater ">")))
+ (message "Timestamp updated"))
+ ((equal arg '(16)) (org-insert-time-stamp time t inactive))
+ (t (org-insert-time-stamp
+ time (or org-time-was-given arg) inactive nil nil
+ (list org-end-time-was-given))))))
+
+;; FIXME: can we use this for something else, like computing time differences?
+(defun org-get-compact-tod (s)
+ (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
+ (let* ((t1 (match-string 1 s))
+ (h1 (string-to-number (match-string 2 s)))
+ (m1 (string-to-number (match-string 3 s)))
+ (t2 (and (match-end 4) (match-string 5 s)))
+ (h2 (and t2 (string-to-number (match-string 6 s))))
+ (m2 (and t2 (string-to-number (match-string 7 s))))
+ dh dm)
+ (if (not t2)
+ t1
+ (setq dh (- h2 h1) dm (- m2 m1))
+ (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
+ (concat t1 "+" (number-to-string dh)
+ (and (/= 0 dm) (format ":%02d" dm)))))))
+
+(defun org-time-stamp-inactive (&optional arg)
+ "Insert an inactive time stamp.
+An inactive time stamp is enclosed in square brackets instead of angle
+brackets. It is inactive in the sense that it does not trigger agenda entries,
+does not link to the calendar and cannot be changed with the S-cursor keys.
+So these are more for recording a certain time/date."
+ (interactive "P")
+ (org-time-stamp arg 'inactive))
+
+(defvar org-date-ovl (make-overlay 1 1))
+(overlay-put org-date-ovl 'face 'org-date-selected)
+(delete-overlay org-date-ovl)
+
+(defvar org-ans1) ; dynamically scoped parameter
+(defvar org-ans2) ; dynamically scoped parameter
+
+(defvar org-plain-time-of-day-regexp) ; defined below
+
+(defvar org-overriding-default-time nil) ; dynamically scoped
+(defvar org-read-date-overlay nil)
+(defvar org-dcst nil) ; dynamically scoped
+(defvar org-read-date-history nil)
+(defvar org-read-date-final-answer nil)
+(defvar org-read-date-analyze-futurep nil)
+(defvar org-read-date-analyze-forced-year nil)
+(defvar org-read-date-inactive)
+
+(defvar org-read-date-minibuffer-local-map
+ (let* ((map (make-sparse-keymap)))
+ (set-keymap-parent map minibuffer-local-map)
+ (org-defkey map (kbd ".")
+ (lambda () (interactive)
+ ;; Are we at the beginning of the prompt?
+ (if (looking-back "^[^:]+: "
+ (let ((inhibit-field-text-motion t))
+ (line-beginning-position)))
+ (org-eval-in-calendar '(calendar-goto-today))
+ (insert "."))))
+ (org-defkey map (kbd "C-.")
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-goto-today))))
+ (org-defkey map [(meta shift left)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-month 1))))
+ (org-defkey map [(meta shift right)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-month 1))))
+ (org-defkey map [(meta shift up)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-year 1))))
+ (org-defkey map [(meta shift down)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-year 1))))
+ (org-defkey map [?\e (shift left)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-month 1))))
+ (org-defkey map [?\e (shift right)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-month 1))))
+ (org-defkey map [?\e (shift up)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-year 1))))
+ (org-defkey map [?\e (shift down)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-year 1))))
+ (org-defkey map [(shift up)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-week 1))))
+ (org-defkey map [(shift down)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-week 1))))
+ (org-defkey map [(shift left)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-backward-day 1))))
+ (org-defkey map [(shift right)]
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-forward-day 1))))
+ (org-defkey map "!"
+ (lambda () (interactive)
+ (org-eval-in-calendar '(diary-view-entries))
+ (message "")))
+ (org-defkey map ">"
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-scroll-left 1))))
+ (org-defkey map "<"
+ (lambda () (interactive)
+ (org-eval-in-calendar '(calendar-scroll-right 1))))
+ (org-defkey map "\C-v"
+ (lambda () (interactive)
+ (org-eval-in-calendar
+ '(calendar-scroll-left-three-months 1))))
+ (org-defkey map "\M-v"
+ (lambda () (interactive)
+ (org-eval-in-calendar
+ '(calendar-scroll-right-three-months 1))))
+ map)
+ "Keymap for minibuffer commands when using `org-read-date'.")
+
+(defvar org-def)
+(defvar org-defdecode)
+(defvar org-with-time)
+
+(defvar calendar-setup) ; Dynamically scoped.
+(defun org-read-date (&optional with-time to-time from-string prompt
+ default-time default-input inactive)
+ "Read a date, possibly a time, and make things smooth for the user.
+The prompt will suggest to enter an ISO date, but you can also enter anything
+which will at least partially be understood by `parse-time-string'.
+Unrecognized parts of the date will default to the current day, month, year,
+hour and minute. If this command is called to replace a timestamp at point,
+or to enter the second timestamp of a range, the default time is taken
+from the existing stamp. Furthermore, the command prefers the future,
+so if you are giving a date where the year is not given, and the day-month
+combination is already past in the current year, it will assume you
+mean next year. For details, see the manual. A few examples:
+
+ 3-2-5 --> 2003-02-05
+ feb 15 --> currentyear-02-15
+ 2/15 --> currentyear-02-15
+ sep 12 9 --> 2009-09-12
+ 12:45 --> today 12:45
+ 22 sept 0:34 --> currentyear-09-22 0:34
+ 12 --> currentyear-currentmonth-12
+ Fri --> nearest Friday after today
+ -Tue --> last Tuesday
+ etc.
+
+Furthermore you can specify a relative date by giving, as the *first* thing
+in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
+change in days weeks, months, years.
+With a single plus or minus, the date is relative to today. With a double
+plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
+ +4d --> four days from today
+ +4 --> same as above
+ +2w --> two weeks from today
+ ++5 --> five days from default date
+
+The function understands only English month and weekday abbreviations.
+
+While prompting, a calendar is popped up - you can also select the
+date with the mouse (button 1). The calendar shows a period of three
+months. To scroll it to other months, use the keys `>' and `<'.
+If you don't like the calendar, turn it off with
+ (setq org-read-date-popup-calendar nil)
+
+With optional argument TO-TIME, the date will immediately be converted
+to an internal time.
+With an optional argument WITH-TIME, the prompt will suggest to
+also insert a time. Note that when WITH-TIME is not set, you can
+still enter a time, and this function will inform the calling routine
+about this change. The calling routine may then choose to change the
+format used to insert the time stamp into the buffer to include the time.
+With optional argument FROM-STRING, read from this string instead from
+the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
+the time/date that is used for everything that is not specified by the
+user."
+ (require 'parse-time)
+ (let* ((org-with-time with-time)
+ (org-time-stamp-rounding-minutes
+ (if (equal org-with-time '(16))
+ '(0 0)
+ org-time-stamp-rounding-minutes))
+ (org-dcst org-display-custom-times)
+ (ct (org-current-time))
+ (org-def (or org-overriding-default-time default-time ct))
+ (org-defdecode (decode-time org-def))
+ (cur-frame (selected-frame))
+ (mouse-autoselect-window nil) ; Don't let the mouse jump
+ (calendar-setup
+ (and (eq calendar-setup 'calendar-only) 'calendar-only))
+ (calendar-move-hook nil)
+ (calendar-view-diary-initially-flag nil)
+ (calendar-view-holidays-initially-flag nil)
+ ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
+ ;; Rationalize `org-def' and `org-defdecode', if required.
+ (when (< (nth 2 org-defdecode) org-extend-today-until)
+ (setf (nth 2 org-defdecode) -1)
+ (setf (nth 1 org-defdecode) 59)
+ (setq org-def (apply #'encode-time org-defdecode))
+ (setq org-defdecode (decode-time org-def)))
+ (let* ((timestr (format-time-string
+ (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
+ org-def))
+ (prompt (concat (if prompt (concat prompt " ") "")
+ (format "Date+time [%s]: " timestr))))
+ (cond
+ (from-string (setq ans from-string))
+ (org-read-date-popup-calendar
+ (save-excursion
+ (save-window-excursion
+ (calendar)
+ (when (eq calendar-setup 'calendar-only)
+ (setq cal-frame
+ (window-frame (get-buffer-window "*Calendar*" 'visible)))
+ (select-frame cal-frame))
+ (org-eval-in-calendar '(setq cursor-type nil) t)
+ (unwind-protect
+ (progn
+ (calendar-forward-day (- (time-to-days org-def)
+ (calendar-absolute-from-gregorian
+ (calendar-current-date))))
+ (org-eval-in-calendar nil t)
+ (let* ((old-map (current-local-map))
+ (map (copy-keymap calendar-mode-map))
+ (minibuffer-local-map
+ (copy-keymap org-read-date-minibuffer-local-map)))
+ (org-defkey map (kbd "RET") 'org-calendar-select)
+ (org-defkey map [mouse-1] 'org-calendar-select-mouse)
+ (org-defkey map [mouse-2] 'org-calendar-select-mouse)
+ (unwind-protect
+ (progn
+ (use-local-map map)
+ (setq org-read-date-inactive inactive)
+ (add-hook 'post-command-hook 'org-read-date-display)
+ (setq org-ans0
+ (read-string prompt
+ default-input
+ 'org-read-date-history
+ nil))
+ ;; org-ans0: from prompt
+ ;; org-ans1: from mouse click
+ ;; org-ans2: from calendar motion
+ (setq ans
+ (concat org-ans0 " " (or org-ans1 org-ans2))))
+ (remove-hook 'post-command-hook 'org-read-date-display)
+ (use-local-map old-map)
+ (when org-read-date-overlay
+ (delete-overlay org-read-date-overlay)
+ (setq org-read-date-overlay nil)))))
+ (bury-buffer "*Calendar*")
+ (when cal-frame
+ (delete-frame cal-frame)
+ (select-frame-set-input-focus cur-frame))))))
+
+ (t ; Naked prompt only
+ (unwind-protect
+ (setq ans (read-string prompt default-input
+ 'org-read-date-history timestr))
+ (when org-read-date-overlay
+ (delete-overlay org-read-date-overlay)
+ (setq org-read-date-overlay nil))))))
+
+ (setq final (org-read-date-analyze ans org-def org-defdecode))
+
+ (when org-read-date-analyze-forced-year
+ (message "Year was forced into %s"
+ (if org-read-date-force-compatible-dates
+ "compatible range (1970-2037)"
+ "range representable on this machine"))
+ (ding))
+
+ ;; One round trip to get rid of 34th of August and stuff like that....
+ (setq final (decode-time (apply 'encode-time final)))
+
+ (setq org-read-date-final-answer ans)
+
+ (if to-time
+ (apply 'encode-time final)
+ (if (and (boundp 'org-time-was-given) org-time-was-given)
+ (format "%04d-%02d-%02d %02d:%02d"
+ (nth 5 final) (nth 4 final) (nth 3 final)
+ (nth 2 final) (nth 1 final))
+ (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
+
+(defun org-read-date-display ()
+ "Display the current date prompt interpretation in the minibuffer."
+ (when org-read-date-display-live
+ (when org-read-date-overlay
+ (delete-overlay org-read-date-overlay))
+ (when (minibufferp (current-buffer))
+ (save-excursion
+ (end-of-line 1)
+ (while (not (equal (buffer-substring
+ (max (point-min) (- (point) 4)) (point))
+ " "))
+ (insert " ")))
+ (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
+ " " (or org-ans1 org-ans2)))
+ (org-end-time-was-given nil)
+ (f (org-read-date-analyze ans org-def org-defdecode))
+ (fmts (if org-dcst
+ org-time-stamp-custom-formats
+ org-time-stamp-formats))
+ (fmt (if (or org-with-time
+ (and (boundp 'org-time-was-given) org-time-was-given))
+ (cdr fmts)
+ (car fmts)))
+ (txt (format-time-string fmt (apply 'encode-time f)))
+ (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
+ (txt (concat "=> " txt)))
+ (when (and org-end-time-was-given
+ (string-match org-plain-time-of-day-regexp txt))
+ (setq txt (concat (substring txt 0 (match-end 0)) "-"
+ org-end-time-was-given
+ (substring txt (match-end 0)))))
+ (when org-read-date-analyze-futurep
+ (setq txt (concat txt " (=>F)")))
+ (setq org-read-date-overlay
+ (make-overlay (1- (point-at-eol)) (point-at-eol)))
+ (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
+
+(defun org-read-date-analyze (ans def defdecode)
+ "Analyze the combined answer of the date prompt."
+ ;; FIXME: cleanup and comment
+ ;; Pass `current-time' result to `decode-time' (instead of calling
+ ;; without arguments) so that only `current-time' has to be
+ ;; overriden in tests.
+ (let ((org-def def)
+ (org-defdecode defdecode)
+ (nowdecode (decode-time (current-time)))
+ delta deltan deltaw deltadef year month day
+ hour minute second wday pm h2 m2 tl wday1
+ iso-year iso-weekday iso-week iso-date futurep kill-year)
+ (setq org-read-date-analyze-futurep nil
+ org-read-date-analyze-forced-year nil)
+ (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
+ (setq ans "+0"))
+
+ (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
+ (setq ans (replace-match "" t t ans)
+ deltan (car delta)
+ deltaw (nth 1 delta)
+ deltadef (nth 2 delta)))
+
+ ;; Check if there is an iso week date in there. If yes, store the
+ ;; info and postpone interpreting it until the rest of the parsing
+ ;; is done.
+ (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
+ (setq iso-year (when (match-end 1)
+ (org-small-year-to-year
+ (string-to-number (match-string 1 ans))))
+ iso-weekday (when (match-end 3)
+ (string-to-number (match-string 3 ans)))
+ iso-week (string-to-number (match-string 2 ans)))
+ (setq ans (replace-match "" t t ans)))
+
+ ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
+ (when (string-match
+ "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
+ (setq year (if (match-end 2)
+ (string-to-number (match-string 2 ans))
+ (progn (setq kill-year t)
+ (string-to-number (format-time-string "%Y"))))
+ month (string-to-number (match-string 3 ans))
+ day (string-to-number (match-string 4 ans)))
+ (setq year (org-small-year-to-year year))
+ (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
+ t nil ans)))
+
+ ;; Help matching dotted european dates
+ (when (string-match
+ "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
+ (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
+ (setq kill-year t)
+ (string-to-number (format-time-string "%Y")))
+ day (string-to-number (match-string 1 ans))
+ month (string-to-number (match-string 2 ans))
+ ans (replace-match (format "%04d-%02d-%02d" year month day)
+ t nil ans)))
+
+ ;; Help matching american dates, like 5/30 or 5/30/7
+ (when (string-match
+ "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
+ (setq year (if (match-end 4)
+ (string-to-number (match-string 4 ans))
+ (progn (setq kill-year t)
+ (string-to-number (format-time-string "%Y"))))
+ month (string-to-number (match-string 1 ans))
+ day (string-to-number (match-string 2 ans)))
+ (setq year (org-small-year-to-year year))
+ (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
+ t nil ans)))
+ ;; Help matching am/pm times, because `parse-time-string' does not do that.
+ ;; If there is a time with am/pm, and *no* time without it, we convert
+ ;; so that matching will be successful.
+ (cl-loop for i from 1 to 2 do ; twice, for end time as well
+ (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
+ (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
+ (setq hour (string-to-number (match-string 1 ans))
+ minute (if (match-end 3)
+ (string-to-number (match-string 3 ans))
+ 0)
+ pm (equal ?p
+ (string-to-char (downcase (match-string 4 ans)))))
+ (if (and (= hour 12) (not pm))
+ (setq hour 0)
+ (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
+ (setq ans (replace-match (format "%02d:%02d" hour minute)
+ t t ans))))
+
+ ;; Check if a time range is given as a duration
+ (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
+ (setq hour (string-to-number (match-string 1 ans))
+ h2 (+ hour (string-to-number (match-string 3 ans)))
+ minute (string-to-number (match-string 2 ans))
+ m2 (+ minute (if (match-end 5) (string-to-number
+ (match-string 5 ans))0)))
+ (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
+ (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
+ t t ans)))
+
+ ;; Check if there is a time range
+ (when (boundp 'org-end-time-was-given)
+ (setq org-time-was-given nil)
+ (when (and (string-match org-plain-time-of-day-regexp ans)
+ (match-end 8))
+ (setq org-end-time-was-given (match-string 8 ans))
+ (setq ans (concat (substring ans 0 (match-beginning 7))
+ (substring ans (match-end 7))))))
+
+ (setq tl (parse-time-string ans)
+ day (or (nth 3 tl) (nth 3 org-defdecode))
+ month
+ (cond ((nth 4 tl))
+ ((not org-read-date-prefer-future) (nth 4 org-defdecode))
+ ;; Day was specified. Make sure DAY+MONTH
+ ;; combination happens in the future.
+ ((nth 3 tl)
+ (setq futurep t)
+ (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
+ (nth 4 nowdecode)))
+ (t (nth 4 org-defdecode)))
+ year
+ (cond ((and (not kill-year) (nth 5 tl)))
+ ((not org-read-date-prefer-future) (nth 5 org-defdecode))
+ ;; Month was guessed in the future and is at least
+ ;; equal to NOWDECODE's. Fix year accordingly.
+ (futurep
+ (if (or (> month (nth 4 nowdecode))
+ (>= day (nth 3 nowdecode)))
+ (nth 5 nowdecode)
+ (1+ (nth 5 nowdecode))))
+ ;; Month was specified. Make sure MONTH+YEAR
+ ;; combination happens in the future.
+ ((nth 4 tl)
+ (setq futurep t)
+ (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
+ ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
+ ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
+ (t (nth 5 nowdecode))))
+ (t (nth 5 org-defdecode)))
+ hour (or (nth 2 tl) (nth 2 org-defdecode))
+ minute (or (nth 1 tl) (nth 1 org-defdecode))
+ second (or (nth 0 tl) 0)
+ wday (nth 6 tl))
+
+ (when (and (eq org-read-date-prefer-future 'time)
+ (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
+ (equal day (nth 3 nowdecode))
+ (equal month (nth 4 nowdecode))
+ (equal year (nth 5 nowdecode))
+ (nth 2 tl)
+ (or (< (nth 2 tl) (nth 2 nowdecode))
+ (and (= (nth 2 tl) (nth 2 nowdecode))
+ (nth 1 tl)
+ (< (nth 1 tl) (nth 1 nowdecode)))))
+ (setq day (1+ day)
+ futurep t))
+
+ ;; Special date definitions below
+ (cond
+ (iso-week
+ ;; There was an iso week
+ (require 'cal-iso)
+ (setq futurep nil)
+ (setq year (or iso-year year)
+ day (or iso-weekday wday 1)
+ wday nil ; to make sure that the trigger below does not match
+ iso-date (calendar-gregorian-from-absolute
+ (calendar-iso-to-absolute
+ (list iso-week day year))))
+ ; FIXME: Should we also push ISO weeks into the future?
+ ; (when (and org-read-date-prefer-future
+ ; (not iso-year)
+ ; (< (calendar-absolute-from-gregorian iso-date)
+ ; (time-to-days (current-time))))
+ ; (setq year (1+ year)
+ ; iso-date (calendar-gregorian-from-absolute
+ ; (calendar-iso-to-absolute
+ ; (list iso-week day year)))))
+ (setq month (car iso-date)
+ year (nth 2 iso-date)
+ day (nth 1 iso-date)))
+ (deltan
+ (setq futurep nil)
+ (unless deltadef
+ ;; Pass `current-time' result to `decode-time' (instead of
+ ;; calling without arguments) so that only `current-time' has
+ ;; to be overriden in tests.
+ (let ((now (decode-time (current-time))))
+ (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
+ (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
+ ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
+ ((equal deltaw "m") (setq month (+ month deltan)))
+ ((equal deltaw "y") (setq year (+ year deltan)))))
+ ((and wday (not (nth 3 tl)))
+ ;; Weekday was given, but no day, so pick that day in the week
+ ;; on or after the derived date.
+ (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
+ (unless (equal wday wday1)
+ (setq day (+ day (% (- wday wday1 -7) 7))))))
+ (when (and (boundp 'org-time-was-given)
+ (nth 2 tl))
+ (setq org-time-was-given t))
+ (when (< year 100) (setq year (+ 2000 year)))
+ ;; Check of the date is representable
+ (if org-read-date-force-compatible-dates
+ (progn
+ (when (< year 1970)
+ (setq year 1970 org-read-date-analyze-forced-year t))
+ (when (> year 2037)
+ (setq year 2037 org-read-date-analyze-forced-year t)))
+ (condition-case nil
+ (ignore (encode-time second minute hour day month year))
+ (error
+ (setq year (nth 5 org-defdecode))
+ (setq org-read-date-analyze-forced-year t))))
+ (setq org-read-date-analyze-futurep futurep)
+ (list second minute hour day month year)))
+
+(defvar parse-time-weekdays)
+(defun org-read-date-get-relative (s today default)
+ "Check string S for special relative date string.
+TODAY and DEFAULT are internal times, for today and for a default.
+Return shift list (N what def-flag)
+WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
+N is the number of WHATs to shift.
+DEF-FLAG is t when a double ++ or -- indicates shift relative to
+ the DEFAULT date rather than TODAY."
+ (require 'parse-time)
+ (when (and
+ (string-match
+ (concat
+ "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
+ "\\([0-9]+\\)?"
+ "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
+ "\\([ \t]\\|$\\)") s)
+ (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
+ (let* ((dir (if (> (match-end 1) (match-beginning 1))
+ (string-to-char (substring (match-string 1 s) -1))
+ ?+))
+ (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
+ (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
+ (what (if (match-end 3) (match-string 3 s) "d"))
+ (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
+ (date (if rel default today))
+ (wday (nth 6 (decode-time date)))
+ delta)
+ (if wday1
+ (progn
+ (setq delta (mod (+ 7 (- wday1 wday)) 7))
+ (when (= delta 0) (setq delta 7))
+ (when (= dir ?-)
+ (setq delta (- delta 7))
+ (when (= delta 0) (setq delta -7)))
+ (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
+ (list delta "d" rel))
+ (list (* n (if (= dir ?-) -1 1)) what rel)))))
+
+(defun org-order-calendar-date-args (arg1 arg2 arg3)
+ "Turn a user-specified date into the internal representation.
+The internal representation needed by the calendar is (month day year).
+This is a wrapper to handle the brain-dead convention in calendar that
+user function argument order change dependent on argument order."
+ (pcase calendar-date-style
+ (`american (list arg1 arg2 arg3))
+ (`european (list arg2 arg1 arg3))
+ (`iso (list arg2 arg3 arg1))))
+
+(defun org-eval-in-calendar (form &optional keepdate)
+ "Eval FORM in the calendar window and return to current window.
+Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
+ (let ((sf (selected-frame))
+ (sw (selected-window)))
+ (select-window (get-buffer-window "*Calendar*" t))
+ (eval form)
+ (when (and (not keepdate) (calendar-cursor-to-date))
+ (let* ((date (calendar-cursor-to-date))
+ (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
+ (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
+ (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
+ (select-window sw)
+ (select-frame-set-input-focus sf)))
+
+(defun org-calendar-select ()
+ "Return to `org-read-date' with the date currently selected.
+This is used by `org-read-date' in a temporary keymap for the calendar buffer."
+ (interactive)
+ (when (calendar-cursor-to-date)
+ (let* ((date (calendar-cursor-to-date))
+ (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
+ (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
+ (when (active-minibuffer-window) (exit-minibuffer))))
+
+(defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
+ "Insert a date stamp for the date given by the internal TIME.
+See `format-time-string' for the format of TIME.
+WITH-HM means use the stamp format that includes the time of the day.
+INACTIVE means use square brackets instead of angular ones, so that the
+stamp will not contribute to the agenda.
+PRE and POST are optional strings to be inserted before and after the
+stamp.
+The command returns the inserted time stamp."
+ (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
+ stamp)
+ (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
+ (insert-before-markers (or pre ""))
+ (when (listp extra)
+ (setq extra (car extra))
+ (if (and (stringp extra)
+ (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
+ (setq extra (format "-%02d:%02d"
+ (string-to-number (match-string 1 extra))
+ (string-to-number (match-string 2 extra))))
+ (setq extra nil)))
+ (when extra
+ (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
+ (insert-before-markers (setq stamp (format-time-string fmt time)))
+ (insert-before-markers (or post ""))
+ (setq org-last-inserted-timestamp stamp)))
+
+(defun org-toggle-time-stamp-overlays ()
+ "Toggle the use of custom time stamp formats."
+ (interactive)
+ (setq org-display-custom-times (not org-display-custom-times))
+ (unless org-display-custom-times
+ (let ((p (point-min)) (bmp (buffer-modified-p)))
+ (while (setq p (next-single-property-change p 'display))
+ (when (and (get-text-property p 'display)
+ (eq (get-text-property p 'face) 'org-date))
+ (remove-text-properties
+ p (setq p (next-single-property-change p 'display))
+ '(display t))))
+ (set-buffer-modified-p bmp)))
+ (org-restart-font-lock)
+ (setq org-table-may-need-update t)
+ (if org-display-custom-times
+ (message "Time stamps are overlaid with custom format")
+ (message "Time stamp overlays removed")))
+
+(defun org-display-custom-time (beg end)
+ "Overlay modified time stamp format over timestamp between BEG and END."
+ (let* ((ts (buffer-substring beg end))
+ t1 w1 with-hm tf time str w2 (off 0))
+ (save-match-data
+ (setq t1 (org-parse-time-string ts t))
+ (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
+ (setq off (- (match-end 0) (match-beginning 0)))))
+ (setq end (- end off))
+ (setq w1 (- end beg)
+ with-hm (and (nth 1 t1) (nth 2 t1))
+ tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
+ time (org-fix-decoded-time t1)
+ str (org-add-props
+ (format-time-string
+ (substring tf 1 -1) (apply 'encode-time time))
+ nil 'mouse-face 'highlight)
+ w2 (length str))
+ (unless (= w2 w1)
+ (add-text-properties (1+ beg) (+ 2 beg)
+ (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
+ (put-text-property beg end 'display str)))
+
+(defun org-fix-decoded-time (time)
+ "Set 0 instead of nil for the first 6 elements of time.
+Don't touch the rest."
+ (let ((n 0))
+ (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
+
+(defun org-time-stamp-to-now (timestamp-string &optional seconds)
+ "Difference between TIMESTAMP-STRING and now in days.
+If SECONDS is non-nil, return the difference in seconds."
+ (let ((fdiff (if seconds #'float-time #'time-to-days)))
+ (- (funcall fdiff (org-time-string-to-time timestamp-string))
+ (funcall fdiff (current-time)))))
+
+(defun org-deadline-close-p (timestamp-string &optional ndays)
+ "Is the time in TIMESTAMP-STRING close to the current date?"
+ (setq ndays (or ndays (org-get-wdays timestamp-string)))
+ (and (<= (org-time-stamp-to-now timestamp-string) ndays)
+ (not (org-entry-is-done-p))))
+
+(defun org-get-wdays (ts &optional delay zero-delay)
+ "Get the deadline lead time appropriate for timestring TS.
+When DELAY is non-nil, get the delay time for scheduled items
+instead of the deadline lead time. When ZERO-DELAY is non-nil
+and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
+don't try to find the delay cookie in the scheduled timestamp."
+ (let ((tv (if delay org-scheduled-delay-days
+ org-deadline-warning-days)))
+ (cond
+ ((or (and delay (< tv 0))
+ (and delay zero-delay (<= tv 0))
+ (and (not delay) (<= tv 0)))
+ ;; Enforce this value no matter what
+ (- tv))
+ ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
+ ;; lead time is specified.
+ (floor (* (string-to-number (match-string 1 ts))
+ (cdr (assoc (match-string 2 ts)
+ '(("d" . 1) ("w" . 7)
+ ("m" . 30.4) ("y" . 365.25)
+ ("h" . 0.041667)))))))
+ ;; go for the default.
+ (t tv))))
+
+(defun org-calendar-select-mouse (ev)
+ "Return to `org-read-date' with the date currently selected.
+This is used by `org-read-date' in a temporary keymap for the calendar buffer."
+ (interactive "e")
+ (mouse-set-point ev)
+ (when (calendar-cursor-to-date)
+ (let* ((date (calendar-cursor-to-date))
+ (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
+ (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
+ (when (active-minibuffer-window) (exit-minibuffer))))
+
+(defun org-check-deadlines (ndays)
+ "Check if there are any deadlines due or past due.
+A deadline is considered due if it happens within `org-deadline-warning-days'
+days from today's date. If the deadline appears in an entry marked DONE,
+it is not shown. A numeric prefix argument NDAYS can be used to test that
+many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
+are shown."
+ (interactive "P")
+ (let* ((org-warn-days
+ (cond
+ ((equal ndays '(4)) 100000)
+ (ndays (prefix-numeric-value ndays))
+ (t (abs org-deadline-warning-days))))
+ (case-fold-search nil)
+ (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
+ (callback
+ (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
+ (message "%d deadlines past-due or due within %d days"
+ (org-occur regexp nil callback)
+ org-warn-days)))
+
+(defsubst org-re-timestamp (type)
+ "Return a regexp for timestamp TYPE.
+Allowed values for TYPE are:
+
+ all: all timestamps
+ active: only active timestamps (<...>)
+ inactive: only inactive timestamps ([...])
+ scheduled: only scheduled timestamps
+ deadline: only deadline timestamps
+ closed: only closed time-stamps
+
+When TYPE is nil, fall back on returning a regexp that matches
+both scheduled and deadline timestamps."
+ (cl-case type
+ (all org-ts-regexp-both)
+ (active org-ts-regexp)
+ (inactive org-ts-regexp-inactive)
+ (scheduled org-scheduled-time-regexp)
+ (deadline org-deadline-time-regexp)
+ (closed org-closed-time-regexp)
+ (otherwise
+ (concat "\\<"
+ (regexp-opt (list org-deadline-string org-scheduled-string))
+ " *<\\([^>]+\\)>"))))
+
+(defun org-check-before-date (d)
+ "Check if there are deadlines or scheduled entries before date D."
+ (interactive (list (org-read-date)))
+ (let* ((case-fold-search nil)
+ (regexp (org-re-timestamp org-ts-type))
+ (ts-type org-ts-type)
+ (callback
+ (lambda ()
+ (let ((match (match-string 1)))
+ (and (if (memq ts-type '(active inactive all))
+ (eq (org-element-type (save-excursion
+ (backward-char)
+ (org-element-context)))
+ 'timestamp)
+ (org-at-planning-p))
+ (time-less-p
+ (org-time-string-to-time match)
+ (org-time-string-to-time d)))))))
+ (message "%d entries before %s"
+ (org-occur regexp nil callback)
+ d)))
+
+(defun org-check-after-date (d)
+ "Check if there are deadlines or scheduled entries after date D."
+ (interactive (list (org-read-date)))
+ (let* ((case-fold-search nil)
+ (regexp (org-re-timestamp org-ts-type))
+ (ts-type org-ts-type)
+ (callback
+ (lambda ()
+ (let ((match (match-string 1)))
+ (and (if (memq ts-type '(active inactive all))
+ (eq (org-element-type (save-excursion
+ (backward-char)
+ (org-element-context)))
+ 'timestamp)
+ (org-at-planning-p))
+ (not (time-less-p
+ (org-time-string-to-time match)
+ (org-time-string-to-time d))))))))
+ (message "%d entries after %s"
+ (org-occur regexp nil callback)
+ d)))
+
+(defun org-check-dates-range (start-date end-date)
+ "Check for deadlines/scheduled entries between START-DATE and END-DATE."
+ (interactive (list (org-read-date nil nil nil "Range starts")
+ (org-read-date nil nil nil "Range end")))
+ (let ((case-fold-search nil)
+ (regexp (org-re-timestamp org-ts-type))
+ (callback
+ (let ((type org-ts-type))
+ (lambda ()
+ (let ((match (match-string 1)))
+ (and
+ (if (memq type '(active inactive all))
+ (eq (org-element-type (save-excursion
+ (backward-char)
+ (org-element-context)))
+ 'timestamp)
+ (org-at-planning-p))
+ (not (time-less-p
+ (org-time-string-to-time match)
+ (org-time-string-to-time start-date)))
+ (time-less-p
+ (org-time-string-to-time match)
+ (org-time-string-to-time end-date))))))))
+ (message "%d entries between %s and %s"
+ (org-occur regexp nil callback) start-date end-date)))
+
+(defun org-evaluate-time-range (&optional to-buffer)
+ "Evaluate a time range by computing the difference between start and end.
+Normally the result is just printed in the echo area, but with prefix arg
+TO-BUFFER, the result is inserted just after the date stamp into the buffer.
+If the time range is actually in a table, the result is inserted into the
+next column.
+For time difference computation, a year is assumed to be exactly 365
+days in order to avoid rounding problems."
+ (interactive "P")
+ (or
+ (org-clock-update-time-maybe)
+ (save-excursion
+ (unless (org-at-date-range-p t)
+ (goto-char (point-at-bol))
+ (re-search-forward org-tr-regexp-both (point-at-eol) t))
+ (unless (org-at-date-range-p t)
+ (user-error "Not at a time-stamp range, and none found in current line")))
+ (let* ((ts1 (match-string 1))
+ (ts2 (match-string 2))
+ (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
+ (match-end (match-end 0))
+ (time1 (org-time-string-to-time ts1))
+ (time2 (org-time-string-to-time ts2))
+ (t1 (float-time time1))
+ (t2 (float-time time2))
+ (diff (abs (- t2 t1)))
+ (negative (< (- t2 t1) 0))
+ ;; (ys (floor (* 365 24 60 60)))
+ (ds (* 24 60 60))
+ (hs (* 60 60))
+ (fy "%dy %dd %02d:%02d")
+ (fy1 "%dy %dd")
+ (fd "%dd %02d:%02d")
+ (fd1 "%dd")
+ (fh "%02d:%02d")
+ y d h m align)
+ (if havetime
+ (setq ; y (floor (/ diff ys)) diff (mod diff ys)
+ y 0
+ d (floor (/ diff ds)) diff (mod diff ds)
+ h (floor (/ diff hs)) diff (mod diff hs)
+ m (floor (/ diff 60)))
+ (setq ; y (floor (/ diff ys)) diff (mod diff ys)
+ y 0
+ d (floor (+ (/ diff ds) 0.5))
+ h 0 m 0))
+ (if (not to-buffer)
+ (message "%s" (org-make-tdiff-string y d h m))
+ (if (org-at-table-p)
+ (progn
+ (goto-char match-end)
+ (setq align t)
+ (and (looking-at " *|") (goto-char (match-end 0))))
+ (goto-char match-end))
+ (when (looking-at
+ "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
+ (replace-match ""))
+ (when negative (insert " -"))
+ (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
+ (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
+ (insert " " (format fh h m))))
+ (when align (org-table-align))
+ (message "Time difference inserted")))))
+
+(defun org-make-tdiff-string (y d h m)
+ (let ((fmt "")
+ (l nil))
+ (when (> y 0)
+ (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
+ (push y l))
+ (when (> d 0)
+ (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
+ (push d l))
+ (when (> h 0)
+ (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
+ (push h l))
+ (when (> m 0)
+ (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
+ (push m l))
+ (apply 'format fmt (nreverse l))))
+
+(defun org-time-string-to-time (s &optional buffer pos)
+ "Convert a timestamp string into internal time."
+ (condition-case errdata
+ (apply 'encode-time (org-parse-time-string s))
+ (error (error "Bad timestamp `%s'%s\nError was: %s"
+ s (if (not (and buffer pos))
+ ""
+ (format-message " at %d in buffer `%s'" pos buffer))
+ (cdr errdata)))))
+
+(defun org-time-string-to-seconds (s)
+ "Convert a timestamp string to a number of seconds."
+ (float-time (org-time-string-to-time s)))
+
+(org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
+
+(defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
+ "Convert time stamp S to an absolute day number.
+
+If DAYNR in non-nil, and there is a specifier for a cyclic time
+stamp, get the closest date to DAYNR. If PREFER is
+`past' (respectively `future') return a date past (respectively
+after) or equal to DAYNR.
+
+POS is the location of time stamp S, as a buffer position in
+BUFFER.
+
+Diary sexp timestamps are matched against DAYNR, when non-nil.
+If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
+signalled."
+ (cond
+ ((string-match "\\`%%\\((.*)\\)" s)
+ ;; Sexp timestamp: try to match DAYNR, if available, since we're
+ ;; only able to match individual dates. If it fails, raise an
+ ;; error.
+ (if (and daynr
+ (org-diary-sexp-entry
+ (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
+ daynr
+ (signal 'org-diary-sexp-no-match (list s))))
+ (daynr (org-closest-date s daynr prefer))
+ (t (time-to-days
+ (condition-case errdata
+ (apply #'encode-time (org-parse-time-string s))
+ (error (error "Bad timestamp `%s'%s\nError was: %s"
+ s
+ (if (not (and buffer pos)) ""
+ (format-message " at %d in buffer `%s'" pos buffer))
+ (cdr errdata))))))))
+
+(defun org-days-to-iso-week (days)
+ "Return the iso week number."
+ (require 'cal-iso)
+ (car (calendar-iso-from-absolute days)))
+
+(defun org-small-year-to-year (year)
+ "Convert 2-digit years into 4-digit years.
+YEAR is expanded into one of the 30 next years, if possible, or
+into a past one. Any year larger than 99 is returned unchanged."
+ (if (>= year 100) year
+ (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
+ (century (/ current 100))
+ (offset (- year (% current 100))))
+ (cond ((> offset 30) (+ (* (1- century) 100) year))
+ ((> offset -70) (+ (* century 100) year))
+ (t (+ (* (1+ century) 100) year))))))
+
+(defun org-time-from-absolute (d)
+ "Return the time corresponding to date D.
+D may be an absolute day number, or a calendar-type list (month day year)."
+ (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
+ (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
+
+(defvar org-agenda-current-date)
+(defun org-calendar-holiday ()
+ "List of holidays, for Diary display in Org mode."
+ (require 'holidays)
+ (let ((hl (calendar-check-holidays org-agenda-current-date)))
+ (and hl (mapconcat #'identity hl "; "))))
+
+(defun org-diary-sexp-entry (sexp entry d)
+ "Process a SEXP diary ENTRY for date D."
+ (require 'diary-lib)
+ ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
+ ;; dynamically.
+ (let* ((sexp `(let ((entry ,entry)
+ (date ',d))
+ ,(car (read-from-string sexp))))
+ (result (if calendar-debug-sexp (eval sexp)
+ (condition-case nil
+ (eval sexp)
+ (error
+ (beep)
+ (message "Bad sexp at line %d in %s: %s"
+ (org-current-line)
+ (buffer-file-name) sexp)
+ (sleep-for 2))))))
+ (cond ((stringp result) (split-string result "; "))
+ ((and (consp result)
+ (not (consp (cdr result)))
+ (stringp (cdr result))) (cdr result))
+ ((and (consp result)
+ (stringp (car result))) result)
+ (result entry))))
+
+(defun org-diary-to-ical-string (frombuf)
+ "Get iCalendar entries from diary entries in buffer FROMBUF.
+This uses the icalendar.el library."
+ (let* ((tmpdir temporary-file-directory)
+ (tmpfile (make-temp-name
+ (expand-file-name "orgics" tmpdir)))
+ buf rtn b e)
+ (with-current-buffer frombuf
+ (icalendar-export-region (point-min) (point-max) tmpfile)
+ (setq buf (find-buffer-visiting tmpfile))
+ (set-buffer buf)
+ (goto-char (point-min))
+ (when (re-search-forward "^BEGIN:VEVENT" nil t)
+ (setq b (match-beginning 0)))
+ (goto-char (point-max))
+ (when (re-search-backward "^END:VEVENT" nil t)
+ (setq e (match-end 0)))
+ (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
+ (kill-buffer buf)
+ (delete-file tmpfile)
+ rtn))
+
+(defun org-closest-date (start current prefer)
+ "Return closest date to CURRENT starting from START.
+
+CURRENT and START are both time stamps.
+
+When PREFER is `past', return a date that is either CURRENT or
+past. When PREFER is `future', return a date that is either
+CURRENT or future.
+
+Only time stamps with a repeater are modified. Any other time
+stamp stay unchanged. In any case, return value is an absolute
+day number."
+ (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
+ ;; No repeater. Do not shift time stamp.
+ (time-to-days (apply #'encode-time (org-parse-time-string start)))
+ (let ((value (string-to-number (match-string 1 start)))
+ (type (match-string 2 start)))
+ (if (= 0 value)
+ ;; Repeater with a 0-value is considered as void.
+ (time-to-days (apply #'encode-time (org-parse-time-string start)))
+ (let* ((base (org-date-to-gregorian start))
+ (target (org-date-to-gregorian current))
+ (sday (calendar-absolute-from-gregorian base))
+ (cday (calendar-absolute-from-gregorian target))
+ n1 n2)
+ ;; If START is already past CURRENT, just return START.
+ (if (<= cday sday) sday
+ ;; Compute closest date before (N1) and closest date past
+ ;; (N2) CURRENT.
+ (pcase type
+ ("h"
+ (let ((missing-hours
+ (mod (+ (- (* 24 (- cday sday))
+ (nth 2 (org-parse-time-string start)))
+ org-extend-today-until)
+ value)))
+ (setf n1 (if (= missing-hours 0) cday
+ (- cday (1+ (/ missing-hours 24)))))
+ (setf n2 (+ cday (/ (- value missing-hours) 24)))))
+ ((or "d" "w")
+ (let ((value (if (equal type "w") (* 7 value) value)))
+ (setf n1 (+ sday (* value (/ (- cday sday) value))))
+ (setf n2 (+ n1 value))))
+ ("m"
+ (let* ((add-months
+ (lambda (d n)
+ ;; Add N months to gregorian date D, i.e.,
+ ;; a list (MONTH DAY YEAR). Return a valid
+ ;; gregorian date.
+ (let ((m (+ (nth 0 d) n)))
+ (list (mod m 12)
+ (nth 1 d)
+ (+ (/ m 12) (nth 2 d))))))
+ (months ; Complete months to TARGET.
+ (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
+ (- (nth 0 target) (nth 0 base))
+ ;; If START's day is greater than
+ ;; TARGET's, remove incomplete month.
+ (if (> (nth 1 target) (nth 1 base)) 0 -1))
+ value)
+ value))
+ (before (funcall add-months base months)))
+ (setf n1 (calendar-absolute-from-gregorian before))
+ (setf n2
+ (calendar-absolute-from-gregorian
+ (funcall add-months before value)))))
+ (_
+ (let* ((d (nth 1 base))
+ (m (nth 0 base))
+ (y (nth 2 base))
+ (years ; Complete years to TARGET.
+ (* (/ (- (nth 2 target)
+ y
+ ;; If START's month and day are
+ ;; greater than TARGET's, remove
+ ;; incomplete year.
+ (if (or (> (nth 0 target) m)
+ (and (= (nth 0 target) m)
+ (> (nth 1 target) d)))
+ 0
+ 1))
+ value)
+ value))
+ (before (list m d (+ y years))))
+ (setf n1 (calendar-absolute-from-gregorian before))
+ (setf n2 (calendar-absolute-from-gregorian
+ (list m d (+ (nth 2 before) value)))))))
+ ;; Handle PREFER parameter, if any.
+ (cond
+ ((eq prefer 'past) (if (= cday n2) n2 n1))
+ ((eq prefer 'future) (if (= cday n1) n1 n2))
+ (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
+
+(defun org-date-to-gregorian (d)
+ "Turn any specification of date D into a Gregorian date for the calendar."
+ (cond ((integerp d) (calendar-gregorian-from-absolute d))
+ ((and (listp d) (= (length d) 3)) d)
+ ((stringp d)
+ (let ((d (org-parse-time-string d)))
+ (list (nth 4 d) (nth 3 d) (nth 5 d))))
+ ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
+
+(defun org-parse-time-string (s &optional nodefault zone)
+ "Parse the standard Org time string.
+
+This should be a lot faster than the normal `parse-time-string'.
+
+If time is not given, defaults to 0:00. However, with optional
+NODEFAULT, hour and minute fields will be nil if not given.
+
+The optional ZONE is omitted or nil for Emacs local time, t for
+Universal Time, ‘wall’ for system wall clock time, or a string as
+in the TZ environment variable."
+ (cond ((string-match org-ts-regexp0 s)
+ (list 0
+ (when (or (match-beginning 8) (not nodefault))
+ (string-to-number (or (match-string 8 s) "0")))
+ (when (or (match-beginning 7) (not nodefault))
+ (string-to-number (or (match-string 7 s) "0")))
+ (string-to-number (match-string 4 s))
+ (string-to-number (match-string 3 s))
+ (string-to-number (match-string 2 s))
+ nil nil zone))
+ ((string-match "^<[^>]+>$" s)
+ ;; FIXME: `decode-time' needs to be called with ZONE as its
+ ;; second argument. However, this requires at least Emacs
+ ;; 25.1. We can do it when we switch to this version as our
+ ;; minimal requirement.
+ (decode-time (seconds-to-time (org-matcher-time s))))
+ (t (error "Not a standard Org time string: %s" s))))
+
+(defun org-timestamp-up (&optional arg)
+ "Increase the date item at the cursor by one.
+If the cursor is on the year, change the year. If it is on the month,
+the day or the time, change that.
+With prefix ARG, change by that many units."
+ (interactive "p")
+ (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
+
+(defun org-timestamp-down (&optional arg)
+ "Decrease the date item at the cursor by one.
+If the cursor is on the year, change the year. If it is on the month,
+the day or the time, change that.
+With prefix ARG, change by that many units."
+ (interactive "p")
+ (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
+
+(defun org-timestamp-up-day (&optional arg)
+ "Increase the date in the time stamp by one day.
+With prefix ARG, change that many days."
+ (interactive "p")
+ (if (and (not (org-at-timestamp-p t))
+ (org-at-heading-p))
+ (org-todo 'up)
+ (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
+
+(defun org-timestamp-down-day (&optional arg)
+ "Decrease the date in the time stamp by one day.
+With prefix ARG, change that many days."
+ (interactive "p")
+ (if (and (not (org-at-timestamp-p t))
+ (org-at-heading-p))
+ (org-todo 'down)
+ (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
+
+(defun org-at-timestamp-p (&optional inactive-ok)
+ "Non-nil if point is inside a timestamp.
+
+When optional argument INACTIVE-OK is non-nil, also consider
+inactive timestamps.
+
+When this function returns a non-nil value, match data is set
+according to `org-ts-regexp3' or `org-ts-regexp2', depending on
+INACTIVE-OK."
+ (interactive)
+ (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
+ (pos (point))
+ (ans (or (looking-at tsr)
+ (save-excursion
+ (skip-chars-backward "^[<\n\r\t")
+ (when (> (point) (point-min)) (backward-char 1))
+ (and (looking-at tsr)
+ (> (- (match-end 0) pos) -1))))))
+ (and ans
+ (boundp 'org-ts-what)
+ (setq org-ts-what
+ (cond
+ ((= pos (match-beginning 0)) 'bracket)
+ ;; Point is considered to be "on the bracket" whether
+ ;; it's really on it or right after it.
+ ((= pos (1- (match-end 0))) 'bracket)
+ ((= pos (match-end 0)) 'after)
+ ((org-pos-in-match-range pos 2) 'year)
+ ((org-pos-in-match-range pos 3) 'month)
+ ((org-pos-in-match-range pos 7) 'hour)
+ ((org-pos-in-match-range pos 8) 'minute)
+ ((or (org-pos-in-match-range pos 4)
+ (org-pos-in-match-range pos 5)) 'day)
+ ((and (> pos (or (match-end 8) (match-end 5)))
+ (< pos (match-end 0)))
+ (- pos (or (match-end 8) (match-end 5))))
+ (t 'day))))
+ ans))
+
+(defun org-toggle-timestamp-type ()
+ "Toggle the type (<active> or [inactive]) of a time stamp."
+ (interactive)
+ (when (org-at-timestamp-p t)
+ (let ((beg (match-beginning 0)) (end (match-end 0))
+ (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
+ (save-excursion
+ (goto-char beg)
+ (while (re-search-forward "[][<>]" end t)
+ (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
+ t t)))
+ (message "Timestamp is now %sactive"
+ (if (equal (char-after beg) ?<) "" "in")))))
+
+(defun org-at-clock-log-p nil
+ "Is the cursor on the clock log line?"
+ (save-excursion
+ (beginning-of-line)
+ (looking-at org-clock-line-re)))
+
+(defvar org-clock-history) ; defined in org-clock.el
+(defvar org-clock-adjust-closest nil) ; defined in org-clock.el
+(defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
+ "Change the date in the time stamp at point.
+The date will be changed by N times WHAT. WHAT can be `day', `month',
+`year', `minute', `second'. If WHAT is not given, the cursor position
+in the timestamp determines what will be changed.
+When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
+ (let ((origin (point)) origin-cat
+ with-hm inactive
+ (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
+ org-ts-what
+ extra rem
+ ts time time0 fixnext clrgx)
+ (unless (org-at-timestamp-p t)
+ (user-error "Not at a timestamp"))
+ (if (and (not what) (eq org-ts-what 'bracket))
+ (org-toggle-timestamp-type)
+ ;; Point isn't on brackets. Remember the part of the time-stamp
+ ;; the point was in. Indeed, size of time-stamps may change,
+ ;; but point must be kept in the same category nonetheless.
+ (setq origin-cat org-ts-what)
+ (when (and (not what) (not (eq org-ts-what 'day))
+ org-display-custom-times
+ (get-text-property (point) 'display)
+ (not (get-text-property (1- (point)) 'display)))
+ (setq org-ts-what 'day))
+ (setq org-ts-what (or what org-ts-what)
+ inactive (= (char-after (match-beginning 0)) ?\[)
+ ts (match-string 0))
+ (replace-match "")
+ (when (string-match
+ "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
+ ts)
+ (setq extra (match-string 1 ts))
+ (when suppress-tmp-delay
+ (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
+ (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
+ (setq with-hm t))
+ (setq time0 (org-parse-time-string ts))
+ (when (and updown
+ (eq org-ts-what 'minute)
+ (not current-prefix-arg))
+ ;; This looks like s-up and s-down. Change by one rounding step.
+ (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
+ (unless (= 0 (setq rem (% (nth 1 time0) dm)))
+ (setcar (cdr time0) (+ (nth 1 time0)
+ (if (> n 0) (- rem) (- dm rem))))))
+ (setq time
+ (apply #'encode-time
+ (or (car time0) 0)
+ (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
+ (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
+ (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
+ (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
+ (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
+ (nthcdr 6 time0)))
+ (when (and (member org-ts-what '(hour minute))
+ extra
+ (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
+ (setq extra (org-modify-ts-extra
+ extra
+ (if (eq org-ts-what 'hour) 2 5)
+ n dm)))
+ (when (integerp org-ts-what)
+ (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
+ (when (eq what 'calendar)
+ (let ((cal-date (org-get-date-from-calendar)))
+ (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
+ (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
+ (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
+ (setcar time0 (or (car time0) 0))
+ (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
+ (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
+ (setq time (apply 'encode-time time0))))
+ ;; Insert the new time-stamp, and ensure point stays in the same
+ ;; category as before (i.e. not after the last position in that
+ ;; category).
+ (let ((pos (point)))
+ ;; Stay before inserted string. `save-excursion' is of no use.
+ (setq org-last-changed-timestamp
+ (org-insert-time-stamp time with-hm inactive nil nil extra))
+ (goto-char pos))
+ (save-match-data
+ (looking-at org-ts-regexp3)
+ (goto-char
+ (pcase origin-cat
+ ;; `day' category ends before `hour' if any, or at the end
+ ;; of the day name.
+ (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
+ (`hour (min (match-end 7) origin))
+ (`minute (min (1- (match-end 8)) origin))
+ ((pred integerp) (min (1- (match-end 0)) origin))
+ ;; Point was right after the time-stamp. However, the
+ ;; time-stamp length might have changed, so refer to
+ ;; (match-end 0) instead.
+ (`after (match-end 0))
+ ;; `year' and `month' have both fixed size: point couldn't
+ ;; have moved into another part.
+ (_ origin))))
+ ;; Update clock if on a CLOCK line.
+ (org-clock-update-time-maybe)
+ ;; Maybe adjust the closest clock in `org-clock-history'
+ (when org-clock-adjust-closest
+ (if (not (and (org-at-clock-log-p)
+ (< 1 (length (delq nil (mapcar 'marker-position
+ org-clock-history))))))
+ (message "No clock to adjust")
+ (cond ((save-excursion ; fix previous clock?
+ (re-search-backward org-ts-regexp0 nil t)
+ (looking-back (concat org-clock-string " \\[")
+ (line-beginning-position)))
+ (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
+ ((save-excursion ; fix next clock?
+ (re-search-backward org-ts-regexp0 nil t)
+ (looking-at (concat org-ts-regexp0 "\\] =>")))
+ (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
+ (save-window-excursion
+ ;; Find closest clock to point, adjust the previous/next one in history
+ (let* ((p (save-excursion (org-back-to-heading t)))
+ (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
+ (clfixnth
+ (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
+ (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
+ (if (not clfixpos)
+ (message "No clock to adjust")
+ (save-excursion
+ (org-goto-marker-or-bmk clfixpos)
+ (org-show-subtree)
+ (when (re-search-forward clrgx nil t)
+ (goto-char (match-beginning 1))
+ (let (org-clock-adjust-closest)
+ (org-timestamp-change n org-ts-what updown))
+ (message "Clock adjusted in %s for heading: %s"
+ (file-name-nondirectory (buffer-file-name))
+ (org-get-heading t t)))))))))
+ ;; Try to recenter the calendar window, if any.
+ (when (and org-calendar-follow-timestamp-change
+ (get-buffer-window "*Calendar*" t)
+ (memq org-ts-what '(day month year)))
+ (org-recenter-calendar (time-to-days time))))))
+
+(defun org-modify-ts-extra (s pos n dm)
+ "Change the different parts of the lead-time and repeat fields in timestamp."
+ (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
+ ng h m new rem)
+ (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
+ (cond
+ ((or (org-pos-in-match-range pos 2)
+ (org-pos-in-match-range pos 3))
+ (setq m (string-to-number (match-string 3 s))
+ h (string-to-number (match-string 2 s)))
+ (if (org-pos-in-match-range pos 2)
+ (setq h (+ h n))
+ (setq n (* dm (with-no-warnings (signum n))))
+ (unless (= 0 (setq rem (% m dm)))
+ (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
+ (setq m (+ m n)))
+ (when (< m 0) (setq m (+ m 60) h (1- h)))
+ (when (> m 59) (setq m (- m 60) h (1+ h)))
+ (setq h (mod h 24))
+ (setq ng 1 new (format "-%02d:%02d" h m)))
+ ((org-pos-in-match-range pos 6)
+ (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
+ ((org-pos-in-match-range pos 5)
+ (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
+
+ ((org-pos-in-match-range pos 9)
+ (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
+ ((org-pos-in-match-range pos 8)
+ (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
+
+ (when ng
+ (setq s (concat
+ (substring s 0 (match-beginning ng))
+ new
+ (substring s (match-end ng))))))
+ s))
+
+(defun org-recenter-calendar (d)
+ "If the calendar is visible, recenter it to date D."
+ (let ((cwin (get-buffer-window "*Calendar*" t)))
+ (when cwin
+ (let ((calendar-move-hook nil))
+ (with-selected-window cwin
+ (calendar-goto-date
+ (if (listp d) d (calendar-gregorian-from-absolute d))))))))
+
+(defun org-goto-calendar (&optional arg)
+ "Go to the Emacs calendar at the current date.
+If there is a time stamp in the current line, go to that date.
+A prefix ARG can be used to force the current date."
+ (interactive "P")
+ (let ((tsr org-ts-regexp) diff
+ (calendar-move-hook nil)
+ (calendar-view-holidays-initially-flag nil)
+ (calendar-view-diary-initially-flag nil))
+ (when (or (org-at-timestamp-p)
+ (save-excursion
+ (beginning-of-line 1)
+ (looking-at (concat ".*" tsr))))
+ (let ((d1 (time-to-days (current-time)))
+ (d2 (time-to-days
+ (org-time-string-to-time (match-string 1)))))
+ (setq diff (- d2 d1))))
+ (calendar)
+ (calendar-goto-today)
+ (when (and diff (not arg)) (calendar-forward-day diff))))
+
+(defun org-get-date-from-calendar ()
+ "Return a list (month day year) of date at point in calendar."
+ (with-current-buffer "*Calendar*"
+ (save-match-data
+ (calendar-cursor-to-date))))
+
+(defun org-date-from-calendar ()
+ "Insert time stamp corresponding to cursor date in *Calendar* buffer.
+If there is already a time stamp at the cursor position, update it."
+ (interactive)
+ (if (org-at-timestamp-p t)
+ (org-timestamp-change 0 'calendar)
+ (let ((cal-date (org-get-date-from-calendar)))
+ (org-insert-time-stamp
+ (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
+
+(defcustom org-effort-durations
+ `(("min" . 1)
+ ("h" . 60)
+ ("d" . ,(* 60 8))
+ ("w" . ,(* 60 8 5))
+ ("m" . ,(* 60 8 5 4))
+ ("y" . ,(* 60 8 5 40)))
+ "Conversion factor to minutes for an effort modifier.
+
+Each entry has the form (MODIFIER . MINUTES).
+
+In an effort string, a number followed by MODIFIER is multiplied
+by the specified number of MINUTES to obtain an effort in
+minutes.
+
+For example, if the value of this variable is ((\"hours\" . 60)), then an
+effort string \"2hours\" is equivalent to 120 minutes."
+ :group 'org-agenda
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(alist :key-type (string :tag "Modifier")
+ :value-type (number :tag "Minutes")))
+
+(defun org-minutes-to-clocksum-string (m)
+ "Format number of minutes as a clocksum string.
+The format is determined by `org-time-clocksum-format',
+`org-time-clocksum-use-fractional' and
+`org-time-clocksum-fractional-format' and
+`org-time-clocksum-use-effort-durations'."
+ (let ((clocksum "")
+ (m (round m)) ; Don't allow fractions of minutes
+ h d w mo y fmt n)
+ (setq h (if org-time-clocksum-use-effort-durations
+ (cdr (assoc "h" org-effort-durations)) 60)
+ d (if org-time-clocksum-use-effort-durations
+ (/ (cdr (assoc "d" org-effort-durations)) h) 24)
+ w (if org-time-clocksum-use-effort-durations
+ (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
+ mo (if org-time-clocksum-use-effort-durations
+ (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
+ y (if org-time-clocksum-use-effort-durations
+ (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
+ ;; fractional format
+ (if org-time-clocksum-use-fractional
+ (cond
+ ;; single format string
+ ((stringp org-time-clocksum-fractional-format)
+ (format org-time-clocksum-fractional-format (/ m (float h))))
+ ;; choice of fractional formats for different time units
+ ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
+ (> (/ (truncate m) (* y d h)) 0))
+ (format fmt (/ m (* y d (float h)))))
+ ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
+ (> (/ (truncate m) (* mo d h)) 0))
+ (format fmt (/ m (* mo d (float h)))))
+ ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
+ (> (/ (truncate m) (* w d h)) 0))
+ (format fmt (/ m (* w d (float h)))))
+ ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
+ (> (/ (truncate m) (* d h)) 0))
+ (format fmt (/ m (* d (float h)))))
+ ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
+ (> (/ (truncate m) h) 0))
+ (format fmt (/ m (float h))))
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
+ (format fmt m))
+ ;; fall back to smallest time unit with a format
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
+ (format fmt (/ m (float h))))
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
+ (format fmt (/ m (* d (float h)))))
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
+ (format fmt (/ m (* w d (float h)))))
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
+ (format fmt (/ m (* mo d (float h)))))
+ ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
+ (format fmt (/ m (* y d (float h))))))
+ ;; standard (non-fractional) format, with single format string
+ (if (stringp org-time-clocksum-format)
+ (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
+ ;; separate formats components
+ (and (setq fmt (plist-get org-time-clocksum-format :years))
+ (or (> (setq n (/ (truncate m) (* y d h))) 0)
+ (plist-get org-time-clocksum-format :require-years))
+ (setq clocksum (concat clocksum (format fmt n))
+ m (- m (* n y d h))))
+ (and (setq fmt (plist-get org-time-clocksum-format :months))
+ (or (> (setq n (/ (truncate m) (* mo d h))) 0)
+ (plist-get org-time-clocksum-format :require-months))
+ (setq clocksum (concat clocksum (format fmt n))
+ m (- m (* n mo d h))))
+ (and (setq fmt (plist-get org-time-clocksum-format :weeks))
+ (or (> (setq n (/ (truncate m) (* w d h))) 0)
+ (plist-get org-time-clocksum-format :require-weeks))
+ (setq clocksum (concat clocksum (format fmt n))
+ m (- m (* n w d h))))
+ (and (setq fmt (plist-get org-time-clocksum-format :days))
+ (or (> (setq n (/ (truncate m) (* d h))) 0)
+ (plist-get org-time-clocksum-format :require-days))
+ (setq clocksum (concat clocksum (format fmt n))
+ m (- m (* n d h))))
+ (and (setq fmt (plist-get org-time-clocksum-format :hours))
+ (or (> (setq n (/ (truncate m) h)) 0)
+ (plist-get org-time-clocksum-format :require-hours))
+ (setq clocksum (concat clocksum (format fmt n))
+ m (- m (* n h))))
+ (and (setq fmt (plist-get org-time-clocksum-format :minutes))
+ (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
+ (setq clocksum (concat clocksum (format fmt m))))
+ ;; return formatted time duration
+ clocksum))))
+
+(defun org-hours-to-clocksum-string (n)
+ (org-minutes-to-clocksum-string (* n 60)))
+
+(defun org-hh:mm-string-to-minutes (s)
+ "Convert a string H:MM to a number of minutes.
+If the string is just a number, interpret it as minutes.
+In fact, the first hh:mm or number in the string will be taken,
+there can be extra stuff in the string.
+If no number is found, the return value is 0."
+ (cond
+ ((integerp s) s)
+ ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
+ (+ (* (string-to-number (match-string 1 s)) 60)
+ (string-to-number (match-string 2 s))))
+ ((string-match "\\([0-9]+\\)" s)
+ (string-to-number (match-string 1 s)))
+ (t 0)))
+
+(defcustom org-image-actual-width t
+ "Should we use the actual width of images when inlining them?
+
+When set to t, always use the image width.
+
+When set to a number, use imagemagick (when available) to set
+the image's width to this value.
+
+When set to a number in a list, try to get the width from any
+#+ATTR.* keyword if it matches a width specification like
+
+ #+ATTR_HTML: :width 300px
+
+and fall back on that number if none is found.
+
+When set to nil, try to get the width from an #+ATTR.* keyword
+and fall back on the original width if none is found.
+
+This requires Emacs >= 24.1, build with imagemagick support."
+ :group 'org-appearance
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Use the image width" t)
+ (integer :tag "Use a number of pixels")
+ (list :tag "Use #+ATTR* or a number of pixels" (integer))
+ (const :tag "Use #+ATTR* or don't resize" nil)))
+
+(defcustom org-agenda-inhibit-startup nil
+ "Inhibit startup when preparing agenda buffers.
+When this variable is t, the initialization of the Org agenda
+buffers is inhibited: e.g. the visibility state is not set, the
+tables are not re-aligned, etc."
+ :type 'boolean
+ :version "24.3"
+ :group 'org-agenda)
+
+(defcustom org-agenda-ignore-properties nil
+ "Avoid updating text properties when building the agenda.
+Properties are used to prepare buffers for effort estimates,
+appointments, statistics and subtree-local categories.
+If you don't use these in the agenda, you can add them to this
+list and agenda building will be a bit faster.
+The value is a list, with zero or more of the symbols `effort', `appt',
+`stats' or `category'."
+ :type '(set :greedy t
+ (const effort)
+ (const appt)
+ (const stats)
+ (const category))
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :group 'org-agenda)
+
+(defun org-duration-string-to-minutes (s &optional output-to-string)
+ "Convert a duration string S to minutes.
+
+A bare number is interpreted as minutes, modifiers can be set by
+customizing `org-effort-durations' (which see).
+
+Entries containing a colon are interpreted as H:MM by
+`org-hh:mm-string-to-minutes'."
+ (let ((result 0)
+ (re (concat "\\([0-9.]+\\) *\\("
+ (regexp-opt (mapcar 'car org-effort-durations))
+ "\\)")))
+ (while (string-match re s)
+ (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
+ (string-to-number (match-string 1 s))))
+ (setq s (replace-match "" nil t s)))
+ (setq result (floor result))
+ (cl-incf result (org-hh:mm-string-to-minutes s))
+ (if output-to-string (number-to-string result) result)))
+
+;;;; Files
+
+(defun org-save-all-org-buffers ()
+ "Save all Org buffers without user confirmation."
+ (interactive)
+ (message "Saving all Org buffers...")
+ (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
+ (when (featurep 'org-id) (org-id-locations-save))
+ (message "Saving all Org buffers... done"))
+
+(defun org-revert-all-org-buffers ()
+ "Revert all Org buffers.
+Prompt for confirmation when there are unsaved changes.
+Be sure you know what you are doing before letting this function
+overwrite your changes.
+
+This function is useful in a setup where one tracks org files
+with a version control system, to revert on one machine after pulling
+changes from another. I believe the procedure must be like this:
+
+1. M-x org-save-all-org-buffers
+2. Pull changes from the other machine, resolve conflicts
+3. M-x org-revert-all-org-buffers"
+ (interactive)
+ (unless (yes-or-no-p "Revert all Org buffers from their files? ")
+ (user-error "Abort"))
+ (save-excursion
+ (save-window-excursion
+ (dolist (b (buffer-list))
+ (when (and (with-current-buffer b (derived-mode-p 'org-mode))
+ (with-current-buffer b buffer-file-name))
+ (pop-to-buffer-same-window b)
+ (revert-buffer t 'no-confirm)))
+ (when (and (featurep 'org-id) org-id-track-globally)
+ (org-id-locations-load)))))
+
+;;;; Agenda files
+
+;;;###autoload
+(defun org-switchb (&optional arg)
+ "Switch between Org buffers.
+
+With `\\[universal-argument]' prefix, restrict available buffers to files.
+
+With `\\[universal-argument] \\[universal-argument]' \
+prefix, restrict available buffers to agenda files."
+ (interactive "P")
+ (let ((blist (org-buffer-list
+ (cond ((equal arg '(4)) 'files)
+ ((equal arg '(16)) 'agenda)))))
+ (pop-to-buffer-same-window
+ (completing-read "Org buffer: "
+ (mapcar #'list (mapcar #'buffer-name blist))
+ nil t))))
+
+(defun org-buffer-list (&optional predicate exclude-tmp)
+ "Return a list of Org buffers.
+PREDICATE can be `export', `files' or `agenda'.
+
+export restrict the list to Export buffers.
+files restrict the list to buffers visiting Org files.
+agenda restrict the list to buffers visiting agenda files.
+
+If EXCLUDE-TMP is non-nil, ignore temporary buffers."
+ (let* ((bfn nil)
+ (agenda-files (and (eq predicate 'agenda)
+ (mapcar 'file-truename (org-agenda-files t))))
+ (filter
+ (cond
+ ((eq predicate 'files)
+ (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
+ ((eq predicate 'export)
+ (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
+ ((eq predicate 'agenda)
+ (lambda (b)
+ (with-current-buffer b
+ (and (derived-mode-p 'org-mode)
+ (setq bfn (buffer-file-name b))
+ (member (file-truename bfn) agenda-files)))))
+ (t (lambda (b) (with-current-buffer b
+ (or (derived-mode-p 'org-mode)
+ (string-match "\\*Org .*Export"
+ (buffer-name b)))))))))
+ (delq nil
+ (mapcar
+ (lambda(b)
+ (if (and (funcall filter b)
+ (or (not exclude-tmp)
+ (not (string-match "tmp" (buffer-name b)))))
+ b
+ nil))
+ (buffer-list)))))
+
+(defun org-agenda-files (&optional unrestricted archives)
+ "Get the list of agenda files.
+Optional UNRESTRICTED means return the full list even if a restriction
+is currently in place.
+When ARCHIVES is t, include all archive files that are really being
+used by the agenda files. If ARCHIVE is `ifmode', do this only if
+`org-agenda-archives-mode' is t."
+ (let ((files
+ (cond
+ ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
+ ((stringp org-agenda-files) (org-read-agenda-file-list))
+ ((listp org-agenda-files) org-agenda-files)
+ (t (error "Invalid value of `org-agenda-files'")))))
+ (setq files (apply 'append
+ (mapcar (lambda (f)
+ (if (file-directory-p f)
+ (directory-files
+ f t org-agenda-file-regexp)
+ (list f)))
+ files)))
+ (when org-agenda-skip-unavailable-files
+ (setq files (delq nil
+ (mapcar (function
+ (lambda (file)
+ (and (file-readable-p file) file)))
+ files))))
+ (when (or (eq archives t)
+ (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
+ (setq files (org-add-archive-files files)))
+ files))
+
+(defun org-agenda-file-p (&optional file)
+ "Return non-nil, if FILE is an agenda file.
+If FILE is omitted, use the file associated with the current
+buffer."
+ (let ((fname (or file (buffer-file-name))))
+ (and fname
+ (member (file-truename fname)
+ (mapcar #'file-truename (org-agenda-files t))))))
+
+(defun org-edit-agenda-file-list ()
+ "Edit the list of agenda files.
+Depending on setup, this either uses customize to edit the variable
+`org-agenda-files', or it visits the file that is holding the list. In the
+latter case, the buffer is set up in a way that saving it automatically kills
+the buffer and restores the previous window configuration."
+ (interactive)
+ (if (stringp org-agenda-files)
+ (let ((cw (current-window-configuration)))
+ (find-file org-agenda-files)
+ (setq-local org-window-configuration cw)
+ (add-hook 'after-save-hook
+ (lambda ()
+ (set-window-configuration
+ (prog1 org-window-configuration
+ (kill-buffer (current-buffer))))
+ (org-install-agenda-files-menu)
+ (message "New agenda file list installed"))
+ nil 'local)
+ (message "%s" (substitute-command-keys
+ "Edit list and finish with \\[save-buffer]")))
+ (customize-variable 'org-agenda-files)))
+
+(defun org-store-new-agenda-file-list (list)
+ "Set new value for the agenda file list and save it correctly."
+ (if (stringp org-agenda-files)
+ (let ((fe (org-read-agenda-file-list t)) b u)
+ (while (setq b (find-buffer-visiting org-agenda-files))
+ (kill-buffer b))
+ (with-temp-file org-agenda-files
+ (insert
+ (mapconcat
+ (lambda (f) ;; Keep un-expanded entries.
+ (if (setq u (assoc f fe))
+ (cdr u)
+ f))
+ list "\n")
+ "\n")))
+ (let ((org-mode-hook nil) (org-inhibit-startup t)
+ (org-insert-mode-line-in-empty-file nil))
+ (setq org-agenda-files list)
+ (customize-save-variable 'org-agenda-files org-agenda-files))))
+
+(defun org-read-agenda-file-list (&optional pair-with-expansion)
+ "Read the list of agenda files from a file.
+If PAIR-WITH-EXPANSION is t return pairs with un-expanded
+filenames, used by `org-store-new-agenda-file-list' to write back
+un-expanded file names."
+ (when (file-directory-p org-agenda-files)
+ (error "`org-agenda-files' cannot be a single directory"))
+ (when (stringp org-agenda-files)
+ (with-temp-buffer
+ (insert-file-contents org-agenda-files)
+ (mapcar
+ (lambda (f)
+ (let ((e (expand-file-name (substitute-in-file-name f)
+ org-directory)))
+ (if pair-with-expansion
+ (cons e f)
+ e)))
+ (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
+
+;;;###autoload
+(defun org-cycle-agenda-files ()
+ "Cycle through the files in `org-agenda-files'.
+If the current buffer visits an agenda file, find the next one in the list.
+If the current buffer does not, find the first agenda file."
+ (interactive)
+ (let* ((fs (or (org-agenda-files t)
+ (user-error "No agenda files")))
+ (files (copy-sequence fs))
+ (tcf (and buffer-file-name (file-truename buffer-file-name)))
+ file)
+ (when tcf
+ (while (and (setq file (pop files))
+ (not (equal (file-truename file) tcf)))))
+ (find-file (car (or files fs)))
+ (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
+
+(defun org-agenda-file-to-front (&optional to-end)
+ "Move/add the current file to the top of the agenda file list.
+If the file is not present in the list, it is added to the front. If it is
+present, it is moved there. With optional argument TO-END, add/move to the
+end of the list."
+ (interactive "P")
+ (let ((org-agenda-skip-unavailable-files nil)
+ (file-alist (mapcar (lambda (x)
+ (cons (file-truename x) x))
+ (org-agenda-files t)))
+ (ctf (file-truename
+ (or buffer-file-name
+ (user-error "Please save the current buffer to a file"))))
+ x had)
+ (setq x (assoc ctf file-alist) had x)
+
+ (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
+ (if to-end
+ (setq file-alist (append (delq x file-alist) (list x)))
+ (setq file-alist (cons x (delq x file-alist))))
+ (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
+ (org-install-agenda-files-menu)
+ (message "File %s to %s of agenda file list"
+ (if had "moved" "added") (if to-end "end" "front"))))
+
+(defun org-remove-file (&optional file)
+ "Remove current file from the list of files in variable `org-agenda-files'.
+These are the files which are being checked for agenda entries.
+Optional argument FILE means use this file instead of the current."
+ (interactive)
+ (let* ((org-agenda-skip-unavailable-files nil)
+ (file (or file buffer-file-name
+ (user-error "Current buffer does not visit a file")))
+ (true-file (file-truename file))
+ (afile (abbreviate-file-name file))
+ (files (delq nil (mapcar
+ (lambda (x)
+ (unless (equal true-file
+ (file-truename x))
+ x))
+ (org-agenda-files t)))))
+ (if (not (= (length files) (length (org-agenda-files t))))
+ (progn
+ (org-store-new-agenda-file-list files)
+ (org-install-agenda-files-menu)
+ (message "Removed from Org Agenda list: %s" afile))
+ (message "File was not in list: %s (not removed)" afile))))
+
+(defun org-file-menu-entry (file)
+ (vector file (list 'find-file file) t))
+
+(defun org-check-agenda-file (file)
+ "Make sure FILE exists. If not, ask user what to do."
+ (unless (file-exists-p file)
+ (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
+ (abbreviate-file-name file))
+ (let ((r (downcase (read-char-exclusive))))
+ (cond
+ ((equal r ?r)
+ (org-remove-file file)
+ (throw 'nextfile t))
+ (t (user-error "Abort"))))))
+
+(defun org-get-agenda-file-buffer (file)
+ "Get an agenda buffer visiting FILE.
+If the buffer needs to be created, add it to the list of buffers
+which might be released later."
+ (let ((buf (org-find-base-buffer-visiting file)))
+ (if buf
+ buf ; just return it
+ ;; Make a new buffer and remember it
+ (setq buf (find-file-noselect file))
+ (when buf (push buf org-agenda-new-buffers))
+ buf)))
+
+(defun org-release-buffers (blist)
+ "Release all buffers in list, asking the user for confirmation when needed.
+When a buffer is unmodified, it is just killed. When modified, it is saved
+\(if the user agrees) and then killed."
+ (let (file)
+ (dolist (buf blist)
+ (setq file (buffer-file-name buf))
+ (when (and (buffer-modified-p buf)
+ file
+ (y-or-n-p (format "Save file %s? " file)))
+ (with-current-buffer buf (save-buffer)))
+ (kill-buffer buf))))
+
+(defun org-agenda-prepare-buffers (files)
+ "Create buffers for all agenda files, protect archived trees and comments."
+ (interactive)
+ (let ((pa '(:org-archived t))
+ (pc '(:org-comment t))
+ (pall '(:org-archived t :org-comment t))
+ (inhibit-read-only t)
+ (org-inhibit-startup org-agenda-inhibit-startup)
+ (rea (concat ":" org-archive-tag ":"))
+ re pos)
+ (setq org-tag-alist-for-agenda nil
+ org-tag-groups-alist-for-agenda nil)
+ (save-excursion
+ (save-restriction
+ (dolist (file files)
+ (catch 'nextfile
+ (if (bufferp file)
+ (set-buffer file)
+ (org-check-agenda-file file)
+ (set-buffer (org-get-agenda-file-buffer file)))
+ (widen)
+ (org-set-regexps-and-options 'tags-only)
+ (setq pos (point))
+ (or (memq 'category org-agenda-ignore-properties)
+ (org-refresh-category-properties))
+ (or (memq 'stats org-agenda-ignore-properties)
+ (org-refresh-stats-properties))
+ (or (memq 'effort org-agenda-ignore-properties)
+ (org-refresh-effort-properties))
+ (or (memq 'appt org-agenda-ignore-properties)
+ (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
+ (setq org-todo-keywords-for-agenda
+ (append org-todo-keywords-for-agenda org-todo-keywords-1))
+ (setq org-done-keywords-for-agenda
+ (append org-done-keywords-for-agenda org-done-keywords))
+ (setq org-todo-keyword-alist-for-agenda
+ (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
+ (setq org-tag-alist-for-agenda
+ (org-uniquify
+ (append org-tag-alist-for-agenda
+ org-current-tag-alist)))
+ ;; Merge current file's tag groups into global
+ ;; `org-tag-groups-alist-for-agenda'.
+ (when org-group-tags
+ (dolist (alist org-tag-groups-alist)
+ (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
+ (if old
+ (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
+ (push alist org-tag-groups-alist-for-agenda)))))
+ (org-with-silent-modifications
+ (save-excursion
+ (remove-text-properties (point-min) (point-max) pall)
+ (when org-agenda-skip-archived-trees
+ (goto-char (point-min))
+ (while (re-search-forward rea nil t)
+ (when (org-at-heading-p t)
+ (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
+ (goto-char (point-min))
+ (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
+ (while (re-search-forward re nil t)
+ (when (save-match-data (org-in-commented-heading-p t))
+ (add-text-properties
+ (match-beginning 0) (org-end-of-subtree t) pc)))))
+ (goto-char pos)))))
+ (setq org-todo-keywords-for-agenda
+ (org-uniquify org-todo-keywords-for-agenda))
+ (setq org-todo-keyword-alist-for-agenda
+ (org-uniquify org-todo-keyword-alist-for-agenda))))
+
+
+;;;; CDLaTeX minor mode
+
+(defvar org-cdlatex-mode-map (make-sparse-keymap)
+ "Keymap for the minor `org-cdlatex-mode'.")
+
+(org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
+(org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
+(org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
+(org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
+(org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
+
+(defvar org-cdlatex-texmathp-advice-is-done nil
+ "Flag remembering if we have applied the advice to texmathp already.")
+
+(define-minor-mode org-cdlatex-mode
+ "Toggle the minor `org-cdlatex-mode'.
+This mode supports entering LaTeX environment and math in LaTeX fragments
+in Org mode.
+\\{org-cdlatex-mode-map}"
+ nil " OCDL" nil
+ (when org-cdlatex-mode
+ (require 'cdlatex)
+ (run-hooks 'cdlatex-mode-hook)
+ (cdlatex-compute-tables))
+ (unless org-cdlatex-texmathp-advice-is-done
+ (setq org-cdlatex-texmathp-advice-is-done t)
+ (defadvice texmathp (around org-math-always-on activate)
+ "Always return t in Org buffers.
+This is because we want to insert math symbols without dollars even outside
+the LaTeX math segments. If Org mode thinks that point is actually inside
+an embedded LaTeX fragment, let `texmathp' do its job.
+`\\[org-cdlatex-mode-map]'"
+ (interactive)
+ (let (p)
+ (cond
+ ((not (derived-mode-p 'org-mode)) ad-do-it)
+ ((eq this-command 'cdlatex-math-symbol)
+ (setq ad-return-value t
+ texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
+ (t
+ (let ((p (org-inside-LaTeX-fragment-p)))
+ (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
+ (setq ad-return-value t
+ texmathp-why '("Org mode embedded math" . 0))
+ (when p ad-do-it)))))))))
+
+(defun turn-on-org-cdlatex ()
+ "Unconditionally turn on `org-cdlatex-mode'."
+ (org-cdlatex-mode 1))
+
+(defun org-try-cdlatex-tab ()
+ "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
+It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
+ - inside a LaTeX fragment, or
+ - after the first word in a line, where an abbreviation expansion could
+ insert a LaTeX environment."
+ (when org-cdlatex-mode
+ (cond
+ ;; Before any word on the line: No expansion possible.
+ ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
+ ;; Just after first word on the line: Expand it. Make sure it
+ ;; cannot happen on headlines, though.
+ ((save-excursion
+ (skip-chars-backward "a-zA-Z0-9*")
+ (skip-chars-backward " \t")
+ (and (bolp) (not (org-at-heading-p))))
+ (cdlatex-tab) t)
+ ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
+
+(defun org-cdlatex-underscore-caret (&optional _arg)
+ "Execute `cdlatex-sub-superscript' in LaTeX fragments.
+Revert to the normal definition outside of these fragments."
+ (interactive "P")
+ (if (org-inside-LaTeX-fragment-p)
+ (call-interactively 'cdlatex-sub-superscript)
+ (let (org-cdlatex-mode)
+ (call-interactively (key-binding (vector last-input-event))))))
+
+(defun org-cdlatex-math-modify (&optional _arg)
+ "Execute `cdlatex-math-modify' in LaTeX fragments.
+Revert to the normal definition outside of these fragments."
+ (interactive "P")
+ (if (org-inside-LaTeX-fragment-p)
+ (call-interactively 'cdlatex-math-modify)
+ (let (org-cdlatex-mode)
+ (call-interactively (key-binding (vector last-input-event))))))
+
+(defun org-cdlatex-environment-indent (&optional environment item)
+ "Execute `cdlatex-environment' and indent the inserted environment.
+
+ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
+
+The inserted environment is indented to current indentation
+unless point is at the beginning of the line, in which the
+environment remains unintended."
+ (interactive)
+ ;; cdlatex-environment always return nil. Therefore, capture output
+ ;; first and determine if an environment was selected.
+ (let* ((beg (point-marker))
+ (end (copy-marker (point) t))
+ (inserted (progn
+ (ignore-errors (cdlatex-environment environment item))
+ (< beg end)))
+ ;; Figure out how many lines to move forward after the
+ ;; environment has been inserted.
+ (lines (when inserted
+ (save-excursion
+ (- (cl-loop while (< beg (point))
+ with x = 0
+ do (forward-line -1)
+ (cl-incf x)
+ finally return x)
+ (if (progn (goto-char beg)
+ (and (progn (skip-chars-forward " \t") (eolp))
+ (progn (skip-chars-backward " \t") (bolp))))
+ 1 0)))))
+ (env (org-trim (delete-and-extract-region beg end))))
+ (when inserted
+ ;; Get indentation of next line unless at column 0.
+ (let ((ind (if (bolp) 0
+ (save-excursion
+ (org-return-indent)
+ (prog1 (org-get-indentation)
+ (when (progn (skip-chars-forward " \t") (eolp))
+ (delete-region beg (point)))))))
+ (bol (progn (skip-chars-backward " \t") (bolp))))
+ ;; Insert a newline before environment unless at column zero
+ ;; to "escape" the current line. Insert a newline if
+ ;; something is one the same line as \end{ENVIRONMENT}.
+ (insert
+ (concat (unless bol "\n") env
+ (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
+ (unless (zerop ind)
+ (save-excursion
+ (goto-char beg)
+ (while (< (point) end)
+ (unless (eolp) (indent-line-to ind))
+ (forward-line))))
+ (goto-char beg)
+ (forward-line lines)
+ (indent-line-to ind)))
+ (set-marker beg nil)
+ (set-marker end nil)))
+
+
+;;;; LaTeX fragments
+
+(defun org-inside-LaTeX-fragment-p ()
+ "Test if point is inside a LaTeX fragment.
+I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
+sequence appearing also before point.
+Even though the matchers for math are configurable, this function assumes
+that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
+delimiters are skipped when they have been removed by customization.
+The return value is nil, or a cons cell with the delimiter and the
+position of this delimiter.
+
+This function does a reasonably good job, but can locally be fooled by
+for example currency specifications. For example it will assume being in
+inline math after \"$22.34\". The LaTeX fragment formatter will only format
+fragments that are properly closed, but during editing, we have to live
+with the uncertainty caused by missing closing delimiters. This function
+looks only before point, not after."
+ (catch 'exit
+ (let ((pos (point))
+ (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
+ (lim (progn
+ (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
+ (point)))
+ dd-on str (start 0) m re)
+ (goto-char pos)
+ (when dodollar
+ (setq str (concat (buffer-substring lim (point)) "\000 X$.")
+ re (nth 1 (assoc "$" org-latex-regexps)))
+ (while (string-match re str start)
+ (cond
+ ((= (match-end 0) (length str))
+ (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
+ ((= (match-end 0) (- (length str) 5))
+ (throw 'exit nil))
+ (t (setq start (match-end 0))))))
+ (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
+ (goto-char pos)
+ (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
+ (and (match-beginning 2) (throw 'exit nil))
+ ;; count $$
+ (while (re-search-backward "\\$\\$" lim t)
+ (setq dd-on (not dd-on)))
+ (goto-char pos)
+ (when dd-on (cons "$$" m))))))
+
+(defun org-inside-latex-macro-p ()
+ "Is point inside a LaTeX macro or its arguments?"
+ (save-match-data
+ (org-in-regexp
+ "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
+
+(defun org--format-latex-make-overlay (beg end image &optional imagetype)
+ "Build an overlay between BEG and END using IMAGE file.
+Argument IMAGETYPE is the extension of the displayed image,
+as a string. It defaults to \"png\"."
+ (let ((ov (make-overlay beg end))
+ (imagetype (or (intern imagetype) 'png)))
+ (overlay-put ov 'org-overlay-type 'org-latex-overlay)
+ (overlay-put ov 'evaporate t)
+ (overlay-put ov
+ 'modification-hooks
+ (list (lambda (o _flag _beg _end &optional _l)
+ (delete-overlay o))))
+ (overlay-put ov
+ 'display
+ (list 'image :type imagetype :file image :ascent 'center))))
+
+(defun org--list-latex-overlays (&optional beg end)
+ "List all Org LaTeX overlays in current buffer.
+Limit to overlays between BEG and END when those are provided."
+ (cl-remove-if-not
+ (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
+ (overlays-in (or beg (point-min)) (or end (point-max)))))
+
+(defun org-remove-latex-fragment-image-overlays (&optional beg end)
+ "Remove all overlays with LaTeX fragment images in current buffer.
+When optional arguments BEG and END are non-nil, remove all
+overlays between them instead. Return a non-nil value when some
+overlays were removed, nil otherwise."
+ (let ((overlays (org--list-latex-overlays beg end)))
+ (mapc #'delete-overlay overlays)
+ overlays))
+
+(defun org-toggle-latex-fragment (&optional arg)
+ "Preview the LaTeX fragment at point, or all locally or globally.
+
+If the cursor is on a LaTeX fragment, create the image and overlay
+it over the source code, if there is none. Remove it otherwise.
+If there is no fragment at point, display all fragments in the
+current section.
+
+With prefix ARG, preview or clear image for all fragments in the
+current subtree or in the whole buffer when used before the first
+headline. With a prefix ARG `\\[universal-argument] \
+\\[universal-argument]' preview or clear images
+for all fragments in the buffer."
+ (interactive "P")
+ (when (display-graphic-p)
+ (catch 'exit
+ (save-excursion
+ (let (beg end msg)
+ (cond
+ ((or (equal arg '(16))
+ (and (equal arg '(4))
+ (org-with-limited-levels (org-before-first-heading-p))))
+ (if (org-remove-latex-fragment-image-overlays)
+ (progn (message "LaTeX fragments images removed from buffer")
+ (throw 'exit nil))
+ (setq msg "Creating images for buffer...")))
+ ((equal arg '(4))
+ (org-with-limited-levels (org-back-to-heading t))
+ (setq beg (point))
+ (setq end (progn (org-end-of-subtree t) (point)))
+ (if (org-remove-latex-fragment-image-overlays beg end)
+ (progn
+ (message "LaTeX fragment images removed from subtree")
+ (throw 'exit nil))
+ (setq msg "Creating images for subtree...")))
+ ((let ((datum (org-element-context)))
+ (when (memq (org-element-type datum)
+ '(latex-environment latex-fragment))
+ (setq beg (org-element-property :begin datum))
+ (setq end (org-element-property :end datum))
+ (if (org-remove-latex-fragment-image-overlays beg end)
+ (progn (message "LaTeX fragment image removed")
+ (throw 'exit nil))
+ (setq msg "Creating image...")))))
+ (t
+ (org-with-limited-levels
+ (setq beg (if (org-at-heading-p) (line-beginning-position)
+ (outline-previous-heading)
+ (point)))
+ (setq end (progn (outline-next-heading) (point)))
+ (if (org-remove-latex-fragment-image-overlays beg end)
+ (progn
+ (message "LaTeX fragment images removed from section")
+ (throw 'exit nil))
+ (setq msg "Creating images for section...")))))
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (org-format-latex
+ (concat org-preview-latex-image-directory "org-ltximg")
+ beg end
+ ;; Emacs cannot overlay images from remote hosts. Create
+ ;; it in `temporary-file-directory' instead.
+ (if (or (not file) (file-remote-p file))
+ temporary-file-directory
+ default-directory)
+ 'overlays msg 'forbuffer org-preview-latex-default-process))
+ (message (concat msg "done")))))))
+
+(defun org-format-latex
+ (prefix &optional beg end dir overlays msg forbuffer processing-type)
+ "Replace LaTeX fragments with links to an image.
+
+The function takes care of creating the replacement image.
+
+Only consider fragments between BEG and END when those are
+provided.
+
+When optional argument OVERLAYS is non-nil, display the image on
+top of the fragment instead of replacing it.
+
+PROCESSING-TYPE is the conversion method to use, as a symbol.
+
+Some of the options can be changed using the variable
+`org-format-latex-options', which see."
+ (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
+ (unless (eq processing-type 'verbatim)
+ (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
+ (cnt 0)
+ checkdir-flag)
+ (goto-char (or beg (point-min)))
+ ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
+ (when (and overlays (memq processing-type '(dvipng imagemagick)))
+ (overlay-recenter (or end (point-max))))
+ (while (re-search-forward math-regexp end t)
+ (unless (and overlays
+ (eq (get-char-property (point) 'org-overlay-type)
+ 'org-latex-overlay))
+ (let* ((context (org-element-context))
+ (type (org-element-type context)))
+ (when (memq type '(latex-environment latex-fragment))
+ (let ((block-type (eq type 'latex-environment))
+ (value (org-element-property :value context))
+ (beg (org-element-property :begin context))
+ (end (save-excursion
+ (goto-char (org-element-property :end context))
+ (skip-chars-backward " \r\t\n")
+ (point))))
+ (cond
+ ((eq processing-type 'mathjax)
+ ;; Prepare for MathJax processing.
+ (if (not (string-match "\\`\\$\\$?" value))
+ (goto-char end)
+ (delete-region beg end)
+ (if (string= (match-string 0 value) "$$")
+ (insert "\\[" (substring value 2 -2) "\\]")
+ (insert "\\(" (substring value 1 -1) "\\)"))))
+ ((assq processing-type org-preview-latex-process-alist)
+ ;; Process to an image.
+ (cl-incf cnt)
+ (goto-char beg)
+ (let* ((processing-info
+ (cdr (assq processing-type org-preview-latex-process-alist)))
+ (face (face-at-point))
+ ;; Get the colors from the face at point.
+ (fg
+ (let ((color (plist-get org-format-latex-options
+ :foreground)))
+ (if (and forbuffer (eq color 'auto))
+ (face-attribute face :foreground nil 'default)
+ color)))
+ (bg
+ (let ((color (plist-get org-format-latex-options
+ :background)))
+ (if (and forbuffer (eq color 'auto))
+ (face-attribute face :background nil 'default)
+ color)))
+ (hash (sha1 (prin1-to-string
+ (list org-format-latex-header
+ org-latex-default-packages-alist
+ org-latex-packages-alist
+ org-format-latex-options
+ forbuffer value fg bg))))
+ (imagetype (or (plist-get processing-info :image-output-type) "png"))
+ (absprefix (expand-file-name prefix dir))
+ (linkfile (format "%s_%s.%s" prefix hash imagetype))
+ (movefile (format "%s_%s.%s" absprefix hash imagetype))
+ (sep (and block-type "\n\n"))
+ (link (concat sep "[[file:" linkfile "]]" sep))
+ (options
+ (org-combine-plists
+ org-format-latex-options
+ `(:foreground ,fg :background ,bg))))
+ (when msg (message msg cnt))
+ (unless checkdir-flag ; Ensure the directory exists.
+ (setq checkdir-flag t)
+ (let ((todir (file-name-directory absprefix)))
+ (unless (file-directory-p todir)
+ (make-directory todir t))))
+ (unless (file-exists-p movefile)
+ (org-create-formula-image
+ value movefile options forbuffer processing-type))
+ (if overlays
+ (progn
+ (dolist (o (overlays-in beg end))
+ (when (eq (overlay-get o 'org-overlay-type)
+ 'org-latex-overlay)
+ (delete-overlay o)))
+ (org--format-latex-make-overlay beg end movefile imagetype)
+ (goto-char end))
+ (delete-region beg end)
+ (insert
+ (org-add-props link
+ (list 'org-latex-src
+ (replace-regexp-in-string "\"" "" value)
+ 'org-latex-src-embed-type
+ (if block-type 'paragraph 'character)))))))
+ ((eq processing-type 'mathml)
+ ;; Process to MathML.
+ (unless (org-format-latex-mathml-available-p)
+ (user-error "LaTeX to MathML converter not configured"))
+ (cl-incf cnt)
+ (when msg (message msg cnt))
+ (goto-char beg)
+ (delete-region beg end)
+ (insert (org-format-latex-as-mathml
+ value block-type prefix dir)))
+ (t
+ (error "Unknown conversion process %s for LaTeX fragments"
+ processing-type)))))))))))
+
+(defun org-create-math-formula (latex-frag &optional mathml-file)
+ "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
+Use `org-latex-to-mathml-convert-command'. If the conversion is
+sucessful, return the portion between \"<math...> </math>\"
+elements otherwise return nil. When MATHML-FILE is specified,
+write the results in to that file. When invoked as an
+interactive command, prompt for LATEX-FRAG, with initial value
+set to the current active region and echo the results for user
+inspection."
+ (interactive (list (let ((frag (when (org-region-active-p)
+ (buffer-substring-no-properties
+ (region-beginning) (region-end)))))
+ (read-string "LaTeX Fragment: " frag nil frag))))
+ (unless latex-frag (user-error "Invalid LaTeX fragment"))
+ (let* ((tmp-in-file
+ (let ((file (file-relative-name
+ (make-temp-name (expand-file-name "ltxmathml-in")))))
+ (write-region latex-frag nil file)
+ file))
+ (tmp-out-file (file-relative-name
+ (make-temp-name (expand-file-name "ltxmathml-out"))))
+ (cmd (format-spec
+ org-latex-to-mathml-convert-command
+ `((?j . ,(and org-latex-to-mathml-jar-file
+ (shell-quote-argument
+ (expand-file-name
+ org-latex-to-mathml-jar-file))))
+ (?I . ,(shell-quote-argument tmp-in-file))
+ (?i . ,latex-frag)
+ (?o . ,(shell-quote-argument tmp-out-file)))))
+ mathml shell-command-output)
+ (when (called-interactively-p 'any)
+ (unless (org-format-latex-mathml-available-p)
+ (user-error "LaTeX to MathML converter not configured")))
+ (message "Running %s" cmd)
+ (setq shell-command-output (shell-command-to-string cmd))
+ (setq mathml
+ (when (file-readable-p tmp-out-file)
+ (with-current-buffer (find-file-noselect tmp-out-file t)
+ (goto-char (point-min))
+ (when (re-search-forward
+ (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
+ (regexp-quote
+ "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
+ nil t)
+ (prog1 (match-string 0) (kill-buffer))))))
+ (cond
+ (mathml
+ (setq mathml
+ (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
+ (when mathml-file
+ (write-region mathml nil mathml-file))
+ (when (called-interactively-p 'any)
+ (message mathml)))
+ ((message "LaTeX to MathML conversion failed")
+ (message shell-command-output)))
+ (delete-file tmp-in-file)
+ (when (file-exists-p tmp-out-file)
+ (delete-file tmp-out-file))
+ mathml))
+
+(defun org-format-latex-as-mathml (latex-frag latex-frag-type
+ prefix &optional dir)
+ "Use `org-create-math-formula' but check local cache first."
+ (let* ((absprefix (expand-file-name prefix dir))
+ (print-length nil) (print-level nil)
+ (formula-id (concat
+ "formula-"
+ (sha1
+ (prin1-to-string
+ (list latex-frag
+ org-latex-to-mathml-convert-command)))))
+ (formula-cache (format "%s-%s.mathml" absprefix formula-id))
+ (formula-cache-dir (file-name-directory formula-cache)))
+
+ (unless (file-directory-p formula-cache-dir)
+ (make-directory formula-cache-dir t))
+
+ (unless (file-exists-p formula-cache)
+ (org-create-math-formula latex-frag formula-cache))
+
+ (if (file-exists-p formula-cache)
+ ;; Successful conversion. Return the link to MathML file.
+ (org-add-props
+ (format "[[file:%s]]" (file-relative-name formula-cache dir))
+ (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
+ 'org-latex-src-embed-type (if latex-frag-type
+ 'paragraph 'character)))
+ ;; Failed conversion. Return the LaTeX fragment verbatim
+ latex-frag)))
+
+(defun org--get-display-dpi ()
+ "Get the DPI of the display.
+The function assumes that the display has the same pixel width in
+the horizontal and vertical directions."
+ (if (display-graphic-p)
+ (round (/ (display-pixel-height)
+ (/ (display-mm-height) 25.4)))
+ (error "Attempt to calculate the dpi of a non-graphic display")))
+
+(defun org-create-formula-image
+ (string tofile options buffer &optional processing-type)
+ "Create an image from LaTeX source using external processes.
+
+The LaTeX STRING is saved to a temporary LaTeX file, then
+converted to an image file by process PROCESSING-TYPE defined in
+`org-preview-latex-process-alist'. A nil value defaults to
+`org-preview-latex-default-process'.
+
+The generated image file is eventually moved to TOFILE.
+
+The OPTIONS argument controls the size, foreground color and
+background color of the generated image.
+
+When BUFFER non-nil, this function is used for LaTeX previewing.
+Otherwise, it is used to deal with LaTeX snippets showed in
+a HTML file."
+ (let* ((processing-type (or processing-type
+ org-preview-latex-default-process))
+ (processing-info
+ (cdr (assq processing-type org-preview-latex-process-alist)))
+ (programs (plist-get processing-info :programs))
+ (error-message (or (plist-get processing-info :message) ""))
+ (use-xcolor (plist-get processing-info :use-xcolor))
+ (image-input-type (plist-get processing-info :image-input-type))
+ (image-output-type (plist-get processing-info :image-output-type))
+ (post-clean (or (plist-get processing-info :post-clean)
+ '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
+ ".svg" ".png" ".jpg" ".jpeg" ".out")))
+ (latex-header
+ (or (plist-get processing-info :latex-header)
+ (org-latex-make-preamble
+ (org-export-get-environment (org-export-get-backend 'latex))
+ org-format-latex-header
+ 'snippet)))
+ (latex-compiler (plist-get processing-info :latex-compiler))
+ (image-converter (plist-get processing-info :image-converter))
+ (tmpdir temporary-file-directory)
+ (texfilebase (make-temp-name
+ (expand-file-name "orgtex" tmpdir)))
+ (texfile (concat texfilebase ".tex"))
+ (image-size-adjust (or (plist-get processing-info :image-size-adjust)
+ '(1.0 . 1.0)))
+ (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
+ (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
+ (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
+ (fg (or (plist-get options (if buffer :foreground :html-foreground))
+ "Black"))
+ (bg (or (plist-get options (if buffer :background :html-background))
+ "Transparent"))
+ (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
+ (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
+ (dolist (program programs)
+ (org-check-external-command program error-message))
+ (if use-xcolor
+ (progn (if (eq fg 'default)
+ (setq fg (org-latex-color :foreground))
+ (setq fg (org-latex-color-format fg)))
+ (if (eq bg 'default)
+ (setq bg (org-latex-color :background))
+ (setq bg (org-latex-color-format
+ (if (string= bg "Transparent") "white" bg))))
+ (with-temp-file texfile
+ (insert latex-header)
+ (insert "\n\\begin{document}\n"
+ "\\definecolor{fg}{rgb}{" fg "}\n"
+ "\\definecolor{bg}{rgb}{" bg "}\n"
+ "\n\\pagecolor{bg}\n"
+ "\n{\\color{fg}\n"
+ string
+ "\n}\n"
+ "\n\\end{document}\n")))
+ (if (eq fg 'default)
+ (setq fg (org-dvipng-color :foreground))
+ (unless (string= fg "Transparent")
+ (setq fg (org-dvipng-color-format fg))))
+ (if (eq bg 'default)
+ (setq bg (org-dvipng-color :background))
+ (unless (string= bg "Transparent")
+ (setq bg (org-dvipng-color-format bg))))
+ (with-temp-file texfile
+ (insert latex-header)
+ (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
+
+ (let* ((err-msg (format "Please adjust '%s' part of \
+`org-preview-latex-process-alist'."
+ processing-type))
+ (image-input-file
+ (org-compile-file
+ texfile latex-compiler image-input-type err-msg log-buf))
+ (image-output-file
+ (org-compile-file
+ image-input-file image-converter image-output-type err-msg log-buf
+ `((?F . ,(shell-quote-argument fg))
+ (?B . ,(shell-quote-argument bg))
+ (?D . ,(shell-quote-argument (format "%s" dpi)))
+ (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
+ (copy-file image-output-file tofile 'replace)
+ (dolist (e post-clean)
+ (when (file-exists-p (concat texfilebase e))
+ (delete-file (concat texfilebase e))))
+ image-output-file)))
+
+(defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
+ "Fill a LaTeX header template TPL.
+In the template, the following place holders will be recognized:
+
+ [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
+ [NO-DEFAULT-PACKAGES] do not include DEF-PKG
+ [PACKAGES] \\usepackage statements for PKG
+ [NO-PACKAGES] do not include PKG
+ [EXTRA] the string EXTRA
+ [NO-EXTRA] do not include EXTRA
+
+For backward compatibility, if both the positive and the negative place
+holder is missing, the positive one (without the \"NO-\") will be
+assumed to be present at the end of the template.
+DEF-PKG and PKG are assumed to be alists of options/packagename lists.
+EXTRA is a string.
+SNIPPETS-P indicates if this is run to create snippet images for HTML."
+ (let (rpl (end ""))
+ (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
+ (setq rpl (if (or (match-end 1) (not def-pkg))
+ "" (org-latex-packages-to-string def-pkg snippets-p t))
+ tpl (replace-match rpl t t tpl))
+ (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
+
+ (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
+ (setq rpl (if (or (match-end 1) (not pkg))
+ "" (org-latex-packages-to-string pkg snippets-p t))
+ tpl (replace-match rpl t t tpl))
+ (when pkg (setq end
+ (concat end "\n"
+ (org-latex-packages-to-string pkg snippets-p)))))
+
+ (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
+ (setq rpl (if (or (match-end 1) (not extra))
+ "" (concat extra "\n"))
+ tpl (replace-match rpl t t tpl))
+ (when (and extra (string-match "\\S-" extra))
+ (setq end (concat end "\n" extra))))
+
+ (if (string-match "\\S-" end)
+ (concat tpl "\n" end)
+ tpl)))
+
+(defun org-latex-packages-to-string (pkg &optional snippets-p newline)
+ "Turn an alist of packages into a string with the \\usepackage macros."
+ (setq pkg (mapconcat (lambda(p)
+ (cond
+ ((stringp p) p)
+ ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
+ (format "%% Package %s omitted" (cadr p)))
+ ((equal "" (car p))
+ (format "\\usepackage{%s}" (cadr p)))
+ (t
+ (format "\\usepackage[%s]{%s}"
+ (car p) (cadr p)))))
+ pkg
+ "\n"))
+ (if newline (concat pkg "\n") pkg))
+
+(defun org-dvipng-color (attr)
+ "Return a RGB color specification for dvipng."
+ (org-dvipng-color-format (face-attribute 'default attr nil)))
+
+(defun org-dvipng-color-format (color-name)
+ "Convert COLOR-NAME to a RGB color value for dvipng."
+ (apply #'format "rgb %s %s %s"
+ (mapcar 'org-normalize-color
+ (color-values color-name))))
+
+(defun org-latex-color (attr)
+ "Return a RGB color for the LaTeX color package."
+ (org-latex-color-format (face-attribute 'default attr nil)))
+
+(defun org-latex-color-format (color-name)
+ "Convert COLOR-NAME to a RGB color value."
+ (apply #'format "%s,%s,%s"
+ (mapcar 'org-normalize-color
+ (color-values color-name))))
+
+(defun org-normalize-color (value)
+ "Return string to be used as color value for an RGB component."
+ (format "%g" (/ value 65535.0)))
+
+
+
+;; Image display
+
+(defvar-local org-inline-image-overlays nil)
+
+(defun org-toggle-inline-images (&optional include-linked)
+ "Toggle the display of inline images.
+INCLUDE-LINKED is passed to `org-display-inline-images'."
+ (interactive "P")
+ (if org-inline-image-overlays
+ (progn
+ (org-remove-inline-images)
+ (when (called-interactively-p 'interactive)
+ (message "Inline image display turned off")))
+ (org-display-inline-images include-linked)
+ (when (called-interactively-p 'interactive)
+ (message (if org-inline-image-overlays
+ (format "%d images displayed inline"
+ (length org-inline-image-overlays))
+ "No images to display inline")))))
+
+(defun org-redisplay-inline-images ()
+ "Refresh the display of inline images."
+ (interactive)
+ (if (not org-inline-image-overlays)
+ (org-toggle-inline-images)
+ (org-toggle-inline-images)
+ (org-toggle-inline-images)))
+
+(defun org-display-inline-images (&optional include-linked refresh beg end)
+ "Display inline images.
+
+An inline image is a link which follows either of these
+conventions:
+
+ 1. Its path is a file with an extension matching return value
+ from `image-file-name-regexp' and it has no contents.
+
+ 2. Its description consists in a single link of the previous
+ type.
+
+When optional argument INCLUDE-LINKED is non-nil, also links with
+a text description part will be inlined. This can be nice for
+a quick look at those images, but it does not reflect what
+exported files will look like.
+
+When optional argument REFRESH is non-nil, refresh existing
+images between BEG and END. This will create new image displays
+only if necessary. BEG and END default to the buffer
+boundaries."
+ (interactive "P")
+ (when (display-graphic-p)
+ (unless refresh
+ (org-remove-inline-images)
+ (when (fboundp 'clear-image-cache) (clear-image-cache)))
+ (org-with-wide-buffer
+ (goto-char (or beg (point-min)))
+ (let ((case-fold-search t)
+ (file-extension-re (image-file-name-regexp)))
+ (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
+ (let ((link (save-match-data (org-element-context))))
+ ;; Check if we're at an inline image.
+ (when (and (equal (org-element-property :type link) "file")
+ (or include-linked
+ (not (org-element-property :contents-begin link)))
+ (let ((parent (org-element-property :parent link)))
+ (or (not (eq (org-element-type parent) 'link))
+ (not (cdr (org-element-contents parent)))))
+ (string-match-p file-extension-re
+ (org-element-property :path link)))
+ (let ((file (expand-file-name
+ (org-link-unescape
+ (org-element-property :path link)))))
+ (when (file-exists-p file)
+ (let ((width
+ ;; Apply `org-image-actual-width' specifications.
+ (cond
+ ((not (image-type-available-p 'imagemagick)) nil)
+ ((eq org-image-actual-width t) nil)
+ ((listp org-image-actual-width)
+ (or
+ ;; First try to find a width among
+ ;; attributes associated to the paragraph
+ ;; containing link.
+ (let ((paragraph
+ (let ((e link))
+ (while (and (setq e (org-element-property
+ :parent e))
+ (not (eq (org-element-type e)
+ 'paragraph))))
+ e)))
+ (when paragraph
+ (save-excursion
+ (goto-char (org-element-property :begin paragraph))
+ (when
+ (re-search-forward
+ "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
+ (org-element-property
+ :post-affiliated paragraph)
+ t)
+ (string-to-number (match-string 1))))))
+ ;; Otherwise, fall-back to provided number.
+ (car org-image-actual-width)))
+ ((numberp org-image-actual-width)
+ org-image-actual-width)))
+ (old (get-char-property-and-overlay
+ (org-element-property :begin link)
+ 'org-image-overlay)))
+ (if (and (car-safe old) refresh)
+ (image-refresh (overlay-get (cdr old) 'display))
+ (let ((image (create-image file
+ (and width 'imagemagick)
+ nil
+ :width width)))
+ (when image
+ (let* ((link
+ ;; If inline image is the description
+ ;; of another link, be sure to
+ ;; consider the latter as the one to
+ ;; apply the overlay on.
+ (let ((parent
+ (org-element-property :parent link)))
+ (if (eq (org-element-type parent) 'link)
+ parent
+ link)))
+ (ov (make-overlay
+ (org-element-property :begin link)
+ (progn
+ (goto-char
+ (org-element-property :end link))
+ (skip-chars-backward " \t")
+ (point)))))
+ (overlay-put ov 'display image)
+ (overlay-put ov 'face 'default)
+ (overlay-put ov 'org-image-overlay t)
+ (overlay-put
+ ov 'modification-hooks
+ (list 'org-display-inline-remove-overlay))
+ (push ov org-inline-image-overlays)))))))))))))))
+
+(defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
+ "Remove inline-display overlay if a corresponding region is modified."
+ (let ((inhibit-modification-hooks t))
+ (when (and ov after)
+ (delete ov org-inline-image-overlays)
+ (delete-overlay ov))))
+
+(defun org-remove-inline-images ()
+ "Remove inline display of images."
+ (interactive)
+ (mapc #'delete-overlay org-inline-image-overlays)
+ (setq org-inline-image-overlays nil))
+
+;;;; Key bindings
+
+;; Outline functions from `outline-mode-prefix-map'
+;; that can be remapped in Org:
+(define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
+(define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
+(define-key org-mode-map [remap outline-forward-same-level]
+ 'org-forward-heading-same-level)
+(define-key org-mode-map [remap outline-backward-same-level]
+ 'org-backward-heading-same-level)
+(define-key org-mode-map [remap outline-show-branches]
+ 'org-kill-note-or-show-branches)
+(define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
+(define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
+(define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
+(define-key org-mode-map [remap outline-next-visible-heading]
+ 'org-next-visible-heading)
+(define-key org-mode-map [remap outline-previous-visible-heading]
+ 'org-previous-visible-heading)
+(define-key org-mode-map [remap show-children] 'org-show-children)
+
+;; Outline functions from `outline-mode-prefix-map' that can not
+;; be remapped in Org:
+
+;; - the column "key binding" shows whether the Outline function is still
+;; available in Org mode on the same key that it has been bound to in
+;; Outline mode:
+;; - "overridden": key used for a different functionality in Org mode
+;; - else: key still bound to the same Outline function in Org mode
+
+;; | Outline function | key binding | Org replacement |
+;; |------------------------------------+-------------+--------------------------|
+;; | `outline-up-heading' | `C-c C-u' | still same function |
+;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
+;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
+;; | `show-entry' | overridden | no replacement |
+;; | `show-branches' | `C-c C-k' | still same function |
+;; | `show-subtree' | overridden | visibility cycling |
+;; | `show-all' | overridden | no replacement |
+;; | `hide-subtree' | overridden | visibility cycling |
+;; | `hide-body' | overridden | no replacement |
+;; | `hide-entry' | overridden | visibility cycling |
+;; | `hide-leaves' | overridden | no replacement |
+;; | `hide-sublevels' | overridden | no replacement |
+;; | `hide-other' | overridden | no replacement |
+
+;; Make `C-c C-x' a prefix key
+(org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
+
+;; TAB key with modifiers
+(org-defkey org-mode-map "\C-i" 'org-cycle)
+(org-defkey org-mode-map [(tab)] 'org-cycle)
+(org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
+(org-defkey org-mode-map "\M-\t" #'pcomplete)
+;; The following line is necessary under Suse GNU/Linux
+(org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
+(org-defkey org-mode-map [(shift tab)] 'org-shifttab)
+(define-key org-mode-map [backtab] 'org-shifttab)
+
+(org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
+(org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
+(org-defkey org-mode-map [(meta return)] 'org-meta-return)
+
+;; Cursor keys with modifiers
+(org-defkey org-mode-map [(meta left)] 'org-metaleft)
+(org-defkey org-mode-map [(meta right)] 'org-metaright)
+(org-defkey org-mode-map [(meta up)] 'org-metaup)
+(org-defkey org-mode-map [(meta down)] 'org-metadown)
+
+(org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
+(org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
+(org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
+(org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
+(org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
+(org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
+
+(org-defkey org-mode-map [(shift up)] 'org-shiftup)
+(org-defkey org-mode-map [(shift down)] 'org-shiftdown)
+(org-defkey org-mode-map [(shift left)] 'org-shiftleft)
+(org-defkey org-mode-map [(shift right)] 'org-shiftright)
+
+(org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
+(org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
+(org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
+(org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
+
+;; Babel keys
+(define-key org-mode-map org-babel-key-prefix org-babel-map)
+(dolist (pair org-babel-key-bindings)
+ (define-key org-babel-map (car pair) (cdr pair)))
+
+;;; Extra keys for tty access.
+;; We only set them when really needed because otherwise the
+;; menus don't show the simple keys
+
+(when (or org-use-extra-keys (not window-system))
+ (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
+ (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
+ (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
+ (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
+ (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
+ (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
+ (org-defkey org-mode-map [?\e (right)] 'org-metaright)
+ (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
+ (org-defkey org-mode-map [?\e (up)] 'org-metaup)
+ (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
+ (org-defkey org-mode-map [?\e (down)] 'org-metadown)
+ (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
+ (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
+ (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
+ (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
+ (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
+ (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
+ (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
+ (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
+ (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
+ (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
+ (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
+ (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
+ (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
+ (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
+ (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
+ (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
+ (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
+
+;; All the other keys
+
+(org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
+(org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
+(if (boundp 'narrow-map)
+ (org-defkey narrow-map "s" 'org-narrow-to-subtree)
+ (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
+(if (boundp 'narrow-map)
+ (org-defkey narrow-map "b" 'org-narrow-to-block)
+ (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
+(if (boundp 'narrow-map)
+ (org-defkey narrow-map "e" 'org-narrow-to-element)
+ (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
+(org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
+(org-defkey org-mode-map "\M-}" 'org-forward-element)
+(org-defkey org-mode-map "\M-{" 'org-backward-element)
+(org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
+(org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
+(org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
+(org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
+(org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
+(org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
+(org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
+(org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
+(org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
+(org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
+(org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
+(org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
+(org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
+(org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
+(org-defkey org-mode-map "\C-c\C-j" 'org-goto)
+(org-defkey org-mode-map "\C-c\C-t" 'org-todo)
+(org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
+(org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
+(org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
+(org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
+(org-defkey org-mode-map "\C-c\C-w" 'org-refile)
+(org-defkey org-mode-map "\C-c\M-w" 'org-copy)
+(org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
+(org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
+(org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
+(org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
+(org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
+(org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
+(org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
+(org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
+(org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
+(org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
+(org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
+(org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
+(org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
+(org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
+(org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
+(org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
+(org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
+(org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
+(org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
+(org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
+(org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
+(org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
+(org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
+(org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
+(org-defkey org-mode-map "\C-c]" 'org-remove-file)
+(org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
+(org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
+(org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
+(org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
+(org-defkey org-mode-map "\C-c^" 'org-sort)
+(org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
+(org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
+(org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
+(org-defkey org-mode-map [remap open-line] 'org-open-line)
+(org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
+(org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
+(org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
+(org-defkey org-mode-map "\M-^" 'org-delete-indentation)
+(org-defkey org-mode-map "\C-m" 'org-return)
+(org-defkey org-mode-map "\C-j" 'org-return-indent)
+(org-defkey org-mode-map "\C-c?" 'org-table-field-info)
+(org-defkey org-mode-map "\C-c " 'org-table-blank-field)
+(org-defkey org-mode-map "\C-c+" 'org-table-sum)
+(org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
+(org-defkey org-mode-map "\C-c'" 'org-edit-special)
+(org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
+(org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
+(org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
+(org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
+(org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
+(org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
+(org-defkey org-mode-map "\C-c\C-a" 'org-attach)
+(org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
+(org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
+(org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
+(org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
+(org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
+(org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
+(org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
+(org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
+(org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
+(org-defkey org-mode-map "\M-h" 'org-mark-element)
+(org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
+;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
+
+(org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
+(org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
+(org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
+
+(org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
+(org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
+(org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
+(org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
+(org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
+(org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
+(org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
+(org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
+(org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
+(org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
+(org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
+(org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
+(org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
+(org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
+(org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
+(org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
+(org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
+(org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
+(org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
+(org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
+(org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
+(org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
+
+(org-defkey org-mode-map "\C-c\C-x." 'org-timer)
+(org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
+(org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
+(org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
+(org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
+
+(define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
+
+(define-key org-mode-map "\C-c\C-x!" 'org-reload)
+
+(define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
+(define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
+
+(define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
+
+
+(defconst org-speed-commands-default
+ '(
+ ("Outline Navigation")
+ ("n" . (org-speed-move-safe 'org-next-visible-heading))
+ ("p" . (org-speed-move-safe 'org-previous-visible-heading))
+ ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
+ ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
+ ("F" . org-next-block)
+ ("B" . org-previous-block)
+ ("u" . (org-speed-move-safe 'outline-up-heading))
+ ("j" . org-goto)
+ ("g" . (org-refile t))
+ ("Outline Visibility")
+ ("c" . org-cycle)
+ ("C" . org-shifttab)
+ (" " . org-display-outline-path)
+ ("s" . org-narrow-to-subtree)
+ ("=" . org-columns)
+ ("Outline Structure Editing")
+ ("U" . org-metaup)
+ ("D" . org-metadown)
+ ("r" . org-metaright)
+ ("l" . org-metaleft)
+ ("R" . org-shiftmetaright)
+ ("L" . org-shiftmetaleft)
+ ("i" . (progn (forward-char 1) (call-interactively
+ 'org-insert-heading-respect-content)))
+ ("^" . org-sort)
+ ("w" . org-refile)
+ ("a" . org-archive-subtree-default-with-confirmation)
+ ("@" . org-mark-subtree)
+ ("#" . org-toggle-comment)
+ ("Clock Commands")
+ ("I" . org-clock-in)
+ ("O" . org-clock-out)
+ ("Meta Data Editing")
+ ("t" . org-todo)
+ ("," . (org-priority))
+ ("0" . (org-priority ?\ ))
+ ("1" . (org-priority ?A))
+ ("2" . (org-priority ?B))
+ ("3" . (org-priority ?C))
+ (":" . org-set-tags-command)
+ ("e" . org-set-effort)
+ ("E" . org-inc-effort)
+ ("W" . (lambda(m) (interactive "sMinutes before warning: ")
+ (org-entry-put (point) "APPT_WARNTIME" m)))
+ ("Agenda Views etc")
+ ("v" . org-agenda)
+ ("/" . org-sparse-tree)
+ ("Misc")
+ ("o" . org-open-at-point)
+ ("?" . org-speed-command-help)
+ ("<" . (org-agenda-set-restriction-lock 'subtree))
+ (">" . (org-agenda-remove-restriction-lock))
+ )
+ "The default speed commands.")
+
+(defun org-print-speed-command (e)
+ (if (> (length (car e)) 1)
+ (progn
+ (princ "\n")
+ (princ (car e))
+ (princ "\n")
+ (princ (make-string (length (car e)) ?-))
+ (princ "\n"))
+ (princ (car e))
+ (princ " ")
+ (if (symbolp (cdr e))
+ (princ (symbol-name (cdr e)))
+ (prin1 (cdr e)))
+ (princ "\n")))
+
+(defun org-speed-command-help ()
+ "Show the available speed commands."
+ (interactive)
+ (if (not org-use-speed-commands)
+ (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
+ (with-output-to-temp-buffer "*Help*"
+ (princ "User-defined Speed commands\n===========================\n")
+ (mapc #'org-print-speed-command org-speed-commands-user)
+ (princ "\n")
+ (princ "Built-in Speed commands\n=======================\n")
+ (mapc #'org-print-speed-command org-speed-commands-default))
+ (with-current-buffer "*Help*"
+ (setq truncate-lines t))))
+
+(defun org-speed-move-safe (cmd)
+ "Execute CMD, but make sure that the cursor always ends up in a headline.
+If not, return to the original position and throw an error."
+ (interactive)
+ (let ((pos (point)))
+ (call-interactively cmd)
+ (unless (and (bolp) (org-at-heading-p))
+ (goto-char pos)
+ (error "Boundary reached while executing %s" cmd))))
+
+(defvar org-self-insert-command-undo-counter 0)
+
+(defvar org-table-auto-blank-field) ; defined in org-table.el
+(defvar org-speed-command nil)
+
+(defun org-speed-command-activate (keys)
+ "Hook for activating single-letter speed commands.
+`org-speed-commands-default' specifies a minimal command set.
+Use `org-speed-commands-user' for further customization."
+ (when (or (and (bolp) (looking-at org-outline-regexp))
+ (and (functionp org-use-speed-commands)
+ (funcall org-use-speed-commands)))
+ (cdr (assoc keys (append org-speed-commands-user
+ org-speed-commands-default)))))
+
+(defun org-babel-speed-command-activate (keys)
+ "Hook for activating single-letter code block commands."
+ (when (and (bolp) (looking-at org-babel-src-block-regexp))
+ (cdr (assoc keys org-babel-key-bindings))))
+
+(defcustom org-speed-command-hook
+ '(org-speed-command-default-hook org-babel-speed-command-hook)
+ "Hook for activating speed commands at strategic locations.
+Hook functions are called in sequence until a valid handler is
+found.
+
+Each hook takes a single argument, a user-pressed command key
+which is also a `self-insert-command' from the global map.
+
+Within the hook, examine the cursor position and the command key
+and return nil or a valid handler as appropriate. Handler could
+be one of an interactive command, a function, or a form.
+
+Set `org-use-speed-commands' to non-nil value to enable this
+hook. The default setting is `org-speed-command-activate'."
+ :group 'org-structure
+ :version "24.1"
+ :type 'hook)
+
+(defun org-self-insert-command (N)
+ "Like `self-insert-command', use overwrite-mode for whitespace in tables.
+If the cursor is in a table looking at whitespace, the whitespace is
+overwritten, and the table is not marked as requiring realignment."
+ (interactive "p")
+ (org-check-before-invisible-edit 'insert)
+ (cond
+ ((and org-use-speed-commands
+ (let ((kv (this-command-keys-vector)))
+ (setq org-speed-command
+ (run-hook-with-args-until-success
+ 'org-speed-command-hook
+ (make-string 1 (aref kv (1- (length kv))))))))
+ (cond
+ ((commandp org-speed-command)
+ (setq this-command org-speed-command)
+ (call-interactively org-speed-command))
+ ((functionp org-speed-command)
+ (funcall org-speed-command))
+ ((and org-speed-command (listp org-speed-command))
+ (eval org-speed-command))
+ (t (let (org-use-speed-commands)
+ (call-interactively 'org-self-insert-command)))))
+ ((and
+ (org-at-table-p)
+ (progn
+ ;; Check if we blank the field, and if that triggers align.
+ (and (featurep 'org-table) org-table-auto-blank-field
+ (memq last-command
+ '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
+ (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
+ ;; Got extra space, this field does not determine
+ ;; column width.
+ (let (org-table-may-need-update) (org-table-blank-field))
+ ;; No extra space, this field may determine column
+ ;; width.
+ (org-table-blank-field)))
+ t)
+ (eq N 1)
+ (looking-at "[^|\n]* \\( \\)|"))
+ ;; There is room for insertion without re-aligning the table.
+ (delete-region (match-beginning 1) (match-end 1))
+ (self-insert-command N))
+ (t
+ (setq org-table-may-need-update t)
+ (self-insert-command N)
+ (org-fix-tags-on-the-fly)
+ (when org-self-insert-cluster-for-undo
+ (if (not (eq last-command 'org-self-insert-command))
+ (setq org-self-insert-command-undo-counter 1)
+ (if (>= org-self-insert-command-undo-counter 20)
+ (setq org-self-insert-command-undo-counter 1)
+ (and (> org-self-insert-command-undo-counter 0)
+ buffer-undo-list (listp buffer-undo-list)
+ (not (cadr buffer-undo-list)) ; remove nil entry
+ (setcdr buffer-undo-list (cddr buffer-undo-list)))
+ (setq org-self-insert-command-undo-counter
+ (1+ org-self-insert-command-undo-counter))))))))
+
+(defun org-check-before-invisible-edit (kind)
+ "Check is editing if kind KIND would be dangerous with invisible text around.
+The detailed reaction depends on the user option `org-catch-invisible-edits'."
+ ;; First, try to get out of here as quickly as possible, to reduce overhead
+ (when (and org-catch-invisible-edits
+ (or (not (boundp 'visible-mode)) (not visible-mode))
+ (or (get-char-property (point) 'invisible)
+ (get-char-property (max (point-min) (1- (point))) 'invisible)))
+ ;; OK, we need to take a closer look
+ (let* ((invisible-at-point (get-char-property (point) 'invisible))
+ (invisible-before-point (unless (bobp) (get-char-property
+ (1- (point)) 'invisible)))
+ (border-and-ok-direction
+ (or
+ ;; Check if we are acting predictably before invisible text
+ (and invisible-at-point (not invisible-before-point)
+ (memq kind '(insert delete-backward)))
+ ;; Check if we are acting predictably after invisible text
+ ;; This works not well, and I have turned it off. It seems
+ ;; better to always show and stop after invisible text.
+ ;; (and (not invisible-at-point) invisible-before-point
+ ;; (memq kind '(insert delete)))
+ )))
+ (when (or (memq invisible-at-point '(outline org-hide-block t))
+ (memq invisible-before-point '(outline org-hide-block t)))
+ (when (eq org-catch-invisible-edits 'error)
+ (user-error "Editing in invisible areas is prohibited, make them visible first"))
+ (if (and org-custom-properties-overlays
+ (y-or-n-p "Display invisible properties in this buffer? "))
+ (org-toggle-custom-properties-visibility)
+ ;; Make the area visible
+ (save-excursion
+ (when invisible-before-point
+ (goto-char (previous-single-char-property-change
+ (point) 'invisible)))
+ (outline-show-subtree))
+ (cond
+ ((eq org-catch-invisible-edits 'show)
+ ;; That's it, we do the edit after showing
+ (message
+ "Unfolding invisible region around point before editing")
+ (sit-for 1))
+ ((and (eq org-catch-invisible-edits 'smart)
+ border-and-ok-direction)
+ (message "Unfolding invisible region around point before editing"))
+ (t
+ ;; Don't do the edit, make the user repeat it in full visibility
+ (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
+
+(defun org-fix-tags-on-the-fly ()
+ "Align tags in headline at point.
+Unlike to `org-set-tags', it ignores region and sorting."
+ (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
+ (org-at-heading-p))
+ (let ((org-ignore-region t)
+ (org-tags-sort-function nil))
+ (org-set-tags nil t))))
+
+(defun org-delete-backward-char (N)
+ "Like `delete-backward-char', insert whitespace at field end in tables.
+When deleting backwards, in tables this function will insert whitespace in
+front of the next \"|\" separator, to keep the table aligned. The table will
+still be marked for re-alignment if the field did fill the entire column,
+because, in this case the deletion might narrow the column."
+ (interactive "p")
+ (save-match-data
+ (org-check-before-invisible-edit 'delete-backward)
+ (if (and (org-at-table-p)
+ (eq N 1)
+ (string-match "|" (buffer-substring (point-at-bol) (point)))
+ (looking-at ".*?|"))
+ (let ((pos (point))
+ (noalign (looking-at "[^|\n\r]* |"))
+ (c org-table-may-need-update))
+ (backward-delete-char N)
+ (unless overwrite-mode
+ (skip-chars-forward "^|")
+ (insert " ")
+ (goto-char (1- pos)))
+ ;; noalign: if there were two spaces at the end, this field
+ ;; does not determine the width of the column.
+ (when noalign (setq org-table-may-need-update c)))
+ (backward-delete-char N)
+ (org-fix-tags-on-the-fly))))
+
+(defun org-delete-char (N)
+ "Like `delete-char', but insert whitespace at field end in tables.
+When deleting characters, in tables this function will insert whitespace in
+front of the next \"|\" separator, to keep the table aligned. The table will
+still be marked for re-alignment if the field did fill the entire column,
+because, in this case the deletion might narrow the column."
+ (interactive "p")
+ (save-match-data
+ (org-check-before-invisible-edit 'delete)
+ (if (and (org-at-table-p)
+ (not (bolp))
+ (not (= (char-after) ?|))
+ (eq N 1))
+ (if (looking-at ".*?|")
+ (let ((pos (point))
+ (noalign (looking-at "[^|\n\r]* |"))
+ (c org-table-may-need-update))
+ (replace-match
+ (concat (substring (match-string 0) 1 -1) " |") nil t)
+ (goto-char pos)
+ ;; noalign: if there were two spaces at the end, this field
+ ;; does not determine the width of the column.
+ (when noalign (setq org-table-may-need-update c)))
+ (delete-char N))
+ (delete-char N)
+ (org-fix-tags-on-the-fly))))
+
+;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
+(put 'org-self-insert-command 'delete-selection
+ (lambda ()
+ (not (run-hook-with-args-until-success
+ 'self-insert-uses-region-functions))))
+(put 'orgtbl-self-insert-command 'delete-selection
+ (lambda ()
+ (not (run-hook-with-args-until-success
+ 'self-insert-uses-region-functions))))
+(put 'org-delete-char 'delete-selection 'supersede)
+(put 'org-delete-backward-char 'delete-selection 'supersede)
+(put 'org-yank 'delete-selection 'yank)
+
+;; Make `flyspell-mode' delay after some commands
+(put 'org-self-insert-command 'flyspell-delayed t)
+(put 'orgtbl-self-insert-command 'flyspell-delayed t)
+(put 'org-delete-char 'flyspell-delayed t)
+(put 'org-delete-backward-char 'flyspell-delayed t)
+
+;; Make pabbrev-mode expand after Org mode commands
+(put 'org-self-insert-command 'pabbrev-expand-after-command t)
+(put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
+
+(defun org-remap (map &rest commands)
+ "In MAP, remap the functions given in COMMANDS.
+COMMANDS is a list of alternating OLDDEF NEWDEF command names."
+ (let (new old)
+ (while commands
+ (setq old (pop commands) new (pop commands))
+ (org-defkey map (vector 'remap old) new))))
+
+(defun org-transpose-words ()
+ "Transpose words for Org.
+This uses the `org-mode-transpose-word-syntax-table' syntax
+table, which interprets characters in `org-emphasis-alist' as
+word constituents."
+ (interactive)
+ (with-syntax-table org-mode-transpose-word-syntax-table
+ (call-interactively 'transpose-words)))
+(org-remap org-mode-map 'transpose-words 'org-transpose-words)
+
+(when (eq org-enable-table-editor 'optimized)
+ ;; If the user wants maximum table support, we need to hijack
+ ;; some standard editing functions
+ (org-remap org-mode-map
+ 'self-insert-command 'org-self-insert-command
+ 'delete-char 'org-delete-char
+ 'delete-backward-char 'org-delete-backward-char)
+ (org-defkey org-mode-map "|" 'org-force-self-insert))
+
+(defvar org-ctrl-c-ctrl-c-hook nil
+ "Hook for functions attaching themselves to `C-c C-c'.
+
+This can be used to add additional functionality to the C-c C-c
+key which executes context-dependent commands. This hook is run
+before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
+run after the last test.
+
+Each function will be called with no arguments. The function
+must check if the context is appropriate for it to act. If yes,
+it should do its thing and then return a non-nil value. If the
+context is wrong, just do nothing and return nil.")
+
+(defvar org-ctrl-c-ctrl-c-final-hook nil
+ "Hook for functions attaching themselves to `C-c C-c'.
+
+This can be used to add additional functionality to the C-c C-c
+key which executes context-dependent commands. This hook is run
+after any other test, while `org-ctrl-c-ctrl-c-hook' is run
+before the first test.
+
+Each function will be called with no arguments. The function
+must check if the context is appropriate for it to act. If yes,
+it should do its thing and then return a non-nil value. If the
+context is wrong, just do nothing and return nil.")
+
+(defvar org-tab-first-hook nil
+ "Hook for functions to attach themselves to TAB.
+See `org-ctrl-c-ctrl-c-hook' for more information.
+This hook runs as the first action when TAB is pressed, even before
+`org-cycle' messes around with the `outline-regexp' to cater for
+inline tasks and plain list item folding.
+If any function in this hook returns t, any other actions that
+would have been caused by TAB (such as table field motion or visibility
+cycling) will not occur.")
+
+(defvar org-tab-after-check-for-table-hook nil
+ "Hook for functions to attach themselves to TAB.
+See `org-ctrl-c-ctrl-c-hook' for more information.
+This hook runs after it has been established that the cursor is not in a
+table, but before checking if the cursor is in a headline or if global cycling
+should be done.
+If any function in this hook returns t, not other actions like visibility
+cycling will be done.")
+
+(defvar org-tab-after-check-for-cycling-hook nil
+ "Hook for functions to attach themselves to TAB.
+See `org-ctrl-c-ctrl-c-hook' for more information.
+This hook runs after it has been established that not table field motion and
+not visibility should be done because of current context. This is probably
+the place where a package like yasnippets can hook in.")
+
+(defvar org-tab-before-tab-emulation-hook nil
+ "Hook for functions to attach themselves to TAB.
+See `org-ctrl-c-ctrl-c-hook' for more information.
+This hook runs after every other options for TAB have been exhausted, but
+before indentation and \t insertion takes place.")
+
+(defvar org-metaleft-hook nil
+ "Hook for functions attaching themselves to `M-left'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-metaright-hook nil
+ "Hook for functions attaching themselves to `M-right'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-metaup-hook nil
+ "Hook for functions attaching themselves to `M-up'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-metadown-hook nil
+ "Hook for functions attaching themselves to `M-down'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftmetaleft-hook nil
+ "Hook for functions attaching themselves to `M-S-left'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftmetaright-hook nil
+ "Hook for functions attaching themselves to `M-S-right'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftmetaup-hook nil
+ "Hook for functions attaching themselves to `M-S-up'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftmetadown-hook nil
+ "Hook for functions attaching themselves to `M-S-down'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-metareturn-hook nil
+ "Hook for functions attaching themselves to `M-RET'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftup-hook nil
+ "Hook for functions attaching themselves to `S-up'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftup-final-hook nil
+ "Hook for functions attaching themselves to `S-up'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftdown-hook nil
+ "Hook for functions attaching themselves to `S-down'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftdown-final-hook nil
+ "Hook for functions attaching themselves to `S-down'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftleft-hook nil
+ "Hook for functions attaching themselves to `S-left'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftleft-final-hook nil
+ "Hook for functions attaching themselves to `S-left'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftright-hook nil
+ "Hook for functions attaching themselves to `S-right'.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+(defvar org-shiftright-final-hook nil
+ "Hook for functions attaching themselves to `S-right'.
+This one runs after all other options except shift-select have been excluded.
+See `org-ctrl-c-ctrl-c-hook' for more information.")
+
+(defun org-modifier-cursor-error ()
+ "Throw an error, a modified cursor command was applied in wrong context."
+ (user-error "This command is active in special context like tables, headlines or items"))
+
+(defun org-shiftselect-error ()
+ "Throw an error because Shift-Cursor command was applied in wrong context."
+ (if (and (boundp 'shift-select-mode) shift-select-mode)
+ (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
+ (user-error "This command works only in special context like headlines or timestamps")))
+
+(defun org-call-for-shift-select (cmd)
+ (let ((this-command-keys-shift-translated t))
+ (call-interactively cmd)))
+
+(defun org-shifttab (&optional arg)
+ "Global visibility cycling or move to previous table field.
+Call `org-table-previous-field' within a table.
+When ARG is nil, cycle globally through visibility states.
+When ARG is a numeric prefix, show contents of this level."
+ (interactive "P")
+ (cond
+ ((org-at-table-p) (call-interactively 'org-table-previous-field))
+ ((integerp arg)
+ (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
+ (message "Content view to level: %d" arg)
+ (org-content (prefix-numeric-value arg2))
+ (org-cycle-show-empty-lines t)
+ (setq org-cycle-global-status 'overview)))
+ (t (call-interactively 'org-global-cycle))))
+
+(defun org-shiftmetaleft ()
+ "Promote subtree or delete table column.
+Calls `org-promote-subtree', `org-outdent-item-tree', or
+`org-table-delete-column', depending on context. See the
+individual commands for more information."
+ (interactive)
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
+ ((org-at-table-p) (call-interactively 'org-table-delete-column))
+ ((org-at-heading-p) (call-interactively 'org-promote-subtree))
+ ((if (not (org-region-active-p)) (org-at-item-p)
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p)))
+ (call-interactively 'org-outdent-item-tree))
+ (t (org-modifier-cursor-error))))
+
+(defun org-shiftmetaright ()
+ "Demote subtree or insert table column.
+Calls `org-demote-subtree', `org-indent-item-tree', or
+`org-table-insert-column', depending on context. See the
+individual commands for more information."
+ (interactive)
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
+ ((org-at-table-p) (call-interactively 'org-table-insert-column))
+ ((org-at-heading-p) (call-interactively 'org-demote-subtree))
+ ((if (not (org-region-active-p)) (org-at-item-p)
+ (save-excursion (goto-char (region-beginning))
+ (org-at-item-p)))
+ (call-interactively 'org-indent-item-tree))
+ (t (org-modifier-cursor-error))))
+
+(defun org-shiftmetaup (&optional _arg)
+ "Drag the line at point up.
+In a table, kill the current row.
+On a clock timestamp, update the value of the timestamp like `S-<up>'
+but also adjust the previous clocked item in the clock history.
+Everywhere else, drag the line at point up."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
+ ((org-at-table-p) (call-interactively 'org-table-kill-row))
+ ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
+ (call-interactively 'org-timestamp-up)))
+ (t (call-interactively 'org-drag-line-backward))))
+
+(defun org-shiftmetadown (&optional _arg)
+ "Drag the line at point down.
+In a table, insert an empty row at the current line.
+On a clock timestamp, update the value of the timestamp like `S-<down>'
+but also adjust the previous clocked item in the clock history.
+Everywhere else, drag the line at point down."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
+ ((org-at-table-p) (call-interactively 'org-table-insert-row))
+ ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
+ (call-interactively 'org-timestamp-down)))
+ (t (call-interactively 'org-drag-line-forward))))
+
+(defsubst org-hidden-tree-error ()
+ (user-error
+ "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
+
+(defun org-metaleft (&optional _arg)
+ "Promote heading, list item at point or move table column left.
+
+Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
+depending on context. With no specific context, calls the Emacs
+default `backward-word'. See the individual commands for more
+information.
+
+This function runs the hook `org-metaleft-hook' as a first step,
+and returns at first non-nil value."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-metaleft-hook))
+ ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
+ ((org-with-limited-levels
+ (or (org-at-heading-p)
+ (and (org-region-active-p)
+ (save-excursion
+ (goto-char (region-beginning))
+ (org-at-heading-p)))))
+ (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
+ (call-interactively 'org-do-promote))
+ ;; At an inline task.
+ ((org-at-heading-p)
+ (call-interactively 'org-inlinetask-promote))
+ ((or (org-at-item-p)
+ (and (org-region-active-p)
+ (save-excursion
+ (goto-char (region-beginning))
+ (org-at-item-p))))
+ (when (org-check-for-hidden 'items) (org-hidden-tree-error))
+ (call-interactively 'org-outdent-item))
+ (t (call-interactively 'backward-word))))
+
+(defun org-metaright (&optional _arg)
+ "Demote heading, list item at point or move table column right.
+
+In front of a drawer or a block keyword, indent it correctly.
+
+Calls `org-do-demote', `org-indent-item', `org-table-move-column',
+`org-indent-drawer' or `org-indent-block' depending on context.
+With no specific context, calls the Emacs default `forward-word'.
+See the individual commands for more information.
+
+This function runs the hook `org-metaright-hook' as a first step,
+and returns at first non-nil value."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-metaright-hook))
+ ((org-at-table-p) (call-interactively 'org-table-move-column))
+ ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
+ ((org-at-block-p) (call-interactively 'org-indent-block))
+ ((org-with-limited-levels
+ (or (org-at-heading-p)
+ (and (org-region-active-p)
+ (save-excursion
+ (goto-char (region-beginning))
+ (org-at-heading-p)))))
+ (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
+ (call-interactively 'org-do-demote))
+ ;; At an inline task.
+ ((org-at-heading-p)
+ (call-interactively 'org-inlinetask-demote))
+ ((or (org-at-item-p)
+ (and (org-region-active-p)
+ (save-excursion
+ (goto-char (region-beginning))
+ (org-at-item-p))))
+ (when (org-check-for-hidden 'items) (org-hidden-tree-error))
+ (call-interactively 'org-indent-item))
+ (t (call-interactively 'forward-word))))
+
+(defun org-check-for-hidden (what)
+ "Check if there are hidden headlines/items in the current visual line.
+WHAT can be either `headlines' or `items'. If the current line is
+an outline or item heading and it has a folded subtree below it,
+this function returns t, nil otherwise."
+ (let ((re (cond
+ ((eq what 'headlines) org-outline-regexp-bol)
+ ((eq what 'items) (org-item-beginning-re))
+ (t (error "This should not happen"))))
+ beg end)
+ (save-excursion
+ (catch 'exit
+ (unless (org-region-active-p)
+ (setq beg (point-at-bol))
+ (beginning-of-line 2)
+ (while (and (not (eobp)) ;; this is like `next-line'
+ (get-char-property (1- (point)) 'invisible))
+ (beginning-of-line 2))
+ (setq end (point))
+ (goto-char beg)
+ (goto-char (point-at-eol))
+ (setq end (max end (point)))
+ (while (re-search-forward re end t)
+ (when (get-char-property (match-beginning 0) 'invisible)
+ (throw 'exit t))))
+ nil))))
+
+(defun org-metaup (&optional _arg)
+ "Move subtree up or move table row up.
+Calls `org-move-subtree-up' or `org-table-move-row' or
+`org-move-item-up', depending on context. See the individual commands
+for more information."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-metaup-hook))
+ ((org-region-active-p)
+ (let* ((a (min (region-beginning) (region-end)))
+ (b (1- (max (region-beginning) (region-end))))
+ (c (save-excursion (goto-char a)
+ (move-beginning-of-line 0)))
+ (d (save-excursion (goto-char a)
+ (move-end-of-line 0) (point))))
+ (transpose-regions a b c d)
+ (goto-char c)))
+ ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
+ ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
+ ((org-at-item-p) (call-interactively 'org-move-item-up))
+ (t (org-drag-element-backward))))
+
+(defun org-metadown (&optional _arg)
+ "Move subtree down or move table row down.
+Calls `org-move-subtree-down' or `org-table-move-row' or
+`org-move-item-down', depending on context. See the individual
+commands for more information."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-metadown-hook))
+ ((org-region-active-p)
+ (let* ((a (min (region-beginning) (region-end)))
+ (b (max (region-beginning) (region-end)))
+ (c (save-excursion (goto-char b)
+ (move-beginning-of-line 1)))
+ (d (save-excursion (goto-char b)
+ (move-end-of-line 1) (1+ (point)))))
+ (transpose-regions a b c d)
+ (goto-char d)))
+ ((org-at-table-p) (call-interactively 'org-table-move-row))
+ ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
+ ((org-at-item-p) (call-interactively 'org-move-item-down))
+ (t (org-drag-element-forward))))
+
+(defun org-shiftup (&optional arg)
+ "Increase item in timestamp or increase priority of current headline.
+Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
+depending on context. See the individual commands for more information."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftup-hook))
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'previous-line))
+ ((org-at-timestamp-p t)
+ (call-interactively (if org-edit-timestamp-down-means-later
+ 'org-timestamp-down 'org-timestamp-up)))
+ ((and (not (eq org-support-shift-select 'always))
+ org-enable-priority-commands
+ (org-at-heading-p))
+ (call-interactively 'org-priority-up))
+ ((and (not org-support-shift-select) (org-at-item-p))
+ (call-interactively 'org-previous-item))
+ ((org-clocktable-try-shift 'up arg))
+ ((run-hook-with-args-until-success 'org-shiftup-final-hook))
+ (org-support-shift-select
+ (org-call-for-shift-select 'previous-line))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftdown (&optional arg)
+ "Decrease item in timestamp or decrease priority of current headline.
+Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
+depending on context. See the individual commands for more information."
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftdown-hook))
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'next-line))
+ ((org-at-timestamp-p t)
+ (call-interactively (if org-edit-timestamp-down-means-later
+ 'org-timestamp-up 'org-timestamp-down)))
+ ((and (not (eq org-support-shift-select 'always))
+ org-enable-priority-commands
+ (org-at-heading-p))
+ (call-interactively 'org-priority-down))
+ ((and (not org-support-shift-select) (org-at-item-p))
+ (call-interactively 'org-next-item))
+ ((org-clocktable-try-shift 'down arg))
+ ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
+ (org-support-shift-select
+ (org-call-for-shift-select 'next-line))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftright (&optional arg)
+ "Cycle the thing at point or in the current line, depending on context.
+Depending on context, this does one of the following:
+
+- switch a timestamp at point one day into the future
+- on a headline, switch to the next TODO keyword.
+- on an item, switch entire list to the next bullet type
+- on a property line, switch to the next allowed value
+- on a clocktable definition line, move time block into the future"
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftright-hook))
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'forward-char))
+ ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-heading-p))
+ (let ((org-inhibit-logging
+ (not org-treat-S-cursor-todo-selection-as-state-change))
+ (org-inhibit-blocking
+ (not org-treat-S-cursor-todo-selection-as-state-change)))
+ (org-call-with-arg 'org-todo 'right)))
+ ((or (and org-support-shift-select
+ (not (eq org-support-shift-select 'always))
+ (org-at-item-bullet-p))
+ (and (not org-support-shift-select) (org-at-item-p)))
+ (org-call-with-arg 'org-cycle-list-bullet nil))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-property-p))
+ (call-interactively 'org-property-next-allowed-value))
+ ((org-clocktable-try-shift 'right arg))
+ ((run-hook-with-args-until-success 'org-shiftright-final-hook))
+ (org-support-shift-select
+ (org-call-for-shift-select 'forward-char))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftleft (&optional arg)
+ "Cycle the thing at point or in the current line, depending on context.
+Depending on context, this does one of the following:
+
+- switch a timestamp at point one day into the past
+- on a headline, switch to the previous TODO keyword.
+- on an item, switch entire list to the previous bullet type
+- on a property line, switch to the previous allowed value
+- on a clocktable definition line, move time block into the past"
+ (interactive "P")
+ (cond
+ ((run-hook-with-args-until-success 'org-shiftleft-hook))
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'backward-char))
+ ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-heading-p))
+ (let ((org-inhibit-logging
+ (not org-treat-S-cursor-todo-selection-as-state-change))
+ (org-inhibit-blocking
+ (not org-treat-S-cursor-todo-selection-as-state-change)))
+ (org-call-with-arg 'org-todo 'left)))
+ ((or (and org-support-shift-select
+ (not (eq org-support-shift-select 'always))
+ (org-at-item-bullet-p))
+ (and (not org-support-shift-select) (org-at-item-p)))
+ (org-call-with-arg 'org-cycle-list-bullet 'previous))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-property-p))
+ (call-interactively 'org-property-previous-allowed-value))
+ ((org-clocktable-try-shift 'left arg))
+ ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
+ (org-support-shift-select
+ (org-call-for-shift-select 'backward-char))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftcontrolright ()
+ "Switch to next TODO set."
+ (interactive)
+ (cond
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'forward-word))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-heading-p))
+ (org-call-with-arg 'org-todo 'nextset))
+ (org-support-shift-select
+ (org-call-for-shift-select 'forward-word))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftcontrolleft ()
+ "Switch to previous TODO set."
+ (interactive)
+ (cond
+ ((and org-support-shift-select (org-region-active-p))
+ (org-call-for-shift-select 'backward-word))
+ ((and (not (eq org-support-shift-select 'always))
+ (org-at-heading-p))
+ (org-call-with-arg 'org-todo 'previousset))
+ (org-support-shift-select
+ (org-call-for-shift-select 'backward-word))
+ (t (org-shiftselect-error))))
+
+(defun org-shiftcontrolup (&optional n)
+ "Change timestamps synchronously up in CLOCK log lines.
+Optional argument N tells to change by that many units."
+ (interactive "P")
+ (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
+ (let (org-support-shift-select)
+ (org-clock-timestamps-up n))
+ (user-error "Not at a clock log")))
+
+(defun org-shiftcontroldown (&optional n)
+ "Change timestamps synchronously down in CLOCK log lines.
+Optional argument N tells to change by that many units."
+ (interactive "P")
+ (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
+ (let (org-support-shift-select)
+ (org-clock-timestamps-down n))
+ (user-error "Not at a clock log")))
+
+(defun org-increase-number-at-point (&optional inc)
+ "Increment the number at point.
+With an optional prefix numeric argument INC, increment using
+this numeric value."
+ (interactive "p")
+ (if (not (number-at-point))
+ (user-error "Not on a number")
+ (unless inc (setq inc 1))
+ (let ((pos (point))
+ (beg (skip-chars-backward "-+^/*0-9eE."))
+ (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
+ (setq nap (buffer-substring-no-properties
+ (+ pos beg) (+ pos beg end)))
+ (delete-region (+ pos beg) (+ pos beg end))
+ (insert (calc-eval (concat (number-to-string inc) "+" nap))))
+ (when (org-at-table-p)
+ (org-table-align)
+ (org-table-end-of-field 1))))
+
+(defun org-decrease-number-at-point (&optional inc)
+ "Decrement the number at point.
+With an optional prefix numeric argument INC, decrement using
+this numeric value."
+ (interactive "p")
+ (org-increase-number-at-point (- (or inc 1))))
+
+(defun org-ctrl-c-ret ()
+ "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
+ (interactive)
+ (cond
+ ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
+ (t (call-interactively 'org-insert-heading))))
+
+(defun org-find-visible ()
+ (let ((s (point)))
+ (while (and (not (= (point-max) (setq s (next-overlay-change s))))
+ (get-char-property s 'invisible)))
+ s))
+(defun org-find-invisible ()
+ (let ((s (point)))
+ (while (and (not (= (point-max) (setq s (next-overlay-change s))))
+ (not (get-char-property s 'invisible))))
+ s))
+
+(defun org-copy-visible (beg end)
+ "Copy the visible parts of the region."
+ (interactive "r")
+ (let (snippets s)
+ (save-excursion
+ (save-restriction
+ (narrow-to-region beg end)
+ (setq s (goto-char (point-min)))
+ (while (not (= (point) (point-max)))
+ (goto-char (org-find-invisible))
+ (push (buffer-substring s (point)) snippets)
+ (setq s (goto-char (org-find-visible))))))
+ (kill-new (apply 'concat (nreverse snippets)))))
+
+(defun org-copy-special ()
+ "Copy region in table or copy current subtree.
+Calls `org-table-copy-region' or `org-copy-subtree', depending on
+context. See the individual commands for more information."
+ (interactive)
+ (call-interactively
+ (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
+
+(defun org-cut-special ()
+ "Cut region in table or cut current subtree.
+Calls `org-table-cut-region' or `org-cut-subtree', depending on
+context. See the individual commands for more information."
+ (interactive)
+ (call-interactively
+ (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
+
+(defun org-paste-special (arg)
+ "Paste rectangular region into table, or past subtree relative to level.
+Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
+See the individual commands for more information."
+ (interactive "P")
+ (if (org-at-table-p)
+ (org-table-paste-rectangle)
+ (org-paste-subtree arg)))
+
+(defun org-edit-special (&optional arg)
+ "Call a special editor for the element at point.
+When at a table, call the formula editor with `org-table-edit-formulas'.
+When in a source code block, call `org-edit-src-code'.
+When in a fixed-width region, call `org-edit-fixed-width-region'.
+When in an export block, call `org-edit-export-block'.
+When at an #+INCLUDE keyword, visit the included file.
+When at a footnote reference, call `org-edit-footnote-reference'
+On a link, call `ffap' to visit the link at point.
+Otherwise, return a user error."
+ (interactive "P")
+ (let ((element (org-element-at-point)))
+ (barf-if-buffer-read-only)
+ (pcase (org-element-type element)
+ (`src-block
+ (if (not arg) (org-edit-src-code)
+ (let* ((info (org-babel-get-src-block-info))
+ (lang (nth 0 info))
+ (params (nth 2 info))
+ (session (cdr (assq :session params))))
+ (if (not session) (org-edit-src-code)
+ ;; At a src-block with a session and function called with
+ ;; an ARG: switch to the buffer related to the inferior
+ ;; process.
+ (switch-to-buffer
+ (funcall (intern (concat "org-babel-prep-session:" lang))
+ session params))))))
+ (`keyword
+ (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
+ (org-open-link-from-string
+ (format "[[%s]]"
+ (expand-file-name
+ (let ((value (org-element-property :value element)))
+ (cond ((not (org-string-nw-p value))
+ (user-error "No file to edit"))
+ ((string-match "\\`\"\\(.*?\\)\"" value)
+ (match-string 1 value))
+ ((string-match "\\`[^ \t\"]\\S-*" value)
+ (match-string 0 value))
+ (t (user-error "No valid file specified")))))))
+ (user-error "No special environment to edit here")))
+ (`table
+ (if (eq (org-element-property :type element) 'table.el)
+ (org-edit-table.el)
+ (call-interactively 'org-table-edit-formulas)))
+ ;; Only Org tables contain `table-row' type elements.
+ (`table-row (call-interactively 'org-table-edit-formulas))
+ (`example-block (org-edit-src-code))
+ (`export-block (org-edit-export-block))
+ (`fixed-width (org-edit-fixed-width-region))
+ (_
+ ;; No notable element at point. Though, we may be at a link or
+ ;; a footnote reference, which are objects. Thus, scan deeper.
+ (let ((context (org-element-context element)))
+ (pcase (org-element-type context)
+ (`footnote-reference (org-edit-footnote-reference))
+ (`inline-src-block (org-edit-inline-src-code))
+ (`link (call-interactively #'ffap))
+ (_ (user-error "No special environment to edit here"))))))))
+
+(defvar org-table-coordinate-overlays) ; defined in org-table.el
+(defun org-ctrl-c-ctrl-c (&optional arg)
+ "Set tags in headline, or update according to changed information at point.
+
+This command does many different things, depending on context:
+
+- If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
+ this is what we do.
+
+- If the cursor is on a statistics cookie, update it.
+
+- If the cursor is in a headline, prompt for tags and insert them
+ into the current line, aligned to `org-tags-column'. When called
+ with prefix arg, realign all tags in the current buffer.
+
+- If the cursor is in one of the special #+KEYWORD lines, this
+ triggers scanning the buffer for these lines and updating the
+ information.
+
+- If the cursor is inside a table, realign the table. This command
+ works even if the automatic table editor has been turned off.
+
+- If the cursor is on a #+TBLFM line, re-apply the formulas to
+ the entire table.
+
+- If the cursor is at a footnote reference or definition, jump to
+ the corresponding definition or references, respectively.
+
+- If the cursor is a the beginning of a dynamic block, update it.
+
+- If the current buffer is a capture buffer, close note and file it.
+
+- If the cursor is on a <<<target>>>, update radio targets and
+ corresponding links in this buffer.
+
+- If the cursor is on a numbered item in a plain list, renumber the
+ ordered list.
+
+- If the cursor is on a checkbox, toggle it.
+
+- If the cursor is on a code block, evaluate it. The variable
+ `org-confirm-babel-evaluate' can be used to control prompting
+ before code block evaluation, by default every code block
+ evaluation requires confirmation. Code block evaluation can be
+ inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
+ (interactive "P")
+ (cond
+ ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
+ (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
+ (org-remove-occur-highlights)
+ (message "Temporary highlights/overlays removed from current buffer"))
+ ((and (local-variable-p 'org-finish-function)
+ (fboundp org-finish-function))
+ (funcall org-finish-function))
+ ((org-babel-hash-at-point))
+ ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
+ (t
+ (let* ((context
+ (org-element-lineage
+ (org-element-context)
+ ;; Limit to supported contexts.
+ '(babel-call clock dynamic-block footnote-definition
+ footnote-reference inline-babel-call inline-src-block
+ inlinetask item keyword node-property paragraph
+ plain-list property-drawer radio-target src-block
+ statistics-cookie table table-cell table-row
+ timestamp)
+ t))
+ (type (org-element-type context)))
+ ;; For convenience: at the first line of a paragraph on the same
+ ;; line as an item, apply function on that item instead.
+ (when (eq type 'paragraph)
+ (let ((parent (org-element-property :parent context)))
+ (when (and (eq (org-element-type parent) 'item)
+ (= (line-beginning-position)
+ (org-element-property :begin parent)))
+ (setq context parent)
+ (setq type 'item))))
+ ;; Act according to type of element or object at point.
+ ;;
+ ;; Do nothing on a blank line, except if it is contained in
+ ;; a src block. Hence, we first check if point is in such
+ ;; a block and then if it is at a blank line.
+ (pcase type
+ ((or `inline-src-block `src-block)
+ (unless org-babel-no-eval-on-ctrl-c-ctrl-c
+ (org-babel-eval-wipe-error-buffer)
+ (org-babel-execute-src-block
+ current-prefix-arg (org-babel-get-src-block-info nil context))))
+ ((guard (org-match-line "[ \t]*$"))
+ (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
+ (user-error
+ (substitute-command-keys
+ "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
+ ((or `babel-call `inline-babel-call)
+ (let ((info (org-babel-lob-get-info context)))
+ (when info (org-babel-execute-src-block nil info))))
+ (`clock (org-clock-update-time-maybe))
+ (`dynamic-block
+ (save-excursion
+ (goto-char (org-element-property :post-affiliated context))
+ (org-update-dblock)))
+ (`footnote-definition
+ (goto-char (org-element-property :post-affiliated context))
+ (call-interactively 'org-footnote-action))
+ (`footnote-reference (call-interactively #'org-footnote-action))
+ ((or `headline `inlinetask)
+ (save-excursion (goto-char (org-element-property :begin context))
+ (call-interactively #'org-set-tags)))
+ (`item
+ ;; At an item: `C-u C-u' sets checkbox to "[-]"
+ ;; unconditionally, whereas `C-u' will toggle its presence.
+ ;; Without a universal argument, if the item has a checkbox,
+ ;; toggle it. Otherwise repair the list.
+ (let* ((box (org-element-property :checkbox context))
+ (struct (org-element-property :structure context))
+ (old-struct (copy-tree struct))
+ (parents (org-list-parents-alist struct))
+ (prevs (org-list-prevs-alist struct))
+ (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
+ (org-list-set-checkbox
+ (org-element-property :begin context) struct
+ (cond ((equal arg '(16)) "[-]")
+ ((and (not box) (equal arg '(4))) "[ ]")
+ ((or (not box) (equal arg '(4))) nil)
+ ((eq box 'on) "[ ]")
+ (t "[X]")))
+ ;; Mimic `org-list-write-struct' but with grabbing a return
+ ;; value from `org-list-struct-fix-box'.
+ (org-list-struct-fix-ind struct parents 2)
+ (org-list-struct-fix-item-end struct)
+ (org-list-struct-fix-bul struct prevs)
+ (org-list-struct-fix-ind struct parents)
+ (let ((block-item
+ (org-list-struct-fix-box struct parents prevs orderedp)))
+ (if (and box (equal struct old-struct))
+ (if (equal arg '(16))
+ (message "Checkboxes already reset")
+ (user-error "Cannot toggle this checkbox: %s"
+ (if (eq box 'on)
+ "all subitems checked"
+ "unchecked subitems")))
+ (org-list-struct-apply-struct struct old-struct)
+ (org-update-checkbox-count-maybe))
+ (when block-item
+ (message "Checkboxes were removed due to empty box at line %d"
+ (org-current-line block-item))))))
+ (`keyword
+ (let ((org-inhibit-startup-visibility-stuff t)
+ (org-startup-align-all-tables nil))
+ (when (boundp 'org-table-coordinate-overlays)
+ (mapc #'delete-overlay org-table-coordinate-overlays)
+ (setq org-table-coordinate-overlays nil))
+ (org-save-outline-visibility 'use-markers (org-mode-restart)))
+ (message "Local setup has been refreshed"))
+ (`plain-list
+ ;; At a plain list, with a double C-u argument, set
+ ;; checkboxes of each item to "[-]", whereas a single one
+ ;; will toggle their presence according to the state of the
+ ;; first item in the list. Without an argument, repair the
+ ;; list.
+ (let* ((begin (org-element-property :contents-begin context))
+ (beginm (move-marker (make-marker) begin))
+ (struct (org-element-property :structure context))
+ (old-struct (copy-tree struct))
+ (first-box (save-excursion
+ (goto-char begin)
+ (looking-at org-list-full-item-re)
+ (match-string-no-properties 3)))
+ (new-box (cond ((equal arg '(16)) "[-]")
+ ((equal arg '(4)) (unless first-box "[ ]"))
+ ((equal first-box "[X]") "[ ]")
+ (t "[X]"))))
+ (cond
+ (arg
+ (dolist (pos
+ (org-list-get-all-items
+ begin struct (org-list-prevs-alist struct)))
+ (org-list-set-checkbox pos struct new-box)))
+ ((and first-box (eq (point) begin))
+ ;; For convenience, when point is at bol on the first
+ ;; item of the list and no argument is provided, simply
+ ;; toggle checkbox of that item, if any.
+ (org-list-set-checkbox begin struct new-box)))
+ (org-list-write-struct
+ struct (org-list-parents-alist struct) old-struct)
+ (org-update-checkbox-count-maybe)
+ (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
+ ((or `property-drawer `node-property)
+ (call-interactively #'org-property-action))
+ (`radio-target
+ (call-interactively #'org-update-radio-target-regexp))
+ (`statistics-cookie
+ (call-interactively #'org-update-statistics-cookies))
+ ((or `table `table-cell `table-row)
+ ;; At a table, recalculate every field and align it. Also
+ ;; send the table if necessary. If the table has
+ ;; a `table.el' type, just give up. At a table row or cell,
+ ;; maybe recalculate line but always align table.
+ (if (eq (org-element-property :type context) 'table.el)
+ (message "%s" (substitute-command-keys "\\<org-mode-map>\
+Use `\\[org-edit-special]' to edit table.el tables"))
+ (let ((org-enable-table-editor t))
+ (if (or (eq type 'table)
+ ;; Check if point is at a TBLFM line.
+ (and (eq type 'table-row)
+ (= (point) (org-element-property :end context))))
+ (save-excursion
+ (if (org-at-TBLFM-p)
+ (progn (require 'org-table)
+ (org-table-calc-current-TBLFM))
+ (goto-char (org-element-property :contents-begin context))
+ (org-call-with-arg 'org-table-recalculate (or arg t))
+ (orgtbl-send-table 'maybe)))
+ (org-table-maybe-eval-formula)
+ (cond (arg (call-interactively #'org-table-recalculate))
+ ((org-table-maybe-recalculate-line))
+ (t (org-table-align)))))))
+ (`timestamp (org-timestamp-change 0 'day))
+ ((and `nil (guard (org-at-heading-p)))
+ ;; When point is on an unsupported object type, we can miss
+ ;; the fact that it also is at a heading. Handle it here.
+ (call-interactively #'org-set-tags))
+ ((guard
+ (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
+ (_
+ (user-error
+ (substitute-command-keys
+ "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
+
+(defun org-mode-restart ()
+ (interactive)
+ (let ((indent-status (bound-and-true-p org-indent-mode)))
+ (funcall major-mode)
+ (hack-local-variables)
+ (when (and indent-status (not (bound-and-true-p org-indent-mode)))
+ (org-indent-mode -1)))
+ (message "%s restarted" major-mode))
+
+(defun org-kill-note-or-show-branches ()
+ "Abort storing current note, or call `outline-show-branches'."
+ (interactive)
+ (if (not org-finish-function)
+ (progn
+ (outline-hide-subtree)
+ (call-interactively 'outline-show-branches))
+ (let ((org-note-abort t))
+ (funcall org-finish-function))))
+
+(defun org-delete-indentation (&optional arg)
+ "Join current line to previous and fix whitespace at join.
+
+If previous line is a headline add to headline title. Otherwise
+the function calls `delete-indentation'.
+
+With a non-nil optional argument, join it to the following one."
+ (interactive "*P")
+ (if (save-excursion
+ (beginning-of-line (if arg 1 0))
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp)))
+ ;; At headline.
+ (let ((tags-column (when (match-beginning 5)
+ (save-excursion (goto-char (match-beginning 5))
+ (current-column))))
+ (string (concat " " (progn (when arg (forward-line 1))
+ (org-trim (delete-and-extract-region
+ (line-beginning-position)
+ (line-end-position)))))))
+ (unless (bobp) (delete-region (point) (1- (point))))
+ (goto-char (or (match-end 4)
+ (match-beginning 5)
+ (match-end 0)))
+ (skip-chars-backward " \t")
+ (save-excursion (insert string))
+ ;; Adjust alignment of tags.
+ (cond
+ ((not tags-column)) ;no tags
+ (org-auto-align-tags (org-set-tags nil t))
+ (t (org--align-tags-here tags-column)))) ;preserve tags column
+ (delete-indentation arg)))
+
+(defun org-open-line (n)
+ "Insert a new row in tables, call `open-line' elsewhere.
+If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
+As a special case, when a document starts with a table, allow to
+call `open-line' on the very first character."
+ (interactive "*p")
+ (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
+ (org-table-insert-row)
+ (open-line n)))
+
+(defun org-return (&optional indent)
+ "Goto next table row or insert a newline.
+
+Calls `org-table-next-row' or `newline', depending on context.
+
+When optional INDENT argument is non-nil, call
+`newline-and-indent' instead of `newline'.
+
+When `org-return-follows-link' is non-nil and point is on
+a timestamp or a link, call `org-open-at-point'. However, it
+will not happen if point is in a table or on a \"dead\"
+object (e.g., within a comment). In these case, you need to use
+`org-open-at-point' directly."
+ (interactive)
+ (let ((context (if org-return-follows-link (org-element-context)
+ (org-element-at-point))))
+ (cond
+ ;; In a table, call `org-table-next-row'.
+ ((or (and (eq (org-element-type context) 'table)
+ (>= (point) (org-element-property :contents-begin context))
+ (< (point) (org-element-property :contents-end context)))
+ (org-element-lineage context '(table-row table-cell) t))
+ (org-table-justify-field-maybe)
+ (call-interactively #'org-table-next-row))
+ ;; On a link or a timestamp, call `org-open-at-point' if
+ ;; `org-return-follows-link' allows it. Tolerate fuzzy
+ ;; locations, e.g., in a comment, as `org-open-at-point'.
+ ((and org-return-follows-link
+ (or (org-in-regexp org-ts-regexp-both nil t)
+ (org-in-regexp org-tsr-regexp-both nil t)
+ (org-in-regexp org-any-link-re nil t)))
+ (call-interactively #'org-open-at-point))
+ ;; Insert newline in heading, but preserve tags.
+ ((and (not (bolp))
+ (save-excursion (beginning-of-line)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))))
+ ;; At headline. Split line. However, if point is on keyword,
+ ;; priority cookie or tags, do not break any of them: add
+ ;; a newline after the headline instead.
+ (let ((tags-column (and (match-beginning 5)
+ (save-excursion (goto-char (match-beginning 5))
+ (current-column))))
+ (string
+ (when (and (match-end 4) (org-point-in-group (point) 4))
+ (delete-and-extract-region (point) (match-end 4)))))
+ ;; Adjust tag alignment.
+ (cond
+ ((not (and tags-column string)))
+ (org-auto-align-tags (org-set-tags nil t))
+ (t (org--align-tags-here tags-column))) ;preserve tags column
+ (end-of-line)
+ (org-show-entry)
+ (if indent (newline-and-indent) (newline))
+ (when string (save-excursion (insert (org-trim string))))))
+ ;; In a list, make sure indenting keeps trailing text within.
+ ((and indent
+ (not (eolp))
+ (org-element-lineage context '(item)))
+ (let ((trailing-data
+ (delete-and-extract-region (point) (line-end-position))))
+ (newline-and-indent)
+ (save-excursion (insert trailing-data))))
+ (t (if indent (newline-and-indent) (newline))))))
+
+(defun org-return-indent ()
+ "Goto next table row or insert a newline and indent.
+Calls `org-table-next-row' or `newline-and-indent', depending on
+context. See the individual commands for more information."
+ (interactive)
+ (org-return t))
+
+(defun org-ctrl-c-star ()
+ "Compute table, or change heading status of lines.
+Calls `org-table-recalculate' or `org-toggle-heading',
+depending on context."
+ (interactive)
+ (cond
+ ((org-at-table-p)
+ (call-interactively 'org-table-recalculate))
+ (t
+ ;; Convert all lines in region to list items
+ (call-interactively 'org-toggle-heading))))
+
+(defun org-ctrl-c-minus ()
+ "Insert separator line in table or modify bullet status of line.
+Also turns a plain line or a region of lines into list items.
+Calls `org-table-insert-hline', `org-toggle-item', or
+`org-cycle-list-bullet', depending on context."
+ (interactive)
+ (cond
+ ((org-at-table-p)
+ (call-interactively 'org-table-insert-hline))
+ ((org-region-active-p)
+ (call-interactively 'org-toggle-item))
+ ((org-in-item-p)
+ (call-interactively 'org-cycle-list-bullet))
+ (t
+ (call-interactively 'org-toggle-item))))
+
+(defun org-toggle-heading (&optional nstars)
+ "Convert headings to normal text, or items or text to headings.
+If there is no active region, only convert the current line.
+
+With a `\\[universal-argument]' prefix, convert the whole list at
+point into heading.
+
+In a region:
+
+- If the first non blank line is a headline, remove the stars
+ from all headlines in the region.
+
+- If it is a normal line, turn each and every normal line (i.e.,
+ not an heading or an item) in the region into headings. If you
+ want to convert only the first line of this region, use one
+ universal prefix argument.
+
+- If it is a plain list item, turn all plain list items into headings.
+
+When converting a line into a heading, the number of stars is chosen
+such that the lines become children of the current entry. However,
+when a numeric prefix argument is given, its value determines the
+number of stars to add."
+ (interactive "P")
+ (let ((skip-blanks
+ (function
+ ;; Return beginning of first non-blank line, starting from
+ ;; line at POS.
+ (lambda (pos)
+ (save-excursion
+ (goto-char pos)
+ (while (org-at-comment-p) (forward-line))
+ (skip-chars-forward " \r\t\n")
+ (point-at-bol)))))
+ beg end toggled)
+ ;; Determine boundaries of changes. If a universal prefix has
+ ;; been given, put the list in a region. If region ends at a bol,
+ ;; do not consider the last line to be in the region.
+
+ (when (and current-prefix-arg (org-at-item-p))
+ (when (listp current-prefix-arg) (setq current-prefix-arg 1))
+ (org-mark-element))
+
+ (if (org-region-active-p)
+ (setq beg (funcall skip-blanks (region-beginning))
+ end (copy-marker (save-excursion
+ (goto-char (region-end))
+ (if (bolp) (point) (point-at-eol)))))
+ (setq beg (funcall skip-blanks (point-at-bol))
+ end (copy-marker (point-at-eol))))
+ ;; Ensure inline tasks don't count as headings.
+ (org-with-limited-levels
+ (save-excursion
+ (goto-char beg)
+ (cond
+ ;; Case 1. Started at an heading: de-star headings.
+ ((org-at-heading-p)
+ (while (< (point) end)
+ (when (org-at-heading-p t)
+ (looking-at org-outline-regexp) (replace-match "")
+ (setq toggled t))
+ (forward-line)))
+ ;; Case 2. Started at an item: change items into headlines.
+ ;; One star will be added by `org-list-to-subtree'.
+ ((org-at-item-p)
+ (while (< (point) end)
+ (when (org-at-item-p)
+ ;; Pay attention to cases when region ends before list.
+ (let* ((struct (org-list-struct))
+ (list-end
+ (min (org-list-get-bottom-point struct) (1+ end))))
+ (save-restriction
+ (narrow-to-region (point) list-end)
+ (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
+ (setq toggled t))
+ (forward-line)))
+ ;; Case 3. Started at normal text: make every line an heading,
+ ;; skipping headlines and items.
+ (t (let* ((stars
+ (make-string
+ (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
+ (add-stars
+ (cond (nstars "") ; stars from prefix only
+ ((equal stars "") "*") ; before first heading
+ (org-odd-levels-only "**") ; inside heading, odd
+ (t "*"))) ; inside heading, oddeven
+ (rpl (concat stars add-stars " "))
+ (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
+ (while (< (point) (if (equal nstars '(4)) lend end))
+ (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
+ (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
+ (replace-match (concat rpl (match-string 2))) (setq toggled t))
+ (forward-line)))))))
+ (unless toggled (message "Cannot toggle heading from here"))))
+
+(defun org-meta-return (&optional _arg)
+ "Insert a new heading or wrap a region in a table.
+Calls `org-insert-heading' or `org-table-wrap-region', depending
+on context. See the individual commands for more information."
+ (interactive)
+ (org-check-before-invisible-edit 'insert)
+ (or (run-hook-with-args-until-success 'org-metareturn-hook)
+ (call-interactively (if (org-at-table-p) #'org-table-wrap-region
+ #'org-insert-heading))))
+
+;;; Menu entries
+
+(defsubst org-in-subtree-not-table-p ()
+ "Are we in a subtree and not in a table?"
+ (and (not (org-before-first-heading-p))
+ (not (org-at-table-p))))
+
+;; Define the Org mode menus
+(easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
+ '("Tbl"
+ ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
+ ["Next Field" org-cycle (org-at-table-p)]
+ ["Previous Field" org-shifttab (org-at-table-p)]
+ ["Next Row" org-return (org-at-table-p)]
+ "--"
+ ["Blank Field" org-table-blank-field (org-at-table-p)]
+ ["Edit Field" org-table-edit-field (org-at-table-p)]
+ ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
+ "--"
+ ("Column"
+ ["Move Column Left" org-metaleft (org-at-table-p)]
+ ["Move Column Right" org-metaright (org-at-table-p)]
+ ["Delete Column" org-shiftmetaleft (org-at-table-p)]
+ ["Insert Column" org-shiftmetaright (org-at-table-p)])
+ ("Row"
+ ["Move Row Up" org-metaup (org-at-table-p)]
+ ["Move Row Down" org-metadown (org-at-table-p)]
+ ["Delete Row" org-shiftmetaup (org-at-table-p)]
+ ["Insert Row" org-shiftmetadown (org-at-table-p)]
+ ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
+ "--"
+ ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
+ ("Rectangle"
+ ["Copy Rectangle" org-copy-special (org-at-table-p)]
+ ["Cut Rectangle" org-cut-special (org-at-table-p)]
+ ["Paste Rectangle" org-paste-special (org-at-table-p)]
+ ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
+ "--"
+ ("Calculate"
+ ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
+ ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
+ ["Edit Formulas" org-edit-special (org-at-table-p)]
+ "--"
+ ["Recalculate line" org-table-recalculate (org-at-table-p)]
+ ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
+ ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
+ "--"
+ ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
+ "--"
+ ["Sum Column/Rectangle" org-table-sum
+ (or (org-at-table-p) (org-region-active-p))]
+ ["Which Column?" org-table-current-column (org-at-table-p)])
+ ["Debug Formulas"
+ org-table-toggle-formula-debugger
+ :style toggle :selected (bound-and-true-p org-table-formula-debug)]
+ ["Show Col/Row Numbers"
+ org-table-toggle-coordinate-overlays
+ :style toggle
+ :selected (bound-and-true-p org-table-overlay-coordinates)]
+ "--"
+ ["Create" org-table-create (and (not (org-at-table-p))
+ org-enable-table-editor)]
+ ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
+ ["Import from File" org-table-import (not (org-at-table-p))]
+ ["Export to File" org-table-export (org-at-table-p)]
+ "--"
+ ["Create/Convert from/to table.el" org-table-create-with-table.el t]
+ "--"
+ ("Plot"
+ ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
+ ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
+
+(easy-menu-define org-org-menu org-mode-map "Org menu"
+ '("Org"
+ ("Show/Hide"
+ ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
+ ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
+ ["Sparse Tree..." org-sparse-tree t]
+ ["Reveal Context" org-reveal t]
+ ["Show All" outline-show-all t]
+ "--"
+ ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
+ "--"
+ ["New Heading" org-insert-heading t]
+ ("Navigate Headings"
+ ["Up" outline-up-heading t]
+ ["Next" outline-next-visible-heading t]
+ ["Previous" outline-previous-visible-heading t]
+ ["Next Same Level" outline-forward-same-level t]
+ ["Previous Same Level" outline-backward-same-level t]
+ "--"
+ ["Jump" org-goto t])
+ ("Edit Structure"
+ ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
+ "--"
+ ["Move Subtree Up" org-metaup (org-at-heading-p)]
+ ["Move Subtree Down" org-metadown (org-at-heading-p)]
+ "--"
+ ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
+ ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
+ ["Paste Subtree" org-paste-special (not (org-at-table-p))]
+ "--"
+ ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
+ "--"
+ ["Copy visible text" org-copy-visible t]
+ "--"
+ ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
+ ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
+ ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
+ ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
+ "--"
+ ["Sort Region/Children" org-sort t]
+ "--"
+ ["Convert to odd levels" org-convert-to-odd-levels t]
+ ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
+ ("Editing"
+ ["Emphasis..." org-emphasize t]
+ ["Edit Source Example" org-edit-special t]
+ "--"
+ ["Footnote new/jump" org-footnote-action t]
+ ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
+ ("Archive"
+ ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
+ "--"
+ ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
+ ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
+ ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
+ )
+ "--"
+ ("Hyperlinks"
+ ["Store Link (Global)" org-store-link t]
+ ["Find existing link to here" org-occur-link-in-agenda-files t]
+ ["Insert Link" org-insert-link t]
+ ["Follow Link" org-open-at-point t]
+ "--"
+ ["Next link" org-next-link t]
+ ["Previous link" org-previous-link t]
+ "--"
+ ["Descriptive Links"
+ org-toggle-link-display
+ :style radio
+ :selected org-descriptive-links
+ ]
+ ["Literal Links"
+ org-toggle-link-display
+ :style radio
+ :selected (not org-descriptive-links)])
+ "--"
+ ("TODO Lists"
+ ["TODO/DONE/-" org-todo t]
+ ("Select keyword"
+ ["Next keyword" org-shiftright (org-at-heading-p)]
+ ["Previous keyword" org-shiftleft (org-at-heading-p)]
+ ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
+ ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
+ ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
+ ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
+ ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
+ "--"
+ ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
+ :selected org-enforce-todo-dependencies :style toggle :active t]
+ "Settings for tree at point"
+ ["Do Children sequentially" org-toggle-ordered-property :style radio
+ :selected (org-entry-get nil "ORDERED")
+ :active org-enforce-todo-dependencies :keys "C-c C-x o"]
+ ["Do Children parallel" org-toggle-ordered-property :style radio
+ :selected (not (org-entry-get nil "ORDERED"))
+ :active org-enforce-todo-dependencies :keys "C-c C-x o"]
+ "--"
+ ["Set Priority" org-priority t]
+ ["Priority Up" org-shiftup t]
+ ["Priority Down" org-shiftdown t]
+ "--"
+ ["Get news from all feeds" org-feed-update-all t]
+ ["Go to the inbox of a feed..." org-feed-goto-inbox t]
+ ["Customize feeds" (customize-variable 'org-feed-alist) t])
+ ("TAGS and Properties"
+ ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
+ ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
+ "--"
+ ["Set property" org-set-property (not (org-before-first-heading-p))]
+ ["Column view of properties" org-columns t]
+ ["Insert Column View DBlock" org-columns-insert-dblock t])
+ ("Dates and Scheduling"
+ ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
+ ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
+ ("Change Date"
+ ["1 Day Later" org-shiftright (org-at-timestamp-p)]
+ ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
+ ["1 ... Later" org-shiftup (org-at-timestamp-p)]
+ ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
+ ["Compute Time Range" org-evaluate-time-range t]
+ ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
+ ["Deadline" org-deadline (not (org-before-first-heading-p))]
+ "--"
+ ["Custom time format" org-toggle-time-stamp-overlays
+ :style radio :selected org-display-custom-times]
+ "--"
+ ["Goto Calendar" org-goto-calendar t]
+ ["Date from Calendar" org-date-from-calendar t]
+ "--"
+ ["Start/Restart Timer" org-timer-start t]
+ ["Pause/Continue Timer" org-timer-pause-or-continue t]
+ ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
+ ["Insert Timer String" org-timer t]
+ ["Insert Timer Item" org-timer-item t])
+ ("Logging work"
+ ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
+ ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
+ ["Clock out" org-clock-out t]
+ ["Clock cancel" org-clock-cancel t]
+ "--"
+ ["Mark as default task" org-clock-mark-default-task t]
+ ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
+ ["Goto running clock" org-clock-goto t]
+ "--"
+ ["Display times" org-clock-display t]
+ ["Create clock table" org-clock-report t]
+ "--"
+ ["Record DONE time"
+ (progn (setq org-log-done (not org-log-done))
+ (message "Switching to %s will %s record a timestamp"
+ (car org-done-keywords)
+ (if org-log-done "automatically" "not")))
+ :style toggle :selected org-log-done])
+ "--"
+ ["Agenda Command..." org-agenda t]
+ ["Set Restriction Lock" org-agenda-set-restriction-lock t]
+ ("File List for Agenda")
+ ("Special views current file"
+ ["TODO Tree" org-show-todo-tree t]
+ ["Check Deadlines" org-check-deadlines t]
+ ["Timeline" org-timeline t]
+ ["Tags/Property tree" org-match-sparse-tree t])
+ "--"
+ ["Export/Publish..." org-export-dispatch t]
+ ("LaTeX"
+ ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
+ :selected org-cdlatex-mode]
+ ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
+ ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
+ ["Modify math symbol" org-cdlatex-math-modify
+ (org-inside-LaTeX-fragment-p)]
+ ["Insert citation" org-reftex-citation t])
+ "--"
+ ("MobileOrg"
+ ["Push Files and Views" org-mobile-push t]
+ ["Get Captured and Flagged" org-mobile-pull t]
+ ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
+ "--"
+ ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
+ "--"
+ ("Documentation"
+ ["Show Version" org-version t]
+ ["Info Documentation" org-info t])
+ ("Customize"
+ ["Browse Org Group" org-customize t]
+ "--"
+ ["Expand This Menu" org-create-customize-menu
+ (fboundp 'customize-menu-create)])
+ ["Send bug report" org-submit-bug-report t]
+ "--"
+ ("Refresh/Reload"
+ ["Refresh setup current buffer" org-mode-restart t]
+ ["Reload Org (after update)" org-reload t]
+ ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
+ ))
+
+(defun org-info (&optional node)
+ "Read documentation for Org in the info system.
+With optional NODE, go directly to that node."
+ (interactive)
+ (info (format "(org)%s" (or node ""))))
+
+;;;###autoload
+(defun org-submit-bug-report ()
+ "Submit a bug report on Org via mail.
+
+Don't hesitate to report any problems or inaccurate documentation.
+
+If you don't have setup sending mail from (X)Emacs, please copy the
+output buffer into your mail program, as it gives us important
+information about your Org version and configuration."
+ (interactive)
+ (require 'reporter)
+ (defvar reporter-prompt-for-summary-p)
+ (org-load-modules-maybe)
+ (org-require-autoloaded-modules)
+ (let ((reporter-prompt-for-summary-p "Bug report subject: "))
+ (reporter-submit-bug-report
+ "emacs-orgmode@gnu.org"
+ (org-version nil 'full)
+ (let (list)
+ (save-window-excursion
+ (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
+ (delete-other-windows)
+ (erase-buffer)
+ (insert "You are about to submit a bug report to the Org mailing list.
+
+We would like to add your full Org and Outline configuration to the
+bug report. This greatly simplifies the work of the maintainer and
+other experts on the mailing list.
+
+HOWEVER, some variables you have customized may contain private
+information. The names of customers, colleagues, or friends, might
+appear in the form of file names, tags, todo states, or search strings.
+If you answer yes to the prompt, you might want to check and remove
+such private information before sending the email.")
+ (add-text-properties (point-min) (point-max) '(face org-warning))
+ (when (yes-or-no-p "Include your Org configuration ")
+ (mapatoms
+ (lambda (v)
+ (and (boundp v)
+ (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
+ (or (and (symbol-value v)
+ (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
+ (and
+ (get v 'custom-type) (get v 'standard-value)
+ (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
+ (push v list)))))
+ (kill-buffer (get-buffer "*Warn about privacy*"))
+ list))
+ nil nil
+ "Remember to cover the basics, that is, what you expected to happen and
+what in fact did happen. You don't know how to make a good report? See
+
+ http://orgmode.org/manual/Feedback.html#Feedback
+
+Your bug report will be posted to the Org mailing list.
+------------------------------------------------------------------------")
+ (save-excursion
+ (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
+ (replace-match "\\1Bug: \\3 [\\2]")))))
+
+
+(defun org-install-agenda-files-menu ()
+ (let ((bl (buffer-list)))
+ (save-excursion
+ (while bl
+ (set-buffer (pop bl))
+ (when (derived-mode-p 'org-mode) (setq bl nil)))
+ (when (derived-mode-p 'org-mode)
+ (easy-menu-change
+ '("Org") "File List for Agenda"
+ (append
+ (list
+ ["Edit File List" (org-edit-agenda-file-list) t]
+ ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
+ ["Remove Current File from List" org-remove-file t]
+ ["Cycle through agenda files" org-cycle-agenda-files t]
+ ["Occur in all agenda files" org-occur-in-agenda-files t]
+ "--")
+ (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
+
+;;;; Documentation
+
+(defun org-require-autoloaded-modules ()
+ (interactive)
+ (mapc #'require
+ '(org-agenda org-archive org-attach org-clock org-colview org-id
+ org-table org-timer)))
+
+;;;###autoload
+(defun org-reload (&optional uncompiled)
+ "Reload all org lisp files.
+With prefix arg UNCOMPILED, load the uncompiled versions."
+ (interactive "P")
+ (require 'loadhist)
+ (let* ((org-dir (org-find-library-dir "org"))
+ (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
+ (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
+ (remove-re (format "\\`%s\\'"
+ (regexp-opt '("org" "org-loaddefs" "org-version"))))
+ (feats (delete-dups
+ (mapcar 'file-name-sans-extension
+ (mapcar 'file-name-nondirectory
+ (delq nil
+ (mapcar 'feature-file
+ features))))))
+ (lfeat (append
+ (sort
+ (setq feats
+ (delq nil (mapcar
+ (lambda (f)
+ (if (and (string-match feature-re f)
+ (not (string-match remove-re f)))
+ f nil))
+ feats)))
+ 'string-lessp)
+ (list "org-version" "org")))
+ (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
+ (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
+ load-uncore load-misses)
+ (setq load-misses
+ (delq 't
+ (mapcar (lambda (f)
+ (or (org-load-noerror-mustsuffix (concat org-dir f))
+ (and (string= org-dir contrib-dir)
+ (org-load-noerror-mustsuffix (concat contrib-dir f)))
+ (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
+ (add-to-list 'load-uncore f 'append)
+ 't)
+ f))
+ lfeat)))
+ (when load-uncore
+ (message "The following feature%s found in load-path, please check if that's correct:\n%s"
+ (if (> (length load-uncore) 1) "s were" " was") load-uncore))
+ (if load-misses
+ (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
+ (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
+ (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
+
+;;;###autoload
+(defun org-customize ()
+ "Call the customize function with org as argument."
+ (interactive)
+ (org-load-modules-maybe)
+ (org-require-autoloaded-modules)
+ (customize-browse 'org))
+
+(defun org-create-customize-menu ()
+ "Create a full customization menu for Org mode, insert it into the menu."
+ (interactive)
+ (org-load-modules-maybe)
+ (org-require-autoloaded-modules)
+ (if (fboundp 'customize-menu-create)
+ (progn
+ (easy-menu-change
+ '("Org") "Customize"
+ `(["Browse Org group" org-customize t]
+ "--"
+ ,(customize-menu-create 'org)
+ ["Set" Custom-set t]
+ ["Save" Custom-save t]
+ ["Reset to Current" Custom-reset-current t]
+ ["Reset to Saved" Custom-reset-saved t]
+ ["Reset to Standard Settings" Custom-reset-standard t]))
+ (message "\"Org\"-menu now contains full customization menu"))
+ (error "Cannot expand menu (outdated version of cus-edit.el)")))
+
+;;;; Miscellaneous stuff
+
+;;; Generally useful functions
+
+(defun org-get-at-eol (property n)
+ "Get text property PROPERTY at the end of line less N characters."
+ (get-text-property (- (point-at-eol) n) property))
+
+(defun org-find-text-property-in-string (prop s)
+ "Return the first non-nil value of property PROP in string S."
+ (or (get-text-property 0 prop s)
+ (get-text-property (or (next-single-property-change 0 prop s) 0)
+ prop s)))
+
+(defun org-display-warning (message)
+ "Display the given MESSAGE as a warning."
+ (display-warning 'org message :warning))
+
+(defun org-eval (form)
+ "Eval FORM and return result."
+ (condition-case error
+ (eval form)
+ (error (format "%%![Error: %s]" error))))
+
+(defun org-in-clocktable-p ()
+ "Check if the cursor is in a clocktable."
+ (let ((pos (point)) start)
+ (save-excursion
+ (end-of-line 1)
+ (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
+ (setq start (match-beginning 0))
+ (re-search-forward "^[ \t]*#\\+END:.*" nil t)
+ (>= (match-end 0) pos)
+ start))))
+
+(defun org-in-verbatim-emphasis ()
+ (save-match-data
+ (and (org-in-regexp org-emph-re 2)
+ (>= (point) (match-beginning 3))
+ (<= (point) (match-end 4))
+ (member (match-string 3) '("=" "~")))))
+
+(defun org-overlay-display (ovl text &optional face evap)
+ "Make overlay OVL display TEXT with face FACE."
+ (overlay-put ovl 'display text)
+ (if face (overlay-put ovl 'face face))
+ (if evap (overlay-put ovl 'evaporate t)))
+
+(defun org-overlay-before-string (ovl text &optional face evap)
+ "Make overlay OVL display TEXT with face FACE."
+ (if face (org-add-props text nil 'face face))
+ (overlay-put ovl 'before-string text)
+ (if evap (overlay-put ovl 'evaporate t)))
+
+(defun org-find-overlays (prop &optional pos delete)
+ "Find all overlays specifying PROP at POS or point.
+If DELETE is non-nil, delete all those overlays."
+ (let (found)
+ (dolist (ov (overlays-at (or pos (point))) found)
+ (cond ((not (overlay-get ov prop)))
+ (delete (delete-overlay ov))
+ (t (push ov found))))))
+
+(defun org-goto-marker-or-bmk (marker &optional bookmark)
+ "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
+ (if (and marker (marker-buffer marker)
+ (buffer-live-p (marker-buffer marker)))
+ (progn
+ (pop-to-buffer-same-window (marker-buffer marker))
+ (when (or (> marker (point-max)) (< marker (point-min)))
+ (widen))
+ (goto-char marker)
+ (org-show-context 'org-goto))
+ (if bookmark
+ (bookmark-jump bookmark)
+ (error "Cannot find location"))))
+
+(defun org-quote-csv-field (s)
+ "Quote field for inclusion in CSV material."
+ (if (string-match "[\",]" s)
+ (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
+ s))
+
+(defun org-force-self-insert (N)
+ "Needed to enforce self-insert under remapping."
+ (interactive "p")
+ (self-insert-command N))
+
+(defun org-string-width (s)
+ "Compute width of string, ignoring invisible characters.
+This ignores character with invisibility property `org-link', and also
+characters with property `org-cwidth', because these will become invisible
+upon the next fontification round."
+ (let (b l)
+ (when (or (eq t buffer-invisibility-spec)
+ (assq 'org-link buffer-invisibility-spec))
+ (while (setq b (text-property-any 0 (length s)
+ 'invisible 'org-link s))
+ (setq s (concat (substring s 0 b)
+ (substring s (or (next-single-property-change
+ b 'invisible s)
+ (length s)))))))
+ (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
+ (setq s (concat (substring s 0 b)
+ (substring s (or (next-single-property-change
+ b 'org-cwidth s)
+ (length s))))))
+ (setq l (string-width s) b -1)
+ (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
+ (setq l (- l (get-text-property b 'org-dwidth-n s))))
+ l))
+
+(defun org-shorten-string (s maxlength)
+ "Shorten string S so that it is no longer than MAXLENGTH characters.
+If the string is shorter or has length MAXLENGTH, just return the
+original string. If it is longer, the functions finds a space in the
+string, breaks this string off at that locations and adds three dots
+as ellipsis. Including the ellipsis, the string will not be longer
+than MAXLENGTH. If finding a good breaking point in the string does
+not work, the string is just chopped off in the middle of a word
+if necessary."
+ (if (<= (length s) maxlength)
+ s
+ (let* ((n (max (- maxlength 4) 1))
+ (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
+ (if (string-match re s)
+ (concat (match-string 1 s) "...")
+ (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
+
+(defun org-get-indentation (&optional line)
+ "Get the indentation of the current line, interpreting tabs.
+When LINE is given, assume it represents a line and compute its indentation."
+ (if line
+ (when (string-match "^ *" (org-remove-tabs line))
+ (match-end 0))
+ (save-excursion
+ (beginning-of-line 1)
+ (skip-chars-forward " \t")
+ (current-column))))
+
+(defun org-get-string-indentation (s)
+ "What indentation has S due to SPACE and TAB at the beginning of the string?"
+ (let ((n -1) (i 0) (w tab-width) c)
+ (catch 'exit
+ (while (< (setq n (1+ n)) (length s))
+ (setq c (aref s n))
+ (cond ((= c ?\ ) (setq i (1+ i)))
+ ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
+ (t (throw 'exit t)))))
+ i))
+
+(defun org-remove-tabs (s &optional width)
+ "Replace tabulators in S with spaces.
+Assumes that s is a single line, starting in column 0."
+ (setq width (or width tab-width))
+ (while (string-match "\t" s)
+ (setq s (replace-match
+ (make-string
+ (- (* width (/ (+ (match-beginning 0) width) width))
+ (match-beginning 0)) ?\ )
+ t t s)))
+ s)
+
+(defun org-fix-indentation (line ind)
+ "Fix indentation in LINE.
+IND is a cons cell with target and minimum indentation.
+If the current indentation in LINE is smaller than the minimum,
+leave it alone. If it is larger than ind, set it to the target."
+ (let* ((l (org-remove-tabs line))
+ (i (org-get-indentation l))
+ (i1 (car ind)) (i2 (cdr ind)))
+ (when (>= i i2) (setq l (substring line i2)))
+ (if (> i1 0)
+ (concat (make-string i1 ?\ ) l)
+ l)))
+
+(defun org-remove-indentation (code &optional n)
+ "Remove maximum common indentation in string CODE and return it.
+N may optionally be the number of columns to remove. Return CODE
+as-is if removal failed."
+ (with-temp-buffer
+ (insert code)
+ (if (org-do-remove-indentation n) (buffer-string) code)))
+
+(defun org-do-remove-indentation (&optional n)
+ "Remove the maximum common indentation from the buffer.
+When optional argument N is a positive integer, remove exactly
+that much characters from indentation, if possible. Return nil
+if it fails."
+ (catch :exit
+ (goto-char (point-min))
+ ;; Find maximum common indentation, if not specified.
+ (let ((n (or n
+ (let ((min-ind (point-max)))
+ (save-excursion
+ (while (re-search-forward "^[ \t]*\\S-" nil t)
+ (let ((ind (1- (current-column))))
+ (if (zerop ind) (throw :exit nil)
+ (setq min-ind (min min-ind ind))))))
+ min-ind))))
+ (if (zerop n) (throw :exit nil)
+ ;; Remove exactly N indentation, but give up if not possible.
+ (while (not (eobp))
+ (let ((ind (progn (skip-chars-forward " \t") (current-column))))
+ (cond ((eolp) (delete-region (line-beginning-position) (point)))
+ ((< ind n) (throw :exit nil))
+ (t (indent-line-to (- ind n))))
+ (forward-line)))
+ ;; Signal success.
+ t))))
+
+(defun org-fill-template (template alist)
+ "Find each %key of ALIST in TEMPLATE and replace it."
+ (let ((case-fold-search nil))
+ (dolist (entry (sort (copy-sequence alist)
+ (lambda (a b) (< (length (car a)) (length (car b))))))
+ (setq template
+ (replace-regexp-in-string
+ (concat "%" (regexp-quote (car entry)))
+ (or (cdr entry) "") template t t)))
+ template))
+
+(defun org-base-buffer (buffer)
+ "Return the base buffer of BUFFER, if it has one. Else return the buffer."
+ (if (not buffer)
+ buffer
+ (or (buffer-base-buffer buffer)
+ buffer)))
+
+(defun org-wrap (string &optional width lines)
+ "Wrap string to either a number of lines, or a width in characters.
+If WIDTH is non-nil, the string is wrapped to that width, however many lines
+that costs. If there is a word longer than WIDTH, the text is actually
+wrapped to the length of that word.
+IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
+many lines, whatever width that takes.
+The return value is a list of lines, without newlines at the end."
+ (let* ((words (org-split-string string "[ \t\n]+"))
+ (maxword (apply 'max (mapcar 'org-string-width words)))
+ w ll)
+ (cond (width
+ (org-do-wrap words (max maxword width)))
+ (lines
+ (setq w maxword)
+ (setq ll (org-do-wrap words maxword))
+ (if (<= (length ll) lines)
+ ll
+ (setq ll words)
+ (while (> (length ll) lines)
+ (setq w (1+ w))
+ (setq ll (org-do-wrap words w)))
+ ll))
+ (t (error "Cannot wrap this")))))
+
+(defun org-do-wrap (words width)
+ "Create lines of maximum width WIDTH (in characters) from word list WORDS."
+ (let (lines line)
+ (while words
+ (setq line (pop words))
+ (while (and words (< (+ (length line) (length (car words))) width))
+ (setq line (concat line " " (pop words))))
+ (setq lines (push line lines)))
+ (nreverse lines)))
+
+(defun org-split-string (string &optional separators)
+ "Splits STRING into substrings at SEPARATORS.
+SEPARATORS is a regular expression.
+No empty strings are returned if there are matches at the beginning
+and end of string."
+ ;; FIXME: why not use (split-string STRING SEPARATORS t)?
+ (let ((start 0) notfirst list)
+ (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
+ (if (and notfirst
+ (= start (match-beginning 0))
+ (< start (length string)))
+ (1+ start) start))
+ (< (match-beginning 0) (length string)))
+ (setq notfirst t)
+ (or (eq (match-beginning 0) 0)
+ (and (eq (match-beginning 0) (match-end 0))
+ (eq (match-beginning 0) start))
+ (push (substring string start (match-beginning 0)) list))
+ (setq start (match-end 0)))
+ (or (eq start (length string))
+ (push (substring string start) list))
+ (nreverse list)))
+
+(defun org-quote-vert (s)
+ "Replace \"|\" with \"\\vert\"."
+ (while (string-match "|" s)
+ (setq s (replace-match "\\vert" t t s)))
+ s)
+
+(defun org-uuidgen-p (s)
+ "Is S an ID created by UUIDGEN?"
+ (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
+
+(defun org-in-src-block-p (&optional inside)
+ "Whether point is in a code source block.
+When INSIDE is non-nil, don't consider we are within a src block
+when point is at #+BEGIN_SRC or #+END_SRC."
+ (let ((case-fold-search t))
+ (or (and (eq (get-char-property (point) 'src-block) t))
+ (and (not inside)
+ (save-match-data
+ (save-excursion
+ (beginning-of-line)
+ (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
+
+(defun org-context ()
+ "Return a list of contexts of the current cursor position.
+If several contexts apply, all are returned.
+Each context entry is a list with a symbol naming the context, and
+two positions indicating start and end of the context. Possible
+contexts are:
+
+:headline anywhere in a headline
+:headline-stars on the leading stars in a headline
+:todo-keyword on a TODO keyword (including DONE) in a headline
+:tags on the TAGS in a headline
+:priority on the priority cookie in a headline
+:item on the first line of a plain list item
+:item-bullet on the bullet/number of a plain list item
+:checkbox on the checkbox in a plain list item
+:table in an Org table
+:table-special on a special filed in a table
+:table-table in a table.el table
+:clocktable in a clocktable
+:src-block in a source block
+:link on a hyperlink
+:keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
+:target on a <<target>>
+:radio-target on a <<<radio-target>>>
+:latex-fragment on a LaTeX fragment
+:latex-preview on a LaTeX fragment with overlaid preview image
+
+This function expects the position to be visible because it uses font-lock
+faces as a help to recognize the following contexts: :table-special, :link,
+and :keyword."
+ (let* ((f (get-text-property (point) 'face))
+ (faces (if (listp f) f (list f)))
+ (case-fold-search t)
+ (p (point)) clist o)
+ ;; First the large context
+ (cond
+ ((org-at-heading-p t)
+ (push (list :headline (point-at-bol) (point-at-eol)) clist)
+ (when (progn
+ (beginning-of-line 1)
+ (looking-at org-todo-line-tags-regexp))
+ (push (org-point-in-group p 1 :headline-stars) clist)
+ (push (org-point-in-group p 2 :todo-keyword) clist)
+ (push (org-point-in-group p 4 :tags) clist))
+ (goto-char p)
+ (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
+ (when (looking-at "\\[#[A-Z0-9]\\]")
+ (push (org-point-in-group p 0 :priority) clist)))
+
+ ((org-at-item-p)
+ (push (org-point-in-group p 2 :item-bullet) clist)
+ (push (list :item (point-at-bol)
+ (save-excursion (org-end-of-item) (point)))
+ clist)
+ (and (org-at-item-checkbox-p)
+ (push (org-point-in-group p 0 :checkbox) clist)))
+
+ ((org-at-table-p)
+ (push (list :table (org-table-begin) (org-table-end)) clist)
+ (when (memq 'org-formula faces)
+ (push (list :table-special
+ (previous-single-property-change p 'face)
+ (next-single-property-change p 'face)) clist)))
+ ((org-at-table-p 'any)
+ (push (list :table-table) clist)))
+ (goto-char p)
+
+ (let ((case-fold-search t))
+ ;; New the "medium" contexts: clocktables, source blocks
+ (cond ((org-in-clocktable-p)
+ (push (list :clocktable
+ (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
+ (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
+ (match-beginning 1))
+ (and (re-search-forward "[ \t]*#\\+END:?" nil t)
+ (match-end 0))) clist))
+ ((org-in-src-block-p)
+ (push (list :src-block
+ (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
+ (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
+ (match-beginning 1))
+ (and (search-forward "#+END_SRC" nil t)
+ (match-beginning 0))) clist))))
+ (goto-char p)
+
+ ;; Now the small context
+ (cond
+ ((org-at-timestamp-p)
+ (push (org-point-in-group p 0 :timestamp) clist))
+ ((memq 'org-link faces)
+ (push (list :link
+ (previous-single-property-change p 'face)
+ (next-single-property-change p 'face)) clist))
+ ((memq 'org-special-keyword faces)
+ (push (list :keyword
+ (previous-single-property-change p 'face)
+ (next-single-property-change p 'face)) clist))
+ ((org-at-target-p)
+ (push (org-point-in-group p 0 :target) clist)
+ (goto-char (1- (match-beginning 0)))
+ (when (looking-at org-radio-target-regexp)
+ (push (org-point-in-group p 0 :radio-target) clist))
+ (goto-char p))
+ ((setq o (cl-some
+ (lambda (o)
+ (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
+ o))
+ (overlays-at (point))))
+ (push (list :latex-fragment
+ (overlay-start o) (overlay-end o)) clist)
+ (push (list :latex-preview
+ (overlay-start o) (overlay-end o)) clist))
+ ((org-inside-LaTeX-fragment-p)
+ ;; FIXME: positions wrong.
+ (push (list :latex-fragment (point) (point)) clist)))
+
+ (setq clist (nreverse (delq nil clist)))
+ clist))
+
+(defun org-in-regexp (regexp &optional nlines visually)
+ "Check if point is inside a match of REGEXP.
+
+Normally only the current line is checked, but you can include
+NLINES extra lines around point into the search. If VISUALLY is
+set, require that the cursor is not after the match but really
+on, so that the block visually is on the match.
+
+Return nil or a cons cell (BEG . END) where BEG and END are,
+respectively, the positions at the beginning and the end of the
+match."
+ (catch :exit
+ (let ((pos (point))
+ (eol (line-end-position (if nlines (1+ nlines) 1))))
+ (save-excursion
+ (beginning-of-line (- 1 (or nlines 0)))
+ (while (and (re-search-forward regexp eol t)
+ (<= (match-beginning 0) pos))
+ (let ((end (match-end 0)))
+ (when (or (> end pos) (and (= end pos) (not visually)))
+ (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
+
+(defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
+ "Non-nil when point is between matches of START-RE and END-RE.
+
+Also return a non-nil value when point is on one of the matches.
+
+Optional arguments LIM-UP and LIM-DOWN bound the search; they are
+buffer positions. Default values are the positions of headlines
+surrounding the point.
+
+The functions returns a cons cell whose car (resp. cdr) is the
+position before START-RE (resp. after END-RE)."
+ (save-match-data
+ (let ((pos (point))
+ (limit-up (or lim-up (save-excursion (outline-previous-heading))))
+ (limit-down (or lim-down (save-excursion (outline-next-heading))))
+ beg end)
+ (save-excursion
+ ;; Point is on a block when on START-RE or if START-RE can be
+ ;; found before it...
+ (and (or (org-in-regexp start-re)
+ (re-search-backward start-re limit-up t))
+ (setq beg (match-beginning 0))
+ ;; ... and END-RE after it...
+ (goto-char (match-end 0))
+ (re-search-forward end-re limit-down t)
+ (> (setq end (match-end 0)) pos)
+ ;; ... without another START-RE in-between.
+ (goto-char (match-beginning 0))
+ (not (re-search-backward start-re (1+ beg) t))
+ ;; Return value.
+ (cons beg end))))))
+
+(defun org-in-block-p (names)
+ "Non-nil when point belongs to a block whose name belongs to NAMES.
+
+NAMES is a list of strings containing names of blocks.
+
+Return first block name matched, or nil. Beware that in case of
+nested blocks, the returned name may not belong to the closest
+block from point."
+ (save-match-data
+ (catch 'exit
+ (let ((case-fold-search t)
+ (lim-up (save-excursion (outline-previous-heading)))
+ (lim-down (save-excursion (outline-next-heading))))
+ (dolist (name names)
+ (let ((n (regexp-quote name)))
+ (when (org-between-regexps-p
+ (concat "^[ \t]*#\\+begin_" n)
+ (concat "^[ \t]*#\\+end_" n)
+ lim-up lim-down)
+ (throw 'exit n)))))
+ nil)))
+
+(defun org-occur-in-agenda-files (regexp &optional _nlines)
+ "Call `multi-occur' with buffers for all agenda files."
+ (interactive "sOrg-files matching: ")
+ (let* ((files (org-agenda-files))
+ (tnames (mapcar #'file-truename files))
+ (extra org-agenda-text-search-extra-files))
+ (when (eq (car extra) 'agenda-archives)
+ (setq extra (cdr extra))
+ (setq files (org-add-archive-files files)))
+ (dolist (f extra)
+ (unless (member (file-truename f) tnames)
+ (unless (member f files) (setq files (append files (list f))))
+ (setq tnames (append tnames (list (file-truename f))))))
+ (multi-occur
+ (mapcar (lambda (x)
+ (with-current-buffer
+ ;; FIXME: Why not just (find-file-noselect x)?
+ ;; Is it to avoid the "revert buffer" prompt?
+ (or (get-file-buffer x) (find-file-noselect x))
+ (widen)
+ (current-buffer)))
+ files)
+ regexp)))
+
+(add-hook 'occur-mode-find-occurrence-hook
+ (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
+
+(defun org-occur-link-in-agenda-files ()
+ "Create a link and search for it in the agendas.
+The link is not stored in `org-stored-links', it is just created
+for the search purpose."
+ (interactive)
+ (let ((link (condition-case nil
+ (org-store-link nil)
+ (error "Unable to create a link to here"))))
+ (org-occur-in-agenda-files (regexp-quote link))))
+
+(defun org-reverse-string (string)
+ "Return the reverse of STRING."
+ (apply 'string (reverse (string-to-list string))))
+
+;; defsubst org-uniquify must be defined before first use
+
+(defun org-uniquify-alist (alist)
+ "Merge elements of ALIST with the same key.
+
+For example, in this alist:
+
+\(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
+ => \\='((a 1 3) (b 2))
+
+merge (a 1) and (a 3) into (a 1 3).
+
+The function returns the new ALIST."
+ (let (rtn)
+ (dolist (e alist rtn)
+ (let (n)
+ (if (not (assoc (car e) rtn))
+ (push e rtn)
+ (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
+ (setq rtn (assq-delete-all (car e) rtn))
+ (push n rtn))))))
+
+(defun org-delete-all (elts list)
+ "Remove all elements in ELTS from LIST.
+Comparison is done with `equal'. It is a destructive operation
+that may remove elements by altering the list structure."
+ (while elts
+ (setq list (delete (pop elts) list)))
+ list)
+
+(defun org-back-over-empty-lines ()
+ "Move backwards over whitespace, to the beginning of the first empty line.
+Returns the number of empty lines passed."
+ (let ((pos (point)))
+ (if (cdr (assq 'heading org-blank-before-new-entry))
+ (skip-chars-backward " \t\n\r")
+ (unless (eobp)
+ (forward-line -1)))
+ (beginning-of-line 2)
+ (goto-char (min (point) pos))
+ (count-lines (point) pos)))
+
+(defun org-skip-whitespace ()
+ (skip-chars-forward " \t\n\r"))
+
+(defun org-point-in-group (point group &optional context)
+ "Check if POINT is in match-group GROUP.
+If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
+match. If the match group does not exist or point is not inside it,
+return nil."
+ (and (match-beginning group)
+ (>= point (match-beginning group))
+ (<= point (match-end group))
+ (if context
+ (list context (match-beginning group) (match-end group))
+ t)))
+
+(defun org-switch-to-buffer-other-window (&rest args)
+ "Switch to buffer in a second window on the current frame.
+In particular, do not allow pop-up frames.
+Returns the newly created buffer."
+ (org-no-popups
+ (apply 'switch-to-buffer-other-window args)))
+
+(defun org-combine-plists (&rest plists)
+ "Create a single property list from all plists in PLISTS.
+The process starts by copying the first list, and then setting properties
+from the other lists. Settings in the last list are the most significant
+ones and overrule settings in the other lists."
+ (let ((rtn (copy-sequence (pop plists)))
+ p v ls)
+ (while plists
+ (setq ls (pop plists))
+ (while ls
+ (setq p (pop ls) v (pop ls))
+ (setq rtn (plist-put rtn p v))))
+ rtn))
+
+(defun org-replace-escapes (string table)
+ "Replace %-escapes in STRING with values in TABLE.
+TABLE is an association list with keys like \"%a\" and string values.
+The sequences in STRING may contain normal field width and padding information,
+for example \"%-5s\". Replacements happen in the sequence given by TABLE,
+so values can contain further %-escapes if they are define later in TABLE."
+ (let ((tbl (copy-alist table))
+ (case-fold-search nil)
+ (pchg 0)
+ re rpl)
+ (dolist (e tbl)
+ (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
+ (when (and (cdr e) (string-match re (cdr e)))
+ (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
+ (safe "SREF"))
+ (add-text-properties 0 3 (list 'sref sref) safe)
+ (setcdr e (replace-match safe t t (cdr e)))))
+ (while (string-match re string)
+ (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
+ (cdr e)))
+ (setq string (replace-match rpl t t string))))
+ (while (setq pchg (next-property-change pchg string))
+ (let ((sref (get-text-property pchg 'sref string)))
+ (when (and sref (string-match "SREF" string pchg))
+ (setq string (replace-match sref t t string)))))
+ string))
+
+(defun org-find-base-buffer-visiting (file)
+ "Like `find-buffer-visiting' but always return the base buffer and
+not an indirect buffer."
+ (let ((buf (or (get-file-buffer file)
+ (find-buffer-visiting file))))
+ (if buf
+ (or (buffer-base-buffer buf) buf)
+ nil)))
+
+;;; TODO: Only called once, from ox-odt which should probably use
+;;; org-export-inline-image-p or something.
+(defun org-file-image-p (file)
+ "Return non-nil if FILE is an image."
+ (save-match-data
+ (string-match (image-file-name-regexp) file)))
+
+(defun org-get-cursor-date (&optional with-time)
+ "Return the date at cursor in as a time.
+This works in the calendar and in the agenda, anywhere else it just
+returns the current time.
+If WITH-TIME is non-nil, returns the time of the event at point (in
+the agenda) or the current time of the day."
+ (let (date day defd tp hod mod)
+ (when with-time
+ (setq tp (get-text-property (point) 'time))
+ (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
+ (setq hod (string-to-number (match-string 1 tp))
+ mod (string-to-number (match-string 2 tp))))
+ (or tp (let ((now (decode-time)))
+ (setq hod (nth 2 now)
+ mod (nth 1 now)))))
+ (cond
+ ((eq major-mode 'calendar-mode)
+ (setq date (calendar-cursor-to-date)
+ defd (encode-time 0 (or mod 0) (or hod 0)
+ (nth 1 date) (nth 0 date) (nth 2 date))))
+ ((eq major-mode 'org-agenda-mode)
+ (setq day (get-text-property (point) 'day))
+ (when day
+ (setq date (calendar-gregorian-from-absolute day)
+ defd (encode-time 0 (or mod 0) (or hod 0)
+ (nth 1 date) (nth 0 date) (nth 2 date))))))
+ (or defd (current-time))))
+
+(defun org-mark-subtree (&optional up)
+ "Mark the current subtree.
+This puts point at the start of the current subtree, and mark at
+the end. If a numeric prefix UP is given, move up into the
+hierarchy of headlines by UP levels before marking the subtree."
+ (interactive "P")
+ (org-with-limited-levels
+ (cond ((org-at-heading-p) (beginning-of-line))
+ ((org-before-first-heading-p) (user-error "Not in a subtree"))
+ (t (outline-previous-visible-heading 1))))
+ (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
+ (if (called-interactively-p 'any)
+ (call-interactively 'org-mark-element)
+ (org-mark-element)))
+
+(defun org-file-newer-than-p (file time)
+ "Non-nil if FILE is newer than TIME.
+FILE is a filename, as a string, TIME is a list of integers, as
+returned by, e.g., `current-time'."
+ (and (file-exists-p file)
+ ;; Only compare times up to whole seconds as some file-systems
+ ;; (e.g. HFS+) do not retain any finer granularity. As
+ ;; a consequence, make sure we return non-nil when the two
+ ;; times are equal.
+ (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
+ (cl-subseq time 0 2)))))
+
+(defun org-compile-file (source process ext &optional err-msg log-buf spec)
+ "Compile a SOURCE file using PROCESS.
+
+PROCESS is either a function or a list of shell commands, as
+strings. EXT is a file extension, without the leading dot, as
+a string. It is used to check if the process actually succeeded.
+
+PROCESS must create a file with the same base name and directory
+as SOURCE, but ending with EXT. The function then returns its
+filename. Otherwise, it raises an error. The error message can
+then be refined by providing string ERR-MSG, which is appended to
+the standard message.
+
+If PROCESS is a function, it is called with a single argument:
+the SOURCE file.
+
+If it is a list of commands, each of them is called using
+`shell-command'. By default, in each command, %b, %f, %F, %o and
+%O are replaced with, respectively, SOURCE base name, name, full
+name, directory and absolute output file name. It is possible,
+however, to use more place-holders by specifying them in optional
+argument SPEC, as an alist following the pattern
+
+ (CHARACTER . REPLACEMENT-STRING).
+
+When PROCESS is a list of commands, optional argument LOG-BUF can
+be set to a buffer or a buffer name. `shell-command' then uses
+it for output."
+ (let* ((base-name (file-name-base source))
+ (full-name (file-truename source))
+ (out-dir (or (file-name-directory source) "./"))
+ (output (expand-file-name (concat base-name "." ext) out-dir))
+ (time (current-time))
+ (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
+ (save-window-excursion
+ (pcase process
+ ((pred functionp) (funcall process (shell-quote-argument source)))
+ ((pred consp)
+ (let ((log-buf (and log-buf (get-buffer-create log-buf)))
+ (spec (append spec
+ `((?b . ,(shell-quote-argument base-name))
+ (?f . ,(shell-quote-argument source))
+ (?F . ,(shell-quote-argument full-name))
+ (?o . ,(shell-quote-argument out-dir))
+ (?O . ,(shell-quote-argument output))))))
+ (dolist (command process)
+ (shell-command (format-spec command spec) log-buf))))
+ (_ (error "No valid command to process %S%s" source err-msg))))
+ ;; Check for process failure. Output file is expected to be
+ ;; located in the same directory as SOURCE.
+ (unless (org-file-newer-than-p output time)
+ (error (format "File %S wasn't produced%s" output err-msg)))
+ output))
+
+;;; Indentation
+
+(defvar org-element-greater-elements)
+(defun org--get-expected-indentation (element contentsp)
+ "Expected indentation column for current line, according to ELEMENT.
+ELEMENT is an element containing point. CONTENTSP is non-nil
+when indentation is to be computed according to contents of
+ELEMENT."
+ (let ((type (org-element-type element))
+ (start (org-element-property :begin element))
+ (post-affiliated (org-element-property :post-affiliated element)))
+ (org-with-wide-buffer
+ (cond
+ (contentsp
+ (cl-case type
+ ((diary-sexp footnote-definition) 0)
+ ((headline inlinetask nil)
+ (if (not org-adapt-indentation) 0
+ (let ((level (org-current-level)))
+ (if level (1+ level) 0))))
+ ((item plain-list) (org-list-item-body-column post-affiliated))
+ (t
+ (goto-char start)
+ (org-get-indentation))))
+ ((memq type '(headline inlinetask nil))
+ (if (org-match-line "[ \t]*$")
+ (org--get-expected-indentation element t)
+ 0))
+ ((memq type '(diary-sexp footnote-definition)) 0)
+ ;; First paragraph of a footnote definition or an item.
+ ;; Indent like parent.
+ ((< (line-beginning-position) start)
+ (org--get-expected-indentation
+ (org-element-property :parent element) t))
+ ;; At first line: indent according to previous sibling, if any,
+ ;; ignoring footnote definitions and inline tasks, or parent's
+ ;; contents.
+ ((= (line-beginning-position) start)
+ (catch 'exit
+ (while t
+ (if (= (point-min) start) (throw 'exit 0)
+ (goto-char (1- start))
+ (let* ((previous (org-element-at-point))
+ (parent previous))
+ (while (and parent (<= (org-element-property :end parent) start))
+ (setq previous parent
+ parent (org-element-property :parent parent)))
+ (cond
+ ((not previous) (throw 'exit 0))
+ ((> (org-element-property :end previous) start)
+ (throw 'exit (org--get-expected-indentation previous t)))
+ ((memq (org-element-type previous)
+ '(footnote-definition inlinetask))
+ (setq start (org-element-property :begin previous)))
+ (t (goto-char (org-element-property :begin previous))
+ (throw 'exit
+ (if (bolp) (org-get-indentation)
+ ;; At first paragraph in an item or
+ ;; a footnote definition.
+ (org--get-expected-indentation
+ (org-element-property :parent previous) t))))))))))
+ ;; Otherwise, move to the first non-blank line above.
+ (t
+ (beginning-of-line)
+ (let ((pos (point)))
+ (skip-chars-backward " \r\t\n")
+ (cond
+ ;; Two blank lines end a footnote definition or a plain
+ ;; list. When we indent an empty line after them, the
+ ;; containing list or footnote definition is over, so it
+ ;; qualifies as a previous sibling. Therefore, we indent
+ ;; like its first line.
+ ((and (memq type '(footnote-definition plain-list))
+ (> (count-lines (point) pos) 2))
+ (goto-char start)
+ (org-get-indentation))
+ ;; Line above is the first one of a paragraph at the
+ ;; beginning of an item or a footnote definition. Indent
+ ;; like parent.
+ ((< (line-beginning-position) start)
+ (org--get-expected-indentation
+ (org-element-property :parent element) t))
+ ;; Line above is the beginning of an element, i.e., point
+ ;; was originally on the blank lines between element's start
+ ;; and contents.
+ ((= (line-beginning-position) post-affiliated)
+ (org--get-expected-indentation element t))
+ ;; POS is after contents in a greater element. Indent like
+ ;; the beginning of the element.
+ ((and (memq type org-element-greater-elements)
+ (let ((cend (org-element-property :contents-end element)))
+ (and cend (<= cend pos))))
+ ;; As a special case, if point is at the end of a footnote
+ ;; definition or an item, indent like the very last element
+ ;; within. If that last element is an item, indent like
+ ;; its contents.
+ (if (memq type '(footnote-definition item plain-list))
+ (let ((last (org-element-at-point)))
+ (goto-char pos)
+ (org--get-expected-indentation
+ last (eq (org-element-type last) 'item)))
+ (goto-char start)
+ (org-get-indentation)))
+ ;; In any other case, indent like the current line.
+ (t (org-get-indentation)))))))))
+
+(defun org--align-node-property ()
+ "Align node property at point.
+Alignment is done according to `org-property-format', which see."
+ (when (save-excursion
+ (beginning-of-line)
+ (looking-at org-property-re))
+ (replace-match
+ (concat (match-string 4)
+ (org-trim
+ (format org-property-format (match-string 1) (match-string 3))))
+ t t)))
+
+(defun org-indent-line ()
+ "Indent line depending on context.
+
+Indentation is done according to the following rules:
+
+ - Footnote definitions, diary sexps, headlines and inline tasks
+ have to start at column 0.
+
+ - On the very first line of an element, consider, in order, the
+ next rules until one matches:
+
+ 1. If there's a sibling element before, ignoring footnote
+ definitions and inline tasks, indent like its first line.
+
+ 2. If element has a parent, indent like its contents. More
+ precisely, if parent is an item, indent after the
+ description part, if any, or the bullet (see
+ `org-list-description-max-indent'). Else, indent like
+ parent's first line.
+
+ 3. Otherwise, indent relatively to current level, if
+ `org-adapt-indentation' is non-nil, or to left margin.
+
+ - On a blank line at the end of an element, indent according to
+ the type of the element. More precisely
+
+ 1. If element is a plain list, an item, or a footnote
+ definition, indent like the very last element within.
+
+ 2. If element is a paragraph, indent like its last non blank
+ line.
+
+ 3. Otherwise, indent like its very first line.
+
+ - In the code part of a source block, use language major mode
+ to indent current line if `org-src-tab-acts-natively' is
+ non-nil. If it is nil, do nothing.
+
+ - Otherwise, indent like the first non-blank line above.
+
+The function doesn't indent an item as it could break the whole
+list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
+`\\[org-shiftmetaright]'.
+
+Also align node properties according to `org-property-format'."
+ (interactive)
+ (cond
+ (orgstruct-is-++
+ (let ((indent-line-function
+ (cl-cadadr (assq 'indent-line-function org-fb-vars))))
+ (indent-according-to-mode)))
+ ((org-at-heading-p) 'noindent)
+ (t
+ (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
+ (type (org-element-type element)))
+ (cond ((and (memq type '(plain-list item))
+ (= (line-beginning-position)
+ (org-element-property :post-affiliated element)))
+ 'noindent)
+ ((and (eq type 'latex-environment)
+ (>= (point) (org-element-property :post-affiliated element))
+ (< (point) (org-with-wide-buffer
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position 2))))
+ 'noindent)
+ ((and (eq type 'src-block)
+ org-src-tab-acts-natively
+ (> (line-beginning-position)
+ (org-element-property :post-affiliated element))
+ (< (line-beginning-position)
+ (org-with-wide-buffer
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position))))
+ (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
+ (t
+ (let ((column (org--get-expected-indentation element nil)))
+ ;; Preserve current column.
+ (if (<= (current-column) (current-indentation))
+ (indent-line-to column)
+ (save-excursion (indent-line-to column))))
+ ;; Align node property. Also preserve current column.
+ (when (eq type 'node-property)
+ (let ((column (current-column)))
+ (org--align-node-property)
+ (org-move-to-column column)))))))))
+
+(defun org-indent-region (start end)
+ "Indent each non-blank line in the region.
+Called from a program, START and END specify the region to
+indent. The function will not indent contents of example blocks,
+verse blocks and export blocks as leading white spaces are
+assumed to be significant there."
+ (interactive "r")
+ (save-excursion
+ (goto-char start)
+ (skip-chars-forward " \r\t\n")
+ (unless (eobp) (beginning-of-line))
+ (let ((indent-to
+ (lambda (ind pos)
+ ;; Set IND as indentation for all lines between point and
+ ;; POS. Blank lines are ignored. Leave point after POS
+ ;; once done.
+ (let ((limit (copy-marker pos)))
+ (while (< (point) limit)
+ (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
+ (forward-line))
+ (set-marker limit nil))))
+ (end (copy-marker end)))
+ (while (< (point) end)
+ (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
+ (let* ((element (org-element-at-point))
+ (type (org-element-type element))
+ (element-end (copy-marker (org-element-property :end element)))
+ (ind (org--get-expected-indentation element nil)))
+ (cond
+ ;; Element indented as a single block. Example blocks
+ ;; preserving indentation are a special case since the
+ ;; "contents" must not be indented whereas the block
+ ;; boundaries can.
+ ((or (memq type '(export-block latex-environment))
+ (and (eq type 'example-block)
+ (not
+ (or org-src-preserve-indentation
+ (org-element-property :preserve-indent element)))))
+ (let ((offset (- ind (org-get-indentation))))
+ (unless (zerop offset)
+ (indent-rigidly (org-element-property :begin element)
+ (org-element-property :end element)
+ offset)))
+ (goto-char element-end))
+ ;; Elements indented line wise. Be sure to exclude
+ ;; example blocks (preserving indentation) and source
+ ;; blocks from this category as they are treated
+ ;; specially later.
+ ((or (memq type '(paragraph table table-row))
+ (not (or (org-element-property :contents-begin element)
+ (memq type '(example-block src-block)))))
+ (when (eq type 'node-property)
+ (org--align-node-property)
+ (beginning-of-line))
+ (funcall indent-to ind (min element-end end)))
+ ;; Elements consisting of three parts: before the
+ ;; contents, the contents, and after the contents. The
+ ;; contents are treated specially, according to the
+ ;; element type, or not indented at all. Other parts are
+ ;; indented as a single block.
+ (t
+ (let* ((post (copy-marker
+ (org-element-property :post-affiliated element)))
+ (cbeg
+ (copy-marker
+ (cond
+ ((not (org-element-property :contents-begin element))
+ ;; Fake contents for source blocks.
+ (org-with-wide-buffer
+ (goto-char post)
+ (line-beginning-position 2)))
+ ((memq type '(footnote-definition item plain-list))
+ ;; Contents in these elements could start on
+ ;; the same line as the beginning of the
+ ;; element. Make sure we start indenting
+ ;; from the second line.
+ (org-with-wide-buffer
+ (goto-char post)
+ (end-of-line)
+ (skip-chars-forward " \r\t\n")
+ (if (eobp) (point) (line-beginning-position))))
+ (t (org-element-property :contents-begin element)))))
+ (cend (copy-marker
+ (or (org-element-property :contents-end element)
+ ;; Fake contents for source blocks.
+ (org-with-wide-buffer
+ (goto-char element-end)
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position)))
+ t)))
+ ;; Do not change items indentation individually as it
+ ;; might break the list as a whole. On the other
+ ;; hand, when at a plain list, indent it as a whole.
+ (cond ((eq type 'plain-list)
+ (let ((offset (- ind (org-get-indentation))))
+ (unless (zerop offset)
+ (indent-rigidly (org-element-property :begin element)
+ (org-element-property :end element)
+ offset))
+ (goto-char cbeg)))
+ ((eq type 'item) (goto-char cbeg))
+ (t (funcall indent-to ind (min cbeg end))))
+ (when (< (point) end)
+ (cl-case type
+ ((example-block verse-block))
+ (src-block
+ ;; In a source block, indent source code
+ ;; according to language major mode, but only if
+ ;; `org-src-tab-acts-natively' is non-nil.
+ (when (and (< (point) end) org-src-tab-acts-natively)
+ (ignore-errors
+ (org-babel-do-in-edit-buffer
+ (indent-region (point-min) (point-max))))))
+ (t (org-indent-region (point) (min cend end))))
+ (goto-char (min cend end))
+ (when (< (point) end)
+ (funcall indent-to ind (min element-end end))))
+ (set-marker post nil)
+ (set-marker cbeg nil)
+ (set-marker cend nil))))
+ (set-marker element-end nil))))
+ (set-marker end nil))))
+
+(defun org-indent-drawer ()
+ "Indent the drawer at point."
+ (interactive)
+ (unless (save-excursion
+ (beginning-of-line)
+ (looking-at-p org-drawer-regexp))
+ (user-error "Not at a drawer"))
+ (let ((element (org-element-at-point)))
+ (unless (memq (org-element-type element) '(drawer property-drawer))
+ (user-error "Not at a drawer"))
+ (org-with-wide-buffer
+ (org-indent-region (org-element-property :begin element)
+ (org-element-property :end element))))
+ (message "Drawer at point indented"))
+
+(defun org-indent-block ()
+ "Indent the block at point."
+ (interactive)
+ (unless (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search t))
+ (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
+ (user-error "Not at a block"))
+ (let ((element (org-element-at-point)))
+ (unless (memq (org-element-type element)
+ '(comment-block center-block dynamic-block example-block
+ export-block quote-block special-block
+ src-block verse-block))
+ (user-error "Not at a block"))
+ (org-with-wide-buffer
+ (org-indent-region (org-element-property :begin element)
+ (org-element-property :end element))))
+ (message "Block at point indented"))
+
+
+;;; Filling
+
+;; We use our own fill-paragraph and auto-fill functions.
+
+;; `org-fill-paragraph' relies on adaptive filling and context
+;; checking. Appropriate `fill-prefix' is computed with
+;; `org-adaptive-fill-function'.
+
+;; `org-auto-fill-function' takes care of auto-filling. It calls
+;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
+;; `org-adaptive-fill-function' value. Internally,
+;; `org-comment-line-break-function' breaks the line.
+
+;; `org-setup-filling' installs filling and auto-filling related
+;; variables during `org-mode' initialization.
+
+(defvar org-element-paragraph-separate) ; org-element.el
+(defun org-setup-filling ()
+ (require 'org-element)
+ ;; Prevent auto-fill from inserting unwanted new items.
+ (when (boundp 'fill-nobreak-predicate)
+ (setq-local
+ fill-nobreak-predicate
+ (org-uniquify
+ (append fill-nobreak-predicate
+ '(org-fill-line-break-nobreak-p
+ org-fill-paragraph-with-timestamp-nobreak-p)))))
+ (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
+ (setq-local paragraph-start paragraph-ending)
+ (setq-local paragraph-separate paragraph-ending))
+ (setq-local fill-paragraph-function 'org-fill-paragraph)
+ (setq-local auto-fill-inhibit-regexp nil)
+ (setq-local adaptive-fill-function 'org-adaptive-fill-function)
+ (setq-local normal-auto-fill-function 'org-auto-fill-function)
+ (setq-local comment-line-break-function 'org-comment-line-break-function))
+
+(defun org-fill-line-break-nobreak-p ()
+ "Non-nil when a new line at point would create an Org line break."
+ (save-excursion
+ (skip-chars-backward "[ \t]")
+ (skip-chars-backward "\\\\")
+ (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
+
+(defun org-fill-paragraph-with-timestamp-nobreak-p ()
+ "Non-nil when a new line at point would split a timestamp."
+ (and (org-at-timestamp-p t)
+ (not (looking-at org-ts-regexp-both))))
+
+(declare-function message-in-body-p "message" ())
+(defvar orgtbl-line-start-regexp) ; From org-table.el
+(defun org-adaptive-fill-function ()
+ "Compute a fill prefix for the current line.
+Return fill prefix, as a string, or nil if current line isn't
+meant to be filled. For convenience, if `adaptive-fill-regexp'
+matches in paragraphs or comments, use it."
+ (catch 'exit
+ (when (derived-mode-p 'message-mode)
+ (save-excursion
+ (beginning-of-line)
+ (cond ((not (message-in-body-p)) (throw 'exit nil))
+ ((looking-at-p org-table-line-regexp) (throw 'exit nil))
+ ((looking-at message-cite-prefix-regexp)
+ (throw 'exit (match-string-no-properties 0)))
+ ((looking-at org-outline-regexp)
+ (throw 'exit (make-string (length (match-string 0)) ?\s))))))
+ (org-with-wide-buffer
+ (unless (org-at-heading-p)
+ (let* ((p (line-beginning-position))
+ (element (save-excursion
+ (beginning-of-line)
+ (org-element-at-point)))
+ (type (org-element-type element))
+ (post-affiliated (org-element-property :post-affiliated element)))
+ (unless (< p post-affiliated)
+ (cl-case type
+ (comment
+ (save-excursion
+ (beginning-of-line)
+ (looking-at "[ \t]*")
+ (concat (match-string 0) "# ")))
+ (footnote-definition "")
+ ((item plain-list)
+ (make-string (org-list-item-body-column post-affiliated) ?\s))
+ (paragraph
+ ;; Fill prefix is usually the same as the current line,
+ ;; unless the paragraph is at the beginning of an item.
+ (let ((parent (org-element-property :parent element)))
+ (save-excursion
+ (beginning-of-line)
+ (cond ((eq (org-element-type parent) 'item)
+ (make-string (org-list-item-body-column
+ (org-element-property :begin parent))
+ ?\s))
+ ((and adaptive-fill-regexp
+ ;; Locally disable
+ ;; `adaptive-fill-function' to let
+ ;; `fill-context-prefix' handle
+ ;; `adaptive-fill-regexp' variable.
+ (let (adaptive-fill-function)
+ (fill-context-prefix
+ post-affiliated
+ (org-element-property :end element)))))
+ ((looking-at "[ \t]+") (match-string 0))
+ (t "")))))
+ (comment-block
+ ;; Only fill contents if P is within block boundaries.
+ (let* ((cbeg (save-excursion (goto-char post-affiliated)
+ (forward-line)
+ (point)))
+ (cend (save-excursion
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position))))
+ (when (and (>= p cbeg) (< p cend))
+ (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
+ (match-string 0)
+ "")))))))))))
+
+(declare-function message-goto-body "message" ())
+(defvar message-cite-prefix-regexp) ; From message.el
+(defun org-fill-paragraph (&optional justify)
+ "Fill element at point, when applicable.
+
+This function only applies to comment blocks, comments, example
+blocks and paragraphs. Also, as a special case, re-align table
+when point is at one.
+
+If JUSTIFY is non-nil (interactively, with prefix argument),
+justify as well. If `sentence-end-double-space' is non-nil, then
+period followed by one space does not end a sentence, so don't
+break a line there. The variable `fill-column' controls the
+width for filling.
+
+For convenience, when point is at a plain list, an item or
+a footnote definition, try to fill the first paragraph within."
+ (interactive)
+ (if (and (derived-mode-p 'message-mode)
+ (or (not (message-in-body-p))
+ (save-excursion (move-beginning-of-line 1)
+ (looking-at message-cite-prefix-regexp))))
+ ;; First ensure filling is correct in message-mode.
+ (let ((fill-paragraph-function
+ (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
+ (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
+ (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
+ (paragraph-separate
+ (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
+ (fill-paragraph nil))
+ (with-syntax-table org-mode-transpose-word-syntax-table
+ ;; Move to end of line in order to get the first paragraph
+ ;; within a plain list or a footnote definition.
+ (let ((element (save-excursion
+ (end-of-line)
+ (or (ignore-errors (org-element-at-point))
+ (user-error "An element cannot be parsed line %d"
+ (line-number-at-pos (point)))))))
+ ;; First check if point is in a blank line at the beginning of
+ ;; the buffer. In that case, ignore filling.
+ (cl-case (org-element-type element)
+ ;; Use major mode filling function is src blocks.
+ (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
+ ;; Align Org tables, leave table.el tables as-is.
+ (table-row (org-table-align) t)
+ (table
+ (when (eq (org-element-property :type element) 'org)
+ (save-excursion
+ (goto-char (org-element-property :post-affiliated element))
+ (org-table-align)))
+ t)
+ (paragraph
+ ;; Paragraphs may contain `line-break' type objects.
+ (let ((beg (max (point-min)
+ (org-element-property :contents-begin element)))
+ (end (min (point-max)
+ (org-element-property :contents-end element))))
+ ;; Do nothing if point is at an affiliated keyword.
+ (if (< (line-end-position) beg) t
+ (when (derived-mode-p 'message-mode)
+ ;; In `message-mode', do not fill following citation
+ ;; in current paragraph nor text before message body.
+ (let ((body-start (save-excursion (message-goto-body))))
+ (when body-start (setq beg (max body-start beg))))
+ (when (save-excursion
+ (re-search-forward
+ (concat "^" message-cite-prefix-regexp) end t))
+ (setq end (match-beginning 0))))
+ ;; Fill paragraph, taking line breaks into account.
+ (save-excursion
+ (goto-char beg)
+ (let ((cuts (list beg)))
+ (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
+ (when (eq 'line-break
+ (org-element-type
+ (save-excursion (backward-char)
+ (org-element-context))))
+ (push (point) cuts)))
+ (dolist (c (delq end cuts))
+ (fill-region-as-paragraph c end justify)
+ (setq end c))))
+ t)))
+ ;; Contents of `comment-block' type elements should be
+ ;; filled as plain text, but only if point is within block
+ ;; markers.
+ (comment-block
+ (let* ((case-fold-search t)
+ (beg (save-excursion
+ (goto-char (org-element-property :begin element))
+ (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
+ (forward-line)
+ (point)))
+ (end (save-excursion
+ (goto-char (org-element-property :end element))
+ (re-search-backward "^[ \t]*#\\+end_comment" nil t)
+ (line-beginning-position))))
+ (if (or (< (point) beg) (> (point) end)) t
+ (fill-region-as-paragraph
+ (save-excursion (end-of-line)
+ (re-search-backward "^[ \t]*$" beg 'move)
+ (line-beginning-position))
+ (save-excursion (beginning-of-line)
+ (re-search-forward "^[ \t]*$" end 'move)
+ (line-beginning-position))
+ justify))))
+ ;; Fill comments.
+ (comment
+ (let ((begin (org-element-property :post-affiliated element))
+ (end (org-element-property :end element)))
+ (when (and (>= (point) begin) (<= (point) end))
+ (let ((begin (save-excursion
+ (end-of-line)
+ (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
+ (progn (forward-line) (point))
+ begin)))
+ (end (save-excursion
+ (end-of-line)
+ (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
+ (1- (line-beginning-position))
+ (skip-chars-backward " \r\t\n")
+ (line-end-position)))))
+ ;; Do not fill comments when at a blank line.
+ (when (> end begin)
+ (let ((fill-prefix
+ (save-excursion
+ (beginning-of-line)
+ (looking-at "[ \t]*#")
+ (let ((comment-prefix (match-string 0)))
+ (goto-char (match-end 0))
+ (if (looking-at adaptive-fill-regexp)
+ (concat comment-prefix (match-string 0))
+ (concat comment-prefix " "))))))
+ (save-excursion
+ (fill-region-as-paragraph begin end justify))))))
+ t))
+ ;; Ignore every other element.
+ (otherwise t))))))
+
+(defun org-auto-fill-function ()
+ "Auto-fill function."
+ ;; Check if auto-filling is meaningful.
+ (let ((fc (current-fill-column)))
+ (when (and fc (> (current-column) fc))
+ (let* ((fill-prefix (org-adaptive-fill-function))
+ ;; Enforce empty fill prefix, if required. Otherwise, it
+ ;; will be computed again.
+ (adaptive-fill-mode (not (equal fill-prefix ""))))
+ (when fill-prefix (do-auto-fill))))))
+
+(defun org-comment-line-break-function (&optional soft)
+ "Break line at point and indent, continuing comment if within one.
+The inserted newline is marked hard if variable
+`use-hard-newlines' is true, unless optional argument SOFT is
+non-nil."
+ (if soft (insert-and-inherit ?\n) (newline 1))
+ (save-excursion (forward-char -1) (delete-horizontal-space))
+ (delete-horizontal-space)
+ (indent-to-left-margin)
+ (insert-before-markers-and-inherit fill-prefix))
+
+
+;;; Fixed Width Areas
+
+(defun org-toggle-fixed-width ()
+ "Toggle fixed-width markup.
+
+Add or remove fixed-width markup on current line, whenever it
+makes sense. Return an error otherwise.
+
+If a region is active and if it contains only fixed-width areas
+or blank lines, remove all fixed-width markup in it. If the
+region contains anything else, convert all non-fixed-width lines
+to fixed-width ones.
+
+Blank lines at the end of the region are ignored unless the
+region only contains such lines."
+ (interactive)
+ (if (not (org-region-active-p))
+ ;; No region:
+ ;;
+ ;; Remove fixed width marker only in a fixed-with element.
+ ;;
+ ;; Add fixed width maker in paragraphs, in blank lines after
+ ;; elements or at the beginning of a headline or an inlinetask,
+ ;; and before any one-line elements (e.g., a clock).
+ (progn
+ (beginning-of-line)
+ (let* ((element (org-element-at-point))
+ (type (org-element-type element)))
+ (cond
+ ((and (eq type 'fixed-width)
+ (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
+ (replace-match
+ "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
+ ((and (memq type '(babel-call clock comment diary-sexp headline
+ horizontal-rule keyword paragraph
+ planning))
+ (<= (org-element-property :post-affiliated element) (point)))
+ (skip-chars-forward " \t")
+ (insert ": "))
+ ((and (looking-at-p "[ \t]*$")
+ (or (eq type 'inlinetask)
+ (save-excursion
+ (skip-chars-forward " \r\t\n")
+ (<= (org-element-property :end element) (point)))))
+ (delete-region (point) (line-end-position))
+ (org-indent-line)
+ (insert ": "))
+ (t (user-error "Cannot insert a fixed-width line here")))))
+ ;; Region active.
+ (let* ((begin (save-excursion
+ (goto-char (region-beginning))
+ (line-beginning-position)))
+ (end (copy-marker
+ (save-excursion
+ (goto-char (region-end))
+ (unless (eolp) (beginning-of-line))
+ (if (save-excursion (re-search-backward "\\S-" begin t))
+ (progn (skip-chars-backward " \r\t\n") (point))
+ (point)))))
+ (all-fixed-width-p
+ (catch 'not-all-p
+ (save-excursion
+ (goto-char begin)
+ (skip-chars-forward " \r\t\n")
+ (when (eobp) (throw 'not-all-p nil))
+ (while (< (point) end)
+ (let ((element (org-element-at-point)))
+ (if (eq (org-element-type element) 'fixed-width)
+ (goto-char (org-element-property :end element))
+ (throw 'not-all-p nil))))
+ t))))
+ (if all-fixed-width-p
+ (save-excursion
+ (goto-char begin)
+ (while (< (point) end)
+ (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
+ (replace-match
+ "" nil nil nil
+ (if (= (line-end-position) (match-end 0)) 0 1)))
+ (forward-line)))
+ (let ((min-ind (point-max)))
+ ;; Find minimum indentation across all lines.
+ (save-excursion
+ (goto-char begin)
+ (if (not (save-excursion (re-search-forward "\\S-" end t)))
+ (setq min-ind 0)
+ (catch 'zerop
+ (while (< (point) end)
+ (unless (looking-at-p "[ \t]*$")
+ (let ((ind (org-get-indentation)))
+ (setq min-ind (min min-ind ind))
+ (when (zerop ind) (throw 'zerop t))))
+ (forward-line)))))
+ ;; Loop over all lines and add fixed-width markup everywhere
+ ;; but in fixed-width lines.
+ (save-excursion
+ (goto-char begin)
+ (while (< (point) end)
+ (cond
+ ((org-at-heading-p)
+ (insert ": ")
+ (forward-line)
+ (while (and (< (point) end) (looking-at-p "[ \t]*$"))
+ (insert ":")
+ (forward-line)))
+ ((looking-at-p "[ \t]*:\\( \\|$\\)")
+ (let* ((element (org-element-at-point))
+ (element-end (org-element-property :end element)))
+ (if (eq (org-element-type element) 'fixed-width)
+ (progn (goto-char element-end)
+ (skip-chars-backward " \r\t\n")
+ (forward-line))
+ (let ((limit (min end element-end)))
+ (while (< (point) limit)
+ (org-move-to-column min-ind t)
+ (insert ": ")
+ (forward-line))))))
+ (t
+ (org-move-to-column min-ind t)
+ (insert ": ")
+ (forward-line)))))))
+ (set-marker end nil))))
+
+
+;;; Comments
+
+;; Org comments syntax is quite complex. It requires the entire line
+;; to be just a comment. Also, even with the right syntax at the
+;; beginning of line, some some elements (i.e. verse-block or
+;; example-block) don't accept comments. Usual Emacs comment commands
+;; cannot cope with those requirements. Therefore, Org replaces them.
+
+;; Org still relies on `comment-dwim', but cannot trust
+;; `comment-only-p'. So, `comment-region-function' and
+;; `uncomment-region-function' both point
+;; to`org-comment-or-uncomment-region'. Eventually,
+;; `org-insert-comment' takes care of insertion of comments at the
+;; beginning of line.
+
+;; `org-setup-comments-handling' install comments related variables
+;; during `org-mode' initialization.
+
+(defun org-setup-comments-handling ()
+ (interactive)
+ (setq-local comment-use-syntax nil)
+ (setq-local comment-start "# ")
+ (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
+ (setq-local comment-insert-comment-function 'org-insert-comment)
+ (setq-local comment-region-function 'org-comment-or-uncomment-region)
+ (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
+
+(defun org-insert-comment ()
+ "Insert an empty comment above current line.
+If the line is empty, insert comment at its beginning. When
+point is within a source block, comment according to the related
+major mode."
+ (if (let ((element (org-element-at-point)))
+ (and (eq (org-element-type element) 'src-block)
+ (< (save-excursion
+ (goto-char (org-element-property :post-affiliated element))
+ (line-end-position))
+ (point))
+ (> (save-excursion
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position))
+ (point))))
+ (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
+ (beginning-of-line)
+ (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
+ (open-line 1))
+ (org-indent-line)
+ (insert "# ")))
+
+(defvar comment-empty-lines) ; From newcomment.el.
+(defun org-comment-or-uncomment-region (beg end &rest _)
+ "Comment or uncomment each non-blank line in the region.
+Uncomment each non-blank line between BEG and END if it only
+contains commented lines. Otherwise, comment them. If region is
+strictly within a source block, use appropriate comment syntax."
+ (if (let ((element (org-element-at-point)))
+ (and (eq (org-element-type element) 'src-block)
+ (< (save-excursion
+ (goto-char (org-element-property :post-affiliated element))
+ (line-end-position))
+ beg)
+ (>= (save-excursion
+ (goto-char (org-element-property :end element))
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position))
+ end)))
+ ;; Translate region boundaries for the Org buffer to the source
+ ;; buffer.
+ (let ((offset (- end beg)))
+ (save-excursion
+ (goto-char beg)
+ (org-babel-do-in-edit-buffer
+ (comment-or-uncomment-region (point) (+ offset (point))))))
+ (save-restriction
+ ;; Restrict region
+ (narrow-to-region (save-excursion (goto-char beg)
+ (skip-chars-forward " \r\t\n" end)
+ (line-beginning-position))
+ (save-excursion (goto-char end)
+ (skip-chars-backward " \r\t\n" beg)
+ (line-end-position)))
+ (let ((uncommentp
+ ;; UNCOMMENTP is non-nil when every non blank line between
+ ;; BEG and END is a comment.
+ (save-excursion
+ (goto-char (point-min))
+ (while (and (not (eobp))
+ (let ((element (org-element-at-point)))
+ (and (eq (org-element-type element) 'comment)
+ (goto-char (min (point-max)
+ (org-element-property
+ :end element)))))))
+ (eobp))))
+ (if uncommentp
+ ;; Only blank lines and comments in region: uncomment it.
+ (save-excursion
+ (goto-char (point-min))
+ (while (not (eobp))
+ (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
+ (replace-match "" nil nil nil 1))
+ (forward-line)))
+ ;; Comment each line in region.
+ (let ((min-indent (point-max)))
+ ;; First find the minimum indentation across all lines.
+ (save-excursion
+ (goto-char (point-min))
+ (while (and (not (eobp)) (not (zerop min-indent)))
+ (unless (looking-at "[ \t]*$")
+ (setq min-indent (min min-indent (current-indentation))))
+ (forward-line)))
+ ;; Then loop over all lines.
+ (save-excursion
+ (goto-char (point-min))
+ (while (not (eobp))
+ (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
+ ;; Don't get fooled by invisible text (e.g. link path)
+ ;; when moving to column MIN-INDENT.
+ (let ((buffer-invisibility-spec nil))
+ (org-move-to-column min-indent t))
+ (insert comment-start))
+ (forward-line)))))))))
+
+(defun org-comment-dwim (_arg)
+ "Call `comment-dwim' within a source edit buffer if needed."
+ (interactive "*P")
+ (if (org-in-src-block-p)
+ (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
+ (call-interactively 'comment-dwim)))
+
+
+;;; Timestamps API
+
+;; This section contains tools to operate on timestamp objects, as
+;; returned by, e.g. `org-element-context'.
+
+(defun org-timestamp--to-internal-time (timestamp &optional end)
+ "Encode TIMESTAMP object into Emacs internal time.
+Use end of date range or time range when END is non-nil."
+ (apply #'encode-time
+ (cons 0
+ (mapcar
+ (lambda (prop) (or (org-element-property prop timestamp) 0))
+ (if end '(:minute-end :hour-end :day-end :month-end :year-end)
+ '(:minute-start :hour-start :day-start :month-start
+ :year-start))))))
+
+(defun org-timestamp-has-time-p (timestamp)
+ "Non-nil when TIMESTAMP has a time specified."
+ (org-element-property :hour-start timestamp))
+
+(defun org-timestamp-format (timestamp format &optional end utc)
+ "Format a TIMESTAMP object into a string.
+
+FORMAT is a format specifier to be passed to
+`format-time-string'.
+
+When optional argument END is non-nil, use end of date-range or
+time-range, if possible.
+
+When optional argument UTC is non-nil, time will be expressed as
+Universal Time."
+ (format-time-string
+ format (org-timestamp--to-internal-time timestamp end)
+ (and utc t)))
+
+(defun org-timestamp-split-range (timestamp &optional end)
+ "Extract a TIMESTAMP object from a date or time range.
+
+END, when non-nil, means extract the end of the range.
+Otherwise, extract its start.
+
+Return a new timestamp object."
+ (let ((type (org-element-property :type timestamp)))
+ (if (memq type '(active inactive diary)) timestamp
+ (let ((split-ts (org-element-copy timestamp)))
+ ;; Set new type.
+ (org-element-put-property
+ split-ts :type (if (eq type 'active-range) 'active 'inactive))
+ ;; Copy start properties over end properties if END is
+ ;; non-nil. Otherwise, copy end properties over `start' ones.
+ (let ((p-alist '((:minute-start . :minute-end)
+ (:hour-start . :hour-end)
+ (:day-start . :day-end)
+ (:month-start . :month-end)
+ (:year-start . :year-end))))
+ (dolist (p-cell p-alist)
+ (org-element-put-property
+ split-ts
+ (funcall (if end #'car #'cdr) p-cell)
+ (org-element-property
+ (funcall (if end #'cdr #'car) p-cell) split-ts)))
+ ;; Eventually refresh `:raw-value'.
+ (org-element-put-property split-ts :raw-value nil)
+ (org-element-put-property
+ split-ts :raw-value (org-element-interpret-data split-ts)))))))
+
+(defun org-timestamp-translate (timestamp &optional boundary)
+ "Translate TIMESTAMP object to custom format.
+
+Format string is defined in `org-time-stamp-custom-formats',
+which see.
+
+When optional argument BOUNDARY is non-nil, it is either the
+symbol `start' or `end'. In this case, only translate the
+starting or ending part of TIMESTAMP if it is a date or time
+range. Otherwise, translate both parts.
+
+Return timestamp as-is if `org-display-custom-times' is nil or if
+it has a `diary' type."
+ (let ((type (org-element-property :type timestamp)))
+ (if (or (not org-display-custom-times) (eq type 'diary))
+ (org-element-interpret-data timestamp)
+ (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
+ org-time-stamp-custom-formats)))
+ (if (and (not boundary) (memq type '(active-range inactive-range)))
+ (concat (org-timestamp-format timestamp fmt)
+ "--"
+ (org-timestamp-format timestamp fmt t))
+ (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
+
+
+
+;;; Other stuff.
+
+(defvar reftex-docstruct-symbol)
+(defvar org--rds)
+
+(defun org-reftex-citation ()
+ "Use reftex-citation to insert a citation into the buffer.
+This looks for a line like
+
+#+BIBLIOGRAPHY: foo plain option:-d
+
+and derives from it that foo.bib is the bibliography file relevant
+for this document. It then installs the necessary environment for RefTeX
+to work in this buffer and calls `reftex-citation' to insert a citation
+into the buffer.
+
+Export of such citations to both LaTeX and HTML is handled by the contributed
+package ox-bibtex by Taru Karttunen."
+ (interactive)
+ (let ((reftex-docstruct-symbol 'org--rds)
+ org--rds bib)
+ (org-with-wide-buffer
+ (let ((case-fold-search t)
+ (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
+ (if (not (save-excursion
+ (or (re-search-forward re nil t)
+ (re-search-backward re nil t))))
+ (user-error "No bibliography defined in file")
+ (setq bib (concat (match-string 1) ".bib")
+ org--rds (list (list 'bib bib))))))
+ (call-interactively 'reftex-citation)))
+
+;;;; Functions extending outline functionality
+
+(defun org-beginning-of-line (&optional n)
+ "Go to the beginning of the current visible line.
+
+If this is a headline, and `org-special-ctrl-a/e' is set, ignore
+tags on the first attempt, and only move to after the tags when
+the cursor is already beyond the end of the headline.
+
+With argument N not nil or 1, move forward N - 1 lines first."
+ (interactive "^p")
+ (let ((origin (point))
+ (special (pcase org-special-ctrl-a/e
+ (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
+ deactivate-mark)
+ ;; First move to a visible line.
+ (if (bound-and-true-p visual-line-mode)
+ (beginning-of-visual-line n)
+ (move-beginning-of-line n)
+ ;; `move-beginning-of-line' may leave point after invisible
+ ;; characters if line starts with such of these (e.g., with
+ ;; a link at column 0). Really move to the beginning of the
+ ;; current visible line.
+ (beginning-of-line))
+ (cond
+ ;; No special behavior. Point is already at the beginning of
+ ;; a line, logical or visual.
+ ((not special))
+ ;; `beginning-of-visual-line' left point before logical beginning
+ ;; of line: point is at the beginning of a visual line. Bail
+ ;; out.
+ ((and (bound-and-true-p visual-line-mode) (not (bolp))))
+ ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
+ ;; At a headline, special position is before the title, but
+ ;; after any TODO keyword or priority cookie.
+ (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
+ (line-end-position)))
+ (bol (point)))
+ (if (eq special 'reversed)
+ (when (and (= origin bol) (eq last-command this-command))
+ (goto-char refpos))
+ (when (or (> origin refpos) (= origin bol))
+ (goto-char refpos)))))
+ ((and (looking-at org-list-full-item-re)
+ (memq (org-element-type (save-match-data (org-element-at-point)))
+ '(item plain-list)))
+ ;; Set special position at first white space character after
+ ;; bullet, and check-box, if any.
+ (let ((after-bullet
+ (let ((box (match-end 3)))
+ (cond ((not box) (match-end 1))
+ ((eq (char-after box) ?\s) (1+ box))
+ (t box)))))
+ (if (eq special 'reversed)
+ (when (and (= (point) origin) (eq last-command this-command))
+ (goto-char after-bullet))
+ (when (or (> origin after-bullet) (= (point) origin))
+ (goto-char after-bullet)))))
+ ;; No special context. Point is already at beginning of line.
+ (t nil))))
+
+(defun org-end-of-line (&optional n)
+ "Go to the end of the line, but before ellipsis, if any.
+
+If this is a headline, and `org-special-ctrl-a/e' is set, ignore
+tags on the first attempt, and only move to after the tags when
+the cursor is already beyond the end of the headline.
+
+With argument N not nil or 1, move forward N - 1 lines first."
+ (interactive "^p")
+ (let ((origin (point))
+ (special (pcase org-special-ctrl-a/e
+ (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
+ deactivate-mark)
+ ;; First move to a visible line.
+ (if (bound-and-true-p visual-line-mode)
+ (beginning-of-visual-line n)
+ (move-beginning-of-line n))
+ (cond
+ ;; At a headline, with tags.
+ ((and special
+ (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp)))
+ (match-end 5))
+ (let ((tags (save-excursion
+ (goto-char (match-beginning 5))
+ (skip-chars-backward " \t")
+ (point)))
+ (visual-end (and (bound-and-true-p visual-line-mode)
+ (save-excursion
+ (end-of-visual-line)
+ (point)))))
+ ;; If `end-of-visual-line' brings us before end of line or
+ ;; even tags, i.e., the headline spans over multiple visual
+ ;; lines, move there.
+ (cond ((and visual-end
+ (< visual-end tags)
+ (<= origin visual-end))
+ (goto-char visual-end))
+ ((eq special 'reversed)
+ (if (and (= origin (line-end-position))
+ (eq this-command last-command))
+ (goto-char tags)
+ (end-of-line)))
+ (t
+ (if (or (< origin tags) (= origin (line-end-position)))
+ (goto-char tags)
+ (end-of-line))))))
+ ((bound-and-true-p visual-line-mode)
+ (let ((bol (line-beginning-position)))
+ (end-of-visual-line)
+ ;; If `end-of-visual-line' gets us past the ellipsis at the
+ ;; end of a line, backtrack and use `end-of-line' instead.
+ (when (/= bol (line-beginning-position))
+ (goto-char bol)
+ (end-of-line))))
+ (t (end-of-line)))))
+
+(define-key org-mode-map "\C-a" 'org-beginning-of-line)
+(define-key org-mode-map "\C-e" 'org-end-of-line)
+
+(defun org-backward-sentence (&optional _arg)
+ "Go to beginning of sentence, or beginning of table field.
+This will call `backward-sentence' or `org-table-beginning-of-field',
+depending on context."
+ (interactive)
+ (let* ((element (org-element-at-point))
+ (contents-begin (org-element-property :contents-begin element))
+ (table (org-element-lineage element '(table) t)))
+ (if (and table
+ (> (point) contents-begin)
+ (<= (point) (org-element-property :contents-end table)))
+ (call-interactively #'org-table-beginning-of-field)
+ (save-restriction
+ (when (and contents-begin
+ (< (point-min) contents-begin)
+ (> (point) contents-begin))
+ (narrow-to-region contents-begin
+ (org-element-property :contents-end element)))
+ (call-interactively #'backward-sentence)))))
+
+(defun org-forward-sentence (&optional _arg)
+ "Go to end of sentence, or end of table field.
+This will call `forward-sentence' or `org-table-end-of-field',
+depending on context."
+ (interactive)
+ (let* ((element (org-element-at-point))
+ (contents-end (org-element-property :contents-end element))
+ (table (org-element-lineage element '(table) t)))
+ (if (and table
+ (>= (point) (org-element-property :contents-begin table))
+ (< (point) contents-end))
+ (call-interactively #'org-table-end-of-field)
+ (save-restriction
+ (when (and contents-end
+ (> (point-max) contents-end)
+ ;; Skip blank lines between elements.
+ (< (org-element-property :end element)
+ (save-excursion (goto-char contents-end)
+ (skip-chars-forward " \r\t\n"))))
+ (narrow-to-region (org-element-property :contents-begin element)
+ contents-end))
+ (call-interactively #'forward-sentence)))))
+
+(define-key org-mode-map "\M-a" 'org-backward-sentence)
+(define-key org-mode-map "\M-e" 'org-forward-sentence)
+
+(defun org-kill-line (&optional _arg)
+ "Kill line, to tags or end of line."
+ (interactive)
+ (cond
+ ((or (not org-special-ctrl-k)
+ (bolp)
+ (not (org-at-heading-p)))
+ (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
+ org-ctrl-k-protect-subtree
+ (or (eq org-ctrl-k-protect-subtree 'error)
+ (not (y-or-n-p "Kill hidden subtree along with headline? "))))
+ (user-error "C-k aborted as it would kill a hidden subtree"))
+ (call-interactively
+ (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
+ ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
+ (kill-region (point) (match-beginning 1))
+ (org-set-tags nil t))
+ (t (kill-region (point) (point-at-eol)))))
+
+(define-key org-mode-map "\C-k" 'org-kill-line)
+
+(defun org-yank (&optional arg)
+ "Yank. If the kill is a subtree, treat it specially.
+This command will look at the current kill and check if is a single
+subtree, or a series of subtrees[1]. If it passes the test, and if the
+cursor is at the beginning of a line or after the stars of a currently
+empty headline, then the yank is handled specially. How exactly depends
+on the value of the following variables.
+
+`org-yank-folded-subtrees'
+ By default, this variable is non-nil, which results in
+ subtree(s) being folded after insertion, except if doing so
+ would swallow text after the yanked text.
+
+`org-yank-adjusted-subtrees'
+ When non-nil (the default value is nil), the subtree will be
+ promoted or demoted in order to fit into the local outline tree
+ structure, which means that the level will be adjusted so that it
+ becomes the smaller one of the two *visible* surrounding headings.
+
+Any prefix to this command will cause `yank' to be called directly with
+no special treatment. In particular, a simple `\\[universal-argument]' prefix \
+will just
+plainly yank the text as it is.
+
+\[1] The test checks if the first non-white line is a heading
+ and if there are no other headings with fewer stars."
+ (interactive "P")
+ (org-yank-generic 'yank arg))
+
+(defun org-yank-generic (command arg)
+ "Perform some yank-like command.
+
+This function implements the behavior described in the `org-yank'
+documentation. However, it has been generalized to work for any
+interactive command with similar behavior."
+
+ ;; pretend to be command COMMAND
+ (setq this-command command)
+
+ (if arg
+ (call-interactively command)
+
+ (let ((subtreep ; is kill a subtree, and the yank position appropriate?
+ (and (org-kill-is-subtree-p)
+ (or (bolp)
+ (and (looking-at "[ \t]*$")
+ (string-match
+ "\\`\\*+\\'"
+ (buffer-substring (point-at-bol) (point)))))))
+ swallowp)
+ (cond
+ ((and subtreep org-yank-folded-subtrees)
+ (let ((beg (point))
+ end)
+ (if (and subtreep org-yank-adjusted-subtrees)
+ (org-paste-subtree nil nil 'for-yank)
+ (call-interactively command))
+
+ (setq end (point))
+ (goto-char beg)
+ (when (and (bolp) subtreep
+ (not (setq swallowp
+ (org-yank-folding-would-swallow-text beg end))))
+ (org-with-limited-levels
+ (or (looking-at org-outline-regexp)
+ (re-search-forward org-outline-regexp-bol end t))
+ (while (and (< (point) end) (looking-at org-outline-regexp))
+ (outline-hide-subtree)
+ (org-cycle-show-empty-lines 'folded)
+ (condition-case nil
+ (outline-forward-same-level 1)
+ (error (goto-char end))))))
+ (when swallowp
+ (message
+ "Inserted text not folded because that would swallow text"))
+
+ (goto-char end)
+ (skip-chars-forward " \t\n\r")
+ (beginning-of-line 1)
+ (push-mark beg 'nomsg)))
+ ((and subtreep org-yank-adjusted-subtrees)
+ (let ((beg (point-at-bol)))
+ (org-paste-subtree nil nil 'for-yank)
+ (push-mark beg 'nomsg)))
+ (t
+ (call-interactively command))))))
+
+(defun org-yank-folding-would-swallow-text (beg end)
+ "Would hide-subtree at BEG swallow any text after END?"
+ (let (level)
+ (org-with-limited-levels
+ (save-excursion
+ (goto-char beg)
+ (when (or (looking-at org-outline-regexp)
+ (re-search-forward org-outline-regexp-bol end t))
+ (setq level (org-outline-level)))
+ (goto-char end)
+ (skip-chars-forward " \t\r\n\v\f")
+ (not (or (eobp)
+ (and (bolp) (looking-at-p org-outline-regexp)
+ (<= (org-outline-level) level))))))))
+
+(define-key org-mode-map "\C-y" 'org-yank)
+
+(defun org-truely-invisible-p ()
+ "Check if point is at a character currently not visible.
+This version does not only check the character property, but also
+`visible-mode'."
+ (unless (bound-and-true-p visible-mode)
+ (org-invisible-p)))
+
+(defun org-invisible-p2 ()
+ "Check if point is at a character currently not visible.
+
+If the point is at EOL (and not at the beginning of a buffer too),
+move it back by one char before doing this check."
+ (save-excursion
+ (when (and (eolp) (not (bobp)))
+ (backward-char 1))
+ (org-invisible-p)))
+
+(defun org-back-to-heading (&optional invisible-ok)
+ "Call `outline-back-to-heading', but provide a better error message."
+ (condition-case nil
+ (outline-back-to-heading invisible-ok)
+ (error (error "Before first headline at position %d in buffer %s"
+ (point) (current-buffer)))))
+
+(defun org-before-first-heading-p ()
+ "Before first heading?"
+ (save-excursion
+ (end-of-line)
+ (null (re-search-backward org-outline-regexp-bol nil t))))
+
+(defun org-at-heading-p (&optional ignored)
+ (outline-on-heading-p t))
+
+(defun org-in-commented-heading-p (&optional no-inheritance)
+ "Non-nil if point is under a commented heading.
+This function also checks ancestors of the current headline,
+unless optional argument NO-INHERITANCE is non-nil."
+ (cond
+ ((org-before-first-heading-p) nil)
+ ((let ((headline (nth 4 (org-heading-components))))
+ (and headline
+ (let ((case-fold-search nil))
+ (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
+ headline)))))
+ (no-inheritance nil)
+ (t
+ (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
+
+(defun org-at-comment-p nil
+ "Is cursor in a commented line?"
+ (save-excursion
+ (save-match-data
+ (beginning-of-line)
+ (looking-at "^[ \t]*# "))))
+
+(defun org-at-drawer-p nil
+ "Is cursor at a drawer keyword?"
+ (save-excursion
+ (move-beginning-of-line 1)
+ (looking-at org-drawer-regexp)))
+
+(defun org-at-block-p nil
+ "Is cursor at a block keyword?"
+ (save-excursion
+ (move-beginning-of-line 1)
+ (looking-at org-block-regexp)))
+
+(defun org-point-at-end-of-empty-headline ()
+ "If point is at the end of an empty headline, return t, else nil.
+If the heading only contains a TODO keyword, it is still still considered
+empty."
+ (let ((case-fold-search nil))
+ (and (looking-at "[ \t]*$")
+ org-todo-line-regexp
+ (save-excursion
+ (beginning-of-line)
+ (looking-at org-todo-line-regexp)
+ (string= (match-string 3) "")))))
+
+(defun org-at-heading-or-item-p ()
+ (or (org-at-heading-p) (org-at-item-p)))
+
+(defun org-at-target-p ()
+ (or (org-in-regexp org-radio-target-regexp)
+ (org-in-regexp org-target-regexp)))
+;; Compatibility alias with Org versions < 7.8.03
+(defalias 'org-on-target-p 'org-at-target-p)
+
+(defun org-up-heading-all (arg)
+ "Move to the heading line of which the present line is a subheading.
+This function considers both visible and invisible heading lines.
+With argument, move up ARG levels."
+ (outline-up-heading arg t))
+
+(defun org-up-heading-safe ()
+ "Move to the heading line of which the present line is a subheading.
+This version will not throw an error. It will return the level of the
+headline found, or nil if no higher level is found.
+
+Also, this function will be a lot faster than `outline-up-heading',
+because it relies on stars being the outline starters. This can really
+make a significant difference in outlines with very many siblings."
+ (when (ignore-errors (org-back-to-heading t))
+ (let ((level-up (1- (funcall outline-level))))
+ (and (> level-up 0)
+ (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
+ (funcall outline-level)))))
+
+(defun org-first-sibling-p ()
+ "Is this heading the first child of its parents?"
+ (interactive)
+ (let ((re org-outline-regexp-bol)
+ level l)
+ (unless (org-at-heading-p t)
+ (user-error "Not at a heading"))
+ (setq level (funcall outline-level))
+ (save-excursion
+ (if (not (re-search-backward re nil t))
+ t
+ (setq l (funcall outline-level))
+ (< l level)))))
+
+(defun org-goto-sibling (&optional previous)
+ "Goto the next sibling, even if it is invisible.
+When PREVIOUS is set, go to the previous sibling instead. Returns t
+when a sibling was found. When none is found, return nil and don't
+move point."
+ (let ((fun (if previous 're-search-backward 're-search-forward))
+ (pos (point))
+ (re org-outline-regexp-bol)
+ level l)
+ (when (ignore-errors (org-back-to-heading t))
+ (setq level (funcall outline-level))
+ (catch 'exit
+ (or previous (forward-char 1))
+ (while (funcall fun re nil t)
+ (setq l (funcall outline-level))
+ (when (< l level) (goto-char pos) (throw 'exit nil))
+ (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
+ (goto-char pos)
+ nil))))
+
+(defun org-show-siblings ()
+ "Show all siblings of the current headline."
+ (save-excursion
+ (while (org-goto-sibling) (org-flag-heading nil)))
+ (save-excursion
+ (while (org-goto-sibling 'previous)
+ (org-flag-heading nil))))
+
+(defun org-goto-first-child ()
+ "Goto the first child, even if it is invisible.
+Return t when a child was found. Otherwise don't move point and
+return nil."
+ (let (level (pos (point)) (re org-outline-regexp-bol))
+ (when (ignore-errors (org-back-to-heading t))
+ (setq level (outline-level))
+ (forward-char 1)
+ (if (and (re-search-forward re nil t) (> (outline-level) level))
+ (progn (goto-char (match-beginning 0)) t)
+ (goto-char pos) nil))))
+
+(defun org-show-hidden-entry ()
+ "Show an entry where even the heading is hidden."
+ (save-excursion
+ (org-show-entry)))
+
+(defun org-flag-heading (flag &optional entry)
+ "Flag the current heading. FLAG non-nil means make invisible.
+When ENTRY is non-nil, show the entire entry."
+ (save-excursion
+ (org-back-to-heading t)
+ ;; Check if we should show the entire entry
+ (if entry
+ (progn
+ (org-show-entry)
+ (save-excursion
+ (and (outline-next-heading)
+ (org-flag-heading nil))))
+ (outline-flag-region (max (point-min) (1- (point)))
+ (save-excursion (outline-end-of-heading) (point))
+ flag))))
+
+(defun org-get-next-sibling ()
+ "Move to next heading of the same level, and return point.
+If there is no such heading, return nil.
+This is like outline-next-sibling, but invisible headings are ok."
+ (let ((level (funcall outline-level)))
+ (outline-next-heading)
+ (while (and (not (eobp)) (> (funcall outline-level) level))
+ (outline-next-heading))
+ (unless (or (eobp) (< (funcall outline-level) level))
+ (point))))
+
+(defun org-get-last-sibling ()
+ "Move to previous heading of the same level, and return point.
+If there is no such heading, return nil."
+ (let ((opoint (point))
+ (level (funcall outline-level)))
+ (outline-previous-heading)
+ (when (and (/= (point) opoint) (outline-on-heading-p t))
+ (while (and (> (funcall outline-level) level)
+ (not (bobp)))
+ (outline-previous-heading))
+ (unless (< (funcall outline-level) level)
+ (point)))))
+
+(defun org-end-of-subtree (&optional invisible-ok to-heading)
+ "Goto to the end of a subtree."
+ ;; This contains an exact copy of the original function, but it uses
+ ;; `org-back-to-heading', to make it work also in invisible
+ ;; trees. And is uses an invisible-ok argument.
+ ;; Under Emacs this is not needed, but the old outline.el needs this fix.
+ ;; Furthermore, when used inside Org, finding the end of a large subtree
+ ;; with many children and grandchildren etc, this can be much faster
+ ;; than the outline version.
+ (org-back-to-heading invisible-ok)
+ (let ((first t)
+ (level (funcall outline-level)))
+ (if (and (derived-mode-p 'org-mode) (< level 1000))
+ ;; A true heading (not a plain list item), in Org
+ ;; This means we can easily find the end by looking
+ ;; only for the right number of stars. Using a regexp to do
+ ;; this is so much faster than using a Lisp loop.
+ (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
+ (forward-char 1)
+ (and (re-search-forward re nil 'move) (beginning-of-line 1)))
+ ;; something else, do it the slow way
+ (while (and (not (eobp))
+ (or first (> (funcall outline-level) level)))
+ (setq first nil)
+ (outline-next-heading)))
+ (unless to-heading
+ (when (memq (preceding-char) '(?\n ?\^M))
+ ;; Go to end of line before heading
+ (forward-char -1)
+ (when (memq (preceding-char) '(?\n ?\^M))
+ ;; leave blank line before heading
+ (forward-char -1)))))
+ (point))
+
+(defun org-end-of-meta-data (&optional full)
+ "Skip planning line and properties drawer in current entry.
+When optional argument FULL is non-nil, also skip empty lines,
+clocking lines and regular drawers at the beginning of the
+entry."
+ (org-back-to-heading t)
+ (forward-line)
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (when (looking-at org-property-drawer-re)
+ (goto-char (match-end 0))
+ (forward-line))
+ (when (and full (not (org-at-heading-p)))
+ (catch 'exit
+ (let ((end (save-excursion (outline-next-heading) (point)))
+ (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
+ (while (not (eobp))
+ (cond ((looking-at-p org-drawer-regexp)
+ (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
+ (forward-line)
+ (throw 'exit t)))
+ ((looking-at-p re) (forward-line))
+ (t (throw 'exit t))))))))
+
+(defun org-forward-heading-same-level (arg &optional invisible-ok)
+ "Move forward to the ARG'th subheading at same level as this one.
+Stop at the first and last subheadings of a superior heading.
+Normally this only looks at visible headings, but when INVISIBLE-OK is
+non-nil it will also look at invisible ones."
+ (interactive "p")
+ (let ((backward? (and arg (< arg 0))))
+ (if (org-before-first-heading-p)
+ (if backward? (goto-char (point-min)) (outline-next-heading))
+ (org-back-to-heading invisible-ok)
+ (unless backward? (end-of-line)) ;do not match current headline
+ (let ((level (- (match-end 0) (match-beginning 0) 1))
+ (f (if backward? #'re-search-backward #'re-search-forward))
+ (count (if arg (abs arg) 1))
+ (result (point)))
+ (while (and (> count 0)
+ (funcall f org-outline-regexp-bol nil 'move))
+ (let ((l (- (match-end 0) (match-beginning 0) 1)))
+ (cond ((< l level) (setq count 0))
+ ((and (= l level)
+ (or invisible-ok
+ (not (org-invisible-p
+ (line-beginning-position)))))
+ (cl-decf count)
+ (when (= l level) (setq result (point)))))))
+ (goto-char result))
+ (beginning-of-line))))
+
+(defun org-backward-heading-same-level (arg &optional invisible-ok)
+ "Move backward to the ARG'th subheading at same level as this one.
+Stop at the first and last subheadings of a superior heading."
+ (interactive "p")
+ (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
+
+(defun org-next-visible-heading (arg)
+ "Move to the next visible heading.
+
+This function wraps `outline-next-visible-heading' with
+`org-with-limited-levels' in order to skip over inline tasks and
+respect customization of `org-odd-levels-only'."
+ (interactive "p")
+ (org-with-limited-levels
+ (outline-next-visible-heading arg)))
+
+(defun org-previous-visible-heading (arg)
+ "Move to the previous visible heading.
+
+This function wraps `outline-previous-visible-heading' with
+`org-with-limited-levels' in order to skip over inline tasks and
+respect customization of `org-odd-levels-only'."
+ (interactive "p")
+ (org-with-limited-levels
+ (outline-previous-visible-heading arg)))
+
+(defun org-next-block (arg &optional backward block-regexp)
+ "Jump to the next block.
+
+With a prefix argument ARG, jump forward ARG many blocks.
+
+When BACKWARD is non-nil, jump to the previous block.
+
+When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
+Match data is set according to this regexp when the function
+returns.
+
+Return point at beginning of the opening line of found block.
+Throw an error if no block is found."
+ (interactive "p")
+ (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
+ (case-fold-search t)
+ (search-fn (if backward #'re-search-backward #'re-search-forward))
+ (count (or arg 1))
+ (origin (point))
+ last-element)
+ (if backward (beginning-of-line) (end-of-line))
+ (while (and (> count 0) (funcall search-fn re nil t))
+ (let ((element (save-excursion
+ (goto-char (match-beginning 0))
+ (save-match-data (org-element-at-point)))))
+ (when (and (memq (org-element-type element)
+ '(center-block comment-block dynamic-block
+ example-block export-block quote-block
+ special-block src-block verse-block))
+ (<= (match-beginning 0)
+ (org-element-property :post-affiliated element)))
+ (setq last-element element)
+ (cl-decf count))))
+ (if (= count 0)
+ (prog1 (goto-char (org-element-property :post-affiliated last-element))
+ (save-match-data (org-show-context)))
+ (goto-char origin)
+ (user-error "No %s code blocks" (if backward "previous" "further")))))
+
+(defun org-previous-block (arg &optional block-regexp)
+ "Jump to the previous block.
+With a prefix argument ARG, jump backward ARG many source blocks.
+When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
+ (interactive "p")
+ (org-next-block arg t block-regexp))
+
+(defun org-forward-paragraph ()
+ "Move forward to beginning of next paragraph or equivalent.
+
+The function moves point to the beginning of the next visible
+structural element, which can be a paragraph, a table, a list
+item, etc. It also provides some special moves for convenience:
+
+ - On an affiliated keyword, jump to the beginning of the
+ relative element.
+ - On an item or a footnote definition, move to the second
+ element inside, if any.
+ - On a table or a property drawer, jump after it.
+ - On a verse or source block, stop after blank lines."
+ (interactive)
+ (when (eobp) (user-error "Cannot move further down"))
+ (let* ((deactivate-mark nil)
+ (element (org-element-at-point))
+ (type (org-element-type element))
+ (post-affiliated (org-element-property :post-affiliated element))
+ (contents-begin (org-element-property :contents-begin element))
+ (contents-end (org-element-property :contents-end element))
+ (end (let ((end (org-element-property :end element)) (parent element))
+ (while (and (setq parent (org-element-property :parent parent))
+ (= (org-element-property :contents-end parent) end))
+ (setq end (org-element-property :end parent)))
+ end)))
+ (cond ((not element)
+ (skip-chars-forward " \r\t\n")
+ (or (eobp) (beginning-of-line)))
+ ;; On affiliated keywords, move to element's beginning.
+ ((< (point) post-affiliated)
+ (goto-char post-affiliated))
+ ;; At a table row, move to the end of the table. Similarly,
+ ;; at a node property, move to the end of the property
+ ;; drawer.
+ ((memq type '(node-property table-row))
+ (goto-char (org-element-property
+ :end (org-element-property :parent element))))
+ ((memq type '(property-drawer table)) (goto-char end))
+ ;; Consider blank lines as separators in verse and source
+ ;; blocks to ease editing.
+ ((memq type '(src-block verse-block))
+ (when (eq type 'src-block)
+ (setq contents-end
+ (save-excursion (goto-char end)
+ (skip-chars-backward " \r\t\n")
+ (line-beginning-position))))
+ (beginning-of-line)
+ (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
+ (if (not (re-search-forward "^[ \t]*$" contents-end t))
+ (goto-char end)
+ (skip-chars-forward " \r\t\n")
+ (if (= (point) contents-end) (goto-char end)
+ (beginning-of-line))))
+ ;; With no contents, just skip element.
+ ((not contents-begin) (goto-char end))
+ ;; If contents are invisible, skip the element altogether.
+ ((org-invisible-p (line-end-position))
+ (cl-case type
+ (headline
+ (org-with-limited-levels (outline-next-visible-heading 1)))
+ ;; At a plain list, make sure we move to the next item
+ ;; instead of skipping the whole list.
+ (plain-list (forward-char)
+ (org-forward-paragraph))
+ (otherwise (goto-char end))))
+ ((>= (point) contents-end) (goto-char end))
+ ((>= (point) contents-begin)
+ ;; This can only happen on paragraphs and plain lists.
+ (cl-case type
+ (paragraph (goto-char end))
+ ;; At a plain list, try to move to second element in
+ ;; first item, if possible.
+ (plain-list (end-of-line)
+ (org-forward-paragraph))))
+ ;; When contents start on the middle of a line (e.g. in
+ ;; items and footnote definitions), try to reach first
+ ;; element starting after current line.
+ ((> (line-end-position) contents-begin)
+ (end-of-line)
+ (org-forward-paragraph))
+ (t (goto-char contents-begin)))))
+
+(defun org-backward-paragraph ()
+ "Move backward to start of previous paragraph or equivalent.
+
+The function moves point to the beginning of the current
+structural element, which can be a paragraph, a table, a list
+item, etc., or to the beginning of the previous visible one if
+point is already there. It also provides some special moves for
+convenience:
+
+ - On an affiliated keyword, jump to the first one.
+ - On a table or a property drawer, move to its beginning.
+ - On a verse or source block, stop before blank lines."
+ (interactive)
+ (when (bobp) (user-error "Cannot move further up"))
+ (let* ((deactivate-mark nil)
+ (element (org-element-at-point))
+ (type (org-element-type element))
+ (contents-begin (org-element-property :contents-begin element))
+ (contents-end (org-element-property :contents-end element))
+ (post-affiliated (org-element-property :post-affiliated element))
+ (begin (org-element-property :begin element)))
+ (cond
+ ((not element) (goto-char (point-min)))
+ ((= (point) begin)
+ (backward-char)
+ (org-backward-paragraph))
+ ((<= (point) post-affiliated) (goto-char begin))
+ ((memq type '(node-property table-row))
+ (goto-char (org-element-property
+ :post-affiliated (org-element-property :parent element))))
+ ((memq type '(property-drawer table)) (goto-char begin))
+ ((memq type '(src-block verse-block))
+ (when (eq type 'src-block)
+ (setq contents-begin
+ (save-excursion (goto-char begin) (forward-line) (point))))
+ (if (= (point) contents-begin) (goto-char post-affiliated)
+ ;; Inside a verse block, see blank lines as paragraph
+ ;; separators.
+ (let ((origin (point)))
+ (skip-chars-backward " \r\t\n" contents-begin)
+ (when (re-search-backward "^[ \t]*$" contents-begin 'move)
+ (skip-chars-forward " \r\t\n" origin)
+ (if (= (point) origin) (goto-char contents-begin)
+ (beginning-of-line))))))
+ ((not contents-begin) (goto-char (or post-affiliated begin)))
+ ((eq type 'paragraph)
+ (goto-char contents-begin)
+ ;; When at first paragraph in an item or a footnote definition,
+ ;; move directly to beginning of line.
+ (let ((parent-contents
+ (org-element-property
+ :contents-begin (org-element-property :parent element))))
+ (when (and parent-contents (= parent-contents contents-begin))
+ (beginning-of-line))))
+ ;; At the end of a greater element, move to the beginning of the
+ ;; last element within.
+ ((>= (point) contents-end)
+ (goto-char (1- contents-end))
+ (org-backward-paragraph))
+ (t (goto-char (or post-affiliated begin))))
+ ;; Ensure we never leave point invisible.
+ (when (org-invisible-p (point)) (beginning-of-visual-line))))
+
+(defun org-forward-element ()
+ "Move forward by one element.
+Move to the next element at the same level, when possible."
+ (interactive)
+ (cond ((eobp) (user-error "Cannot move further down"))
+ ((org-with-limited-levels (org-at-heading-p))
+ (let ((origin (point)))
+ (goto-char (org-end-of-subtree nil t))
+ (unless (org-with-limited-levels (org-at-heading-p))
+ (goto-char origin)
+ (user-error "Cannot move further down"))))
+ (t
+ (let* ((elem (org-element-at-point))
+ (end (org-element-property :end elem))
+ (parent (org-element-property :parent elem)))
+ (cond ((and parent (= (org-element-property :contents-end parent) end))
+ (goto-char (org-element-property :end parent)))
+ ((integer-or-marker-p end) (goto-char end))
+ (t (message "No element at point")))))))
+
+(defun org-backward-element ()
+ "Move backward by one element.
+Move to the previous element at the same level, when possible."
+ (interactive)
+ (cond ((bobp) (user-error "Cannot move further up"))
+ ((org-with-limited-levels (org-at-heading-p))
+ ;; At a headline, move to the previous one, if any, or stay
+ ;; here.
+ (let ((origin (point)))
+ (org-with-limited-levels (org-backward-heading-same-level 1))
+ ;; When current headline has no sibling above, move to its
+ ;; parent.
+ (when (= (point) origin)
+ (or (org-with-limited-levels (org-up-heading-safe))
+ (progn (goto-char origin)
+ (user-error "Cannot move further up"))))))
+ (t
+ (let* ((elem (org-element-at-point))
+ (beg (org-element-property :begin elem)))
+ (cond
+ ;; Move to beginning of current element if point isn't
+ ;; there already.
+ ((null beg) (message "No element at point"))
+ ((/= (point) beg) (goto-char beg))
+ (t (goto-char beg)
+ (skip-chars-backward " \r\t\n")
+ (unless (bobp)
+ (let ((prev (org-element-at-point)))
+ (goto-char (org-element-property :begin prev))
+ (while (and (setq prev (org-element-property :parent prev))
+ (<= (org-element-property :end prev) beg))
+ (goto-char (org-element-property :begin prev)))))))))))
+
+(defun org-up-element ()
+ "Move to upper element."
+ (interactive)
+ (if (org-with-limited-levels (org-at-heading-p))
+ (unless (org-up-heading-safe) (user-error "No surrounding element"))
+ (let* ((elem (org-element-at-point))
+ (parent (org-element-property :parent elem)))
+ (if parent (goto-char (org-element-property :begin parent))
+ (if (org-with-limited-levels (org-before-first-heading-p))
+ (user-error "No surrounding element")
+ (org-with-limited-levels (org-back-to-heading)))))))
+
+(defun org-down-element ()
+ "Move to inner element."
+ (interactive)
+ (let ((element (org-element-at-point)))
+ (cond
+ ((memq (org-element-type element) '(plain-list table))
+ (goto-char (org-element-property :contents-begin element))
+ (forward-char))
+ ((memq (org-element-type element) org-element-greater-elements)
+ ;; If contents are hidden, first disclose them.
+ (when (org-invisible-p (line-end-position)) (org-cycle))
+ (goto-char (or (org-element-property :contents-begin element)
+ (user-error "No content for this element"))))
+ (t (user-error "No inner element")))))
+
+(defun org-drag-element-backward ()
+ "Move backward element at point."
+ (interactive)
+ (let ((elem (or (org-element-at-point)
+ (user-error "No element at point"))))
+ (if (eq (org-element-type elem) 'headline)
+ ;; Preserve point when moving a whole tree, even if point was
+ ;; on blank lines below the headline.
+ (let ((offset (skip-chars-backward " \t\n")))
+ (unwind-protect (org-move-subtree-up)
+ (forward-char (- offset))))
+ (let ((prev-elem
+ (save-excursion
+ (goto-char (org-element-property :begin elem))
+ (skip-chars-backward " \r\t\n")
+ (unless (bobp)
+ (let* ((beg (org-element-property :begin elem))
+ (prev (org-element-at-point))
+ (up prev))
+ (while (and (setq up (org-element-property :parent up))
+ (<= (org-element-property :end up) beg))
+ (setq prev up))
+ prev)))))
+ ;; Error out if no previous element or previous element is
+ ;; a parent of the current one.
+ (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
+ (user-error "Cannot drag element backward")
+ (let ((pos (point)))
+ (org-element-swap-A-B prev-elem elem)
+ (goto-char (+ (org-element-property :begin prev-elem)
+ (- pos (org-element-property :begin elem))))))))))
+
+(defun org-drag-element-forward ()
+ "Move forward element at point."
+ (interactive)
+ (let* ((pos (point))
+ (elem (or (org-element-at-point)
+ (user-error "No element at point"))))
+ (when (= (point-max) (org-element-property :end elem))
+ (user-error "Cannot drag element forward"))
+ (goto-char (org-element-property :end elem))
+ (let ((next-elem (org-element-at-point)))
+ (when (or (org-element-nested-p elem next-elem)
+ (and (eq (org-element-type next-elem) 'headline)
+ (not (eq (org-element-type elem) 'headline))))
+ (goto-char pos)
+ (user-error "Cannot drag element forward"))
+ ;; Compute new position of point: it's shifted by NEXT-ELEM
+ ;; body's length (without final blanks) and by the length of
+ ;; blanks between ELEM and NEXT-ELEM.
+ (let ((size-next (- (save-excursion
+ (goto-char (org-element-property :end next-elem))
+ (skip-chars-backward " \r\t\n")
+ (forward-line)
+ ;; Small correction if buffer doesn't end
+ ;; with a newline character.
+ (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
+ (org-element-property :begin next-elem)))
+ (size-blank (- (org-element-property :end elem)
+ (save-excursion
+ (goto-char (org-element-property :end elem))
+ (skip-chars-backward " \r\t\n")
+ (forward-line)
+ (point)))))
+ (org-element-swap-A-B elem next-elem)
+ (goto-char (+ pos size-next size-blank))))))
+
+(defun org-drag-line-forward (arg)
+ "Drag the line at point ARG lines forward."
+ (interactive "p")
+ (dotimes (_ (abs arg))
+ (let ((c (current-column)))
+ (if (< 0 arg)
+ (progn
+ (beginning-of-line 2)
+ (transpose-lines 1)
+ (beginning-of-line 0))
+ (transpose-lines 1)
+ (beginning-of-line -1))
+ (org-move-to-column c))))
+
+(defun org-drag-line-backward (arg)
+ "Drag the line at point ARG lines backward."
+ (interactive "p")
+ (org-drag-line-forward (- arg)))
+
+(defun org-mark-element ()
+ "Put point at beginning of this element, mark at end.
+
+Interactively, if this command is repeated or (in Transient Mark
+mode) if the mark is active, it marks the next element after the
+ones already marked."
+ (interactive)
+ (let (deactivate-mark)
+ (if (and (called-interactively-p 'any)
+ (or (and (eq last-command this-command) (mark t))
+ (and transient-mark-mode mark-active)))
+ (set-mark
+ (save-excursion
+ (goto-char (mark))
+ (goto-char (org-element-property :end (org-element-at-point)))))
+ (let ((element (org-element-at-point)))
+ (end-of-line)
+ (push-mark (org-element-property :end element) t t)
+ (goto-char (org-element-property :begin element))))))
+
+(defun org-narrow-to-element ()
+ "Narrow buffer to current element."
+ (interactive)
+ (let ((elem (org-element-at-point)))
+ (cond
+ ((eq (car elem) 'headline)
+ (narrow-to-region
+ (org-element-property :begin elem)
+ (org-element-property :end elem)))
+ ((memq (car elem) org-element-greater-elements)
+ (narrow-to-region
+ (org-element-property :contents-begin elem)
+ (org-element-property :contents-end elem)))
+ (t
+ (narrow-to-region
+ (org-element-property :begin elem)
+ (org-element-property :end elem))))))
+
+(defun org-transpose-element ()
+ "Transpose current and previous elements, keeping blank lines between.
+Point is moved after both elements."
+ (interactive)
+ (org-skip-whitespace)
+ (let ((end (org-element-property :end (org-element-at-point))))
+ (org-drag-element-backward)
+ (goto-char end)))
+
+(defun org-unindent-buffer ()
+ "Un-indent the visible part of the buffer.
+Relative indentation (between items, inside blocks, etc.) isn't
+modified."
+ (interactive)
+ (unless (eq major-mode 'org-mode)
+ (user-error "Cannot un-indent a buffer not in Org mode"))
+ (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
+ (unindent-tree
+ (lambda (contents)
+ (dolist (element (reverse contents))
+ (if (memq (org-element-type element) '(headline section))
+ (funcall unindent-tree (org-element-contents element))
+ (save-excursion
+ (save-restriction
+ (narrow-to-region
+ (org-element-property :begin element)
+ (org-element-property :end element))
+ (org-do-remove-indentation))))))))
+ (funcall unindent-tree (org-element-contents parse-tree))))
+
+(defun org-show-children (&optional level)
+ "Show all direct subheadings of this heading.
+Prefix arg LEVEL is how many levels below the current level
+should be shown. Default is enough to cause the following
+heading to appear."
+ (interactive "p")
+ ;; If `orgstruct-mode' is active, use the slower version.
+ (if orgstruct-mode (call-interactively #'outline-show-children)
+ (save-excursion
+ (org-back-to-heading t)
+ (let* ((current-level (funcall outline-level))
+ (max-level (org-get-valid-level
+ current-level
+ (if level (prefix-numeric-value level) 1)))
+ (end (save-excursion (org-end-of-subtree t t)))
+ (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
+ (past-first-child nil)
+ ;; Make sure to skip inlinetasks.
+ (re (format regexp-fmt
+ current-level
+ (cond
+ ((not (featurep 'org-inlinetask)) "")
+ (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
+ 3))
+ (t (1- org-inlinetask-min-level))))))
+ ;; Display parent heading.
+ (outline-flag-region (line-end-position 0) (line-end-position) nil)
+ (forward-line)
+ ;; Display children. First child may be deeper than expected
+ ;; MAX-LEVEL. Since we want to display it anyway, adjust
+ ;; MAX-LEVEL accordingly.
+ (while (re-search-forward re end t)
+ (unless past-first-child
+ (setq re (format regexp-fmt
+ current-level
+ (max (funcall outline-level) max-level)))
+ (setq past-first-child t))
+ (outline-flag-region
+ (line-end-position 0) (line-end-position) nil))))))
+
+(defun org-show-subtree ()
+ "Show everything after this heading at deeper levels."
+ (interactive)
+ (outline-flag-region
+ (point)
+ (save-excursion
+ (org-end-of-subtree t t))
+ nil))
+
+(defun org-show-entry ()
+ "Show the body directly following this heading.
+Show the heading too, if it is currently invisible."
+ (interactive)
+ (save-excursion
+ (ignore-errors
+ (org-back-to-heading t)
+ (outline-flag-region
+ (max (point-min) (1- (point)))
+ (save-excursion
+ (if (re-search-forward
+ (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
+ (match-beginning 1)
+ (point-max)))
+ nil)
+ (org-cycle-hide-drawers 'children))))
+
+(defun org-make-options-regexp (kwds &optional extra)
+ "Make a regular expression for keyword lines.
+KWDS is a list of keywords, as strings. Optional argument EXTRA,
+when non-nil, is a regexp matching keywords names."
+ (concat "^[ \t]*#\\+\\("
+ (regexp-opt kwds)
+ (and extra (concat (and kwds "\\|") extra))
+ "\\):[ \t]*\\(.*\\)"))
+
+;;;; Integration with and fixes for other packages
+
+;;; Imenu support
+
+(defvar-local org-imenu-markers nil
+ "All markers currently used by Imenu.")
+
+(defun org-imenu-new-marker (&optional pos)
+ "Return a new marker for use by Imenu, and remember the marker."
+ (let ((m (make-marker)))
+ (move-marker m (or pos (point)))
+ (push m org-imenu-markers)
+ m))
+
+(defun org-imenu-get-tree ()
+ "Produce the index for Imenu."
+ (dolist (x org-imenu-markers) (move-marker x nil))
+ (setq org-imenu-markers nil)
+ (let* ((case-fold-search nil)
+ (n org-imenu-depth)
+ (re (concat "^" (org-get-limited-outline-regexp)))
+ (subs (make-vector (1+ n) nil))
+ (last-level 0)
+ m level head0 head)
+ (org-with-wide-buffer
+ (goto-char (point-max))
+ (while (re-search-backward re nil t)
+ (setq level (org-reduced-level (funcall outline-level)))
+ (when (and (<= level n)
+ (looking-at org-complex-heading-regexp)
+ (setq head0 (match-string-no-properties 4)))
+ (setq head (org-link-display-format head0)
+ m (org-imenu-new-marker))
+ (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
+ (if (>= level last-level)
+ (push (cons head m) (aref subs level))
+ (push (cons head (aref subs (1+ level))) (aref subs level))
+ (cl-loop for i from (1+ level) to n do (aset subs i nil)))
+ (setq last-level level))))
+ (aref subs 1)))
+
+(eval-after-load "imenu"
+ '(progn
+ (add-hook 'imenu-after-jump-hook
+ (lambda ()
+ (when (derived-mode-p 'org-mode)
+ (org-show-context 'org-goto))))))
+
+(defun org-link-display-format (s)
+ "Replace links in string S with their description.
+If there is no description, use the link target."
+ (save-match-data
+ (replace-regexp-in-string
+ org-bracket-link-analytic-regexp
+ (lambda (m)
+ (if (match-end 5) (match-string 5 m)
+ (concat (match-string 1 m) (match-string 3 m))))
+ s nil t)))
+
+(defun org-toggle-link-display ()
+ "Toggle the literal or descriptive display of links."
+ (interactive)
+ (if org-descriptive-links
+ (progn (org-remove-from-invisibility-spec '(org-link))
+ (org-restart-font-lock)
+ (setq org-descriptive-links nil))
+ (progn (add-to-invisibility-spec '(org-link))
+ (org-restart-font-lock)
+ (setq org-descriptive-links t))))
+
+;; Speedbar support
+
+(defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
+ "Overlay marking the agenda restriction line in speedbar.")
+(overlay-put org-speedbar-restriction-lock-overlay
+ 'face 'org-agenda-restriction-lock)
+(overlay-put org-speedbar-restriction-lock-overlay
+ 'help-echo "Agendas are currently limited to this item.")
+(delete-overlay org-speedbar-restriction-lock-overlay)
+
+(defun org-speedbar-set-agenda-restriction ()
+ "Restrict future agenda commands to the location at point in speedbar.
+To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
+ (interactive)
+ (require 'org-agenda)
+ (let (p m tp np dir txt)
+ (cond
+ ((setq p (text-property-any (point-at-bol) (point-at-eol)
+ 'org-imenu t))
+ (setq m (get-text-property p 'org-imenu-marker))
+ (with-current-buffer (marker-buffer m)
+ (goto-char m)
+ (org-agenda-set-restriction-lock 'subtree)))
+ ((setq p (text-property-any (point-at-bol) (point-at-eol)
+ 'speedbar-function 'speedbar-find-file))
+ (setq tp (previous-single-property-change
+ (1+ p) 'speedbar-function)
+ np (next-single-property-change
+ tp 'speedbar-function)
+ dir (speedbar-line-directory)
+ txt (buffer-substring-no-properties (or tp (point-min))
+ (or np (point-max))))
+ (with-current-buffer (find-file-noselect
+ (let ((default-directory dir))
+ (expand-file-name txt)))
+ (unless (derived-mode-p 'org-mode)
+ (user-error "Cannot restrict to non-Org mode file"))
+ (org-agenda-set-restriction-lock 'file)))
+ (t (user-error "Don't know how to restrict Org mode agenda")))
+ (move-overlay org-speedbar-restriction-lock-overlay
+ (point-at-bol) (point-at-eol))
+ (setq current-prefix-arg nil)
+ (org-agenda-maybe-redo)))
+
+(defvar speedbar-file-key-map)
+(declare-function speedbar-add-supported-extension "speedbar" (extension))
+(eval-after-load "speedbar"
+ '(progn
+ (speedbar-add-supported-extension ".org")
+ (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
+ (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
+ (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
+ (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
+ (add-hook 'speedbar-visiting-tag-hook
+ (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
+
+;;; Fixes and Hacks for problems with other packages
+
+(defun org--flyspell-object-check-p (element)
+ "Non-nil when Flyspell can check object at point.
+ELEMENT is the element at point."
+ (let ((object (save-excursion
+ (when (looking-at-p "\\>") (backward-char))
+ (org-element-context element))))
+ (cl-case (org-element-type object)
+ ;; Prevent checks in links due to keybinding conflict with
+ ;; Flyspell.
+ ((code entity export-snippet inline-babel-call
+ inline-src-block line-break latex-fragment link macro
+ statistics-cookie target timestamp verbatim)
+ nil)
+ (footnote-reference
+ ;; Only in inline footnotes, within the definition.
+ (and (eq (org-element-property :type object) 'inline)
+ (< (save-excursion
+ (goto-char (org-element-property :begin object))
+ (search-forward ":" nil t 2))
+ (point))))
+ (otherwise t))))
+
+(defun org-mode-flyspell-verify ()
+ "Function used for `flyspell-generic-check-word-predicate'."
+ (if (org-at-heading-p)
+ ;; At a headline or an inlinetask, check title only. This is
+ ;; faster than relying on `org-element-at-point'.
+ (and (save-excursion (beginning-of-line)
+ (and (let ((case-fold-search t))
+ (not (looking-at-p "\\*+ END[ \t]*$")))
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp))))
+ (match-beginning 4)
+ (>= (point) (match-beginning 4))
+ (or (not (match-beginning 5))
+ (< (point) (match-beginning 5))))
+ (let* ((element (org-element-at-point))
+ (post-affiliated (org-element-property :post-affiliated element)))
+ (cond
+ ;; Ignore checks in all affiliated keywords but captions.
+ ((< (point) post-affiliated)
+ (and (save-excursion
+ (beginning-of-line)
+ (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
+ (> (point) (match-end 0))
+ (org--flyspell-object-check-p element)))
+ ;; Ignore checks in LOGBOOK (or equivalent) drawer.
+ ((let ((log (org-log-into-drawer)))
+ (and log
+ (let ((drawer (org-element-lineage element '(drawer))))
+ (and drawer
+ (eq (compare-strings
+ log nil nil
+ (org-element-property :drawer-name drawer) nil nil t)
+ t)))))
+ nil)
+ (t
+ (cl-case (org-element-type element)
+ ((comment quote-section) t)
+ (comment-block
+ ;; Allow checks between block markers, not on them.
+ (and (> (line-beginning-position) post-affiliated)
+ (save-excursion
+ (end-of-line)
+ (skip-chars-forward " \r\t\n")
+ (< (point) (org-element-property :end element)))))
+ ;; Arbitrary list of keywords where checks are meaningful.
+ ;; Make sure point is on the value part of the element.
+ (keyword
+ (and (member (org-element-property :key element)
+ '("DESCRIPTION" "TITLE"))
+ (save-excursion
+ (search-backward ":" (line-beginning-position) t))))
+ ;; Check is globally allowed in paragraphs verse blocks and
+ ;; table rows (after affiliated keywords) but some objects
+ ;; must not be affected.
+ ((paragraph table-row verse-block)
+ (let ((cbeg (org-element-property :contents-begin element))
+ (cend (org-element-property :contents-end element)))
+ (and cbeg (>= (point) cbeg) (< (point) cend)
+ (org--flyspell-object-check-p element))))))))))
+(put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
+
+(defun org-remove-flyspell-overlays-in (beg end)
+ "Remove flyspell overlays in region."
+ (and (bound-and-true-p flyspell-mode)
+ (fboundp 'flyspell-delete-region-overlays)
+ (flyspell-delete-region-overlays beg end)))
+
+(defvar flyspell-delayed-commands)
+(eval-after-load "flyspell"
+ '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
+
+;; Make `bookmark-jump' shows the jump location if it was hidden.
+(eval-after-load "bookmark"
+ '(if (boundp 'bookmark-after-jump-hook)
+ ;; We can use the hook
+ (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
+ ;; Hook not available, use advice
+ (defadvice bookmark-jump (after org-make-visible activate)
+ "Make the position visible."
+ (org-bookmark-jump-unhide))))
+
+;; Make sure saveplace shows the location if it was hidden
+(eval-after-load "saveplace"
+ '(defadvice save-place-find-file-hook (after org-make-visible activate)
+ "Make the position visible."
+ (org-bookmark-jump-unhide)))
+
+;; Make sure ecb shows the location if it was hidden
+(eval-after-load "ecb"
+ '(defadvice ecb-method-clicked (after esf/org-show-context activate)
+ "Make hierarchy visible when jumping into location from ECB tree buffer."
+ (when (derived-mode-p 'org-mode)
+ (org-show-context))))
+
+(defun org-bookmark-jump-unhide ()
+ "Unhide the current position, to show the bookmark location."
+ (and (derived-mode-p 'org-mode)
+ (or (org-invisible-p)
+ (save-excursion (goto-char (max (point-min) (1- (point))))
+ (org-invisible-p)))
+ (org-show-context 'bookmark-jump)))
+
+(defun org-mark-jump-unhide ()
+ "Make the point visible with `org-show-context' after jumping to the mark."
+ (when (and (derived-mode-p 'org-mode)
+ (org-invisible-p))
+ (org-show-context 'mark-goto)))
+
+(eval-after-load "simple"
+ '(defadvice pop-to-mark-command (after org-make-visible activate)
+ "Make the point visible with `org-show-context'."
+ (org-mark-jump-unhide)))
+
+(eval-after-load "simple"
+ '(defadvice exchange-point-and-mark (after org-make-visible activate)
+ "Make the point visible with `org-show-context'."
+ (org-mark-jump-unhide)))
+
+(eval-after-load "simple"
+ '(defadvice pop-global-mark (after org-make-visible activate)
+ "Make the point visible with `org-show-context'."
+ (org-mark-jump-unhide)))
+
+;; Make session.el ignore our circular variable
+(defvar session-globals-exclude)
+(eval-after-load "session"
+ '(add-to-list 'session-globals-exclude 'org-mark-ring))
+
+;;;; Finish up
+
+(provide 'org)
+
+(run-hooks 'org-load-hook)
+
+;;; org.el ends here
diff --git a/lisp/ox-ascii.el b/lisp/ox-ascii.el
new file mode 100644
index 0000000..2a129e9
--- /dev/null
+++ b/lisp/ox-ascii.el
@@ -0,0 +1,2179 @@
+;;; ox-ascii.el --- ASCII Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements an ASCII back-end for Org generic exporter.
+;; See Org manual for more information.
+
+;;; Code:
+
+(require 'ox)
+(require 'ox-publish)
+(require 'cl-lib)
+
+(declare-function aa2u "ext:ascii-art-to-unicode" ())
+
+;;; Define Back-End
+;;
+;; The following setting won't allow modifying preferred charset
+;; through a buffer keyword or an option item, but, since the property
+;; will appear in communication channel nonetheless, it allows
+;; overriding `org-ascii-charset' variable on the fly by the ext-plist
+;; mechanism.
+;;
+;; We also install a filter for headlines and sections, in order to
+;; control blank lines separating them in output string.
+
+(org-export-define-backend 'ascii
+ '((bold . org-ascii-bold)
+ (center-block . org-ascii-center-block)
+ (clock . org-ascii-clock)
+ (code . org-ascii-code)
+ (drawer . org-ascii-drawer)
+ (dynamic-block . org-ascii-dynamic-block)
+ (entity . org-ascii-entity)
+ (example-block . org-ascii-example-block)
+ (export-block . org-ascii-export-block)
+ (export-snippet . org-ascii-export-snippet)
+ (fixed-width . org-ascii-fixed-width)
+ (footnote-reference . org-ascii-footnote-reference)
+ (headline . org-ascii-headline)
+ (horizontal-rule . org-ascii-horizontal-rule)
+ (inline-src-block . org-ascii-inline-src-block)
+ (inlinetask . org-ascii-inlinetask)
+ (inner-template . org-ascii-inner-template)
+ (italic . org-ascii-italic)
+ (item . org-ascii-item)
+ (keyword . org-ascii-keyword)
+ (latex-environment . org-ascii-latex-environment)
+ (latex-fragment . org-ascii-latex-fragment)
+ (line-break . org-ascii-line-break)
+ (link . org-ascii-link)
+ (node-property . org-ascii-node-property)
+ (paragraph . org-ascii-paragraph)
+ (plain-list . org-ascii-plain-list)
+ (plain-text . org-ascii-plain-text)
+ (planning . org-ascii-planning)
+ (property-drawer . org-ascii-property-drawer)
+ (quote-block . org-ascii-quote-block)
+ (radio-target . org-ascii-radio-target)
+ (section . org-ascii-section)
+ (special-block . org-ascii-special-block)
+ (src-block . org-ascii-src-block)
+ (statistics-cookie . org-ascii-statistics-cookie)
+ (strike-through . org-ascii-strike-through)
+ (subscript . org-ascii-subscript)
+ (superscript . org-ascii-superscript)
+ (table . org-ascii-table)
+ (table-cell . org-ascii-table-cell)
+ (table-row . org-ascii-table-row)
+ (target . org-ascii-target)
+ (template . org-ascii-template)
+ (timestamp . org-ascii-timestamp)
+ (underline . org-ascii-underline)
+ (verbatim . org-ascii-verbatim)
+ (verse-block . org-ascii-verse-block))
+ :menu-entry
+ '(?t "Export to Plain Text"
+ ((?A "As ASCII buffer"
+ (lambda (a s v b)
+ (org-ascii-export-as-ascii a s v b '(:ascii-charset ascii))))
+ (?a "As ASCII file"
+ (lambda (a s v b)
+ (org-ascii-export-to-ascii a s v b '(:ascii-charset ascii))))
+ (?L "As Latin1 buffer"
+ (lambda (a s v b)
+ (org-ascii-export-as-ascii a s v b '(:ascii-charset latin1))))
+ (?l "As Latin1 file"
+ (lambda (a s v b)
+ (org-ascii-export-to-ascii a s v b '(:ascii-charset latin1))))
+ (?U "As UTF-8 buffer"
+ (lambda (a s v b)
+ (org-ascii-export-as-ascii a s v b '(:ascii-charset utf-8))))
+ (?u "As UTF-8 file"
+ (lambda (a s v b)
+ (org-ascii-export-to-ascii a s v b '(:ascii-charset utf-8))))))
+ :filters-alist '((:filter-headline . org-ascii-filter-headline-blank-lines)
+ (:filter-parse-tree org-ascii-filter-paragraph-spacing
+ org-ascii-filter-comment-spacing)
+ (:filter-section . org-ascii-filter-headline-blank-lines))
+ :options-alist
+ '((:subtitle "SUBTITLE" nil nil parse)
+ (:ascii-bullets nil nil org-ascii-bullets)
+ (:ascii-caption-above nil nil org-ascii-caption-above)
+ (:ascii-charset nil nil org-ascii-charset)
+ (:ascii-global-margin nil nil org-ascii-global-margin)
+ (:ascii-format-drawer-function nil nil org-ascii-format-drawer-function)
+ (:ascii-format-inlinetask-function
+ nil nil org-ascii-format-inlinetask-function)
+ (:ascii-headline-spacing nil nil org-ascii-headline-spacing)
+ (:ascii-indented-line-width nil nil org-ascii-indented-line-width)
+ (:ascii-inlinetask-width nil nil org-ascii-inlinetask-width)
+ (:ascii-inner-margin nil nil org-ascii-inner-margin)
+ (:ascii-links-to-notes nil nil org-ascii-links-to-notes)
+ (:ascii-list-margin nil nil org-ascii-list-margin)
+ (:ascii-paragraph-spacing nil nil org-ascii-paragraph-spacing)
+ (:ascii-quote-margin nil nil org-ascii-quote-margin)
+ (:ascii-table-keep-all-vertical-lines
+ nil nil org-ascii-table-keep-all-vertical-lines)
+ (:ascii-table-use-ascii-art nil nil org-ascii-table-use-ascii-art)
+ (:ascii-table-widen-columns nil nil org-ascii-table-widen-columns)
+ (:ascii-text-width nil nil org-ascii-text-width)
+ (:ascii-underline nil nil org-ascii-underline)
+ (:ascii-verbatim-format nil nil org-ascii-verbatim-format)))
+
+
+
+;;; User Configurable Variables
+
+(defgroup org-export-ascii nil
+ "Options for exporting Org mode files to ASCII."
+ :tag "Org Export ASCII"
+ :group 'org-export)
+
+(defcustom org-ascii-text-width 72
+ "Maximum width of exported text.
+This number includes margin size, as set in
+`org-ascii-global-margin'."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-ascii-global-margin 0
+ "Width of the left margin, in number of characters."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-ascii-inner-margin 2
+ "Width of the inner margin, in number of characters.
+Inner margin is applied between each headline."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-ascii-quote-margin 6
+ "Width of margin used for quoting text, in characters.
+This margin is applied on both sides of the text."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-ascii-list-margin 0
+ "Width of margin used for plain lists, in characters.
+This margin applies to top level list only, not to its
+sub-lists."
+ :group 'org-export-ascii
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'integer)
+
+(defcustom org-ascii-inlinetask-width 30
+ "Width of inline tasks, in number of characters.
+This number ignores any margin."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+(defcustom org-ascii-headline-spacing '(1 . 2)
+ "Number of blank lines inserted around headlines.
+
+This variable can be set to a cons cell. In that case, its car
+represents the number of blank lines present before headline
+contents whereas its cdr reflects the number of blank lines after
+contents.
+
+A nil value replicates the number of blank lines found in the
+original Org buffer at the same place."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Replicate original spacing" nil)
+ (cons :tag "Set a uniform spacing"
+ (integer :tag "Number of blank lines before contents")
+ (integer :tag "Number of blank lines after contents"))))
+
+(defcustom org-ascii-indented-line-width 'auto
+ "Additional indentation width for the first line in a paragraph.
+If the value is an integer, indent the first line of each
+paragraph by this width, unless it is located at the beginning of
+a section, in which case indentation is removed from that line.
+If it is the symbol `auto' preserve indentation from original
+document."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (integer :tag "Number of white spaces characters")
+ (const :tag "Preserve original width" auto)))
+
+(defcustom org-ascii-paragraph-spacing 'auto
+ "Number of white lines between paragraphs.
+If the value is an integer, add this number of blank lines
+between contiguous paragraphs. If is it the symbol `auto', keep
+the same number of blank lines as in the original document."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (integer :tag "Number of blank lines")
+ (const :tag "Preserve original spacing" auto)))
+
+(defcustom org-ascii-charset 'ascii
+ "The charset allowed to represent various elements and objects.
+Possible values are:
+`ascii' Only use plain ASCII characters
+`latin1' Include Latin-1 characters
+`utf-8' Use all UTF-8 characters"
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "ASCII" ascii)
+ (const :tag "Latin-1" latin1)
+ (const :tag "UTF-8" utf-8)))
+
+(defcustom org-ascii-underline '((ascii ?= ?~ ?-)
+ (latin1 ?= ?~ ?-)
+ (utf-8 ?═ ?─ ?╌ ?┄ ?┈))
+ "Characters for underlining headings in ASCII export.
+
+Alist whose key is a symbol among `ascii', `latin1' and `utf-8'
+and whose value is a list of characters.
+
+For each supported charset, this variable associates a sequence
+of underline characters. In a sequence, the characters will be
+used in order for headlines level 1, 2, ... If no character is
+available for a given level, the headline won't be underlined."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(list
+ (cons :tag "Underline characters sequence"
+ (const :tag "ASCII charset" ascii)
+ (repeat character))
+ (cons :tag "Underline characters sequence"
+ (const :tag "Latin-1 charset" latin1)
+ (repeat character))
+ (cons :tag "Underline characters sequence"
+ (const :tag "UTF-8 charset" utf-8)
+ (repeat character))))
+
+(defcustom org-ascii-bullets '((ascii ?* ?+ ?-)
+ (latin1 ?§ ?¶)
+ (utf-8 ?◊))
+ "Bullet characters for headlines converted to lists in ASCII export.
+
+Alist whose key is a symbol among `ascii', `latin1' and `utf-8'
+and whose value is a list of characters.
+
+The first character is used for the first level considered as low
+level, and so on. If there are more levels than characters given
+here, the list will be repeated.
+
+Note that this variable doesn't affect plain lists
+representation."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(list
+ (cons :tag "Bullet characters for low level headlines"
+ (const :tag "ASCII charset" ascii)
+ (repeat character))
+ (cons :tag "Bullet characters for low level headlines"
+ (const :tag "Latin-1 charset" latin1)
+ (repeat character))
+ (cons :tag "Bullet characters for low level headlines"
+ (const :tag "UTF-8 charset" utf-8)
+ (repeat character))))
+
+(defcustom org-ascii-links-to-notes t
+ "Non-nil means convert links to notes before the next headline.
+When nil, the link will be exported in place. If the line
+becomes long in this way, it will be wrapped."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-ascii-table-keep-all-vertical-lines nil
+ "Non-nil means keep all vertical lines in ASCII tables.
+When nil, vertical lines will be removed except for those needed
+for column grouping."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-ascii-table-widen-columns t
+ "Non-nil means widen narrowed columns for export.
+When nil, narrowed columns will look in ASCII export just like in
+Org mode, i.e. with \"=>\" as ellipsis."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-ascii-table-use-ascii-art nil
+ "Non-nil means table.el tables are turned into ascii-art.
+
+It only makes sense when export charset is `utf-8'. It is nil by
+default since it requires ascii-art-to-unicode.el package. You
+can download it here:
+
+ http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-ascii-caption-above nil
+ "When non-nil, place caption string before the element.
+Otherwise, place it right after it."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-ascii-verbatim-format "`%s'"
+ "Format string used for verbatim text and inline code."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-ascii-format-drawer-function
+ (lambda (_name contents _width) contents)
+ "Function called to format a drawer in ASCII.
+
+The function must accept three parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+ WIDTH the text width within the drawer.
+
+The function should return either the string to be exported or
+nil to ignore the drawer.
+
+The default value simply returns the value of CONTENTS."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'function)
+
+(defcustom org-ascii-format-inlinetask-function
+ 'org-ascii-format-inlinetask-default
+ "Function called to format an inlinetask in ASCII.
+
+The function must accept nine parameters:
+ TODO the todo keyword, as a string
+ TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
+ PRIORITY the inlinetask priority, as a string
+ NAME the inlinetask name, as a string.
+ TAGS the inlinetask tags, as a list of strings.
+ CONTENTS the contents of the inlinetask, as a string.
+ WIDTH the width of the inlinetask, as a number.
+ INLINETASK the inlinetask itself.
+ INFO the info channel.
+
+The function should return either the string to be exported or
+nil to ignore the inline task."
+ :group 'org-export-ascii
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+
+
+;;; Internal Functions
+
+;; Internal functions fall into three categories.
+
+;; The first one is about text formatting. The core functions are
+;; `org-ascii--current-text-width' and
+;; `org-ascii--current-justification', which determine, respectively,
+;; the current text width allowed to a given element and its expected
+;; justification. Once this information is known,
+;; `org-ascii--fill-string', `org-ascii--justify-lines',
+;; `org-ascii--justify-element' `org-ascii--box-string' and
+;; `org-ascii--indent-string' can operate on a given output string.
+;; In particular, justification happens at the regular (i.e.,
+;; non-greater) element level, which means that when the exporting
+;; process reaches a container (e.g., a center block) content are
+;; already justified.
+
+;; The second category contains functions handling elements listings,
+;; triggered by "#+TOC:" keyword. As such, `org-ascii--build-toc'
+;; returns a complete table of contents, `org-ascii--list-listings'
+;; returns a list of referenceable src-block elements, and
+;; `org-ascii--list-tables' does the same for table elements.
+
+;; The third category includes general helper functions.
+;; `org-ascii--build-title' creates the title for a given headline
+;; or inlinetask element. `org-ascii--build-caption' returns the
+;; caption string associated to a table or a src-block.
+;; `org-ascii--describe-links' creates notes about links for
+;; insertion at the end of a section. It uses
+;; `org-ascii--unique-links' to get the list of links to describe.
+;; Eventually, `org-ascii--translate' translates a string according
+;; to language and charset specification.
+
+
+(defun org-ascii--fill-string (s text-width info &optional justify)
+ "Fill a string with specified text-width and return it.
+
+S is the string being filled. TEXT-WIDTH is an integer
+specifying maximum length of a line. INFO is the plist used as
+a communication channel.
+
+Optional argument JUSTIFY can specify any type of justification
+among `left', `center', `right' or `full'. A nil value is
+equivalent to `left'. For a justification that doesn't also fill
+string, see `org-ascii--justify-lines' and
+`org-ascii--justify-block'.
+
+Return nil if S isn't a string."
+ (when (stringp s)
+ (let ((double-space-p sentence-end-double-space))
+ (with-temp-buffer
+ (let ((fill-column text-width)
+ (use-hard-newlines t)
+ (sentence-end-double-space double-space-p))
+ (insert (if (plist-get info :preserve-breaks)
+ (replace-regexp-in-string "\n" hard-newline s)
+ s))
+ (fill-region (point-min) (point-max) justify))
+ (buffer-string)))))
+
+(defun org-ascii--justify-lines (s text-width how)
+ "Justify all lines in string S.
+TEXT-WIDTH is an integer specifying maximum length of a line.
+HOW determines the type of justification: it can be `left',
+`right', `full' or `center'."
+ (with-temp-buffer
+ (insert s)
+ (goto-char (point-min))
+ (let ((fill-column text-width)
+ ;; Disable `adaptive-fill-mode' so it doesn't prevent
+ ;; filling lines matching `adaptive-fill-regexp'.
+ (adaptive-fill-mode nil))
+ (while (< (point) (point-max))
+ (justify-current-line how)
+ (forward-line)))
+ (buffer-string)))
+
+(defun org-ascii--justify-element (contents element info)
+ "Justify CONTENTS of ELEMENT.
+INFO is a plist used as a communication channel. Justification
+is done according to the type of element. More accurately,
+paragraphs are filled and other elements are justified as blocks,
+that is according to the widest non blank line in CONTENTS."
+ (if (not (org-string-nw-p contents)) contents
+ (let ((text-width (org-ascii--current-text-width element info))
+ (how (org-ascii--current-justification element)))
+ (cond
+ ((eq (org-element-type element) 'paragraph)
+ ;; Paragraphs are treated specially as they need to be filled.
+ (org-ascii--fill-string contents text-width info how))
+ ((eq how 'left) contents)
+ (t (with-temp-buffer
+ (insert contents)
+ (goto-char (point-min))
+ (catch 'exit
+ (let ((max-width 0))
+ ;; Compute maximum width. Bail out if it is greater
+ ;; than page width, since no justification is
+ ;; possible.
+ (save-excursion
+ (while (not (eobp))
+ (unless (looking-at-p "[ \t]*$")
+ (end-of-line)
+ (let ((column (current-column)))
+ (cond
+ ((>= column text-width) (throw 'exit contents))
+ ((> column max-width) (setq max-width column)))))
+ (forward-line)))
+ ;; Justify every line according to TEXT-WIDTH and
+ ;; MAX-WIDTH.
+ (let ((offset (/ (- text-width max-width)
+ (if (eq how 'right) 1 2))))
+ (if (zerop offset) (throw 'exit contents)
+ (while (not (eobp))
+ (unless (looking-at-p "[ \t]*$")
+ (indent-to-column offset))
+ (forward-line)))))
+ (buffer-string))))))))
+
+(defun org-ascii--indent-string (s width)
+ "Indent string S by WIDTH white spaces.
+Empty lines are not indented."
+ (when (stringp s)
+ (replace-regexp-in-string
+ "\\(^\\)[ \t]*\\S-" (make-string width ?\s) s nil nil 1)))
+
+(defun org-ascii--box-string (s info)
+ "Return string S with a partial box to its left.
+INFO is a plist used as a communication channel."
+ (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)))
+ (format (if utf8p "┌────\n%s\n└────" ",----\n%s\n`----")
+ (replace-regexp-in-string
+ "^" (if utf8p "│ " "| ")
+ ;; Remove last newline character.
+ (replace-regexp-in-string "\n[ \t]*\\'" "" s)))))
+
+(defun org-ascii--current-text-width (element info)
+ "Return maximum text width for ELEMENT's contents.
+INFO is a plist used as a communication channel."
+ (pcase (org-element-type element)
+ ;; Elements with an absolute width: `headline' and `inlinetask'.
+ (`inlinetask (plist-get info :ascii-inlinetask-width))
+ (`headline
+ (- (plist-get info :ascii-text-width)
+ (let ((low-level-rank (org-export-low-level-p element info)))
+ (if low-level-rank (* low-level-rank 2)
+ (plist-get info :ascii-global-margin)))))
+ ;; Elements with a relative width: store maximum text width in
+ ;; TOTAL-WIDTH.
+ (_
+ (let* ((genealogy (org-element-lineage element nil t))
+ ;; Total width is determined by the presence, or not, of an
+ ;; inline task among ELEMENT parents.
+ (total-width
+ (if (cl-some (lambda (parent)
+ (eq (org-element-type parent) 'inlinetask))
+ genealogy)
+ (plist-get info :ascii-inlinetask-width)
+ ;; No inlinetask: Remove global margin from text width.
+ (- (plist-get info :ascii-text-width)
+ (plist-get info :ascii-global-margin)
+ (let ((parent (org-export-get-parent-headline element)))
+ ;; Inner margin doesn't apply to text before first
+ ;; headline.
+ (if (not parent) 0
+ (let ((low-level-rank
+ (org-export-low-level-p parent info)))
+ ;; Inner margin doesn't apply to contents of
+ ;; low level headlines, since they've got their
+ ;; own indentation mechanism.
+ (if low-level-rank (* low-level-rank 2)
+ (plist-get info :ascii-inner-margin)))))))))
+ (- total-width
+ ;; Each `quote-block' and `verse-block' above narrows text
+ ;; width by twice the standard margin size.
+ (+ (* (cl-count-if (lambda (parent)
+ (memq (org-element-type parent)
+ '(quote-block verse-block)))
+ genealogy)
+ 2
+ (plist-get info :ascii-quote-margin))
+ ;; Apply list margin once per "top-level" plain-list
+ ;; containing current line
+ (* (cl-count-if
+ (lambda (e)
+ (and (eq (org-element-type e) 'plain-list)
+ (not (eq (org-element-type (org-export-get-parent e))
+ 'item))))
+ genealogy)
+ (plist-get info :ascii-list-margin))
+ ;; Text width within a plain-list is restricted by
+ ;; indentation of current item. If that's the case,
+ ;; compute it with the help of `:structure' property from
+ ;; parent item, if any.
+ (let ((item
+ (if (eq (org-element-type element) 'item) element
+ (cl-find-if (lambda (parent)
+ (eq (org-element-type parent) 'item))
+ genealogy))))
+ (if (not item) 0
+ ;; Compute indentation offset of the current item,
+ ;; that is the sum of the difference between its
+ ;; indentation and the indentation of the top item in
+ ;; the list and current item bullet's length. Also
+ ;; remove checkbox length, and tag length (for
+ ;; description lists) or bullet length.
+ (let ((struct (org-element-property :structure item))
+ (beg-item (org-element-property :begin item)))
+ (+ (- (org-list-get-ind beg-item struct)
+ (org-list-get-ind
+ (org-list-get-top-point struct) struct))
+ (string-width (or (org-ascii--checkbox item info)
+ ""))
+ (string-width
+ (let ((tag (org-element-property :tag item)))
+ (if tag (org-export-data tag info)
+ (org-element-property :bullet item))))))))))))))
+
+(defun org-ascii--current-justification (element)
+ "Return expected justification for ELEMENT's contents.
+Return value is a symbol among `left', `center', `right' and
+`full'."
+ (let (justification)
+ (while (and (not justification)
+ (setq element (org-element-property :parent element)))
+ (pcase (org-element-type element)
+ (`center-block (setq justification 'center))
+ (`special-block
+ (let ((name (org-element-property :type element)))
+ (cond ((string= name "JUSTIFYRIGHT") (setq justification 'right))
+ ((string= name "JUSTIFYLEFT") (setq justification 'left)))))))
+ (or justification 'left)))
+
+(defun org-ascii--build-title
+ (element info text-width &optional underline notags toc)
+ "Format ELEMENT title and return it.
+
+ELEMENT is either an `headline' or `inlinetask' element. INFO is
+a plist used as a communication channel. TEXT-WIDTH is an
+integer representing the maximum length of a line.
+
+When optional argument UNDERLINE is non-nil, underline title,
+without the tags, according to `org-ascii-underline'
+specifications.
+
+If optional argument NOTAGS is non-nil, no tags will be added to
+the title.
+
+When optional argument TOC is non-nil, use optional title if
+possible. It doesn't apply to `inlinetask' elements."
+ (let* ((headlinep (eq (org-element-type element) 'headline))
+ (numbers
+ ;; Numbering is specific to headlines.
+ (and headlinep (org-export-numbered-headline-p element info)
+ ;; All tests passed: build numbering string.
+ (concat
+ (mapconcat
+ 'number-to-string
+ (org-export-get-headline-number element info) ".")
+ " ")))
+ (text
+ (org-trim
+ (org-export-data
+ (if (and toc headlinep) (org-export-get-alt-title element info)
+ (org-element-property :title element))
+ info)))
+ (todo
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword element)))
+ (and todo (concat (org-export-data todo info) " ")))))
+ (tags (and (not notags)
+ (plist-get info :with-tags)
+ (let ((tag-list (org-export-get-tags element info)))
+ (and tag-list
+ (format ":%s:"
+ (mapconcat 'identity tag-list ":"))))))
+ (priority
+ (and (plist-get info :with-priority)
+ (let ((char (org-element-property :priority element)))
+ (and char (format "(#%c) " char)))))
+ (first-part (concat numbers todo priority text)))
+ (concat
+ first-part
+ ;; Align tags, if any.
+ (when tags
+ (format
+ (format " %%%ds"
+ (max (- text-width (1+ (string-width first-part)))
+ (string-width tags)))
+ tags))
+ ;; Maybe underline text, if ELEMENT type is `headline' and an
+ ;; underline character has been defined.
+ (when (and underline headlinep)
+ (let ((under-char
+ (nth (1- (org-export-get-relative-level element info))
+ (cdr (assq (plist-get info :ascii-charset)
+ (plist-get info :ascii-underline))))))
+ (and under-char
+ (concat "\n"
+ (make-string (/ (string-width first-part)
+ (char-width under-char))
+ under-char))))))))
+
+(defun org-ascii--has-caption-p (element _info)
+ "Non-nil when ELEMENT has a caption affiliated keyword.
+INFO is a plist used as a communication channel. This function
+is meant to be used as a predicate for `org-export-get-ordinal'."
+ (org-element-property :caption element))
+
+(defun org-ascii--build-caption (element info)
+ "Return caption string for ELEMENT, if applicable.
+
+INFO is a plist used as a communication channel.
+
+The caption string contains the sequence number of ELEMENT along
+with its real caption. Return nil when ELEMENT has no affiliated
+caption keyword."
+ (let ((caption (org-export-get-caption element)))
+ (when caption
+ ;; Get sequence number of current src-block among every
+ ;; src-block with a caption.
+ (let ((reference
+ (org-export-get-ordinal
+ element info nil 'org-ascii--has-caption-p))
+ (title-fmt (org-ascii--translate
+ (pcase (org-element-type element)
+ (`table "Table %d:")
+ (`src-block "Listing %d:"))
+ info)))
+ (org-ascii--fill-string
+ (concat (format title-fmt reference)
+ " "
+ (org-export-data caption info))
+ (org-ascii--current-text-width element info) info)))))
+
+(defun org-ascii--build-toc (info &optional n keyword local)
+ "Return a table of contents.
+
+INFO is a plist used as a communication channel.
+
+Optional argument N, when non-nil, is an integer specifying the
+depth of the table.
+
+Optional argument KEYWORD specifies the TOC keyword, if any, from
+which the table of contents generation has been initiated.
+
+When optional argument LOCAL is non-nil, build a table of
+contents according to the current headline."
+ (concat
+ (unless local
+ (let ((title (org-ascii--translate "Table of Contents" info)))
+ (concat title "\n"
+ (make-string
+ (string-width title)
+ (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_))
+ "\n\n")))
+ (let ((text-width
+ (if keyword (org-ascii--current-text-width keyword info)
+ (- (plist-get info :ascii-text-width)
+ (plist-get info :ascii-global-margin)))))
+ (mapconcat
+ (lambda (headline)
+ (let* ((level (org-export-get-relative-level headline info))
+ (indent (* (1- level) 3)))
+ (concat
+ (unless (zerop indent) (concat (make-string (1- indent) ?.) " "))
+ (org-ascii--build-title
+ headline info (- text-width indent) nil
+ (or (not (plist-get info :with-tags))
+ (eq (plist-get info :with-tags) 'not-in-toc))
+ 'toc))))
+ (org-export-collect-headlines info n (and local keyword)) "\n"))))
+
+(defun org-ascii--list-listings (keyword info)
+ "Return a list of listings.
+
+KEYWORD is the keyword that initiated the list of listings
+generation. INFO is a plist used as a communication channel."
+ (let ((title (org-ascii--translate "List of Listings" info)))
+ (concat
+ title "\n"
+ (make-string (string-width title)
+ (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_))
+ "\n\n"
+ (let ((text-width
+ (if keyword (org-ascii--current-text-width keyword info)
+ (- (plist-get info :ascii-text-width)
+ (plist-get info :ascii-global-margin))))
+ ;; Use a counter instead of retrieving ordinal of each
+ ;; src-block.
+ (count 0))
+ (mapconcat
+ (lambda (src-block)
+ ;; Store initial text so its length can be computed. This is
+ ;; used to properly align caption right to it in case of
+ ;; filling (like contents of a description list item).
+ (let* ((initial-text
+ (format (org-ascii--translate "Listing %d:" info)
+ (cl-incf count)))
+ (initial-width (string-width initial-text)))
+ (concat
+ initial-text " "
+ (org-trim
+ (org-ascii--indent-string
+ (org-ascii--fill-string
+ ;; Use short name in priority, if available.
+ (let ((caption (or (org-export-get-caption src-block t)
+ (org-export-get-caption src-block))))
+ (org-export-data caption info))
+ (- text-width initial-width) info)
+ initial-width)))))
+ (org-export-collect-listings info) "\n")))))
+
+(defun org-ascii--list-tables (keyword info)
+ "Return a list of tables.
+
+KEYWORD is the keyword that initiated the list of tables
+generation. INFO is a plist used as a communication channel."
+ (let ((title (org-ascii--translate "List of Tables" info)))
+ (concat
+ title "\n"
+ (make-string (string-width title)
+ (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_))
+ "\n\n"
+ (let ((text-width
+ (if keyword (org-ascii--current-text-width keyword info)
+ (- (plist-get info :ascii-text-width)
+ (plist-get info :ascii-global-margin))))
+ ;; Use a counter instead of retrieving ordinal of each
+ ;; src-block.
+ (count 0))
+ (mapconcat
+ (lambda (table)
+ ;; Store initial text so its length can be computed. This is
+ ;; used to properly align caption right to it in case of
+ ;; filling (like contents of a description list item).
+ (let* ((initial-text
+ (format (org-ascii--translate "Table %d:" info)
+ (cl-incf count)))
+ (initial-width (string-width initial-text)))
+ (concat
+ initial-text " "
+ (org-trim
+ (org-ascii--indent-string
+ (org-ascii--fill-string
+ ;; Use short name in priority, if available.
+ (let ((caption (or (org-export-get-caption table t)
+ (org-export-get-caption table))))
+ (org-export-data caption info))
+ (- text-width initial-width) info)
+ initial-width)))))
+ (org-export-collect-tables info) "\n")))))
+
+(defun org-ascii--unique-links (element info)
+ "Return a list of unique link references in ELEMENT.
+ELEMENT is either a headline element or a section element. INFO
+is a plist used as a communication channel."
+ (let* (seen
+ (unique-link-p
+ ;; Return LINK if it wasn't referenced so far, or nil.
+ ;; Update SEEN links along the way.
+ (lambda (link)
+ (let ((footprint
+ ;; Normalize description in footprints.
+ (cons (org-element-property :raw-link link)
+ (let ((contents (org-element-contents link)))
+ (and contents
+ (replace-regexp-in-string
+ "[ \r\t\n]+" " "
+ (org-trim
+ (org-element-interpret-data contents))))))))
+ ;; Ignore LINK if it hasn't been translated already. It
+ ;; can happen if it is located in an affiliated keyword
+ ;; that was ignored.
+ (when (and (org-string-nw-p
+ (gethash link (plist-get info :exported-data)))
+ (not (member footprint seen)))
+ (push footprint seen) link)))))
+ (org-element-map (if (eq (org-element-type element) 'section)
+ element
+ ;; In a headline, only retrieve links in title
+ ;; and relative section, not in children.
+ (list (org-element-property :title element)
+ (car (org-element-contents element))))
+ 'link unique-link-p info nil 'headline t)))
+
+(defun org-ascii--describe-datum (datum info)
+ "Describe DATUM object or element.
+If DATUM is a string, consider it to be a file name, per
+`org-export-resolve-id-link'. INFO is the communication channel,
+as a plist."
+ (pcase (org-element-type datum)
+ (`plain-text (format "See file %s" datum)) ;External file
+ (`headline
+ (format (org-ascii--translate "See section %s" info)
+ (if (org-export-numbered-headline-p datum info)
+ (mapconcat #'number-to-string
+ (org-export-get-headline-number datum info)
+ ".")
+ (org-export-data (org-element-property :title datum) info))))
+ (_
+ (let ((number (org-export-get-ordinal
+ datum info nil #'org-ascii--has-caption-p))
+ ;; If destination is a target, make sure we can name the
+ ;; container it refers to.
+ (enumerable
+ (org-element-lineage datum '(headline paragrah src-block table) t)))
+ (pcase (org-element-type enumerable)
+ (`headline
+ (format (org-ascii--translate "See section %s" info)
+ (if (org-export-numbered-headline-p enumerable info)
+ (mapconcat #'number-to-string number ".")
+ (org-export-data
+ (org-element-property :title enumerable) info))))
+ ((guard (not number))
+ (org-ascii--translate "Unknown reference" info))
+ (`paragraph
+ (format (org-ascii--translate "See figure %s" info) number))
+ (`src-block
+ (format (org-ascii--translate "See listing %s" info) number))
+ (`table
+ (format (org-ascii--translate "See table %s" info) number))
+ (_ (org-ascii--translate "Unknown reference" info)))))))
+
+(defun org-ascii--describe-links (links width info)
+ "Return a string describing a list of links.
+LINKS is a list of link type objects, as returned by
+`org-ascii--unique-links'. WIDTH is the text width allowed for
+the output string. INFO is a plist used as a communication
+channel."
+ (mapconcat
+ (lambda (link)
+ (let* ((type (org-element-property :type link))
+ (description (org-element-contents link))
+ (anchor (org-export-data
+ (or description (org-element-property :raw-link link))
+ info)))
+ (cond
+ ((member type '("coderef" "radio")) nil)
+ ((member type '("custom-id" "fuzzy" "id"))
+ ;; Only links with a description need an entry. Other are
+ ;; already handled in `org-ascii-link'.
+ (when description
+ (let ((dest (if (equal type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (concat
+ (org-ascii--fill-string
+ (format "[%s] %s" anchor (org-ascii--describe-datum dest info))
+ width info)
+ "\n\n"))))
+ ;; Do not add a link that cannot be resolved and doesn't have
+ ;; any description: destination is already visible in the
+ ;; paragraph.
+ ((not (org-element-contents link)) nil)
+ ;; Do not add a link already handled by custom export
+ ;; functions.
+ ((org-export-custom-protocol-maybe link anchor 'ascii) nil)
+ (t
+ (concat
+ (org-ascii--fill-string
+ (format "[%s] %s" anchor (org-element-property :raw-link link))
+ width info)
+ "\n\n")))))
+ links ""))
+
+(defun org-ascii--checkbox (item info)
+ "Return checkbox string for ITEM or nil.
+INFO is a plist used as a communication channel."
+ (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)))
+ (pcase (org-element-property :checkbox item)
+ (`on (if utf8p "☑ " "[X] "))
+ (`off (if utf8p "☐ " "[ ] "))
+ (`trans (if utf8p "☒ " "[-] ")))))
+
+
+
+;;; Template
+
+(defun org-ascii-template--document-title (info)
+ "Return document title, as a string.
+INFO is a plist used as a communication channel."
+ (let* ((text-width (plist-get info :ascii-text-width))
+ ;; Links in the title will not be resolved later, so we make
+ ;; sure their path is located right after them.
+ (info (org-combine-plists info '(:ascii-links-to-notes nil)))
+ (with-title (plist-get info :with-title))
+ (title (org-export-data
+ (when with-title (plist-get info :title)) info))
+ (subtitle (org-export-data
+ (when with-title (plist-get info :subtitle)) info))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (and (plist-get info :with-email)
+ (org-export-data (plist-get info :email) info)))
+ (date (and (plist-get info :with-date)
+ (org-export-data (org-export-get-date info) info))))
+ ;; There are two types of title blocks depending on the presence
+ ;; of a title to display.
+ (if (string= title "")
+ ;; Title block without a title. DATE is positioned at the top
+ ;; right of the document, AUTHOR to the top left and EMAIL
+ ;; just below.
+ (cond
+ ((and (org-string-nw-p date) (org-string-nw-p author))
+ (concat
+ author
+ (make-string (- text-width (string-width date) (string-width author))
+ ?\s)
+ date
+ (when (org-string-nw-p email) (concat "\n" email))
+ "\n\n\n"))
+ ((and (org-string-nw-p date) (org-string-nw-p email))
+ (concat
+ email
+ (make-string (- text-width (string-width date) (string-width email))
+ ?\s)
+ date "\n\n\n"))
+ ((org-string-nw-p date)
+ (concat
+ (org-ascii--justify-lines date text-width 'right)
+ "\n\n\n"))
+ ((and (org-string-nw-p author) (org-string-nw-p email))
+ (concat author "\n" email "\n\n\n"))
+ ((org-string-nw-p author) (concat author "\n\n\n"))
+ ((org-string-nw-p email) (concat email "\n\n\n")))
+ ;; Title block with a title. Document's TITLE, along with the
+ ;; AUTHOR and its EMAIL are both overlined and an underlined,
+ ;; centered. Date is just below, also centered.
+ (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))
+ ;; Format TITLE. It may be filled if it is too wide,
+ ;; that is wider than the two thirds of the total width.
+ (title-len (min (apply #'max
+ (mapcar #'length
+ (org-split-string
+ (concat title "\n" subtitle) "\n")))
+ (/ (* 2 text-width) 3)))
+ (formatted-title (org-ascii--fill-string title title-len info))
+ (formatted-subtitle (when (org-string-nw-p subtitle)
+ (org-ascii--fill-string subtitle title-len info)))
+ (line
+ (make-string
+ (min (+ (max title-len
+ (string-width (or author ""))
+ (string-width (or email "")))
+ 2)
+ text-width) (if utf8p ?━ ?_))))
+ (org-ascii--justify-lines
+ (concat line "\n"
+ (unless utf8p "\n")
+ (upcase formatted-title)
+ (and formatted-subtitle (concat "\n" formatted-subtitle))
+ (cond
+ ((and (org-string-nw-p author) (org-string-nw-p email))
+ (concat "\n\n" author "\n" email))
+ ((org-string-nw-p author) (concat "\n\n" author))
+ ((org-string-nw-p email) (concat "\n\n" email)))
+ "\n" line
+ (when (org-string-nw-p date) (concat "\n\n\n" date))
+ "\n\n\n") text-width 'center)))))
+
+(defun org-ascii-inner-template (contents info)
+ "Return complete document string after ASCII conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (org-element-normalize-string
+ (let ((global-margin (plist-get info :ascii-global-margin)))
+ (org-ascii--indent-string
+ (concat
+ ;; 1. Document's body.
+ contents
+ ;; 2. Footnote definitions.
+ (let ((definitions (org-export-collect-footnote-definitions info))
+ ;; Insert full links right inside the footnote definition
+ ;; as they have no chance to be inserted later.
+ (info (org-combine-plists info '(:ascii-links-to-notes nil))))
+ (when definitions
+ (concat
+ "\n\n\n"
+ (let ((title (org-ascii--translate "Footnotes" info)))
+ (concat
+ title "\n"
+ (make-string
+ (string-width title)
+ (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_))))
+ "\n\n"
+ (let ((text-width (- (plist-get info :ascii-text-width)
+ global-margin)))
+ (mapconcat
+ (lambda (ref)
+ (let ((id (format "[%s] " (car ref))))
+ ;; Distinguish between inline definitions and
+ ;; full-fledged definitions.
+ (org-trim
+ (let ((def (nth 2 ref)))
+ (if (org-element-map def org-element-all-elements
+ #'identity info 'first-match)
+ ;; Full-fledged definition: footnote ID is
+ ;; inserted inside the first parsed
+ ;; paragraph (FIRST), if any, to be sure
+ ;; filling will take it into consideration.
+ (let ((first (car (org-element-contents def))))
+ (if (not (eq (org-element-type first) 'paragraph))
+ (concat id "\n" (org-export-data def info))
+ (push id (nthcdr 2 first))
+ (org-export-data def info)))
+ ;; Fill paragraph once footnote ID is inserted
+ ;; in order to have a correct length for first
+ ;; line.
+ (org-ascii--fill-string
+ (concat id (org-export-data def info))
+ text-width info))))))
+ definitions "\n\n"))))))
+ global-margin))))
+
+(defun org-ascii-template (contents info)
+ "Return complete document string after ASCII conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((global-margin (plist-get info :ascii-global-margin)))
+ (concat
+ ;; Build title block.
+ (org-ascii--indent-string
+ (concat (org-ascii-template--document-title info)
+ ;; 2. Table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth
+ (concat
+ (org-ascii--build-toc info (and (wholenump depth) depth))
+ "\n\n\n"))))
+ global-margin)
+ ;; Document's body.
+ contents
+ ;; Creator. Justify it to the bottom right.
+ (and (plist-get info :with-creator)
+ (org-ascii--indent-string
+ (let ((text-width
+ (- (plist-get info :ascii-text-width) global-margin)))
+ (concat
+ "\n\n\n"
+ (org-ascii--fill-string
+ (plist-get info :creator) text-width info 'right)))
+ global-margin)))))
+
+(defun org-ascii--translate (s info)
+ "Translate string S according to specified language and charset.
+INFO is a plist used as a communication channel."
+ (let ((charset (intern (format ":%s" (plist-get info :ascii-charset)))))
+ (org-export-translate s charset info)))
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-ascii-bold (_bold contents _info)
+ "Transcode BOLD from Org to ASCII.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (format "*%s*" contents))
+
+
+;;;; Center Block
+
+(defun org-ascii-center-block (_center-block contents _info)
+ "Transcode a CENTER-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ ;; Center has already been taken care of at a lower level, so
+ ;; there's nothing left to do.
+ contents)
+
+
+;;;; Clock
+
+(defun org-ascii-clock (clock _contents info)
+ "Transcode a CLOCK object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-ascii--justify-element
+ (concat org-clock-string " "
+ (org-timestamp-translate (org-element-property :value clock))
+ (let ((time (org-element-property :duration clock)))
+ (and time
+ (concat " => "
+ (apply 'format
+ "%2s:%02s"
+ (org-split-string time ":"))))))
+ clock info))
+
+
+;;;; Code
+
+(defun org-ascii-code (code _contents info)
+ "Return a CODE object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format (plist-get info :ascii-verbatim-format)
+ (org-element-property :value code)))
+
+
+;;;; Drawer
+
+(defun org-ascii-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((name (org-element-property :drawer-name drawer))
+ (width (org-ascii--current-text-width drawer info)))
+ (funcall (plist-get info :ascii-format-drawer-function)
+ name contents width)))
+
+
+;;;; Dynamic Block
+
+(defun org-ascii-dynamic-block (_dynamic-block contents _info)
+ "Transcode a DYNAMIC-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ contents)
+
+
+;;;; Entity
+
+(defun org-ascii-entity (entity _contents info)
+ "Transcode an ENTITY object from Org to ASCII.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property
+ (intern (concat ":" (symbol-name (plist-get info :ascii-charset))))
+ entity))
+
+
+;;;; Example Block
+
+(defun org-ascii-example-block (example-block _contents info)
+ "Transcode a EXAMPLE-BLOCK element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-ascii--justify-element
+ (org-ascii--box-string
+ (org-export-format-code-default example-block info) info)
+ example-block info))
+
+
+;;;; Export Snippet
+
+(defun org-ascii-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'ascii)
+ (org-element-property :value export-snippet)))
+
+
+;;;; Export Block
+
+(defun org-ascii-export-block (export-block _contents info)
+ "Transcode a EXPORT-BLOCK element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "ASCII")
+ (org-ascii--justify-element
+ (org-element-property :value export-block) export-block info)))
+
+
+;;;; Fixed Width
+
+(defun org-ascii-fixed-width (fixed-width _contents info)
+ "Transcode a FIXED-WIDTH element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-ascii--justify-element
+ (org-ascii--box-string
+ (org-remove-indentation
+ (org-element-property :value fixed-width)) info)
+ fixed-width info))
+
+
+;;;; Footnote Definition
+
+;; Footnote Definitions are ignored. They are compiled at the end of
+;; the document, by `org-ascii-inner-template'.
+
+
+;;;; Footnote Reference
+
+(defun org-ascii-footnote-reference (footnote-reference _contents info)
+ "Transcode a FOOTNOTE-REFERENCE element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (format "[%s]" (org-export-get-footnote-number footnote-reference info)))
+
+
+;;;; Headline
+
+(defun org-ascii-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to ASCII.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ ;; Don't export footnote section, which will be handled at the end
+ ;; of the template.
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((low-level (org-export-low-level-p headline info))
+ (width (org-ascii--current-text-width headline info))
+ ;; Export title early so that any link in it can be
+ ;; exported and seen in `org-ascii--unique-links'.
+ (title (org-ascii--build-title headline info width (not low-level)))
+ ;; Blank lines between headline and its contents.
+ ;; `org-ascii-headline-spacing', when set, overwrites
+ ;; original buffer's spacing.
+ (pre-blanks
+ (make-string (or (car (plist-get info :ascii-headline-spacing))
+ (org-element-property :pre-blank headline)
+ 0)
+ ?\n))
+ (links (and (plist-get info :ascii-links-to-notes)
+ (org-ascii--describe-links
+ (org-ascii--unique-links headline info) width info)))
+ ;; Re-build contents, inserting section links at the right
+ ;; place. The cost is low since build results are cached.
+ (body
+ (if (not (org-string-nw-p links)) contents
+ (let* ((contents (org-element-contents headline))
+ (section (let ((first (car contents)))
+ (and (eq (org-element-type first) 'section)
+ first))))
+ (concat (and section
+ (concat (org-element-normalize-string
+ (org-export-data section info))
+ "\n\n"))
+ links
+ (mapconcat (lambda (e) (org-export-data e info))
+ (if section (cdr contents) contents)
+ ""))))))
+ ;; Deep subtree: export it as a list item.
+ (if low-level
+ (let* ((bullets (cdr (assq (plist-get info :ascii-charset)
+ (plist-get info :ascii-bullets))))
+ (bullet
+ (format "%c "
+ (nth (mod (1- low-level) (length bullets)) bullets))))
+ (concat bullet title "\n" pre-blanks
+ ;; Contents, indented by length of bullet.
+ (org-ascii--indent-string body (length bullet))))
+ ;; Else: Standard headline.
+ (concat title "\n" pre-blanks body)))))
+
+
+;;;; Horizontal Rule
+
+(defun org-ascii-horizontal-rule (horizontal-rule _contents info)
+ "Transcode an HORIZONTAL-RULE object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((text-width (org-ascii--current-text-width horizontal-rule info))
+ (spec-width
+ (org-export-read-attribute :attr_ascii horizontal-rule :width)))
+ (org-ascii--justify-lines
+ (make-string (if (and spec-width (string-match "^[0-9]+$" spec-width))
+ (string-to-number spec-width)
+ text-width)
+ (if (eq (plist-get info :ascii-charset) 'utf-8) ?― ?-))
+ text-width 'center)))
+
+
+;;;; Inline Src Block
+
+(defun org-ascii-inline-src-block (inline-src-block _contents info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (format (plist-get info :ascii-verbatim-format)
+ (org-element-property :value inline-src-block)))
+
+
+;;;; Inlinetask
+
+(defun org-ascii-format-inlinetask-default
+ (_todo _type _priority _name _tags contents width inlinetask info)
+ "Format an inline task element for ASCII export.
+See `org-ascii-format-inlinetask-function' for a description
+of the parameters."
+ (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))
+ (width (or width (plist-get info :ascii-inlinetask-width))))
+ (org-ascii--indent-string
+ (concat
+ ;; Top line, with an additional blank line if not in UTF-8.
+ (make-string width (if utf8p ?━ ?_)) "\n"
+ (unless utf8p (concat (make-string width ? ) "\n"))
+ ;; Add title. Fill it if wider than inlinetask.
+ (let ((title (org-ascii--build-title inlinetask info width)))
+ (if (<= (string-width title) width) title
+ (org-ascii--fill-string title width info)))
+ "\n"
+ ;; If CONTENTS is not empty, insert it along with
+ ;; a separator.
+ (when (org-string-nw-p contents)
+ (concat (make-string width (if utf8p ?─ ?-)) "\n" contents))
+ ;; Bottom line.
+ (make-string width (if utf8p ?━ ?_)))
+ ;; Flush the inlinetask to the right.
+ (- (plist-get info :ascii-text-width) (plist-get info :ascii-global-margin)
+ (if (not (org-export-get-parent-headline inlinetask)) 0
+ (plist-get info :ascii-inner-margin))
+ (org-ascii--current-text-width inlinetask info)))))
+
+(defun org-ascii-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((width (org-ascii--current-text-width inlinetask info)))
+ (funcall (plist-get info :ascii-format-inlinetask-function)
+ ;; todo.
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property
+ :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info))))
+ ;; todo-type
+ (org-element-property :todo-type inlinetask)
+ ;; priority
+ (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask))
+ ;; title
+ (org-export-data (org-element-property :title inlinetask) info)
+ ;; tags
+ (and (plist-get info :with-tags)
+ (org-element-property :tags inlinetask))
+ ;; contents and width
+ contents width inlinetask info)))
+
+
+;;;; Italic
+
+(defun org-ascii-italic (_italic contents _info)
+ "Transcode italic from Org to ASCII.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (format "/%s/" contents))
+
+
+;;;; Item
+
+(defun org-ascii-item (item contents info)
+ "Transcode an ITEM element from Org to ASCII.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))
+ (checkbox (org-ascii--checkbox item info))
+ (list-type (org-element-property :type (org-export-get-parent item)))
+ (bullet
+ ;; First parent of ITEM is always the plain-list. Get
+ ;; `:type' property from it.
+ (org-list-bullet-string
+ (pcase list-type
+ (`descriptive
+ (concat checkbox
+ (org-export-data (org-element-property :tag item) info)
+ ": "))
+ (`ordered
+ ;; Return correct number for ITEM, paying attention to
+ ;; counters.
+ (let* ((struct (org-element-property :structure item))
+ (bul (org-element-property :bullet item))
+ (num (number-to-string
+ (car (last (org-list-get-item-number
+ (org-element-property :begin item)
+ struct
+ (org-list-prevs-alist struct)
+ (org-list-parents-alist struct)))))))
+ (replace-regexp-in-string "[0-9]+" num bul)))
+ (_ (let ((bul (org-element-property :bullet item)))
+ ;; Change bullets into more visible form if UTF-8 is active.
+ (if (not utf8p) bul
+ (replace-regexp-in-string
+ "-" "•"
+ (replace-regexp-in-string
+ "+" "⁃"
+ (replace-regexp-in-string "*" "‣" bul))))))))))
+ (concat
+ bullet
+ (unless (eq list-type 'descriptive) checkbox)
+ ;; Contents: Pay attention to indentation. Note: check-boxes are
+ ;; already taken care of at the paragraph level so they don't
+ ;; interfere with indentation.
+ (let ((contents (org-ascii--indent-string contents (string-width bullet))))
+ (if (eq (org-element-type (car (org-element-contents item))) 'paragraph)
+ (org-trim contents)
+ (concat "\n" contents))))))
+
+
+;;;; Keyword
+
+(defun org-ascii-keyword (keyword _contents info)
+ "Transcode a KEYWORD element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "ASCII") (org-ascii--justify-element value keyword info))
+ ((string= key "TOC")
+ (org-ascii--justify-element
+ (let ((case-fold-search t))
+ (cond
+ ((string-match-p "\\<headlines\\>" value)
+ (let ((depth (and (string-match "\\<[0-9]+\\>" value)
+ (string-to-number (match-string 0 value))))
+ (localp (string-match-p "\\<local\\>" value)))
+ (org-ascii--build-toc info depth keyword localp)))
+ ((string-match-p "\\<tables\\>" value)
+ (org-ascii--list-tables keyword info))
+ ((string-match-p "\\<listings\\>" value)
+ (org-ascii--list-listings keyword info))))
+ keyword info)))))
+
+
+;;;; Latex Environment
+
+(defun org-ascii-latex-environment (latex-environment _contents info)
+ "Transcode a LATEX-ENVIRONMENT element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (when (plist-get info :with-latex)
+ (org-ascii--justify-element
+ (org-remove-indentation (org-element-property :value latex-environment))
+ latex-environment info)))
+
+
+;;;; Latex Fragment
+
+(defun org-ascii-latex-fragment (latex-fragment _contents info)
+ "Transcode a LATEX-FRAGMENT object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (when (plist-get info :with-latex)
+ (org-element-property :value latex-fragment)))
+
+
+;;;; Line Break
+
+(defun org-ascii-line-break (_line-break _contents _info)
+ "Transcode a LINE-BREAK object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+ information." hard-newline)
+
+
+;;;; Link
+
+(defun org-ascii-link (link desc info)
+ "Transcode a LINK object from Org to ASCII.
+
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information."
+ (let ((type (org-element-property :type link)))
+ (cond
+ ((org-export-custom-protocol-maybe link desc 'ascii))
+ ((string= type "coderef")
+ (let ((ref (org-element-property :path link)))
+ (format (org-export-get-coderef-format ref desc)
+ (org-export-resolve-coderef ref info))))
+ ;; Do not apply a special syntax on radio links. Though, use
+ ;; transcoded target's contents as output.
+ ((string= type "radio") desc)
+ ((member type '("custom-id" "fuzzy" "id"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (pcase (org-element-type destination)
+ ((guard desc)
+ (if (plist-get info :ascii-links-to-notes)
+ (format "[%s]" desc)
+ (concat desc
+ (format " (%s)"
+ (org-ascii--describe-datum destination info)))))
+ ;; External file.
+ (`plain-text destination)
+ (`headline
+ (if (org-export-numbered-headline-p destination info)
+ (mapconcat #'number-to-string
+ (org-export-get-headline-number destination info)
+ ".")
+ (org-export-data (org-element-property :title destination) info)))
+ ;; Handle enumerable elements and targets within them.
+ ((and (let number (org-export-get-ordinal
+ destination info nil #'org-ascii--has-caption-p))
+ (guard number))
+ (if (atom number) (number-to-string number)
+ (mapconcat #'number-to-string number ".")))
+ ;; Don't know what to do. Signal it.
+ (_ "???"))))
+ (t
+ (let ((raw-link (org-element-property :raw-link link)))
+ (if (not (org-string-nw-p desc)) (format "[%s]" raw-link)
+ (concat (format "[%s]" desc)
+ (and (not (plist-get info :ascii-links-to-notes))
+ (format " (%s)" raw-link)))))))))
+
+
+;;;; Node Properties
+
+(defun org-ascii-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+
+;;;; Paragraph
+
+(defun org-ascii-paragraph (paragraph contents info)
+ "Transcode a PARAGRAPH element from Org to ASCII.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ (org-ascii--justify-element
+ (let ((indented-line-width (plist-get info :ascii-indented-line-width)))
+ (if (not (wholenump indented-line-width)) contents
+ (concat
+ ;; Do not indent first paragraph in a section.
+ (unless (and (not (org-export-get-previous-element paragraph info))
+ (eq (org-element-type (org-export-get-parent paragraph))
+ 'section))
+ (make-string indented-line-width ?\s))
+ (replace-regexp-in-string "\\`[ \t]+" "" contents))))
+ paragraph info))
+
+
+;;;; Plain List
+
+(defun org-ascii-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element from Org to ASCII.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let ((margin (plist-get info :ascii-list-margin)))
+ (if (or (< margin 1)
+ (eq (org-element-type (org-export-get-parent plain-list)) 'item))
+ contents
+ (org-ascii--indent-string contents margin))))
+
+
+;;;; Plain Text
+
+(defun org-ascii-plain-text (text info)
+ "Transcode a TEXT string from Org to ASCII.
+INFO is a plist used as a communication channel."
+ (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)))
+ (when (and utf8p (plist-get info :with-smart-quotes))
+ (setq text (org-export-activate-smart-quotes text :utf-8 info)))
+ (if (not (plist-get info :with-special-strings)) text
+ (setq text (replace-regexp-in-string "\\\\-" "" text))
+ (if (not utf8p) text
+ ;; Usual replacements in utf-8 with proper option set.
+ (replace-regexp-in-string
+ "\\.\\.\\." "…"
+ (replace-regexp-in-string
+ "--" "–"
+ (replace-regexp-in-string "---" "—" text)))))))
+
+
+;;;; Planning
+
+(defun org-ascii-planning (planning _contents info)
+ "Transcode a PLANNING element from Org to ASCII.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-ascii--justify-element
+ (mapconcat
+ #'identity
+ (delq nil
+ (list (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat org-closed-string " "
+ (org-timestamp-translate closed))))
+ (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat org-deadline-string " "
+ (org-timestamp-translate deadline))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat org-scheduled-string " "
+ (org-timestamp-translate scheduled))))))
+ " ")
+ planning info))
+
+
+;;;; Property Drawer
+
+(defun org-ascii-property-drawer (property-drawer contents info)
+ "Transcode a PROPERTY-DRAWER element from Org to ASCII.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (org-ascii--justify-element contents property-drawer info)))
+
+
+;;;; Quote Block
+
+(defun org-ascii-quote-block (_quote-block contents info)
+ "Transcode a QUOTE-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (org-ascii--indent-string contents (plist-get info :ascii-quote-margin)))
+
+
+;;;; Radio Target
+
+(defun org-ascii-radio-target (_radio-target contents _info)
+ "Transcode a RADIO-TARGET object from Org to ASCII.
+CONTENTS is the contents of the target. INFO is a plist holding
+contextual information."
+ contents)
+
+
+;;;; Section
+
+(defun org-ascii-section (section contents info)
+ "Transcode a SECTION element from Org to ASCII.
+CONTENTS is the contents of the section. INFO is a plist holding
+contextual information."
+ (let ((links
+ (and (plist-get info :ascii-links-to-notes)
+ ;; Take care of links in first section of the document.
+ (not (org-element-lineage section '(headline)))
+ (org-ascii--describe-links
+ (org-ascii--unique-links section info)
+ (org-ascii--current-text-width section info)
+ info))))
+ (org-ascii--indent-string
+ (if (not (org-string-nw-p links)) contents
+ (concat (org-element-normalize-string contents) "\n\n" links))
+ ;; Do not apply inner margin if parent headline is low level.
+ (let ((headline (org-export-get-parent-headline section)))
+ (if (or (not headline) (org-export-low-level-p headline info)) 0
+ (plist-get info :ascii-inner-margin))))))
+
+
+;;;; Special Block
+
+(defun org-ascii-special-block (_special-block contents _info)
+ "Transcode a SPECIAL-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ ;; "JUSTIFYLEFT" and "JUSTFYRIGHT" have already been taken care of
+ ;; at a lower level. There is no other special block type to
+ ;; handle.
+ contents)
+
+
+;;;; Src Block
+
+(defun org-ascii-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to ASCII.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let ((caption (org-ascii--build-caption src-block info))
+ (caption-above-p (plist-get info :ascii-caption-above))
+ (code (org-export-format-code-default src-block info)))
+ (if (equal code "") ""
+ (org-ascii--justify-element
+ (concat
+ (and caption caption-above-p (concat caption "\n"))
+ (org-ascii--box-string code info)
+ (and caption (not caption-above-p) (concat "\n" caption)))
+ src-block info))))
+
+
+;;;; Statistics Cookie
+
+(defun org-ascii-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-element-property :value statistics-cookie))
+
+
+;;;; Subscript
+
+(defun org-ascii-subscript (subscript contents _info)
+ "Transcode a SUBSCRIPT object from Org to ASCII.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (if (org-element-property :use-brackets-p subscript)
+ (format "_{%s}" contents)
+ (format "_%s" contents)))
+
+
+;;;; Superscript
+
+(defun org-ascii-superscript (superscript contents _info)
+ "Transcode a SUPERSCRIPT object from Org to ASCII.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (if (org-element-property :use-brackets-p superscript)
+ (format "^{%s}" contents)
+ (format "^%s" contents)))
+
+
+;;;; Strike-through
+
+(defun org-ascii-strike-through (_strike-through contents _info)
+ "Transcode STRIKE-THROUGH from Org to ASCII.
+CONTENTS is text with strike-through markup. INFO is a plist
+holding contextual information."
+ (format "+%s+" contents))
+
+
+;;;; Table
+
+(defun org-ascii-table (table contents info)
+ "Transcode a TABLE element from Org to ASCII.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (let ((caption (org-ascii--build-caption table info))
+ (caption-above-p (plist-get info :ascii-caption-above)))
+ (org-ascii--justify-element
+ (concat
+ ;; Possibly add a caption string above.
+ (and caption caption-above-p (concat caption "\n"))
+ ;; Insert table. Note: "table.el" tables are left unmodified.
+ (cond ((eq (org-element-property :type table) 'org) contents)
+ ((and (plist-get info :ascii-table-use-ascii-art)
+ (eq (plist-get info :ascii-charset) 'utf-8)
+ (require 'ascii-art-to-unicode nil t))
+ (with-temp-buffer
+ (insert (org-remove-indentation
+ (org-element-property :value table)))
+ (goto-char (point-min))
+ (aa2u)
+ (goto-char (point-max))
+ (skip-chars-backward " \r\t\n")
+ (buffer-substring (point-min) (point))))
+ (t (org-remove-indentation (org-element-property :value table))))
+ ;; Possible add a caption string below.
+ (and (not caption-above-p) caption))
+ table info)))
+
+
+;;;; Table Cell
+
+(defun org-ascii--table-cell-width (table-cell info)
+ "Return width of TABLE-CELL.
+
+INFO is a plist used as a communication channel.
+
+Width of a cell is determined either by a width cookie in the
+same column as the cell, or by the maximum cell's length in that
+column.
+
+When `org-ascii-table-widen-columns' is non-nil, width cookies
+are ignored."
+ (let* ((row (org-export-get-parent table-cell))
+ (table (org-export-get-parent row))
+ (col (let ((cells (org-element-contents row)))
+ (- (length cells) (length (memq table-cell cells)))))
+ (cache
+ (or (plist-get info :ascii-table-cell-width-cache)
+ (plist-get (setq info
+ (plist-put info :ascii-table-cell-width-cache
+ (make-hash-table :test 'equal)))
+ :ascii-table-cell-width-cache)))
+ (key (cons table col))
+ (widenp (plist-get info :ascii-table-widen-columns)))
+ (or (gethash key cache)
+ (puthash
+ key
+ (let ((cookie-width (org-export-table-cell-width table-cell info)))
+ (or (and (not widenp) cookie-width)
+ (let ((contents-width
+ (let ((max-width 0))
+ (org-element-map table 'table-row
+ (lambda (row)
+ (setq max-width
+ (max (string-width
+ (org-export-data
+ (org-element-contents
+ (elt (org-element-contents row) col))
+ info))
+ max-width)))
+ info)
+ max-width)))
+ (cond ((not cookie-width) contents-width)
+ (widenp (max cookie-width contents-width))
+ (t cookie-width)))))
+ cache))))
+
+(defun org-ascii-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL object from Org to ASCII.
+CONTENTS is the cell contents. INFO is a plist used as
+a communication channel."
+ ;; Determine column width. When `org-ascii-table-widen-columns'
+ ;; is nil and some width cookie has set it, use that value.
+ ;; Otherwise, compute the maximum width among transcoded data of
+ ;; each cell in the column.
+ (let ((width (org-ascii--table-cell-width table-cell info)))
+ ;; When contents are too large, truncate them.
+ (unless (or (plist-get info :ascii-table-widen-columns)
+ (<= (string-width (or contents "")) width))
+ (setq contents (concat (substring contents 0 (- width 2)) "=>")))
+ ;; Align contents correctly within the cell.
+ (let* ((indent-tabs-mode nil)
+ (data
+ (when contents
+ (org-ascii--justify-lines
+ contents width
+ (org-export-table-cell-alignment table-cell info)))))
+ (setq contents
+ (concat data
+ (make-string (- width (string-width (or data ""))) ?\s))))
+ ;; Return cell.
+ (concat (format " %s " contents)
+ (when (memq 'right (org-export-table-cell-borders table-cell info))
+ (if (eq (plist-get info :ascii-charset) 'utf-8) "│" "|")))))
+
+
+;;;; Table Row
+
+(defun org-ascii-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to ASCII.
+CONTENTS is the row contents. INFO is a plist used as
+a communication channel."
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let ((build-hline
+ (function
+ (lambda (lcorner horiz vert rcorner)
+ (concat
+ (apply
+ 'concat
+ (org-element-map table-row 'table-cell
+ (lambda (cell)
+ (let ((width (org-ascii--table-cell-width cell info))
+ (borders (org-export-table-cell-borders cell info)))
+ (concat
+ ;; In order to know if CELL starts the row, do
+ ;; not compare it with the first cell in the
+ ;; row as there might be a special column.
+ ;; Instead, compare it with first exportable
+ ;; cell, obtained with `org-element-map'.
+ (when (and (memq 'left borders)
+ (eq (org-element-map table-row 'table-cell
+ 'identity info t)
+ cell))
+ lcorner)
+ (make-string (+ 2 width) (string-to-char horiz))
+ (cond
+ ((not (memq 'right borders)) nil)
+ ((eq (car (last (org-element-contents table-row))) cell)
+ rcorner)
+ (t vert)))))
+ info)) "\n"))))
+ (utf8p (eq (plist-get info :ascii-charset) 'utf-8))
+ (borders (org-export-table-cell-borders
+ (org-element-map table-row 'table-cell 'identity info t)
+ info)))
+ (concat (cond
+ ((and (memq 'top borders) (or utf8p (memq 'above borders)))
+ (if utf8p (funcall build-hline "┍" "━" "┯" "┑")
+ (funcall build-hline "+" "-" "+" "+")))
+ ((memq 'above borders)
+ (if utf8p (funcall build-hline "├" "─" "┼" "┤")
+ (funcall build-hline "+" "-" "+" "+"))))
+ (when (memq 'left borders) (if utf8p "│" "|"))
+ contents "\n"
+ (when (and (memq 'bottom borders) (or utf8p (memq 'below borders)))
+ (if utf8p (funcall build-hline "┕" "━" "┷" "┙")
+ (funcall build-hline "+" "-" "+" "+")))))))
+
+
+;;;; Timestamp
+
+(defun org-ascii-timestamp (timestamp _contents info)
+ "Transcode a TIMESTAMP object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-ascii-plain-text (org-timestamp-translate timestamp) info))
+
+
+;;;; Underline
+
+(defun org-ascii-underline (_underline contents _info)
+ "Transcode UNDERLINE from Org to ASCII.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (format "_%s_" contents))
+
+
+;;;; Verbatim
+
+(defun org-ascii-verbatim (verbatim _contents info)
+ "Return a VERBATIM object from Org to ASCII.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (format (plist-get info :ascii-verbatim-format)
+ (org-element-property :value verbatim)))
+
+
+;;;; Verse Block
+
+(defun org-ascii-verse-block (verse-block contents info)
+ "Transcode a VERSE-BLOCK element from Org to ASCII.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (org-ascii--indent-string
+ (org-ascii--justify-element contents verse-block info)
+ (plist-get info :ascii-quote-margin)))
+
+
+
+;;; Filters
+
+(defun org-ascii-filter-headline-blank-lines (headline _backend info)
+ "Filter controlling number of blank lines after a headline.
+
+HEADLINE is a string representing a transcoded headline. BACKEND
+is symbol specifying back-end used for export. INFO is plist
+containing the communication channel.
+
+This function only applies to `ascii' back-end. See
+`org-ascii-headline-spacing' for information."
+ (let ((headline-spacing (plist-get info :ascii-headline-spacing)))
+ (if (not headline-spacing) headline
+ (let ((blanks (make-string (1+ (cdr headline-spacing)) ?\n)))
+ (replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" blanks headline)))))
+
+(defun org-ascii-filter-paragraph-spacing (tree _backend info)
+ "Filter controlling number of blank lines between paragraphs.
+
+TREE is the parse tree. BACKEND is the symbol specifying
+back-end used for export. INFO is a plist used as
+a communication channel.
+
+See `org-ascii-paragraph-spacing' for information."
+ (let ((paragraph-spacing (plist-get info :ascii-paragraph-spacing)))
+ (when (wholenump paragraph-spacing)
+ (org-element-map tree 'paragraph
+ (lambda (p)
+ (when (eq (org-element-type (org-export-get-next-element p info))
+ 'paragraph)
+ (org-element-put-property p :post-blank paragraph-spacing))))))
+ tree)
+
+(defun org-ascii-filter-comment-spacing (tree _backend info)
+ "Filter removing blank lines between comments.
+TREE is the parse tree. BACKEND is the symbol specifying
+back-end used for export. INFO is a plist used as
+a communication channel."
+ (org-element-map tree '(comment comment-block)
+ (lambda (c)
+ (when (memq (org-element-type (org-export-get-next-element c info))
+ '(comment comment-block))
+ (org-element-put-property c :post-blank 0))))
+ tree)
+
+
+
+;;; End-user functions
+
+;;;###autoload
+(defun org-ascii-export-as-ascii
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a text buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip title and
+table of contents from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org ASCII Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'ascii "*Org ASCII Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (text-mode))))
+
+;;;###autoload
+(defun org-ascii-export-to-ascii
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a text file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip title and
+table of contents from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((file (org-export-output-file-name ".txt" subtreep)))
+ (org-export-to-file 'ascii file
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-ascii-publish-to-ascii (plist filename pub-dir)
+ "Publish an Org file to ASCII.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to
+ 'ascii filename ".txt" `(:ascii-charset ascii ,@plist) pub-dir))
+
+;;;###autoload
+(defun org-ascii-publish-to-latin1 (plist filename pub-dir)
+ "Publish an Org file to Latin-1.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to
+ 'ascii filename ".txt" `(:ascii-charset latin1 ,@plist) pub-dir))
+
+;;;###autoload
+(defun org-ascii-publish-to-utf8 (plist filename pub-dir)
+ "Publish an org file to UTF-8.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to
+ 'ascii filename ".txt" `(:ascii-charset utf-8 ,@plist) pub-dir))
+
+
+(provide 'ox-ascii)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; coding: utf-8
+;; End:
+
+;;; ox-ascii.el ends here
diff --git a/lisp/ox-beamer.el b/lisp/ox-beamer.el
new file mode 100644
index 0000000..82651d3
--- /dev/null
+++ b/lisp/ox-beamer.el
@@ -0,0 +1,1141 @@
+;;; ox-beamer.el --- Beamer Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten.dominik AT gmail DOT com>
+;; Nicolas Goaziou <n.goaziou AT gmail DOT com>
+;; Keywords: org, wp, tex
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements both a Beamer back-end, derived from the
+;; LaTeX one and a minor mode easing structure edition of the
+;; document. See Org manual for more information.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox-latex)
+
+;; Install a default set-up for Beamer export.
+(unless (assoc "beamer" org-latex-classes)
+ (add-to-list 'org-latex-classes
+ '("beamer"
+ "\\documentclass[presentation]{beamer}"
+ ("\\section{%s}" . "\\section*{%s}")
+ ("\\subsection{%s}" . "\\subsection*{%s}")
+ ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))))
+
+
+
+;;; User-Configurable Variables
+
+(defgroup org-export-beamer nil
+ "Options specific for using the beamer class in LaTeX export."
+ :tag "Org Beamer"
+ :group 'org-export
+ :version "24.2")
+
+(defcustom org-beamer-frame-level 1
+ "The level at which headlines become frames.
+
+Headlines at a lower level will be translated into a sectioning
+structure. At a higher level, they will be translated into
+blocks.
+
+If a headline with a \"BEAMER_env\" property set to \"frame\" is
+found within a tree, its level locally overrides this number.
+
+This variable has no effect on headlines with the \"BEAMER_env\"
+property set to either \"ignoreheading\", \"appendix\", or
+\"note\", which will respectively, be invisible, become an
+appendix or a note.
+
+This integer is relative to the minimal level of a headline
+within the parse tree, defined as 1."
+ :group 'org-export-beamer
+ :type 'integer)
+
+(defcustom org-beamer-frame-default-options ""
+ "Default options string to use for frames.
+For example, it could be set to \"allowframebreaks\"."
+ :group 'org-export-beamer
+ :type '(string :tag "[options]"))
+
+(defcustom org-beamer-column-view-format
+ "%45ITEM %10BEAMER_env(Env) %10BEAMER_act(Act) %4BEAMER_col(Col) %8BEAMER_opt(Opt)"
+ "Column view format that should be used to fill the template."
+ :group 'org-export-beamer
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Do not insert Beamer column view format" nil)
+ (string :tag "Beamer column view format")))
+
+(defcustom org-beamer-theme "default"
+ "Default theme used in Beamer presentations."
+ :group 'org-export-beamer
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Do not insert a Beamer theme" nil)
+ (string :tag "Beamer theme")))
+
+(defcustom org-beamer-environments-extra nil
+ "Environments triggered by tags in Beamer export.
+Each entry has 4 elements:
+
+name Name of the environment
+key Selection key for `org-beamer-select-environment'
+open The opening template for the environment, with the following escapes
+ %a the action/overlay specification
+ %A the default action/overlay specification
+ %R the raw BEAMER_act value
+ %o the options argument, with square brackets
+ %O the raw BEAMER_opt value
+ %h the headline text
+ %r the raw headline text (i.e. without any processing)
+ %H if there is headline text, that raw text in {} braces
+ %U if there is headline text, that raw text in [] brackets
+close The closing string of the environment."
+ :group 'org-export-beamer
+ :version "24.4"
+ :package-version '(Org . "8.1")
+ :type '(repeat
+ (list
+ (string :tag "Environment")
+ (string :tag "Selection key")
+ (string :tag "Begin")
+ (string :tag "End"))))
+
+(defcustom org-beamer-outline-frame-title "Outline"
+ "Default title of a frame containing an outline."
+ :group 'org-export-beamer
+ :type '(string :tag "Outline frame title"))
+
+(defcustom org-beamer-outline-frame-options ""
+ "Outline frame options appended after \\begin{frame}.
+You might want to put e.g. \"allowframebreaks=0.9\" here."
+ :group 'org-export-beamer
+ :type '(string :tag "Outline frame options"))
+
+
+(defcustom org-beamer-subtitle-format "\\subtitle{%s}"
+ "Format string used for transcoded subtitle.
+The format string should have at most one \"%s\"-expression,
+which is replaced with the subtitle."
+ :group 'org-export-beamer
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(string :tag "Format string"))
+
+
+;;; Internal Variables
+
+(defconst org-beamer-column-widths
+ "0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.0 :ETC"
+"The column widths that should be installed as allowed property values.")
+
+(defconst org-beamer-environments-special
+ '(("againframe" "A")
+ ("appendix" "x")
+ ("column" "c")
+ ("columns" "C")
+ ("frame" "f")
+ ("fullframe" "F")
+ ("ignoreheading" "i")
+ ("note" "n")
+ ("noteNH" "N"))
+ "Alist of environments treated in a special way by the back-end.
+Keys are environment names, as strings, values are bindings used
+in `org-beamer-select-environment'. Environments listed here,
+along with their binding, are hard coded and cannot be modified
+through `org-beamer-environments-extra' variable.")
+
+(defconst org-beamer-environments-default
+ '(("block" "b" "\\begin{block}%a{%h}" "\\end{block}")
+ ("alertblock" "a" "\\begin{alertblock}%a{%h}" "\\end{alertblock}")
+ ("verse" "v" "\\begin{verse}%a %% %h" "\\end{verse}")
+ ("quotation" "q" "\\begin{quotation}%a %% %h" "\\end{quotation}")
+ ("quote" "Q" "\\begin{quote}%a %% %h" "\\end{quote}")
+ ("structureenv" "s" "\\begin{structureenv}%a %% %h" "\\end{structureenv}")
+ ("theorem" "t" "\\begin{theorem}%a%U" "\\end{theorem}")
+ ("definition" "d" "\\begin{definition}%a%U" "\\end{definition}")
+ ("example" "e" "\\begin{example}%a%U" "\\end{example}")
+ ("exampleblock" "E" "\\begin{exampleblock}%a{%h}" "\\end{exampleblock}")
+ ("proof" "p" "\\begin{proof}%a%U" "\\end{proof}")
+ ("beamercolorbox" "o" "\\begin{beamercolorbox}%o{%h}" "\\end{beamercolorbox}"))
+ "Environments triggered by properties in Beamer export.
+These are the defaults - for user definitions, see
+`org-beamer-environments-extra'.")
+
+(defconst org-beamer-verbatim-elements
+ '(code example-block fixed-width inline-src-block src-block verbatim)
+ "List of element or object types producing verbatim text.
+This is used internally to determine when a frame should have the
+\"fragile\" option.")
+
+
+
+;;; Internal functions
+
+(defun org-beamer--normalize-argument (argument type)
+ "Return ARGUMENT string with proper boundaries.
+
+TYPE is a symbol among the following:
+`action' Return ARGUMENT within angular brackets.
+`defaction' Return ARGUMENT within both square and angular brackets.
+`option' Return ARGUMENT within square brackets."
+ (if (not (string-match "\\S-" argument)) ""
+ (cl-case type
+ (action (format "<%s>" (org-unbracket-string "<" ">" argument)))
+ (defaction
+ (format "[<%s>]"
+ (org-unbracket-string "<" ">" (org-unbracket-string "[" "]" argument))))
+ (option (format "[%s]" (org-unbracket-string "[" "]" argument)))
+ (otherwise (error "Invalid `type' argument to `org-beamer--normalize-argument': %s"
+ type)))))
+
+(defun org-beamer--element-has-overlay-p (element)
+ "Non-nil when ELEMENT has an overlay specified.
+An element has an overlay specification when it starts with an
+`beamer' export-snippet whose value is between angular brackets.
+Return overlay specification, as a string, or nil."
+ (let ((first-object (car (org-element-contents element))))
+ (when (eq (org-element-type first-object) 'export-snippet)
+ (let ((value (org-element-property :value first-object)))
+ (and (string-prefix-p "<" value) (string-suffix-p ">" value)
+ value)))))
+
+
+
+;;; Define Back-End
+
+(org-export-define-derived-backend 'beamer 'latex
+ :menu-entry
+ '(?l 1
+ ((?B "As LaTeX buffer (Beamer)" org-beamer-export-as-latex)
+ (?b "As LaTeX file (Beamer)" org-beamer-export-to-latex)
+ (?P "As PDF file (Beamer)" org-beamer-export-to-pdf)
+ (?O "As PDF file and open (Beamer)"
+ (lambda (a s v b)
+ (if a (org-beamer-export-to-pdf t s v b)
+ (org-open-file (org-beamer-export-to-pdf nil s v b)))))))
+ :options-alist
+ '((:headline-levels nil "H" org-beamer-frame-level)
+ (:latex-class "LATEX_CLASS" nil "beamer" t)
+ (:beamer-subtitle-format nil nil org-beamer-subtitle-format)
+ (:beamer-column-view-format "COLUMNS" nil org-beamer-column-view-format)
+ (:beamer-theme "BEAMER_THEME" nil org-beamer-theme)
+ (:beamer-color-theme "BEAMER_COLOR_THEME" nil nil t)
+ (:beamer-font-theme "BEAMER_FONT_THEME" nil nil t)
+ (:beamer-inner-theme "BEAMER_INNER_THEME" nil nil t)
+ (:beamer-outer-theme "BEAMER_OUTER_THEME" nil nil t)
+ (:beamer-header "BEAMER_HEADER" nil nil newline)
+ (:beamer-environments-extra nil nil org-beamer-environments-extra)
+ (:beamer-frame-default-options nil nil org-beamer-frame-default-options)
+ (:beamer-outline-frame-options nil nil org-beamer-outline-frame-options)
+ (:beamer-outline-frame-title nil nil org-beamer-outline-frame-title))
+ :translate-alist '((bold . org-beamer-bold)
+ (export-block . org-beamer-export-block)
+ (export-snippet . org-beamer-export-snippet)
+ (headline . org-beamer-headline)
+ (item . org-beamer-item)
+ (keyword . org-beamer-keyword)
+ (link . org-beamer-link)
+ (plain-list . org-beamer-plain-list)
+ (radio-target . org-beamer-radio-target)
+ (template . org-beamer-template)))
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-beamer-bold (bold contents _info)
+ "Transcode BLOCK object into Beamer code.
+CONTENTS is the text being bold. INFO is a plist used as
+a communication channel."
+ (format "\\alert%s{%s}"
+ (or (org-beamer--element-has-overlay-p bold) "")
+ contents))
+
+
+;;;; Export Block
+
+(defun org-beamer-export-block (export-block _contents _info)
+ "Transcode an EXPORT-BLOCK element into Beamer code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (when (member (org-element-property :type export-block) '("BEAMER" "LATEX"))
+ (org-remove-indentation (org-element-property :value export-block))))
+
+
+;;;; Export Snippet
+
+(defun org-beamer-export-snippet (export-snippet _contents info)
+ "Transcode an EXPORT-SNIPPET object into Beamer code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((backend (org-export-snippet-backend export-snippet))
+ (value (org-element-property :value export-snippet)))
+ ;; Only "latex" and "beamer" snippets are retained.
+ (cond ((eq backend 'latex) value)
+ ;; Ignore "beamer" snippets specifying overlays.
+ ((and (eq backend 'beamer)
+ (or (org-export-get-previous-element export-snippet info)
+ (not (string-match "\\`<.*>\\'" value))))
+ value))))
+
+
+;;;; Headline
+;;
+;; The main function to translate a headline is
+;; `org-beamer-headline'.
+;;
+;; Depending on the level at which a headline is considered as
+;; a frame (given by `org-beamer--frame-level'), the headline is
+;; either a section (`org-beamer--format-section'), a frame
+;; (`org-beamer--format-frame') or a block
+;; (`org-beamer--format-block').
+;;
+;; `org-beamer-headline' also takes care of special environments
+;; like "ignoreheading", "note", "noteNH", "appendix" and
+;; "againframe".
+
+(defun org-beamer--get-label (headline info)
+ "Return label for HEADLINE, as a string.
+
+INFO is a plist used as a communication channel.
+
+The value is either the label specified in \"BEAMER_opt\"
+property, the custom ID, if there is one and
+`:latex-prefer-user-labels' property has a non nil value, or
+a unique internal label. This function assumes HEADLINE will be
+treated as a frame."
+ (cond
+ ((let ((opt (org-element-property :BEAMER_OPT headline)))
+ (and (stringp opt)
+ (string-match "\\(?:^\\|,\\)label=\\(.*?\\)\\(?:$\\|,\\)" opt)
+ (let ((label (match-string 1 opt)))
+ (if (string-match-p "\\`{.*}\\'" label)
+ (substring label 1 -1)
+ label)))))
+ ((and (plist-get info :latex-prefer-user-labels)
+ (org-element-property :CUSTOM_ID headline)))
+ (t (format "sec:%s" (org-export-get-reference headline info)))))
+
+(defun org-beamer--frame-level (headline info)
+ "Return frame level in subtree containing HEADLINE.
+INFO is a plist used as a communication channel."
+ (or
+ ;; 1. Look for "frame" environment in parents, starting from the
+ ;; farthest.
+ (catch 'exit
+ (dolist (parent (nreverse (org-element-lineage headline)))
+ (let ((env (org-element-property :BEAMER_ENV parent)))
+ (when (and env (member-ignore-case env '("frame" "fullframe")))
+ (throw 'exit (org-export-get-relative-level parent info))))))
+ ;; 2. Look for "frame" environment in HEADLINE.
+ (let ((env (org-element-property :BEAMER_ENV headline)))
+ (and env (member-ignore-case env '("frame" "fullframe"))
+ (org-export-get-relative-level headline info)))
+ ;; 3. Look for "frame" environment in sub-tree.
+ (org-element-map headline 'headline
+ (lambda (hl)
+ (let ((env (org-element-property :BEAMER_ENV hl)))
+ (when (and env (member-ignore-case env '("frame" "fullframe")))
+ (org-export-get-relative-level hl info))))
+ info 'first-match)
+ ;; 4. No "frame" environment in tree: use default value.
+ (plist-get info :headline-levels)))
+
+(defun org-beamer--format-section (headline contents info)
+ "Format HEADLINE as a sectioning part.
+CONTENTS holds the contents of the headline. INFO is a plist
+used as a communication channel."
+ (let ((latex-headline
+ (org-export-with-backend
+ ;; We create a temporary export back-end which behaves the
+ ;; same as current one, but adds "\protect" in front of the
+ ;; output of some objects.
+ (org-export-create-backend
+ :parent 'latex
+ :transcoders
+ (let ((protected-output
+ (function
+ (lambda (object contents info)
+ (let ((code (org-export-with-backend
+ 'beamer object contents info)))
+ (if (org-string-nw-p code) (concat "\\protect" code)
+ code))))))
+ (mapcar #'(lambda (type) (cons type protected-output))
+ '(bold footnote-reference italic strike-through timestamp
+ underline))))
+ headline
+ contents
+ info))
+ (mode-specs (org-element-property :BEAMER_ACT headline)))
+ (if (and mode-specs
+ (string-match "\\`\\\\\\(.*?\\)\\(?:\\*\\|\\[.*\\]\\)?{"
+ latex-headline))
+ ;; Insert overlay specifications.
+ (replace-match (concat (match-string 1 latex-headline)
+ (format "<%s>" mode-specs))
+ nil nil latex-headline 1)
+ latex-headline)))
+
+(defun org-beamer--format-frame (headline contents info)
+ "Format HEADLINE as a frame.
+CONTENTS holds the contents of the headline. INFO is a plist
+used as a communication channel."
+ (let ((fragilep
+ ;; FRAGILEP is non-nil when HEADLINE contains an element
+ ;; among `org-beamer-verbatim-elements'.
+ (org-element-map headline org-beamer-verbatim-elements 'identity
+ info 'first-match)))
+ (concat "\\begin{frame}"
+ ;; Overlay specification, if any. When surrounded by
+ ;; square brackets, consider it as a default
+ ;; specification.
+ (let ((action (org-element-property :BEAMER_ACT headline)))
+ (cond
+ ((not action) "")
+ ((string-match "\\`\\[.*\\]\\'" action )
+ (org-beamer--normalize-argument action 'defaction))
+ (t (org-beamer--normalize-argument action 'action))))
+ ;; Options, if any.
+ (let* ((beamer-opt (org-element-property :BEAMER_OPT headline))
+ (options
+ ;; Collect options from default value and headline's
+ ;; properties. Also add a label for links.
+ (append
+ (org-split-string
+ (plist-get info :beamer-frame-default-options) ",")
+ (and beamer-opt
+ (org-split-string
+ ;; Remove square brackets if user provided
+ ;; them.
+ (and (string-match "^\\[?\\(.*\\)\\]?$" beamer-opt)
+ (match-string 1 beamer-opt))
+ ","))
+ ;; Provide an automatic label for the frame
+ ;; unless the user specified one. Also refrain
+ ;; from labeling `allowframebreaks' frames; this
+ ;; is not allowed by beamer.
+ (unless (and beamer-opt
+ (or (string-match "\\(^\\|,\\)label=" beamer-opt)
+ (string-match "allowframebreaks" beamer-opt)))
+ (list
+ (let ((label (org-beamer--get-label headline info)))
+ ;; Labels containing colons need to be
+ ;; wrapped within braces.
+ (format (if (string-match-p ":" label)
+ "label={%s}"
+ "label=%s")
+ label)))))))
+ ;; Change options list into a string.
+ (org-beamer--normalize-argument
+ (mapconcat
+ 'identity
+ (if (or (not fragilep) (member "fragile" options)) options
+ (cons "fragile" options))
+ ",")
+ 'option))
+ ;; Title.
+ (let ((env (org-element-property :BEAMER_ENV headline)))
+ (format "{%s}"
+ (if (and env (equal (downcase env) "fullframe")) ""
+ (org-export-data
+ (org-element-property :title headline) info))))
+ "\n"
+ ;; The following workaround is required in fragile frames
+ ;; as Beamer will append "\par" to the beginning of the
+ ;; contents. So we need to make sure the command is
+ ;; separated from the contents by at least one space. If
+ ;; it isn't, it will create "\parfirst-word" command and
+ ;; remove the first word from the contents in the PDF
+ ;; output.
+ (if (not fragilep) contents
+ (replace-regexp-in-string "\\`\n*" "\\& " (or contents "")))
+ "\\end{frame}")))
+
+(defun org-beamer--format-block (headline contents info)
+ "Format HEADLINE as a block.
+CONTENTS holds the contents of the headline. INFO is a plist
+used as a communication channel."
+ (let* ((column-width (org-element-property :BEAMER_COL headline))
+ ;; ENVIRONMENT defaults to "block" if none is specified and
+ ;; there is no column specification. If there is a column
+ ;; specified but still no explicit environment, ENVIRONMENT
+ ;; is "column".
+ (environment (let ((env (org-element-property :BEAMER_ENV headline)))
+ (cond
+ ;; "block" is the fallback environment.
+ ((and (not env) (not column-width)) "block")
+ ;; "column" only.
+ ((not env) "column")
+ ;; Use specified environment.
+ (t env))))
+ (raw-title (org-element-property :raw-value headline))
+ (env-format
+ (cond ((member environment '("column" "columns")) nil)
+ ((assoc environment
+ (append (plist-get info :beamer-environments-extra)
+ org-beamer-environments-default)))
+ (t (user-error "Wrong block type at a headline named \"%s\""
+ raw-title))))
+ (title (org-export-data (org-element-property :title headline) info))
+ (raw-options (org-element-property :BEAMER_OPT headline))
+ (options (if raw-options
+ (org-beamer--normalize-argument raw-options 'option)
+ ""))
+ ;; Start a "columns" environment when explicitly requested or
+ ;; when there is no previous headline or the previous
+ ;; headline do not have a BEAMER_column property.
+ (parent-env (org-element-property
+ :BEAMER_ENV (org-export-get-parent-headline headline)))
+ (start-columns-p
+ (or (equal environment "columns")
+ (and column-width
+ (not (and parent-env
+ (equal (downcase parent-env) "columns")))
+ (or (org-export-first-sibling-p headline info)
+ (not (org-element-property
+ :BEAMER_COL
+ (org-export-get-previous-element
+ headline info)))))))
+ ;; End the "columns" environment when explicitly requested or
+ ;; when there is no next headline or the next headline do not
+ ;; have a BEAMER_column property.
+ (end-columns-p
+ (or (equal environment "columns")
+ (and column-width
+ (not (and parent-env
+ (equal (downcase parent-env) "columns")))
+ (or (org-export-last-sibling-p headline info)
+ (not (org-element-property
+ :BEAMER_COL
+ (org-export-get-next-element headline info))))))))
+ (concat
+ (when start-columns-p
+ ;; Column can accept options only when the environment is
+ ;; explicitly defined.
+ (if (not (equal environment "columns")) "\\begin{columns}\n"
+ (format "\\begin{columns}%s\n" options)))
+ (when column-width
+ (format "\\begin{column}%s{%s}\n"
+ ;; One can specify placement for column only when
+ ;; HEADLINE stands for a column on its own.
+ (if (equal environment "column") options "")
+ (format "%s\\columnwidth" column-width)))
+ ;; Block's opening string.
+ (when (nth 2 env-format)
+ (concat
+ (org-fill-template
+ (nth 2 env-format)
+ (nconc
+ ;; If BEAMER_act property has its value enclosed in square
+ ;; brackets, it is a default overlay specification and
+ ;; overlay specification is empty. Otherwise, it is an
+ ;; overlay specification and the default one is nil.
+ (let ((action (org-element-property :BEAMER_ACT headline)))
+ (cond
+ ((not action) (list (cons "a" "") (cons "A" "") (cons "R" "")))
+ ((and (string-prefix-p "[" action)
+ (string-suffix-p "]" action))
+ (list
+ (cons "A" (org-beamer--normalize-argument action 'defaction))
+ (cons "a" "")
+ (cons "R" action)))
+ (t
+ (list (cons "a" (org-beamer--normalize-argument action 'action))
+ (cons "A" "")
+ (cons "R" action)))))
+ (list (cons "o" options)
+ (cons "O" (or raw-options ""))
+ (cons "h" title)
+ (cons "r" raw-title)
+ (cons "H" (if (equal raw-title "") ""
+ (format "{%s}" raw-title)))
+ (cons "U" (if (equal raw-title "") ""
+ (format "[%s]" raw-title))))))
+ "\n"))
+ contents
+ ;; Block's closing string, if any.
+ (and (nth 3 env-format) (concat (nth 3 env-format) "\n"))
+ (when column-width "\\end{column}\n")
+ (when end-columns-p "\\end{columns}"))))
+
+(defun org-beamer-headline (headline contents info)
+ "Transcode HEADLINE element into Beamer code.
+CONTENTS is the contents of the headline. INFO is a plist used
+as a communication channel."
+ (unless (org-element-property :footnote-section-p headline)
+ (let ((level (org-export-get-relative-level headline info))
+ (frame-level (org-beamer--frame-level headline info))
+ (environment (let ((env (org-element-property :BEAMER_ENV headline)))
+ (or (org-string-nw-p env) "block"))))
+ (cond
+ ;; Case 1: Resume frame specified by "BEAMER_ref" property.
+ ((equal environment "againframe")
+ (let ((ref (org-element-property :BEAMER_REF headline)))
+ ;; Reference to frame being resumed is mandatory. Ignore
+ ;; the whole headline if it isn't provided.
+ (when (org-string-nw-p ref)
+ (concat "\\againframe"
+ ;; Overlay specification.
+ (let ((overlay (org-element-property :BEAMER_ACT headline)))
+ (when overlay
+ (org-beamer--normalize-argument
+ overlay
+ (if (string-match "\\`\\[.*\\]\\'" overlay) 'defaction
+ 'action))))
+ ;; Options.
+ (let ((options (org-element-property :BEAMER_OPT headline)))
+ (when options
+ (org-beamer--normalize-argument options 'option)))
+ ;; Resolve reference provided by "BEAMER_ref"
+ ;; property. This is done by building a minimal
+ ;; fake link and calling the appropriate resolve
+ ;; function, depending on the reference syntax.
+ (let ((target
+ (if (string-match "\\`\\(id:\\|#\\)" ref)
+ (org-export-resolve-id-link
+ `(link (:path ,(substring ref (match-end 0))))
+ info)
+ (org-export-resolve-fuzzy-link
+ `(link (:path
+ ;; Look for headlines only.
+ ,(if (eq (string-to-char ref) ?*) ref
+ (concat "*" ref))))
+ info))))
+ ;; Now use user-defined label provided in TARGET
+ ;; headline, or fallback to standard one.
+ (format "{%s}" (org-beamer--get-label target info)))))))
+ ;; Case 2: Creation of an appendix is requested.
+ ((equal environment "appendix")
+ (concat "\\appendix"
+ (org-element-property :BEAMER_ACT headline)
+ "\n"
+ (make-string (org-element-property :pre-blank headline) ?\n)
+ contents))
+ ;; Case 3: Ignore heading.
+ ((equal environment "ignoreheading")
+ (concat (make-string (org-element-property :pre-blank headline) ?\n)
+ contents))
+ ;; Case 4: HEADLINE is a note.
+ ((member environment '("note" "noteNH"))
+ (format "\\note{%s}"
+ (concat (and (equal environment "note")
+ (concat
+ (org-export-data
+ (org-element-property :title headline) info)
+ "\n"))
+ (org-trim contents))))
+ ;; Case 5: HEADLINE is a frame.
+ ((= level frame-level)
+ (org-beamer--format-frame headline contents info))
+ ;; Case 6: Regular section, extracted from
+ ;; `org-latex-classes'.
+ ((< level frame-level)
+ (org-beamer--format-section headline contents info))
+ ;; Case 7: Otherwise, HEADLINE is a block.
+ (t (org-beamer--format-block headline contents info))))))
+
+
+;;;; Item
+
+(defun org-beamer-item (item contents info)
+ "Transcode an ITEM element into Beamer code.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (org-export-with-backend
+ ;; Delegate item export to `latex'. However, we use `beamer'
+ ;; transcoders for objects in the description tag.
+ (org-export-create-backend
+ :parent 'beamer
+ :transcoders
+ (list
+ (cons
+ 'item
+ (lambda (item _c _i)
+ (let ((action
+ (let ((first (car (org-element-contents item))))
+ (and (eq (org-element-type first) 'paragraph)
+ (org-beamer--element-has-overlay-p first))))
+ (output (org-latex-item item contents info)))
+ (if (not (and action (string-match "\\\\item" output))) output
+ ;; If the item starts with a paragraph and that paragraph
+ ;; starts with an export snippet specifying an overlay,
+ ;; append it to the \item command.
+ (replace-match (concat "\\\\item" action) nil nil output)))))))
+ item contents info))
+
+
+;;;; Keyword
+
+(defun org-beamer-keyword (keyword contents info)
+ "Transcode a KEYWORD element into Beamer code.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ ;; Handle specifically BEAMER and TOC (headlines only) keywords.
+ ;; Otherwise, fallback to `latex' back-end.
+ (cond
+ ((equal key "BEAMER") value)
+ ((and (equal key "TOC") (string-match "\\<headlines\\>" value))
+ (let ((depth (or (and (string-match "[0-9]+" value)
+ (string-to-number (match-string 0 value)))
+ (plist-get info :with-toc)))
+ (options (and (string-match "\\[.*?\\]" value)
+ (match-string 0 value))))
+ (concat
+ (when (wholenump depth) (format "\\setcounter{tocdepth}{%s}\n" depth))
+ "\\tableofcontents" options)))
+ (t (org-export-with-backend 'latex keyword contents info)))))
+
+
+;;;; Link
+
+(defun org-beamer-link (link contents info)
+ "Transcode a LINK object into Beamer code.
+CONTENTS is the description part of the link. INFO is a plist
+used as a communication channel."
+ (or (org-export-custom-protocol-maybe link contents 'beamer)
+ ;; Fall-back to LaTeX export. However, prefer "\hyperlink" over
+ ;; "\hyperref" since the former handles overlay specifications.
+ (let ((latex-link (org-export-with-backend 'latex link contents info)))
+ (if (string-match "\\`\\\\hyperref\\[\\(.*?\\)\\]" latex-link)
+ (replace-match
+ (format "\\\\hyperlink%s{\\1}"
+ (or (org-beamer--element-has-overlay-p link) ""))
+ nil nil latex-link)
+ latex-link))))
+
+
+;;;; Plain List
+;;
+;; Plain lists support `:environment', `:overlay' and `:options'
+;; attributes.
+
+(defun org-beamer-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element into Beamer code.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let* ((type (org-element-property :type plain-list))
+ (attributes (org-combine-plists
+ (org-export-read-attribute :attr_latex plain-list)
+ (org-export-read-attribute :attr_beamer plain-list)))
+ (latex-type (let ((env (plist-get attributes :environment)))
+ (cond (env)
+ ((eq type 'ordered) "enumerate")
+ ((eq type 'descriptive) "description")
+ (t "itemize")))))
+ (org-latex--wrap-label
+ plain-list
+ (format "\\begin{%s}%s%s\n%s\\end{%s}"
+ latex-type
+ ;; Default overlay specification, if any.
+ (org-beamer--normalize-argument
+ (or (plist-get attributes :overlay) "")
+ 'defaction)
+ ;; Second optional argument depends on the list type.
+ (org-beamer--normalize-argument
+ (or (plist-get attributes :options) "")
+ 'option)
+ ;; Eventually insert contents and close environment.
+ contents
+ latex-type)
+ info)))
+
+
+;;;; Radio Target
+
+(defun org-beamer-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object into Beamer code.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (format "\\hypertarget%s{%s}{%s}"
+ (or (org-beamer--element-has-overlay-p radio-target) "")
+ (org-export-get-reference radio-target info)
+ text))
+
+
+;;;; Template
+;;
+;; Template used is similar to the one used in `latex' back-end,
+;; excepted for the table of contents and Beamer themes.
+
+(defun org-beamer-template (contents info)
+ "Return complete document string after Beamer conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((title (org-export-data (plist-get info :title) info))
+ (subtitle (org-export-data (plist-get info :subtitle) info)))
+ (concat
+ ;; Time-stamp.
+ (and (plist-get info :time-stamp-file)
+ (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
+ ;; LaTeX compiler
+ (org-latex--insert-compiler info)
+ ;; Document class and packages.
+ (org-latex-make-preamble info)
+ ;; Insert themes.
+ (let ((format-theme
+ (function
+ (lambda (prop command)
+ (let ((theme (plist-get info prop)))
+ (when theme
+ (concat command
+ (if (not (string-match "\\[.*\\]" theme))
+ (format "{%s}\n" theme)
+ (format "%s{%s}\n"
+ (match-string 0 theme)
+ (org-trim
+ (replace-match "" nil nil theme)))))))))))
+ (mapconcat (lambda (args) (apply format-theme args))
+ '((:beamer-theme "\\usetheme")
+ (:beamer-color-theme "\\usecolortheme")
+ (:beamer-font-theme "\\usefonttheme")
+ (:beamer-inner-theme "\\useinnertheme")
+ (:beamer-outer-theme "\\useoutertheme"))
+ ""))
+ ;; Possibly limit depth for headline numbering.
+ (let ((sec-num (plist-get info :section-numbers)))
+ (when (integerp sec-num)
+ (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
+ ;; Author.
+ (let ((author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (and (plist-get info :with-email)
+ (org-export-data (plist-get info :email) info))))
+ (cond ((and author email (not (string= "" email)))
+ (format "\\author{%s\\thanks{%s}}\n" author email))
+ ((or author email) (format "\\author{%s}\n" (or author email)))))
+ ;; Date.
+ (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
+ (format "\\date{%s}\n" (org-export-data date info)))
+ ;; Title
+ (format "\\title{%s}\n" title)
+ (when (org-string-nw-p subtitle)
+ (concat (format (plist-get info :beamer-subtitle-format) subtitle) "\n"))
+ ;; Beamer-header
+ (let ((beamer-header (plist-get info :beamer-header)))
+ (when beamer-header
+ (format "%s\n" (plist-get info :beamer-header))))
+ ;; 9. Hyperref options.
+ (let ((template (plist-get info :latex-hyperref-template)))
+ (and (stringp template)
+ (format-spec template (org-latex--format-spec info))))
+ ;; Document start.
+ "\\begin{document}\n\n"
+ ;; Title command.
+ (org-element-normalize-string
+ (cond ((not (plist-get info :with-title)) nil)
+ ((string= "" title) nil)
+ ((not (stringp org-latex-title-command)) nil)
+ ((string-match "\\(?:[^%]\\|^\\)%s"
+ org-latex-title-command)
+ (format org-latex-title-command title))
+ (t org-latex-title-command)))
+ ;; Table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth
+ (concat
+ (format "\\begin{frame}%s{%s}\n"
+ (org-beamer--normalize-argument
+ (plist-get info :beamer-outline-frame-options) 'option)
+ (plist-get info :beamer-outline-frame-title))
+ (when (wholenump depth)
+ (format "\\setcounter{tocdepth}{%d}\n" depth))
+ "\\tableofcontents\n"
+ "\\end{frame}\n\n")))
+ ;; Document's body.
+ contents
+ ;; Creator.
+ (if (plist-get info :with-creator)
+ (concat (plist-get info :creator) "\n")
+ "")
+ ;; Document end.
+ "\\end{document}")))
+
+
+
+;;; Minor Mode
+
+
+(defvar org-beamer-mode-map (make-sparse-keymap)
+ "The keymap for `org-beamer-mode'.")
+(define-key org-beamer-mode-map "\C-c\C-b" 'org-beamer-select-environment)
+
+;;;###autoload
+(define-minor-mode org-beamer-mode
+ "Support for editing Beamer oriented Org mode files."
+ nil " Bm" 'org-beamer-mode-map)
+
+(when (fboundp 'font-lock-add-keywords)
+ (font-lock-add-keywords
+ 'org-mode
+ '((":\\(B_[a-z]+\\|BMCOL\\):" 1 'org-beamer-tag prepend))
+ 'prepend))
+
+(defface org-beamer-tag '((t (:box (:line-width 1 :color grey40))))
+ "The special face for beamer tags."
+ :group 'org-export-beamer)
+
+(defun org-beamer-property-changed (property value)
+ "Track the BEAMER_env property with tags.
+PROPERTY is the name of the modified property. VALUE is its new
+value."
+ (cond
+ ((equal property "BEAMER_env")
+ (save-excursion
+ (org-back-to-heading t)
+ ;; Filter out Beamer-related tags and install environment tag.
+ (let ((tags (cl-remove-if (lambda (x) (string-match "^B_" x))
+ (org-get-tags)))
+ (env-tag (and (org-string-nw-p value) (concat "B_" value))))
+ (org-set-tags-to (if env-tag (cons env-tag tags) tags))
+ (when env-tag (org-toggle-tag env-tag 'on)))))
+ ((equal property "BEAMER_col")
+ (org-toggle-tag "BMCOL" (if (org-string-nw-p value) 'on 'off)))))
+
+(add-hook 'org-property-changed-functions 'org-beamer-property-changed)
+
+(defun org-beamer-allowed-property-values (property)
+ "Supply allowed values for PROPERTY."
+ (cond
+ ((and (equal property "BEAMER_env")
+ (not (org-entry-get nil (concat property "_ALL") 'inherit)))
+ ;; If no allowed values for BEAMER_env have been defined,
+ ;; supply all defined environments
+ (mapcar 'car (append org-beamer-environments-special
+ org-beamer-environments-extra
+ org-beamer-environments-default)))
+ ((and (equal property "BEAMER_col")
+ (not (org-entry-get nil (concat property "_ALL") 'inherit)))
+ ;; If no allowed values for BEAMER_col have been defined,
+ ;; supply some
+ (org-split-string org-beamer-column-widths " "))))
+
+(add-hook 'org-property-allowed-value-functions
+ 'org-beamer-allowed-property-values)
+
+
+
+;;; Commands
+
+;;;###autoload
+(defun org-beamer-export-as-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a Beamer buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org BEAMER Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'beamer "*Org BEAMER Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
+
+;;;###autoload
+(defun org-beamer-export-to-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a Beamer presentation (tex).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((file (org-export-output-file-name ".tex" subtreep)))
+ (org-export-to-file 'beamer file
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-beamer-export-to-pdf
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a Beamer presentation (PDF).
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name."
+ (interactive)
+ (let ((file (org-export-output-file-name ".tex" subtreep)))
+ (org-export-to-file 'beamer file
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))))
+
+;;;###autoload
+(defun org-beamer-select-environment ()
+ "Select the environment to be used by beamer for this entry.
+While this uses (for convenience) a tag selection interface, the
+result of this command will be that the BEAMER_env *property* of
+the entry is set.
+
+In addition to this, the command will also set a tag as a visual
+aid, but the tag does not have any semantic meaning."
+ (interactive)
+ ;; Make sure `org-beamer-environments-special' has a higher
+ ;; priority than `org-beamer-environments-extra'.
+ (let* ((envs (append org-beamer-environments-special
+ org-beamer-environments-extra
+ org-beamer-environments-default))
+ (org-current-tag-alist
+ (append '((:startgroup))
+ (mapcar (lambda (e) (cons (concat "B_" (car e))
+ (string-to-char (nth 1 e))))
+ envs)
+ '((:endgroup))
+ '(("BMCOL" . ?|))))
+ (org-tag-persistent-alist nil)
+ (org-use-fast-tag-selection t)
+ (org-fast-tag-selection-single-key t))
+ (org-set-tags)
+ (let ((tags (or (ignore-errors (org-get-tags-string)) "")))
+ (cond
+ ;; For a column, automatically ask for its width.
+ ((eq org-last-tag-selection-key ?|)
+ (if (string-match ":BMCOL:" tags)
+ (org-set-property "BEAMER_col" (read-string "Column width: "))
+ (org-delete-property "BEAMER_col")))
+ ;; For an "againframe" section, automatically ask for reference
+ ;; to resumed frame and overlay specifications.
+ ((eq org-last-tag-selection-key ?A)
+ (if (equal (org-entry-get nil "BEAMER_env") "againframe")
+ (progn (org-entry-delete nil "BEAMER_env")
+ (org-entry-delete nil "BEAMER_ref")
+ (org-entry-delete nil "BEAMER_act"))
+ (org-entry-put nil "BEAMER_env" "againframe")
+ (org-set-property
+ "BEAMER_ref"
+ (read-string "Frame reference (*Title, #custom-id, id:...): "))
+ (org-set-property "BEAMER_act"
+ (read-string "Overlay specification: "))))
+ ((string-match (concat ":B_\\(" (mapconcat 'car envs "\\|") "\\):") tags)
+ (org-entry-put nil "BEAMER_env" (match-string 1 tags)))
+ (t (org-entry-delete nil "BEAMER_env"))))))
+
+;;;###autoload
+(defun org-beamer-publish-to-latex (plist filename pub-dir)
+ "Publish an Org file to a Beamer presentation (LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'beamer filename ".tex" plist pub-dir))
+
+;;;###autoload
+(defun org-beamer-publish-to-pdf (plist filename pub-dir)
+ "Publish an Org file to a Beamer presentation (PDF, via LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ ;; Unlike to `org-beamer-publish-to-latex', PDF file is generated in
+ ;; working directory and then moved to publishing directory.
+ (org-publish-attachment
+ plist
+ ;; Default directory could be anywhere when this function is
+ ;; called. We ensure it is set to source file directory during
+ ;; compilation so as to not break links to external documents.
+ (let ((default-directory (file-name-directory filename)))
+ (org-latex-compile
+ (org-publish-org-to
+ 'beamer filename ".tex" plist (file-name-directory filename))))
+ pub-dir))
+
+
+(provide 'ox-beamer)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-beamer.el ends here
diff --git a/lisp/ox-html.el b/lisp/ox-html.el
new file mode 100644
index 0000000..9c0ba65
--- /dev/null
+++ b/lisp/ox-html.el
@@ -0,0 +1,3723 @@
+;;; ox-html.el --- HTML Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Jambunathan K <kjambunathan at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a HTML back-end for Org generic exporter.
+;; See Org manual for more information.
+
+;;; Code:
+
+;;; Dependencies
+
+(require 'cl-lib)
+(require 'format-spec)
+(require 'ox)
+(require 'ox-publish)
+(require 'table)
+
+
+;;; Function Declarations
+
+(declare-function org-id-find-id-file "org-id" (id))
+(declare-function htmlize-region "ext:htmlize" (beg end))
+(declare-function mm-url-decode-entities "mm-url" ())
+
+(defvar htmlize-css-name-prefix)
+(defvar htmlize-output-type)
+(defvar htmlize-output-type)
+(defvar htmlize-css-name-prefix)
+
+;;; Define Back-End
+
+(org-export-define-backend 'html
+ '((bold . org-html-bold)
+ (center-block . org-html-center-block)
+ (clock . org-html-clock)
+ (code . org-html-code)
+ (drawer . org-html-drawer)
+ (dynamic-block . org-html-dynamic-block)
+ (entity . org-html-entity)
+ (example-block . org-html-example-block)
+ (export-block . org-html-export-block)
+ (export-snippet . org-html-export-snippet)
+ (fixed-width . org-html-fixed-width)
+ (footnote-definition . org-html-footnote-definition)
+ (footnote-reference . org-html-footnote-reference)
+ (headline . org-html-headline)
+ (horizontal-rule . org-html-horizontal-rule)
+ (inline-src-block . org-html-inline-src-block)
+ (inlinetask . org-html-inlinetask)
+ (inner-template . org-html-inner-template)
+ (italic . org-html-italic)
+ (item . org-html-item)
+ (keyword . org-html-keyword)
+ (latex-environment . org-html-latex-environment)
+ (latex-fragment . org-html-latex-fragment)
+ (line-break . org-html-line-break)
+ (link . org-html-link)
+ (node-property . org-html-node-property)
+ (paragraph . org-html-paragraph)
+ (plain-list . org-html-plain-list)
+ (plain-text . org-html-plain-text)
+ (planning . org-html-planning)
+ (property-drawer . org-html-property-drawer)
+ (quote-block . org-html-quote-block)
+ (radio-target . org-html-radio-target)
+ (section . org-html-section)
+ (special-block . org-html-special-block)
+ (src-block . org-html-src-block)
+ (statistics-cookie . org-html-statistics-cookie)
+ (strike-through . org-html-strike-through)
+ (subscript . org-html-subscript)
+ (superscript . org-html-superscript)
+ (table . org-html-table)
+ (table-cell . org-html-table-cell)
+ (table-row . org-html-table-row)
+ (target . org-html-target)
+ (template . org-html-template)
+ (timestamp . org-html-timestamp)
+ (underline . org-html-underline)
+ (verbatim . org-html-verbatim)
+ (verse-block . org-html-verse-block))
+ :filters-alist '((:filter-options . org-html-infojs-install-script)
+ (:filter-final-output . org-html-final-function))
+ :menu-entry
+ '(?h "Export to HTML"
+ ((?H "As HTML buffer" org-html-export-as-html)
+ (?h "As HTML file" org-html-export-to-html)
+ (?o "As HTML file and open"
+ (lambda (a s v b)
+ (if a (org-html-export-to-html t s v b)
+ (org-open-file (org-html-export-to-html nil s v b)))))))
+ :options-alist
+ '((:html-doctype "HTML_DOCTYPE" nil org-html-doctype)
+ (:html-container "HTML_CONTAINER" nil org-html-container-element)
+ (:description "DESCRIPTION" nil nil newline)
+ (:keywords "KEYWORDS" nil nil space)
+ (:html-html5-fancy nil "html5-fancy" org-html-html5-fancy)
+ (:html-link-use-abs-url nil "html-link-use-abs-url" org-html-link-use-abs-url)
+ (:html-link-home "HTML_LINK_HOME" nil org-html-link-home)
+ (:html-link-up "HTML_LINK_UP" nil org-html-link-up)
+ (:html-mathjax "HTML_MATHJAX" nil "" space)
+ (:html-postamble nil "html-postamble" org-html-postamble)
+ (:html-preamble nil "html-preamble" org-html-preamble)
+ (:html-head "HTML_HEAD" nil org-html-head newline)
+ (:html-head-extra "HTML_HEAD_EXTRA" nil org-html-head-extra newline)
+ (:subtitle "SUBTITLE" nil nil parse)
+ (:html-head-include-default-style
+ nil "html-style" org-html-head-include-default-style)
+ (:html-head-include-scripts nil "html-scripts" org-html-head-include-scripts)
+ (:html-allow-name-attribute-in-anchors
+ nil nil org-html-allow-name-attribute-in-anchors)
+ (:html-divs nil nil org-html-divs)
+ (:html-checkbox-type nil nil org-html-checkbox-type)
+ (:html-extension nil nil org-html-extension)
+ (:html-footnote-format nil nil org-html-footnote-format)
+ (:html-footnote-separator nil nil org-html-footnote-separator)
+ (:html-footnotes-section nil nil org-html-footnotes-section)
+ (:html-format-drawer-function nil nil org-html-format-drawer-function)
+ (:html-format-headline-function nil nil org-html-format-headline-function)
+ (:html-format-inlinetask-function
+ nil nil org-html-format-inlinetask-function)
+ (:html-home/up-format nil nil org-html-home/up-format)
+ (:html-indent nil nil org-html-indent)
+ (:html-infojs-options nil nil org-html-infojs-options)
+ (:html-infojs-template nil nil org-html-infojs-template)
+ (:html-inline-image-rules nil nil org-html-inline-image-rules)
+ (:html-link-org-files-as-html nil nil org-html-link-org-files-as-html)
+ (:html-mathjax-options nil nil org-html-mathjax-options)
+ (:html-mathjax-template nil nil org-html-mathjax-template)
+ (:html-metadata-timestamp-format nil nil org-html-metadata-timestamp-format)
+ (:html-postamble-format nil nil org-html-postamble-format)
+ (:html-preamble-format nil nil org-html-preamble-format)
+ (:html-table-align-individual-fields
+ nil nil org-html-table-align-individual-fields)
+ (:html-table-caption-above nil nil org-html-table-caption-above)
+ (:html-table-data-tags nil nil org-html-table-data-tags)
+ (:html-table-header-tags nil nil org-html-table-header-tags)
+ (:html-table-use-header-tags-for-first-column
+ nil nil org-html-table-use-header-tags-for-first-column)
+ (:html-tag-class-prefix nil nil org-html-tag-class-prefix)
+ (:html-text-markup-alist nil nil org-html-text-markup-alist)
+ (:html-todo-kwd-class-prefix nil nil org-html-todo-kwd-class-prefix)
+ (:html-toplevel-hlevel nil nil org-html-toplevel-hlevel)
+ (:html-use-infojs nil nil org-html-use-infojs)
+ (:html-validation-link nil nil org-html-validation-link)
+ (:html-viewport nil nil org-html-viewport)
+ (:html-inline-images nil nil org-html-inline-images)
+ (:html-table-attributes nil nil org-html-table-default-attributes)
+ (:html-table-row-open-tag nil nil org-html-table-row-open-tag)
+ (:html-table-row-close-tag nil nil org-html-table-row-close-tag)
+ (:html-xml-declaration nil nil org-html-xml-declaration)
+ (:infojs-opt "INFOJS_OPT" nil nil)
+ ;; Redefine regular options.
+ (:creator "CREATOR" nil org-html-creator-string)
+ (:with-latex nil "tex" org-html-with-latex)
+ ;; Retrieve LaTeX header for fragments.
+ (:latex-header "LATEX_HEADER" nil nil newline)))
+
+
+;;; Internal Variables
+
+(defvar org-html-format-table-no-css)
+(defvar htmlize-buffer-places) ; from htmlize.el
+
+(defvar org-html--pre/postamble-class "status"
+ "CSS class used for pre/postamble")
+
+(defconst org-html-doctype-alist
+ '(("html4-strict" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"
+\"http://www.w3.org/TR/html4/strict.dtd\">")
+ ("html4-transitional" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
+\"http://www.w3.org/TR/html4/loose.dtd\">")
+ ("html4-frameset" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\"
+\"http://www.w3.org/TR/html4/frameset.dtd\">")
+
+ ("xhtml-strict" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
+\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">")
+ ("xhtml-transitional" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
+\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">")
+ ("xhtml-frameset" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\"
+\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">")
+ ("xhtml-11" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"
+\"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">")
+
+ ("html5" . "<!DOCTYPE html>")
+ ("xhtml5" . "<!DOCTYPE html>"))
+ "An alist mapping (x)html flavors to specific doctypes.")
+
+(defconst org-html-html5-elements
+ '("article" "aside" "audio" "canvas" "details" "figcaption"
+ "figure" "footer" "header" "menu" "meter" "nav" "output"
+ "progress" "section" "video")
+ "New elements in html5.
+
+For blocks that should contain headlines, use the HTML_CONTAINER
+property on the headline itself.")
+
+(defconst org-html-special-string-regexps
+ '(("\\\\-" . "&#x00ad;") ; shy
+ ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
+ ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
+ ("\\.\\.\\." . "&#x2026;")) ; hellip
+ "Regular expressions for special string conversion.")
+
+(defconst org-html-scripts
+ "<script type=\"text/javascript\">
+/*
+@licstart The following is the entire license notice for the
+JavaScript code in this tag.
+
+Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+The JavaScript code in this tag is free software: you can
+redistribute it and/or modify it under the terms of the GNU
+General Public License (GNU GPL) as published by the Free Software
+Foundation, either version 3 of the License, or (at your option)
+any later version. The code is distributed WITHOUT ANY WARRANTY;
+without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
+
+As additional permission under GNU GPL version 3 section 7, you
+may distribute non-source (e.g., minimized or compacted) forms of
+that code without the copy of the GNU GPL normally required by
+section 4, provided you include this license notice and a URL
+through which recipients can access the Corresponding Source.
+
+
+@licend The above is the entire license notice
+for the JavaScript code in this tag.
+*/
+<!--/*--><![CDATA[/*><!--*/
+ function CodeHighlightOn(elem, id)
+ {
+ var target = document.getElementById(id);
+ if(null != target) {
+ elem.cacheClassElem = elem.className;
+ elem.cacheClassTarget = target.className;
+ target.className = \"code-highlighted\";
+ elem.className = \"code-highlighted\";
+ }
+ }
+ function CodeHighlightOff(elem, id)
+ {
+ var target = document.getElementById(id);
+ if(elem.cacheClassElem)
+ elem.className = elem.cacheClassElem;
+ if(elem.cacheClassTarget)
+ target.className = elem.cacheClassTarget;
+ }
+/*]]>*///-->
+</script>"
+ "Basic JavaScript that is needed by HTML files produced by Org mode.")
+
+(defconst org-html-style-default
+ "<style type=\"text/css\">
+ <!--/*--><![CDATA[/*><!--*/
+ .title { text-align: center;
+ margin-bottom: .2em; }
+ .subtitle { text-align: center;
+ font-size: medium;
+ font-weight: bold;
+ margin-top:0; }
+ .todo { font-family: monospace; color: red; }
+ .done { font-family: monospace; color: green; }
+ .priority { font-family: monospace; color: orange; }
+ .tag { background-color: #eee; font-family: monospace;
+ padding: 2px; font-size: 80%; font-weight: normal; }
+ .timestamp { color: #bebebe; }
+ .timestamp-kwd { color: #5f9ea0; }
+ .org-right { margin-left: auto; margin-right: 0px; text-align: right; }
+ .org-left { margin-left: 0px; margin-right: auto; text-align: left; }
+ .org-center { margin-left: auto; margin-right: auto; text-align: center; }
+ .underline { text-decoration: underline; }
+ #postamble p, #preamble p { font-size: 90%; margin: .2em; }
+ p.verse { margin-left: 3%; }
+ pre {
+ border: 1px solid #ccc;
+ box-shadow: 3px 3px 3px #eee;
+ padding: 8pt;
+ font-family: monospace;
+ overflow: auto;
+ margin: 1.2em;
+ }
+ pre.src {
+ position: relative;
+ overflow: visible;
+ padding-top: 1.2em;
+ }
+ pre.src:before {
+ display: none;
+ position: absolute;
+ background-color: white;
+ top: -10px;
+ right: 10px;
+ padding: 3px;
+ border: 1px solid black;
+ }
+ pre.src:hover:before { display: inline;}
+ /* Languages per Org manual */
+ pre.src-asymptote:before { content: 'Asymptote'; }
+ pre.src-awk:before { content: 'Awk'; }
+ pre.src-C:before { content: 'C'; }
+ /* pre.src-C++ doesn't work in CSS */
+ pre.src-clojure:before { content: 'Clojure'; }
+ pre.src-css:before { content: 'CSS'; }
+ pre.src-D:before { content: 'D'; }
+ pre.src-ditaa:before { content: 'ditaa'; }
+ pre.src-dot:before { content: 'Graphviz'; }
+ pre.src-calc:before { content: 'Emacs Calc'; }
+ pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
+ pre.src-fortran:before { content: 'Fortran'; }
+ pre.src-gnuplot:before { content: 'gnuplot'; }
+ pre.src-haskell:before { content: 'Haskell'; }
+ pre.src-java:before { content: 'Java'; }
+ pre.src-js:before { content: 'Javascript'; }
+ pre.src-latex:before { content: 'LaTeX'; }
+ pre.src-ledger:before { content: 'Ledger'; }
+ pre.src-lisp:before { content: 'Lisp'; }
+ pre.src-lilypond:before { content: 'Lilypond'; }
+ pre.src-lua:before { content: 'Lua'; }
+ pre.src-matlab:before { content: 'MATLAB'; }
+ pre.src-mscgen:before { content: 'Mscgen'; }
+ pre.src-ocaml:before { content: 'Objective Caml'; }
+ pre.src-octave:before { content: 'Octave'; }
+ pre.src-org:before { content: 'Org mode'; }
+ pre.src-oz:before { content: 'OZ'; }
+ pre.src-plantuml:before { content: 'Plantuml'; }
+ pre.src-processing:before { content: 'Processing.js'; }
+ pre.src-python:before { content: 'Python'; }
+ pre.src-R:before { content: 'R'; }
+ pre.src-ruby:before { content: 'Ruby'; }
+ pre.src-sass:before { content: 'Sass'; }
+ pre.src-scheme:before { content: 'Scheme'; }
+ pre.src-screen:before { content: 'Gnu Screen'; }
+ pre.src-sed:before { content: 'Sed'; }
+ pre.src-sh:before { content: 'shell'; }
+ pre.src-sql:before { content: 'SQL'; }
+ pre.src-sqlite:before { content: 'SQLite'; }
+ /* additional languages in org.el's org-babel-load-languages alist */
+ pre.src-forth:before { content: 'Forth'; }
+ pre.src-io:before { content: 'IO'; }
+ pre.src-J:before { content: 'J'; }
+ pre.src-makefile:before { content: 'Makefile'; }
+ pre.src-maxima:before { content: 'Maxima'; }
+ pre.src-perl:before { content: 'Perl'; }
+ pre.src-picolisp:before { content: 'Pico Lisp'; }
+ pre.src-scala:before { content: 'Scala'; }
+ pre.src-shell:before { content: 'Shell Script'; }
+ pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
+ /* additional language identifiers per \"defun org-babel-execute\"
+ in ob-*.el */
+ pre.src-cpp:before { content: 'C++'; }
+ pre.src-abc:before { content: 'ABC'; }
+ pre.src-coq:before { content: 'Coq'; }
+ pre.src-groovy:before { content: 'Groovy'; }
+ /* additional language identifiers from org-babel-shell-names in
+ ob-shell.el: ob-shell is the only babel language using a lambda to put
+ the execution function name together. */
+ pre.src-bash:before { content: 'bash'; }
+ pre.src-csh:before { content: 'csh'; }
+ pre.src-ash:before { content: 'ash'; }
+ pre.src-dash:before { content: 'dash'; }
+ pre.src-ksh:before { content: 'ksh'; }
+ pre.src-mksh:before { content: 'mksh'; }
+ pre.src-posh:before { content: 'posh'; }
+ /* Additional Emacs modes also supported by the LaTeX listings package */
+ pre.src-ada:before { content: 'Ada'; }
+ pre.src-asm:before { content: 'Assembler'; }
+ pre.src-caml:before { content: 'Caml'; }
+ pre.src-delphi:before { content: 'Delphi'; }
+ pre.src-html:before { content: 'HTML'; }
+ pre.src-idl:before { content: 'IDL'; }
+ pre.src-mercury:before { content: 'Mercury'; }
+ pre.src-metapost:before { content: 'MetaPost'; }
+ pre.src-modula-2:before { content: 'Modula-2'; }
+ pre.src-pascal:before { content: 'Pascal'; }
+ pre.src-ps:before { content: 'PostScript'; }
+ pre.src-prolog:before { content: 'Prolog'; }
+ pre.src-simula:before { content: 'Simula'; }
+ pre.src-tcl:before { content: 'tcl'; }
+ pre.src-tex:before { content: 'TeX'; }
+ pre.src-plain-tex:before { content: 'Plain TeX'; }
+ pre.src-verilog:before { content: 'Verilog'; }
+ pre.src-vhdl:before { content: 'VHDL'; }
+ pre.src-xml:before { content: 'XML'; }
+ pre.src-nxml:before { content: 'XML'; }
+ /* add a generic configuration mode; LaTeX export needs an additional
+ (add-to-list 'org-latex-listings-langs '(conf \" \")) in .emacs */
+ pre.src-conf:before { content: 'Configuration File'; }
+
+ table { border-collapse:collapse; }
+ caption.t-above { caption-side: top; }
+ caption.t-bottom { caption-side: bottom; }
+ td, th { vertical-align:top; }
+ th.org-right { text-align: center; }
+ th.org-left { text-align: center; }
+ th.org-center { text-align: center; }
+ td.org-right { text-align: right; }
+ td.org-left { text-align: left; }
+ td.org-center { text-align: center; }
+ dt { font-weight: bold; }
+ .footpara { display: inline; }
+ .footdef { margin-bottom: 1em; }
+ .figure { padding: 1em; }
+ .figure p { text-align: center; }
+ .inlinetask {
+ padding: 10px;
+ border: 2px solid gray;
+ margin: 10px;
+ background: #ffffcc;
+ }
+ #org-div-home-and-up
+ { text-align: right; font-size: 70%; white-space: nowrap; }
+ textarea { overflow-x: auto; }
+ .linenr { font-size: smaller }
+ .code-highlighted { background-color: #ffff00; }
+ .org-info-js_info-navigation { border-style: none; }
+ #org-info-js_console-label
+ { font-size: 10px; font-weight: bold; white-space: nowrap; }
+ .org-info-js_search-highlight
+ { background-color: #ffff00; color: #000000; font-weight: bold; }
+ .org-svg { width: 90%; }
+ /*]]>*/-->
+</style>"
+ "The default style specification for exported HTML files.
+You can use `org-html-head' and `org-html-head-extra' to add to
+this style. If you don't want to include this default style,
+customize `org-html-head-include-default-style'.")
+
+
+;;; User Configuration Variables
+
+(defgroup org-export-html nil
+ "Options for exporting Org mode files to HTML."
+ :tag "Org Export HTML"
+ :group 'org-export)
+
+;;;; Handle infojs
+
+(defvar org-html-infojs-opts-table
+ '((path PATH "http://orgmode.org/org-info.js")
+ (view VIEW "info")
+ (toc TOC :with-toc)
+ (ftoc FIXED_TOC "0")
+ (tdepth TOC_DEPTH "max")
+ (sdepth SECTION_DEPTH "max")
+ (mouse MOUSE_HINT "underline")
+ (buttons VIEW_BUTTONS "0")
+ (ltoc LOCAL_TOC "1")
+ (up LINK_UP :html-link-up)
+ (home LINK_HOME :html-link-home))
+ "JavaScript options, long form for script, default values.")
+
+(defcustom org-html-use-infojs 'when-configured
+ "Non-nil when Sebastian Rose's Java Script org-info.js should be active.
+This option can be nil or t to never or always use the script.
+It can also be the symbol `when-configured', meaning that the
+script will be linked into the export file if and only if there
+is a \"#+INFOJS_OPT:\" line in the buffer. See also the variable
+`org-html-infojs-options'."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Never" nil)
+ (const :tag "When configured in buffer" when-configured)
+ (const :tag "Always" t)))
+
+(defcustom org-html-infojs-options
+ (mapcar (lambda (x) (cons (car x) (nth 2 x))) org-html-infojs-opts-table)
+ "Options settings for the INFOJS JavaScript.
+Each of the options must have an entry in `org-html-infojs-opts-table'.
+The value can either be a string that will be passed to the script, or
+a property. This property is then assumed to be a property that is defined
+by the Export/Publishing setup of Org.
+The `sdepth' and `tdepth' parameters can also be set to \"max\", which
+means to use the maximum value consistent with other options."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type
+ `(set :greedy t :inline t
+ ,@(mapcar
+ (lambda (x)
+ (list 'cons (list 'const (car x))
+ '(choice
+ (symbol :tag "Publishing/Export property")
+ (string :tag "Value"))))
+ org-html-infojs-opts-table)))
+
+(defcustom org-html-infojs-template
+ "<script type=\"text/javascript\" src=\"%SCRIPT_PATH\">
+/**
+ *
+ * @source: %SCRIPT_PATH
+ *
+ * @licstart The following is the entire license notice for the
+ * JavaScript code in %SCRIPT_PATH.
+ *
+ * Copyright (C) 2012-2013 Free Software Foundation, Inc.
+ *
+ *
+ * The JavaScript code in this tag is free software: you can
+ * redistribute it and/or modify it under the terms of the GNU
+ * General Public License (GNU GPL) as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option)
+ * any later version. The code is distributed WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
+ *
+ * As additional permission under GNU GPL version 3 section 7, you
+ * may distribute non-source (e.g., minimized or compacted) forms of
+ * that code without the copy of the GNU GPL normally required by
+ * section 4, provided you include this license notice and a URL
+ * through which recipients can access the Corresponding Source.
+ *
+ * @licend The above is the entire license notice
+ * for the JavaScript code in %SCRIPT_PATH.
+ *
+ */
+</script>
+
+<script type=\"text/javascript\">
+
+/*
+@licstart The following is the entire license notice for the
+JavaScript code in this tag.
+
+Copyright (C) 2012-2013 Free Software Foundation, Inc.
+
+The JavaScript code in this tag is free software: you can
+redistribute it and/or modify it under the terms of the GNU
+General Public License (GNU GPL) as published by the Free Software
+Foundation, either version 3 of the License, or (at your option)
+any later version. The code is distributed WITHOUT ANY WARRANTY;
+without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
+
+As additional permission under GNU GPL version 3 section 7, you
+may distribute non-source (e.g., minimized or compacted) forms of
+that code without the copy of the GNU GPL normally required by
+section 4, provided you include this license notice and a URL
+through which recipients can access the Corresponding Source.
+
+
+@licend The above is the entire license notice
+for the JavaScript code in this tag.
+*/
+
+<!--/*--><![CDATA[/*><!--*/
+%MANAGER_OPTIONS
+org_html_manager.setup(); // activate after the parameters are set
+/*]]>*///-->
+</script>"
+ "The template for the export style additions when org-info.js is used.
+Option settings will replace the %MANAGER-OPTIONS cookie."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defun org-html-infojs-install-script (exp-plist _backend)
+ "Install script in export options when appropriate.
+EXP-PLIST is a plist containing export options. BACKEND is the
+export back-end currently used."
+ (unless (or (memq 'body-only (plist-get exp-plist :export-options))
+ (not (plist-get exp-plist :html-use-infojs))
+ (and (eq (plist-get exp-plist :html-use-infojs) 'when-configured)
+ (let ((opt (plist-get exp-plist :infojs-opt)))
+ (or (not opt)
+ (string= "" opt)
+ (string-match "\\<view:nil\\>" opt)))))
+ (let* ((template (plist-get exp-plist :html-infojs-template))
+ (ptoc (plist-get exp-plist :with-toc))
+ (hlevels (plist-get exp-plist :headline-levels))
+ (sdepth hlevels)
+ (tdepth (if (integerp ptoc) (min ptoc hlevels) hlevels))
+ (options (plist-get exp-plist :infojs-opt))
+ (infojs-opt (plist-get exp-plist :html-infojs-options))
+ (table org-html-infojs-opts-table)
+ style)
+ (dolist (entry table)
+ (let* ((opt (car entry))
+ (var (nth 1 entry))
+ ;; Compute default values for script option OPT from
+ ;; `org-html-infojs-options' variable.
+ (default
+ (let ((default (cdr (assq opt infojs-opt))))
+ (if (and (symbolp default) (not (memq default '(t nil))))
+ (plist-get exp-plist default)
+ default)))
+ ;; Value set through INFOJS_OPT keyword has precedence
+ ;; over the default one.
+ (val (if (and options
+ (string-match (format "\\<%s:\\(\\S-+\\)" opt)
+ options))
+ (match-string 1 options)
+ default)))
+ (pcase opt
+ (`path (setq template
+ (replace-regexp-in-string
+ "%SCRIPT_PATH" val template t t)))
+ (`sdepth (when (integerp (read val))
+ (setq sdepth (min (read val) sdepth))))
+ (`tdepth (when (integerp (read val))
+ (setq tdepth (min (read val) tdepth))))
+ (_ (setq val
+ (cond
+ ((or (eq val t) (equal val "t")) "1")
+ ((or (eq val nil) (equal val "nil")) "0")
+ ((stringp val) val)
+ (t (format "%s" val))))
+ (push (cons var val) style)))))
+ ;; Now we set the depth of the *generated* TOC to SDEPTH,
+ ;; because the toc will actually determine the splitting. How
+ ;; much of the toc will actually be displayed is governed by the
+ ;; TDEPTH option.
+ (setq exp-plist (plist-put exp-plist :with-toc sdepth))
+ ;; The table of contents should not show more sections than we
+ ;; generate.
+ (setq tdepth (min tdepth sdepth))
+ (push (cons "TOC_DEPTH" tdepth) style)
+ ;; Build style string.
+ (setq style (mapconcat
+ (lambda (x)
+ (format "org_html_manager.set(\"%s\", \"%s\");"
+ (car x) (cdr x)))
+ style "\n"))
+ (when (and style (> (length style) 0))
+ (and (string-match "%MANAGER_OPTIONS" template)
+ (setq style (replace-match style t t template))
+ (setq exp-plist
+ (plist-put
+ exp-plist :html-head-extra
+ (concat (or (plist-get exp-plist :html-head-extra) "")
+ "\n"
+ style)))))
+ ;; This script absolutely needs the table of contents, so we
+ ;; change that setting.
+ (unless (plist-get exp-plist :with-toc)
+ (setq exp-plist (plist-put exp-plist :with-toc t)))
+ ;; Return the modified property list.
+ exp-plist)))
+
+;;;; Bold, etc.
+
+(defcustom org-html-text-markup-alist
+ '((bold . "<b>%s</b>")
+ (code . "<code>%s</code>")
+ (italic . "<i>%s</i>")
+ (strike-through . "<del>%s</del>")
+ (underline . "<span class=\"underline\">%s</span>")
+ (verbatim . "<code>%s</code>"))
+ "Alist of HTML expressions to convert text markup.
+
+The key must be a symbol among `bold', `code', `italic',
+`strike-through', `underline' and `verbatim'. The value is
+a formatting string to wrap fontified text with.
+
+If no association can be found for a given markup, text will be
+returned as-is."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(alist :key-type (symbol :tag "Markup type")
+ :value-type (string :tag "Format string"))
+ :options '(bold code italic strike-through underline verbatim))
+
+(defcustom org-html-indent nil
+ "Non-nil means to indent the generated HTML.
+Warning: non-nil may break indentation of source code blocks."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+;;;; Drawers
+
+(defcustom org-html-format-drawer-function (lambda (_name contents) contents)
+ "Function called to format a drawer in HTML code.
+
+The function must accept two parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+
+The function should return the string to be exported.
+
+For example, the variable could be set to the following function
+in order to mimic default behavior:
+
+The default value simply returns the value of CONTENTS."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'function)
+
+;;;; Footnotes
+
+(defcustom org-html-footnotes-section "<div id=\"footnotes\">
+<h2 class=\"footnotes\">%s: </h2>
+<div id=\"text-footnotes\">
+%s
+</div>
+</div>"
+ "Format for the footnotes section.
+Should contain a two instances of %s. The first will be replaced with the
+language-specific word for \"Footnotes\", the second one will be replaced
+by the footnotes themselves."
+ :group 'org-export-html
+ :type 'string)
+
+(defcustom org-html-footnote-format "<sup>%s</sup>"
+ "The format for the footnote reference.
+%s will be replaced by the footnote reference itself."
+ :group 'org-export-html
+ :type 'string)
+
+(defcustom org-html-footnote-separator "<sup>, </sup>"
+ "Text used to separate footnotes."
+ :group 'org-export-html
+ :type 'string)
+
+;;;; Headline
+
+(defcustom org-html-toplevel-hlevel 2
+ "The <H> level for level 1 headings in HTML export.
+This is also important for the classes that will be wrapped around headlines
+and outline structure. If this variable is 1, the top-level headlines will
+be <h1>, and the corresponding classes will be outline-1, section-number-1,
+and outline-text-1. If this is 2, all of these will get a 2 instead.
+The default for this variable is 2, because we use <h1> for formatting the
+document title."
+ :group 'org-export-html
+ :type 'integer)
+
+(defcustom org-html-format-headline-function
+ 'org-html-format-headline-default-function
+ "Function to format headline text.
+
+This function will be called with six arguments:
+TODO the todo keyword (string or nil).
+TODO-TYPE the type of todo (symbol: `todo', `done', nil)
+PRIORITY the priority of the headline (integer or nil)
+TEXT the main headline text (string).
+TAGS the tags (string or nil).
+INFO the export options (plist).
+
+The function result will be used in the section format string."
+ :group 'org-export-html
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+;;;; HTML-specific
+
+(defcustom org-html-allow-name-attribute-in-anchors nil
+ "When nil, do not set \"name\" attribute in anchors.
+By default, when appropriate, anchors are formatted with \"id\"
+but without \"name\" attribute."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+;;;; Inlinetasks
+
+(defcustom org-html-format-inlinetask-function
+ 'org-html-format-inlinetask-default-function
+ "Function called to format an inlinetask in HTML code.
+
+The function must accept seven parameters:
+ TODO the todo keyword, as a string
+ TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
+ PRIORITY the inlinetask priority, as a string
+ NAME the inlinetask name, as a string.
+ TAGS the inlinetask tags, as a list of strings.
+ CONTENTS the contents of the inlinetask, as a string.
+ INFO the export options, as a plist
+
+The function should return the string to be exported."
+ :group 'org-export-html
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+;;;; LaTeX
+
+(defcustom org-html-with-latex org-export-with-latex
+ "Non-nil means process LaTeX math snippets.
+
+When set, the exporter will process LaTeX environments and
+fragments.
+
+This option can also be set with the +OPTIONS line,
+e.g. \"tex:mathjax\". Allowed values are:
+
+ nil Ignore math snippets.
+ `verbatim' Keep everything in verbatim
+ `mathjax', t Do MathJax preprocessing and arrange for MathJax.js to
+ be loaded.
+ SYMBOL Any symbol defined in `org-preview-latex-process-alist',
+ e.g., `dvipng'."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Do not process math in any way" nil)
+ (const :tag "Leave math verbatim" verbatim)
+ (const :tag "Use MathJax to display math" mathjax)
+ (symbol :tag "Convert to image to display math" :value dvipng)))
+
+;;;; Links :: Generic
+
+(defcustom org-html-link-org-files-as-html t
+ "Non-nil means make file links to `file.org' point to `file.html'.
+When `org-mode' is exporting an `org-mode' file to HTML, links to
+non-html files are directly put into a href tag in HTML.
+However, links to other Org files (recognized by the extension
+\".org\") should become links to the corresponding HTML
+file, assuming that the linked `org-mode' file will also be
+converted to HTML.
+When nil, the links still point to the plain \".org\" file."
+ :group 'org-export-html
+ :type 'boolean)
+
+;;;; Links :: Inline images
+
+(defcustom org-html-inline-images t
+ "Non-nil means inline images into exported HTML pages.
+This is done using an <img> tag. When nil, an anchor with href is used to
+link to the image."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.1")
+ :type 'boolean)
+
+(defcustom org-html-inline-image-rules
+ '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'")
+ ("http" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'")
+ ("https" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'"))
+ "Rules characterizing image files that can be inlined into HTML.
+A rule consists in an association whose key is the type of link
+to consider, and value is a regexp that will be matched against
+link's path."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(alist :key-type (string :tag "Type")
+ :value-type (regexp :tag "Path")))
+
+;;;; Plain Text
+
+(defvar org-html-protect-char-alist
+ '(("&" . "&amp;")
+ ("<" . "&lt;")
+ (">" . "&gt;"))
+ "Alist of characters to be converted by `org-html-encode-plain-text'.")
+
+;;;; Src Block
+
+(defcustom org-html-htmlize-output-type 'inline-css
+ "Output type to be used by htmlize when formatting code snippets.
+Choices are `css' to export the CSS selectors only,`inline-css'
+to export the CSS attribute values inline in the HTML or `nil' to
+export plain text. We use as default `inline-css', in order to
+make the resulting HTML self-containing.
+
+However, this will fail when using Emacs in batch mode for export, because
+then no rich font definitions are in place. It will also not be good if
+people with different Emacs setup contribute HTML files to a website,
+because the fonts will represent the individual setups. In these cases,
+it is much better to let Org/Htmlize assign classes only, and to use
+a style file to define the look of these classes.
+To get a start for your css file, start Emacs session and make sure that
+all the faces you are interested in are defined, for example by loading files
+in all modes you want. Then, use the command
+`\\[org-html-htmlize-generate-css]' to extract class definitions."
+ :group 'org-export-html
+ :type '(choice (const css) (const inline-css) (const nil)))
+
+(defcustom org-html-htmlize-font-prefix "org-"
+ "The prefix for CSS class names for htmlize font specifications."
+ :group 'org-export-html
+ :type 'string)
+
+;;;; Table
+
+(defcustom org-html-table-default-attributes
+ '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups" :frame "hsides")
+ "Default attributes and values which will be used in table tags.
+This is a plist where attributes are symbols, starting with
+colons, and values are strings.
+
+When exporting to HTML5, these values will be disregarded."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(plist :key-type (symbol :tag "Property")
+ :value-type (string :tag "Value")))
+
+(defcustom org-html-table-header-tags '("<th scope=\"%s\"%s>" . "</th>")
+ "The opening and ending tags for table header fields.
+This is customizable so that alignment options can be specified.
+The first %s will be filled with the scope of the field, either row or col.
+The second %s will be replaced by a style entry to align the field.
+See also the variable `org-html-table-use-header-tags-for-first-column'.
+See also the variable `org-html-table-align-individual-fields'."
+ :group 'org-export-html
+ :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
+
+(defcustom org-html-table-data-tags '("<td%s>" . "</td>")
+ "The opening and ending tags for table data fields.
+This is customizable so that alignment options can be specified.
+The first %s will be filled with the scope of the field, either row or col.
+The second %s will be replaced by a style entry to align the field.
+See also the variable `org-html-table-align-individual-fields'."
+ :group 'org-export-html
+ :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
+
+(defcustom org-html-table-row-open-tag "<tr>"
+ "The opening tag for table rows.
+This is customizable so that alignment options can be specified.
+Instead of strings, these can be a Lisp function that will be
+evaluated for each row in order to construct the table row tags.
+
+The function will be called with these arguments:
+
+ `number': row number (0 is the first row)
+ `group-number': group number of current row
+ `start-group?': non-nil means the row starts a group
+ `end-group?': non-nil means the row ends a group
+ `top?': non-nil means this is the top row
+ `bottom?': non-nil means this is the bottom row
+
+For example:
+
+ (setq org-html-table-row-open-tag
+ (lambda (number group-number start-group? end-group-p top? bottom?)
+ (cond (top? \"<tr class=\\\"tr-top\\\">\")
+ (bottom? \"<tr class=\\\"tr-bottom\\\">\")
+ (t (if (= (mod number 2) 1)
+ \"<tr class=\\\"tr-odd\\\">\"
+ \"<tr class=\\\"tr-even\\\">\")))))
+
+will use the \"tr-top\" and \"tr-bottom\" classes for the top row
+and the bottom row, and otherwise alternate between \"tr-odd\" and
+\"tr-even\" for odd and even rows."
+ :group 'org-export-html
+ :type '(choice :tag "Opening tag"
+ (string :tag "Specify")
+ (function)))
+
+(defcustom org-html-table-row-close-tag "</tr>"
+ "The closing tag for table rows.
+This is customizable so that alignment options can be specified.
+Instead of strings, this can be a Lisp function that will be
+evaluated for each row in order to construct the table row tags.
+
+See documentation of `org-html-table-row-open-tag'."
+ :group 'org-export-html
+ :type '(choice :tag "Closing tag"
+ (string :tag "Specify")
+ (function)))
+
+(defcustom org-html-table-align-individual-fields t
+ "Non-nil means attach style attributes for alignment to each table field.
+When nil, alignment will only be specified in the column tags, but this
+is ignored by some browsers (like Firefox, Safari). Opera does it right
+though."
+ :group 'org-export-html
+ :type 'boolean)
+
+(defcustom org-html-table-use-header-tags-for-first-column nil
+ "Non-nil means format column one in tables with header tags.
+When nil, also column one will use data tags."
+ :group 'org-export-html
+ :type 'boolean)
+
+(defcustom org-html-table-caption-above t
+ "When non-nil, place caption string at the beginning of the table.
+Otherwise, place it near the end."
+ :group 'org-export-html
+ :type 'boolean)
+
+;;;; Tags
+
+(defcustom org-html-tag-class-prefix ""
+ "Prefix to class names for TODO keywords.
+Each tag gets a class given by the tag itself, with this prefix.
+The default prefix is empty because it is nice to just use the keyword
+as a class name. But if you get into conflicts with other, existing
+CSS classes, then this prefix can be very useful."
+ :group 'org-export-html
+ :type 'string)
+
+;;;; Template :: Generic
+
+(defcustom org-html-extension "html"
+ "The extension for exported HTML files."
+ :group 'org-export-html
+ :type 'string)
+
+(defcustom org-html-xml-declaration
+ '(("html" . "<?xml version=\"1.0\" encoding=\"%s\"?>")
+ ("php" . "<?php echo \"<?xml version=\\\"1.0\\\" encoding=\\\"%s\\\" ?>\"; ?>"))
+ "The extension for exported HTML files.
+%s will be replaced with the charset of the exported file.
+This may be a string, or an alist with export extensions
+and corresponding declarations.
+
+This declaration only applies when exporting to XHTML."
+ :group 'org-export-html
+ :type '(choice
+ (string :tag "Single declaration")
+ (repeat :tag "Dependent on extension"
+ (cons (string :tag "Extension")
+ (string :tag "Declaration")))))
+
+(defcustom org-html-coding-system 'utf-8
+ "Coding system for HTML export.
+Use utf-8 as the default value."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'coding-system)
+
+(defcustom org-html-doctype "xhtml-strict"
+ "Document type definition to use for exported HTML files.
+Can be set with the in-buffer HTML_DOCTYPE property or for
+publishing, with :html-doctype."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type (append
+ '(choice)
+ (mapcar (lambda (x) `(const ,(car x))) org-html-doctype-alist)
+ '((string :tag "Custom doctype" ))))
+
+(defcustom org-html-html5-fancy nil
+ "Non-nil means using new HTML5 elements.
+This variable is ignored for anything other than HTML5 export.
+
+For compatibility with Internet Explorer, it's probably a good
+idea to download some form of the html5shiv (for instance
+https://code.google.com/p/html5shiv/) and add it to your
+HTML_HEAD_EXTRA, so that your pages don't break for users of IE
+versions 8 and below."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-html-container-element "div"
+ "HTML element to use for wrapping top level sections.
+Can be set with the in-buffer HTML_CONTAINER property or for
+publishing, with :html-container.
+
+Note that changing the default will prevent you from using
+org-info.js for your website."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-html-divs
+ '((preamble "div" "preamble")
+ (content "div" "content")
+ (postamble "div" "postamble"))
+ "Alist of the three section elements for HTML export.
+The car of each entry is one of `preamble', `content' or `postamble'.
+The cdrs of each entry are the ELEMENT_TYPE and ID for each
+section of the exported document.
+
+Note that changing the default will prevent you from using
+org-info.js for your website."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(list :greedy t
+ (list :tag "Preamble"
+ (const :format "" preamble)
+ (string :tag "element") (string :tag " id"))
+ (list :tag "Content"
+ (const :format "" content)
+ (string :tag "element") (string :tag " id"))
+ (list :tag "Postamble" (const :format "" postamble)
+ (string :tag " id") (string :tag "element"))))
+
+(defconst org-html-checkbox-types
+ '((unicode .
+ ((on . "&#x2611;") (off . "&#x2610;") (trans . "&#x2610;")))
+ (ascii .
+ ((on . "<code>[X]</code>")
+ (off . "<code>[&#xa0;]</code>")
+ (trans . "<code>[-]</code>")))
+ (html .
+ ((on . "<input type='checkbox' checked='checked' />")
+ (off . "<input type='checkbox' />")
+ (trans . "<input type='checkbox' />"))))
+ "Alist of checkbox types.
+The cdr of each entry is an alist list three checkbox types for
+HTML export: `on', `off' and `trans'.
+
+The choices are:
+ `unicode' Unicode characters (HTML entities)
+ `ascii' ASCII characters
+ `html' HTML checkboxes
+
+Note that only the ascii characters implement tri-state
+checkboxes. The other two use the `off' checkbox for `trans'.")
+
+(defcustom org-html-checkbox-type 'ascii
+ "The type of checkboxes to use for HTML export.
+See `org-html-checkbox-types' for for the values used for each
+option."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "ASCII characters" ascii)
+ (const :tag "Unicode characters" unicode)
+ (const :tag "HTML checkboxes" html)))
+
+(defcustom org-html-metadata-timestamp-format "%Y-%m-%d %a %H:%M"
+ "Format used for timestamps in preamble, postamble and metadata.
+See `format-time-string' for more information on its components."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+;;;; Template :: Mathjax
+
+(defcustom org-html-mathjax-options
+ '((path "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML" )
+ (scale "100")
+ (align "center")
+ (font "TeX")
+ (linebreaks "false")
+ (autonumber "AMS")
+ (indent "0em")
+ (multlinewidth "85%")
+ (tagindent ".8em")
+ (tagside "right"))
+ "Options for MathJax setup.
+
+Alist of the following elements. All values are strings.
+
+path The path to MathJax.
+scale Scaling with HTML-CSS, MathML and SVG output engines.
+align How to align display math: left, center, or right.
+font The font to use with HTML-CSS and SVG output. As of MathJax 2.5
+ the following values are understood: \"TeX\", \"STIX-Web\",
+ \"Asana-Math\", \"Neo-Euler\", \"Gyre-Pagella\",
+ \"Gyre-Termes\", and \"Latin-Modern\".
+linebreaks Let MathJax perform automatic linebreaks. Valid values
+ are \"true\" and \"false\".
+indent If align is not center, how far from the left/right side?
+ Valid values are \"left\" and \"right\"
+multlinewidth The width of the multline environment.
+autonumber How to number equations. Valid values are \"None\",
+ \"all\" and \"AMS Math\".
+tagindent The amount tags are indented.
+tagside Which side to show tags/labels on. Valid values are
+ \"left\" and \"right\"
+
+You can also customize this for each buffer, using something like
+
+#+HTML_MATHJAX: align: left indent: 5em tagside: left font: Neo-Euler
+
+For further information about MathJax options, see the MathJax documentation:
+
+ http://docs.mathjax.org/"
+ :group 'org-export-html
+ :package-version '(Org . "8.3")
+ :type '(list :greedy t
+ (list :tag "path (the path from where to load MathJax.js)"
+ (const :format " " path) (string))
+ (list :tag "scale (scaling for the displayed math)"
+ (const :format " " scale) (string))
+ (list :tag "align (alignment of displayed equations)"
+ (const :format " " align) (string))
+ (list :tag "font (used to display math)"
+ (const :format " " font)
+ (choice (const "TeX")
+ (const "STIX-Web")
+ (const "Asana-Math")
+ (const "Neo-Euler")
+ (const "Gyre-Pagella")
+ (const "Gyre-Termes")
+ (const "Latin-Modern")))
+ (list :tag "linebreaks (automatic line-breaking)"
+ (const :format " " linebreaks)
+ (choice (const "true")
+ (const "false")))
+ (list :tag "autonumber (when should equations be numbered)"
+ (const :format " " autonumber)
+ (choice (const "AMS")
+ (const "None")
+ (const "All")))
+ (list :tag "indent (indentation with left or right alignment)"
+ (const :format " " indent) (string))
+ (list :tag "multlinewidth (width to use for the multline environment)"
+ (const :format " " multlinewidth) (string))
+ (list :tag "tagindent (the indentation of tags from left or right)"
+ (const :format " " tagindent) (string))
+ (list :tag "tagside (location of tags)"
+ (const :format " " tagside)
+ (choice (const "left")
+ (const "right")))))
+
+(defcustom org-html-mathjax-template
+ "<script type=\"text/x-mathjax-config\">
+ MathJax.Hub.Config({
+ displayAlign: \"%ALIGN\",
+ displayIndent: \"%INDENT\",
+
+ \"HTML-CSS\": { scale: %SCALE,
+ linebreaks: { automatic: \"%LINEBREAKS\" },
+ webFont: \"%FONT\"
+ },
+ SVG: {scale: %SCALE,
+ linebreaks: { automatic: \"%LINEBREAKS\" },
+ font: \"%FONT\"},
+ NativeMML: {scale: %SCALE},
+ TeX: { equationNumbers: {autoNumber: \"%AUTONUMBER\"},
+ MultLineWidth: \"%MULTLINEWIDTH\",
+ TagSide: \"%TAGSIDE\",
+ TagIndent: \"%TAGINDENT\"
+ }
+});
+</script>
+<script type=\"text/javascript\"
+ src=\"%PATH\"></script>"
+ "The MathJax template. See also `org-html-mathjax-options'."
+ :group 'org-export-html
+ :type 'string)
+
+;;;; Template :: Postamble
+
+(defcustom org-html-postamble 'auto
+ "Non-nil means insert a postamble in HTML export.
+
+When set to `auto', check against the
+`org-export-with-author/email/creator/date' variables to set the
+content of the postamble. When set to a string, use this string
+as the postamble. When t, insert a string as defined by the
+formatting string in `org-html-postamble-format'.
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+Setting :html-postamble in publishing projects will take
+precedence over this variable."
+ :group 'org-export-html
+ :type '(choice (const :tag "No postamble" nil)
+ (const :tag "Auto postamble" auto)
+ (const :tag "Default formatting string" t)
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defcustom org-html-postamble-format
+ '(("en" "<p class=\"author\">Author: %a (%e)</p>
+<p class=\"date\">Date: %d</p>
+<p class=\"creator\">%c</p>
+<p class=\"validation\">%v</p>"))
+ "Alist of languages and format strings for the HTML postamble.
+
+The first element of each list is the language code, as used for
+the LANGUAGE keyword. See `org-export-default-language'.
+
+The second element of each list is a format string to format the
+postamble itself. This format string can contain these elements:
+
+ %t stands for the title.
+ %s stands for the subtitle.
+ %a stands for the author's name.
+ %e stands for the author's email.
+ %d stands for the date.
+ %c will be replaced by `org-html-creator-string'.
+ %v will be replaced by `org-html-validation-link'.
+ %T will be replaced by the export time.
+ %C will be replaced by the last modification time.
+
+If you need to use a \"%\" character, you need to escape it
+like that: \"%%\"."
+ :group 'org-export-html
+ :type '(repeat
+ (list (string :tag "Language")
+ (string :tag "Format string"))))
+
+(defcustom org-html-validation-link
+ "<a href=\"http://validator.w3.org/check?uri=referer\">Validate</a>"
+ "Link to HTML validation service."
+ :group 'org-export-html
+ :type 'string)
+
+(defcustom org-html-creator-string
+ (format "<a href=\"http://www.gnu.org/software/emacs/\">Emacs</a> %s (<a href=\"http://orgmode.org\">Org</a> mode %s)"
+ emacs-version
+ (if (fboundp 'org-version) (org-version) "unknown version"))
+ "Information about the creator of the HTML document.
+This option can also be set on with the CREATOR keyword."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(string :tag "Creator string"))
+
+;;;; Template :: Preamble
+
+(defcustom org-html-preamble t
+ "Non-nil means insert a preamble in HTML export.
+
+When t, insert a string as defined by the formatting string in
+`org-html-preamble-format'. When set to a string, use this
+formatting string instead (see `org-html-postamble-format' for an
+example of such a formatting string).
+
+When set to a function, apply this function and insert the
+returned string. The function takes the property list of export
+options as its only argument.
+
+Setting :html-preamble in publishing projects will take
+precedence over this variable."
+ :group 'org-export-html
+ :type '(choice (const :tag "No preamble" nil)
+ (const :tag "Default preamble" t)
+ (string :tag "Custom formatting string")
+ (function :tag "Function (must return a string)")))
+
+(defcustom org-html-preamble-format '(("en" ""))
+ "Alist of languages and format strings for the HTML preamble.
+
+The first element of each list is the language code, as used for
+the LANGUAGE keyword. See `org-export-default-language'.
+
+The second element of each list is a format string to format the
+preamble itself. This format string can contain these elements:
+
+ %t stands for the title.
+ %s stands for the subtitle.
+ %a stands for the author's name.
+ %e stands for the author's email.
+ %d stands for the date.
+ %c will be replaced by `org-html-creator-string'.
+ %v will be replaced by `org-html-validation-link'.
+ %T will be replaced by the export time.
+ %C will be replaced by the last modification time.
+
+If you need to use a \"%\" character, you need to escape it
+like that: \"%%\".
+
+See the default value of `org-html-postamble-format' for an
+example."
+ :group 'org-export-html
+ :type '(repeat
+ (list (string :tag "Language")
+ (string :tag "Format string"))))
+
+(defcustom org-html-link-up ""
+ "Where should the \"UP\" link of exported HTML pages lead?"
+ :group 'org-export-html
+ :type '(string :tag "File or URL"))
+
+(defcustom org-html-link-home ""
+ "Where should the \"HOME\" link of exported HTML pages lead?"
+ :group 'org-export-html
+ :type '(string :tag "File or URL"))
+
+(defcustom org-html-link-use-abs-url nil
+ "Should we prepend relative links with HTML_LINK_HOME?"
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.1")
+ :type 'boolean)
+
+(defcustom org-html-home/up-format
+ "<div id=\"org-div-home-and-up\">
+ <a accesskey=\"h\" href=\"%s\"> UP </a>
+ |
+ <a accesskey=\"H\" href=\"%s\"> HOME </a>
+</div>"
+ "Snippet used to insert the HOME and UP links.
+This is a format string, the first %s will receive the UP link,
+the second the HOME link. If both `org-html-link-up' and
+`org-html-link-home' are empty, the entire snippet will be
+ignored."
+ :group 'org-export-html
+ :type 'string)
+
+;;;; Template :: Scripts
+
+(defcustom org-html-head-include-scripts t
+ "Non-nil means include the JavaScript snippets in exported HTML files.
+The actual script is defined in `org-html-scripts' and should
+not be modified."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+;;;; Template :: Styles
+
+(defcustom org-html-head-include-default-style t
+ "Non-nil means include the default style in exported HTML files.
+The actual style is defined in `org-html-style-default' and
+should not be modified. Use `org-html-head' to use your own
+style information."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+;;;###autoload
+(put 'org-html-head-include-default-style 'safe-local-variable 'booleanp)
+
+(defcustom org-html-head ""
+ "Org-wide head definitions for exported HTML files.
+
+This variable can contain the full HTML structure to provide a
+style, including the surrounding HTML tags. You can consider
+including definitions for the following classes: title, todo,
+done, timestamp, timestamp-kwd, tag, target.
+
+For example, a valid value would be:
+
+ <style type=\"text/css\">
+ <![CDATA[
+ p { font-weight: normal; color: gray; }
+ h1 { color: black; }
+ .title { text-align: center; }
+ .todo, .timestamp-kwd { color: red; }
+ .done { color: green; }
+ ]]>
+ </style>
+
+If you want to refer to an external style, use something like
+
+ <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\" />
+
+As the value of this option simply gets inserted into the HTML
+<head> header, you can use it to add any arbitrary text to the
+header.
+
+You can set this on a per-file basis using #+HTML_HEAD:,
+or for publication projects using the :html-head property."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+;;;###autoload
+(put 'org-html-head 'safe-local-variable 'stringp)
+
+(defcustom org-html-head-extra ""
+ "More head information to add in the HTML output.
+
+You can set this on a per-file basis using #+HTML_HEAD_EXTRA:,
+or for publication projects using the :html-head-extra property."
+ :group 'org-export-html
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+;;;###autoload
+(put 'org-html-head-extra 'safe-local-variable 'stringp)
+
+;;;; Template :: Viewport
+
+(defcustom org-html-viewport '((width "device-width")
+ (initial-scale "1")
+ (minimum-scale "")
+ (maximum-scale "")
+ (user-scalable ""))
+ "Viewport options for mobile-optimized sites.
+
+The following values are recognized
+
+width Size of the viewport.
+initial-scale Zoom level when the page is first loaded.
+minimum-scale Minimum allowed zoom level.
+maximum-scale Maximum allowed zoom level.
+user-scalable Whether zoom can be changed.
+
+The viewport meta tag is inserted if this variable is non-nil.
+
+See the following site for a reference:
+https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag"
+ :group 'org-export-html
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice (const :tag "Disable" nil)
+ (list :tag "Enable"
+ (list :tag "Width of viewport"
+ (const :format " " width)
+ (choice (const :tag "unset" "")
+ (string)))
+ (list :tag "Initial scale"
+ (const :format " " initial-scale)
+ (choice (const :tag "unset" "")
+ (string)))
+ (list :tag "Minimum scale/zoom"
+ (const :format " " minimum-scale)
+ (choice (const :tag "unset" "")
+ (string)))
+ (list :tag "Maximum scale/zoom"
+ (const :format " " maximum-scale)
+ (choice (const :tag "unset" "")
+ (string)))
+ (list :tag "User scalable/zoomable"
+ (const :format " " user-scalable)
+ (choice (const :tag "unset" "")
+ (const "true")
+ (const "false"))))))
+
+;;;; Todos
+
+(defcustom org-html-todo-kwd-class-prefix ""
+ "Prefix to class names for TODO keywords.
+Each TODO keyword gets a class given by the keyword itself, with this prefix.
+The default prefix is empty because it is nice to just use the keyword
+as a class name. But if you get into conflicts with other, existing
+CSS classes, then this prefix can be very useful."
+ :group 'org-export-html
+ :type 'string)
+
+
+;;; Internal Functions
+
+(defun org-html-xhtml-p (info)
+ (let ((dt (downcase (plist-get info :html-doctype))))
+ (string-match-p "xhtml" dt)))
+
+(defun org-html-html5-p (info)
+ (let ((dt (downcase (plist-get info :html-doctype))))
+ (member dt '("html5" "xhtml5" "<!doctype html>"))))
+
+(defun org-html--html5-fancy-p (info)
+ "Non-nil when exporting to HTML5 with fancy elements.
+INFO is the current state of the export process, as a plist."
+ (and (plist-get info :html-html5-fancy)
+ (org-html-html5-p info)))
+
+(defun org-html-close-tag (tag attr info)
+ "Return close-tag for string TAG.
+ATTR specifies additional attributes. INFO is a property list
+containing current export state."
+ (concat "<" tag
+ (org-string-nw-p (concat " " attr))
+ (if (org-html-xhtml-p info) " />" ">")))
+
+(defun org-html-doctype (info)
+ "Return correct HTML doctype tag.
+INFO is a plist used as a communication channel. Doctype tag is
+extracted from `org-html-doctype-alist', or the literal value
+of :html-doctype from INFO if :html-doctype is not found in the
+alist."
+ (let ((dt (plist-get info :html-doctype)))
+ (or (cdr (assoc dt org-html-doctype-alist)) dt)))
+
+(defun org-html--make-attribute-string (attributes)
+ "Return a list of attributes, as a string.
+ATTRIBUTES is a plist where values are either strings or nil. An
+attribute with a nil value will be omitted from the result."
+ (let (output)
+ (dolist (item attributes (mapconcat 'identity (nreverse output) " "))
+ (cond ((null item) (pop output))
+ ((symbolp item) (push (substring (symbol-name item) 1) output))
+ (t (let ((key (car output))
+ (value (replace-regexp-in-string
+ "\"" "&quot;" (org-html-encode-plain-text item))))
+ (setcar output (format "%s=\"%s\"" key value))))))))
+
+(defun org-html--wrap-image (contents info &optional caption label)
+ "Wrap CONTENTS string within an appropriate environment for images.
+INFO is a plist used as a communication channel. When optional
+arguments CAPTION and LABEL are given, use them for caption and
+\"id\" attribute."
+ (let ((html5-fancy (org-html--html5-fancy-p info)))
+ (format (if html5-fancy "\n<figure%s>\n%s%s\n</figure>"
+ "\n<div%s class=\"figure\">\n%s%s\n</div>")
+ ;; ID.
+ (if (org-string-nw-p label) (format " id=\"%s\"" label) "")
+ ;; Contents.
+ (if html5-fancy contents (format "<p>%s</p>" contents))
+ ;; Caption.
+ (if (not (org-string-nw-p caption)) ""
+ (format (if html5-fancy "\n<figcaption>%s</figcaption>"
+ "\n<p>%s</p>")
+ caption)))))
+
+(defun org-html--format-image (source attributes info)
+ "Return \"img\" tag with given SOURCE and ATTRIBUTES.
+SOURCE is a string specifying the location of the image.
+ATTRIBUTES is a plist, as returned by
+`org-export-read-attribute'. INFO is a plist used as
+a communication channel."
+ (if (string= "svg" (file-name-extension source))
+ (org-html--svg-image source attributes info)
+ (org-html-close-tag
+ "img"
+ (org-html--make-attribute-string
+ (org-combine-plists
+ (list :src source
+ :alt (if (string-match-p "^ltxpng/" source)
+ (org-html-encode-plain-text
+ (org-find-text-property-in-string 'org-latex-src source))
+ (file-name-nondirectory source)))
+ attributes))
+ info)))
+
+(defun org-html--svg-image (source attributes info)
+ "Return \"object\" embedding svg file SOURCE with given ATTRIBUTES.
+INFO is a plist used as a communication channel.
+
+The special attribute \"fallback\" can be used to specify a
+fallback image file to use if the object embedding is not
+supported. CSS class \"org-svg\" is assigned as the class of the
+object unless a different class is specified with an attribute."
+ (let ((fallback (plist-get attributes :fallback))
+ (attrs (org-html--make-attribute-string
+ (org-combine-plists
+ ;; Remove fallback attribute, which is not meant to
+ ;; appear directly in the attributes string, and
+ ;; provide a default class if none is set.
+ '(:class "org-svg") attributes '(:fallback nil)))))
+ (format "<object type=\"image/svg+xml\" data=\"%s\" %s>\n%s</object>"
+ source
+ attrs
+ (if fallback
+ (org-html-close-tag
+ "img" (format "src=\"%s\" %s" fallback attrs) info)
+ "Sorry, your browser does not support SVG."))))
+
+(defun org-html--textarea-block (element)
+ "Transcode ELEMENT into a textarea block.
+ELEMENT is either a src block or an example block."
+ (let* ((code (car (org-export-unravel-code element)))
+ (attr (org-export-read-attribute :attr_html element)))
+ (format "<p>\n<textarea cols=\"%s\" rows=\"%s\">\n%s</textarea>\n</p>"
+ (or (plist-get attr :width) 80)
+ (or (plist-get attr :height) (org-count-lines code))
+ code)))
+
+(defun org-html--has-caption-p (element &optional _info)
+ "Non-nil when ELEMENT has a caption affiliated keyword.
+INFO is a plist used as a communication channel. This function
+is meant to be used as a predicate for `org-export-get-ordinal' or
+a value to `org-html-standalone-image-predicate'."
+ (org-element-property :caption element))
+
+;;;; Table
+
+(defun org-html-htmlize-region-for-paste (beg end)
+ "Convert the region between BEG and END to HTML, using htmlize.el.
+This is much like `htmlize-region-for-paste', only that it uses
+the settings define in the org-... variables."
+ (let* ((htmlize-output-type org-html-htmlize-output-type)
+ (htmlize-css-name-prefix org-html-htmlize-font-prefix)
+ (htmlbuf (htmlize-region beg end)))
+ (unwind-protect
+ (with-current-buffer htmlbuf
+ (buffer-substring (plist-get htmlize-buffer-places 'content-start)
+ (plist-get htmlize-buffer-places 'content-end)))
+ (kill-buffer htmlbuf))))
+
+;;;###autoload
+(defun org-html-htmlize-generate-css ()
+ "Create the CSS for all font definitions in the current Emacs session.
+Use this to create face definitions in your CSS style file that can then
+be used by code snippets transformed by htmlize.
+This command just produces a buffer that contains class definitions for all
+faces used in the current Emacs session. You can copy and paste the ones you
+need into your CSS file.
+
+If you then set `org-html-htmlize-output-type' to `css', calls
+to the function `org-html-htmlize-region-for-paste' will
+produce code that uses these same face definitions."
+ (interactive)
+ (require 'htmlize)
+ (and (get-buffer "*html*") (kill-buffer "*html*"))
+ (with-temp-buffer
+ (let ((fl (face-list))
+ (htmlize-css-name-prefix "org-")
+ (htmlize-output-type 'css)
+ f i)
+ (while (setq f (pop fl)
+ i (and f (face-attribute f :inherit)))
+ (when (and (symbolp f) (or (not i) (not (listp i))))
+ (insert (org-add-props (copy-sequence "1") nil 'face f))))
+ (htmlize-region (point-min) (point-max))))
+ (pop-to-buffer-same-window "*html*")
+ (goto-char (point-min))
+ (if (re-search-forward "<style" nil t)
+ (delete-region (point-min) (match-beginning 0)))
+ (if (re-search-forward "</style>" nil t)
+ (delete-region (1+ (match-end 0)) (point-max)))
+ (beginning-of-line 1)
+ (if (looking-at " +") (replace-match ""))
+ (goto-char (point-min)))
+
+(defun org-html--make-string (n string)
+ "Build a string by concatenating N times STRING."
+ (let (out) (dotimes (_ n out) (setq out (concat string out)))))
+
+(defun org-html-fix-class-name (kwd) ; audit callers of this function
+ "Turn todo keyword KWD into a valid class name.
+Replaces invalid characters with \"_\"."
+ (replace-regexp-in-string "[^a-zA-Z0-9_]" "_" kwd nil t))
+
+(defun org-html-footnote-section (info)
+ "Format the footnote section.
+INFO is a plist used as a communication channel."
+ (let* ((fn-alist (org-export-collect-footnote-definitions info))
+ (fn-alist
+ (cl-loop for (n _type raw) in fn-alist collect
+ (cons n (if (eq (org-element-type raw) 'org-data)
+ (org-trim (org-export-data raw info))
+ (format "<div class=\"footpara\">%s</div>"
+ (org-trim (org-export-data raw info))))))))
+ (when fn-alist
+ (format
+ (plist-get info :html-footnotes-section)
+ (org-html--translate "Footnotes" info)
+ (format
+ "\n%s\n"
+ (mapconcat
+ (lambda (fn)
+ (let ((n (car fn)) (def (cdr fn)))
+ (format
+ "<div class=\"footdef\">%s %s</div>\n"
+ (format
+ (plist-get info :html-footnote-format)
+ (org-html--anchor
+ (format "fn.%d" n)
+ n
+ (format " class=\"footnum\" href=\"#fnr.%d\"" n)
+ info))
+ def)))
+ fn-alist
+ "\n"))))))
+
+
+;;; Template
+
+(defun org-html--build-meta-info (info)
+ "Return meta tags for exported document.
+INFO is a plist used as a communication channel."
+ (let ((protect-string
+ (lambda (str)
+ (replace-regexp-in-string
+ "\"" "&quot;" (org-html-encode-plain-text str))))
+ (title (org-export-data (plist-get info :title) info))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth
+ ;; Return raw Org syntax, skipping non
+ ;; exportable objects.
+ (org-element-interpret-data
+ (org-element-map auth
+ (cons 'plain-text org-element-all-objects)
+ 'identity info))))))
+ (description (plist-get info :description))
+ (keywords (plist-get info :keywords))
+ (charset (or (and org-html-coding-system
+ (fboundp 'coding-system-get)
+ (coding-system-get org-html-coding-system
+ 'mime-charset))
+ "iso-8859-1")))
+ (concat
+ (when (plist-get info :time-stamp-file)
+ (format-time-string
+ (concat "<!-- "
+ (plist-get info :html-metadata-timestamp-format)
+ " -->\n")))
+ (format
+ (if (org-html-html5-p info)
+ (org-html-close-tag "meta" "charset=\"%s\"" info)
+ (org-html-close-tag
+ "meta" "http-equiv=\"Content-Type\" content=\"text/html;charset=%s\""
+ info))
+ charset) "\n"
+ (let ((viewport-options
+ (cl-remove-if-not (lambda (cell) (org-string-nw-p (cadr cell)))
+ (plist-get info :html-viewport))))
+ (and viewport-options
+ (concat
+ (org-html-close-tag
+ "meta"
+ (format "name=\"viewport\" content=\"%s\""
+ (mapconcat
+ (lambda (elm) (format "%s=%s" (car elm) (cadr elm)))
+ viewport-options ", "))
+ info)
+ "\n")))
+ (format "<title>%s</title>\n" title)
+ (org-html-close-tag "meta" "name=\"generator\" content=\"Org mode\"" info)
+ "\n"
+ (and (org-string-nw-p author)
+ (concat
+ (org-html-close-tag "meta"
+ (format "name=\"author\" content=\"%s\""
+ (funcall protect-string author))
+ info)
+ "\n"))
+ (and (org-string-nw-p description)
+ (concat
+ (org-html-close-tag "meta"
+ (format "name=\"description\" content=\"%s\"\n"
+ (funcall protect-string description))
+ info)
+ "\n"))
+ (and (org-string-nw-p keywords)
+ (concat
+ (org-html-close-tag "meta"
+ (format "name=\"keywords\" content=\"%s\""
+ (funcall protect-string keywords))
+ info)
+ "\n")))))
+
+(defun org-html--build-head (info)
+ "Return information for the <head>..</head> of the HTML output.
+INFO is a plist used as a communication channel."
+ (org-element-normalize-string
+ (concat
+ (when (plist-get info :html-head-include-default-style)
+ (org-element-normalize-string org-html-style-default))
+ (org-element-normalize-string (plist-get info :html-head))
+ (org-element-normalize-string (plist-get info :html-head-extra))
+ (when (and (plist-get info :html-htmlized-css-url)
+ (eq org-html-htmlize-output-type 'css))
+ (org-html-close-tag "link"
+ (format "rel=\"stylesheet\" href=\"%s\" type=\"text/css\""
+ (plist-get info :html-htmlized-css-url))
+ info))
+ (when (plist-get info :html-head-include-scripts) org-html-scripts))))
+
+(defun org-html--build-mathjax-config (info)
+ "Insert the user setup into the mathjax template.
+INFO is a plist used as a communication channel."
+ (when (and (memq (plist-get info :with-latex) '(mathjax t))
+ (org-element-map (plist-get info :parse-tree)
+ '(latex-fragment latex-environment) 'identity info t))
+ (let ((template (plist-get info :html-mathjax-template))
+ (options (plist-get info :html-mathjax-options))
+ (in-buffer (or (plist-get info :html-mathjax) "")))
+ (dolist (e options (org-element-normalize-string template))
+ (let ((name (car e))
+ (val (nth 1 e)))
+ (when (string-match (concat "\\<" (symbol-name name) ":") in-buffer)
+ (setq val
+ (car (read-from-string (substring in-buffer (match-end 0))))))
+ (unless (stringp val) (setq val (format "%s" val)))
+ (while (string-match (concat "%" (upcase (symbol-name name)))
+ template)
+ (setq template (replace-match val t t template))))))))
+
+(defun org-html-format-spec (info)
+ "Return format specification for preamble and postamble.
+INFO is a plist used as a communication channel."
+ (let ((timestamp-format (plist-get info :html-metadata-timestamp-format)))
+ `((?t . ,(org-export-data (plist-get info :title) info))
+ (?s . ,(org-export-data (plist-get info :subtitle) info))
+ (?d . ,(org-export-data (org-export-get-date info timestamp-format)
+ info))
+ (?T . ,(format-time-string timestamp-format))
+ (?a . ,(org-export-data (plist-get info :author) info))
+ (?e . ,(mapconcat
+ (lambda (e) (format "<a href=\"mailto:%s\">%s</a>" e e))
+ (split-string (plist-get info :email) ",+ *")
+ ", "))
+ (?c . ,(plist-get info :creator))
+ (?C . ,(let ((file (plist-get info :input-file)))
+ (format-time-string timestamp-format
+ (and file (nth 5 (file-attributes file))))))
+ (?v . ,(or (plist-get info :html-validation-link) "")))))
+
+(defun org-html--build-pre/postamble (type info)
+ "Return document preamble or postamble as a string, or nil.
+TYPE is either `preamble' or `postamble', INFO is a plist used as a
+communication channel."
+ (let ((section (plist-get info (intern (format ":html-%s" type))))
+ (spec (org-html-format-spec info)))
+ (when section
+ (let ((section-contents
+ (if (functionp section) (funcall section info)
+ (cond
+ ((stringp section) (format-spec section spec))
+ ((eq section 'auto)
+ (let ((date (cdr (assq ?d spec)))
+ (author (cdr (assq ?a spec)))
+ (email (cdr (assq ?e spec)))
+ (creator (cdr (assq ?c spec)))
+ (validation-link (cdr (assq ?v spec))))
+ (concat
+ (when (and (plist-get info :with-date)
+ (org-string-nw-p date))
+ (format "<p class=\"date\">%s: %s</p>\n"
+ (org-html--translate "Date" info)
+ date))
+ (when (and (plist-get info :with-author)
+ (org-string-nw-p author))
+ (format "<p class=\"author\">%s: %s</p>\n"
+ (org-html--translate "Author" info)
+ author))
+ (when (and (plist-get info :with-email)
+ (org-string-nw-p email))
+ (format "<p class=\"email\">%s: %s</p>\n"
+ (org-html--translate "Email" info)
+ email))
+ (when (plist-get info :time-stamp-file)
+ (format
+ "<p class=\"date\">%s: %s</p>\n"
+ (org-html--translate "Created" info)
+ (format-time-string
+ (plist-get info :html-metadata-timestamp-format))))
+ (when (plist-get info :with-creator)
+ (format "<p class=\"creator\">%s</p>\n" creator))
+ (format "<p class=\"validation\">%s</p>\n"
+ validation-link))))
+ (t (format-spec
+ (or (cadr (assoc-string
+ (plist-get info :language)
+ (eval (intern
+ (format "org-html-%s-format" type)))
+ t))
+ (cadr
+ (assoc-string
+ "en"
+ (eval
+ (intern (format "org-html-%s-format" type)))
+ t)))
+ spec))))))
+ (let ((div (assq type (plist-get info :html-divs))))
+ (when (org-string-nw-p section-contents)
+ (concat
+ (format "<%s id=\"%s\" class=\"%s\">\n"
+ (nth 1 div)
+ (nth 2 div)
+ org-html--pre/postamble-class)
+ (org-element-normalize-string section-contents)
+ (format "</%s>\n" (nth 1 div)))))))))
+
+(defun org-html-inner-template (contents info)
+ "Return body of document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (concat
+ ;; Table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth (org-html-toc depth info)))
+ ;; Document contents.
+ contents
+ ;; Footnotes section.
+ (org-html-footnote-section info)))
+
+(defun org-html-template (contents info)
+ "Return complete document string after HTML conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (concat
+ (when (and (not (org-html-html5-p info)) (org-html-xhtml-p info))
+ (let* ((xml-declaration (plist-get info :html-xml-declaration))
+ (decl (or (and (stringp xml-declaration) xml-declaration)
+ (cdr (assoc (plist-get info :html-extension)
+ xml-declaration))
+ (cdr (assoc "html" xml-declaration))
+ "")))
+ (when (not (or (not decl) (string= "" decl)))
+ (format "%s\n"
+ (format decl
+ (or (and org-html-coding-system
+ (fboundp 'coding-system-get)
+ (coding-system-get org-html-coding-system 'mime-charset))
+ "iso-8859-1"))))))
+ (org-html-doctype info)
+ "\n"
+ (concat "<html"
+ (cond ((org-html-xhtml-p info)
+ (format
+ " xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"%s\" xml:lang=\"%s\""
+ (plist-get info :language) (plist-get info :language)))
+ ((org-html-html5-p info)
+ (format " lang=\"%s\"" (plist-get info :language))))
+ ">\n")
+ "<head>\n"
+ (org-html--build-meta-info info)
+ (org-html--build-head info)
+ (org-html--build-mathjax-config info)
+ "</head>\n"
+ "<body>\n"
+ (let ((link-up (org-trim (plist-get info :html-link-up)))
+ (link-home (org-trim (plist-get info :html-link-home))))
+ (unless (and (string= link-up "") (string= link-home ""))
+ (format (plist-get info :html-home/up-format)
+ (or link-up link-home)
+ (or link-home link-up))))
+ ;; Preamble.
+ (org-html--build-pre/postamble 'preamble info)
+ ;; Document contents.
+ (let ((div (assq 'content (plist-get info :html-divs))))
+ (format "<%s id=\"%s\">\n" (nth 1 div) (nth 2 div)))
+ ;; Document title.
+ (when (plist-get info :with-title)
+ (let ((title (plist-get info :title))
+ (subtitle (plist-get info :subtitle))
+ (html5-fancy (org-html--html5-fancy-p info)))
+ (when title
+ (format
+ (if html5-fancy
+ "<header>\n<h1 class=\"title\">%s</h1>\n%s</header>"
+ "<h1 class=\"title\">%s%s</h1>\n")
+ (org-export-data title info)
+ (if subtitle
+ (format
+ (if html5-fancy
+ "<p class=\"subtitle\">%s</p>\n"
+ "\n<br>\n<span class=\"subtitle\">%s</span>\n")
+ (org-export-data subtitle info))
+ "")))))
+ contents
+ (format "</%s>\n" (nth 1 (assq 'content (plist-get info :html-divs))))
+ ;; Postamble.
+ (org-html--build-pre/postamble 'postamble info)
+ ;; Closing document.
+ "</body>\n</html>"))
+
+(defun org-html--translate (s info)
+ "Translate string S according to specified language.
+INFO is a plist used as a communication channel."
+ (org-export-translate s :html info))
+
+;;;; Anchor
+
+(defun org-html--anchor (id desc attributes info)
+ "Format a HTML anchor."
+ (let* ((name (and (plist-get info :html-allow-name-attribute-in-anchors) id))
+ (attributes (concat (and id (format " id=\"%s\"" id))
+ (and name (format " name=\"%s\"" name))
+ attributes)))
+ (format "<a%s>%s</a>" attributes (or desc ""))))
+
+;;;; Todo
+
+(defun org-html--todo (todo info)
+ "Format TODO keywords into HTML."
+ (when todo
+ (format "<span class=\"%s %s%s\">%s</span>"
+ (if (member todo org-done-keywords) "done" "todo")
+ (or (plist-get info :html-todo-kwd-class-prefix) "")
+ (org-html-fix-class-name todo)
+ todo)))
+
+;;;; Priority
+
+(defun org-html--priority (priority _info)
+ "Format a priority into HTML.
+PRIORITY is the character code of the priority or nil. INFO is
+a plist containing export options."
+ (and priority (format "<span class=\"priority\">[%c]</span>" priority)))
+
+;;;; Tags
+
+(defun org-html--tags (tags info)
+ "Format TAGS into HTML.
+INFO is a plist containing export options."
+ (when tags
+ (format "<span class=\"tag\">%s</span>"
+ (mapconcat
+ (lambda (tag)
+ (format "<span class=\"%s\">%s</span>"
+ (concat (plist-get info :html-tag-class-prefix)
+ (org-html-fix-class-name tag))
+ tag))
+ tags "&#xa0;"))))
+
+;;;; Src Code
+
+(defun org-html-fontify-code (code lang)
+ "Color CODE with htmlize library.
+CODE is a string representing the source code to colorize. LANG
+is the language used for CODE, as a string, or nil."
+ (when code
+ (cond
+ ;; Case 1: No lang. Possibly an example block.
+ ((not lang)
+ ;; Simple transcoding.
+ (org-html-encode-plain-text code))
+ ;; Case 2: No htmlize or an inferior version of htmlize
+ ((not (and (require 'htmlize nil t) (fboundp 'htmlize-region-for-paste)))
+ ;; Emit a warning.
+ (message "Cannot fontify src block (htmlize.el >= 1.34 required)")
+ ;; Simple transcoding.
+ (org-html-encode-plain-text code))
+ ;; Case 3: plain text explicitly set
+ ((not org-html-htmlize-output-type)
+ ;; Simple transcoding.
+ (org-html-encode-plain-text code))
+ (t
+ ;; Map language
+ (setq lang (or (assoc-default lang org-src-lang-modes) lang))
+ (let* ((lang-mode (and lang (intern (format "%s-mode" lang)))))
+ (cond
+ ;; Case 1: Language is not associated with any Emacs mode
+ ((not (functionp lang-mode))
+ ;; Simple transcoding.
+ (org-html-encode-plain-text code))
+ ;; Case 2: Default. Fontify code.
+ (t
+ ;; htmlize
+ (setq code
+ (let ((output-type org-html-htmlize-output-type)
+ (font-prefix org-html-htmlize-font-prefix))
+ (with-temp-buffer
+ ;; Switch to language-specific mode.
+ (funcall lang-mode)
+ (insert code)
+ ;; Fontify buffer.
+ (org-font-lock-ensure)
+ ;; Remove formatting on newline characters.
+ (save-excursion
+ (let ((beg (point-min))
+ (end (point-max)))
+ (goto-char beg)
+ (while (progn (end-of-line) (< (point) end))
+ (put-text-property (point) (1+ (point)) 'face nil)
+ (forward-char 1))))
+ (org-src-mode)
+ (set-buffer-modified-p nil)
+ ;; Htmlize region.
+ (let ((org-html-htmlize-output-type output-type)
+ (org-html-htmlize-font-prefix font-prefix))
+ (org-html-htmlize-region-for-paste
+ (point-min) (point-max))))))
+ ;; Strip any enclosing <pre></pre> tags.
+ (let* ((beg (and (string-match "\\`<pre[^>]*>\n*" code) (match-end 0)))
+ (end (and beg (string-match "</pre>\\'" code))))
+ (if (and beg end) (substring code beg end) code)))))))))
+
+(defun org-html-do-format-code
+ (code &optional lang refs retain-labels num-start)
+ "Format CODE string as source code.
+Optional arguments LANG, REFS, RETAIN-LABELS and NUM-START are,
+respectively, the language of the source code, as a string, an
+alist between line numbers and references (as returned by
+`org-export-unravel-code'), a boolean specifying if labels should
+appear in the source code, and the number associated to the first
+line of code."
+ (let* ((code-lines (org-split-string code "\n"))
+ (code-length (length code-lines))
+ (num-fmt
+ (and num-start
+ (format "%%%ds: "
+ (length (number-to-string (+ code-length num-start))))))
+ (code (org-html-fontify-code code lang)))
+ (org-export-format-code
+ code
+ (lambda (loc line-num ref)
+ (setq loc
+ (concat
+ ;; Add line number, if needed.
+ (when num-start
+ (format "<span class=\"linenr\">%s</span>"
+ (format num-fmt line-num)))
+ ;; Transcoded src line.
+ loc
+ ;; Add label, if needed.
+ (when (and ref retain-labels) (format " (%s)" ref))))
+ ;; Mark transcoded line as an anchor, if needed.
+ (if (not ref) loc
+ (format "<span id=\"coderef-%s\" class=\"coderef-off\">%s</span>"
+ ref loc)))
+ num-start refs)))
+
+(defun org-html-format-code (element info)
+ "Format contents of ELEMENT as source code.
+ELEMENT is either an example block or a src block. INFO is
+a plist used as a communication channel."
+ (let* ((lang (org-element-property :language element))
+ ;; Extract code and references.
+ (code-info (org-export-unravel-code element))
+ (code (car code-info))
+ (refs (cdr code-info))
+ ;; Does the src block contain labels?
+ (retain-labels (org-element-property :retain-labels element))
+ ;; Does it have line numbers?
+ (num-start (org-export-get-loc element info)))
+ (org-html-do-format-code code lang refs retain-labels num-start)))
+
+
+;;; Tables of Contents
+
+(defun org-html-toc (depth info &optional scope)
+ "Build a table of contents.
+DEPTH is an integer specifying the depth of the table. INFO is
+a plist used as a communication channel. Optional argument SCOPE
+is an element defining the scope of the table. Return the table
+of contents as a string, or nil if it is empty."
+ (let ((toc-entries
+ (mapcar (lambda (headline)
+ (cons (org-html--format-toc-headline headline info)
+ (org-export-get-relative-level headline info)))
+ (org-export-collect-headlines info depth scope))))
+ (when toc-entries
+ (let ((toc (concat "<div id=\"text-table-of-contents\">"
+ (org-html--toc-text toc-entries)
+ "</div>\n")))
+ (if scope toc
+ (let ((outer-tag (if (org-html--html5-fancy-p info)
+ "nav"
+ "div")))
+ (concat (format "<%s id=\"table-of-contents\">\n" outer-tag)
+ (let ((top-level (plist-get info :html-toplevel-hlevel)))
+ (format "<h%d>%s</h%d>\n"
+ top-level
+ (org-html--translate "Table of Contents" info)
+ top-level))
+ toc
+ (format "</%s>\n" outer-tag))))))))
+
+(defun org-html--toc-text (toc-entries)
+ "Return innards of a table of contents, as a string.
+TOC-ENTRIES is an alist where key is an entry title, as a string,
+and value is its relative level, as an integer."
+ (let* ((prev-level (1- (cdar toc-entries)))
+ (start-level prev-level))
+ (concat
+ (mapconcat
+ (lambda (entry)
+ (let ((headline (car entry))
+ (level (cdr entry)))
+ (concat
+ (let* ((cnt (- level prev-level))
+ (times (if (> cnt 0) (1- cnt) (- cnt))))
+ (setq prev-level level)
+ (concat
+ (org-html--make-string
+ times (cond ((> cnt 0) "\n<ul>\n<li>")
+ ((< cnt 0) "</li>\n</ul>\n")))
+ (if (> cnt 0) "\n<ul>\n<li>" "</li>\n<li>")))
+ headline)))
+ toc-entries "")
+ (org-html--make-string (- prev-level start-level) "</li>\n</ul>\n"))))
+
+(defun org-html--format-toc-headline (headline info)
+ "Return an appropriate table of contents entry for HEADLINE.
+INFO is a plist used as a communication channel."
+ (let* ((headline-number (org-export-get-headline-number headline info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ (text (org-export-data-with-backend
+ (org-export-get-alt-title headline info)
+ ;; Create an anonymous back-end that will ignore any
+ ;; footnote-reference, link, radio-target and target
+ ;; in table of contents.
+ (org-export-create-backend
+ :parent 'html
+ :transcoders '((footnote-reference . ignore)
+ (link . (lambda (object c i) c))
+ (radio-target . (lambda (object c i) c))
+ (target . ignore)))
+ info))
+ (tags (and (eq (plist-get info :with-tags) t)
+ (org-export-get-tags headline info))))
+ (format "<a href=\"#%s\">%s</a>"
+ ;; Label.
+ (or (org-element-property :CUSTOM_ID headline)
+ (org-export-get-reference headline info))
+ ;; Body.
+ (concat
+ (and (not (org-export-low-level-p headline info))
+ (org-export-numbered-headline-p headline info)
+ (concat (mapconcat #'number-to-string headline-number ".")
+ ". "))
+ (apply (plist-get info :html-format-headline-function)
+ todo todo-type priority text tags :section-number nil)))))
+
+(defun org-html-list-of-listings (info)
+ "Build a list of listings.
+INFO is a plist used as a communication channel. Return the list
+of listings as a string, or nil if it is empty."
+ (let ((lol-entries (org-export-collect-listings info)))
+ (when lol-entries
+ (concat "<div id=\"list-of-listings\">\n"
+ (let ((top-level (plist-get info :html-toplevel-hlevel)))
+ (format "<h%d>%s</h%d>\n"
+ top-level
+ (org-html--translate "List of Listings" info)
+ top-level))
+ "<div id=\"text-list-of-listings\">\n<ul>\n"
+ (let ((count 0)
+ (initial-fmt (format "<span class=\"listing-number\">%s</span>"
+ (org-html--translate "Listing %d:" info))))
+ (mapconcat
+ (lambda (entry)
+ (let ((label (and (org-element-property :name entry)
+ (org-export-get-reference entry info)))
+ (title (org-trim
+ (org-export-data
+ (or (org-export-get-caption entry t)
+ (org-export-get-caption entry))
+ info))))
+ (concat
+ "<li>"
+ (if (not label)
+ (concat (format initial-fmt (cl-incf count))
+ " "
+ title)
+ (format "<a href=\"#%s\">%s %s</a>"
+ label
+ (format initial-fmt (cl-incf count))
+ title))
+ "</li>")))
+ lol-entries "\n"))
+ "\n</ul>\n</div>\n</div>"))))
+
+(defun org-html-list-of-tables (info)
+ "Build a list of tables.
+INFO is a plist used as a communication channel. Return the list
+of tables as a string, or nil if it is empty."
+ (let ((lol-entries (org-export-collect-tables info)))
+ (when lol-entries
+ (concat "<div id=\"list-of-tables\">\n"
+ (let ((top-level (plist-get info :html-toplevel-hlevel)))
+ (format "<h%d>%s</h%d>\n"
+ top-level
+ (org-html--translate "List of Tables" info)
+ top-level))
+ "<div id=\"text-list-of-tables\">\n<ul>\n"
+ (let ((count 0)
+ (initial-fmt (format "<span class=\"table-number\">%s</span>"
+ (org-html--translate "Table %d:" info))))
+ (mapconcat
+ (lambda (entry)
+ (let ((label (and (org-element-property :name entry)
+ (org-export-get-reference entry info)))
+ (title (org-trim
+ (org-export-data
+ (or (org-export-get-caption entry t)
+ (org-export-get-caption entry))
+ info))))
+ (concat
+ "<li>"
+ (if (not label)
+ (concat (format initial-fmt (cl-incf count))
+ " "
+ title)
+ (format "<a href=\"#%s\">%s %s</a>"
+ label
+ (format initial-fmt (cl-incf count))
+ title))
+ "</li>")))
+ lol-entries "\n"))
+ "\n</ul>\n</div>\n</div>"))))
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-html-bold (_bold contents info)
+ "Transcode BOLD from Org to HTML.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (format (or (cdr (assq 'bold (plist-get info :html-text-markup-alist))) "%s")
+ contents))
+
+;;;; Center Block
+
+(defun org-html-center-block (_center-block contents _info)
+ "Transcode a CENTER-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (format "<div class=\"org-center\">\n%s</div>" contents))
+
+;;;; Clock
+
+(defun org-html-clock (clock _contents _info)
+ "Transcode a CLOCK element from Org to HTML.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format "<p>
+<span class=\"timestamp-wrapper\">
+<span class=\"timestamp-kwd\">%s</span> <span class=\"timestamp\">%s</span>%s
+</span>
+</p>"
+ org-clock-string
+ (org-timestamp-translate (org-element-property :value clock))
+ (let ((time (org-element-property :duration clock)))
+ (and time (format " <span class=\"timestamp\">(%s)</span>" time)))))
+
+;;;; Code
+
+(defun org-html-code (code _contents info)
+ "Transcode CODE from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format (or (cdr (assq 'code (plist-get info :html-text-markup-alist))) "%s")
+ (org-html-encode-plain-text (org-element-property :value code))))
+
+;;;; Drawer
+
+(defun org-html-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (funcall (plist-get info :html-format-drawer-function)
+ (org-element-property :drawer-name drawer)
+ contents))
+
+;;;; Dynamic Block
+
+(defun org-html-dynamic-block (_dynamic-block contents _info)
+ "Transcode a DYNAMIC-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information. See `org-export-data'."
+ contents)
+
+;;;; Entity
+
+(defun org-html-entity (entity _contents _info)
+ "Transcode an ENTITY object from Org to HTML.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :html entity))
+
+;;;; Example Block
+
+(defun org-html-example-block (example-block _contents info)
+ "Transcode a EXAMPLE-BLOCK element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((attributes (org-export-read-attribute :attr_html example-block)))
+ (if (plist-get attributes :textarea)
+ (org-html--textarea-block example-block)
+ (format "<pre class=\"example\"%s>\n%s</pre>"
+ (let* ((name (org-element-property :name example-block))
+ (a (org-html--make-attribute-string
+ (if (or (not name) (plist-member attributes :id))
+ attributes
+ (plist-put attributes :id name)))))
+ (if (org-string-nw-p a) (concat " " a) ""))
+ (org-html-format-code example-block info)))))
+
+;;;; Export Snippet
+
+(defun org-html-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (when (eq (org-export-snippet-backend export-snippet) 'html)
+ (org-element-property :value export-snippet)))
+
+;;;; Export Block
+
+(defun org-html-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "HTML")
+ (org-remove-indentation (org-element-property :value export-block))))
+
+;;;; Fixed Width
+
+(defun org-html-fixed-width (fixed-width _contents _info)
+ "Transcode a FIXED-WIDTH element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (format "<pre class=\"example\">\n%s</pre>"
+ (org-html-do-format-code
+ (org-remove-indentation
+ (org-element-property :value fixed-width)))))
+
+;;;; Footnote Reference
+
+(defun org-html-footnote-reference (footnote-reference _contents info)
+ "Transcode a FOOTNOTE-REFERENCE element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (concat
+ ;; Insert separator between two footnotes in a row.
+ (let ((prev (org-export-get-previous-element footnote-reference info)))
+ (when (eq (org-element-type prev) 'footnote-reference)
+ (plist-get info :html-footnote-separator)))
+ (let* ((n (org-export-get-footnote-number footnote-reference info))
+ (id (format "fnr.%d%s"
+ n
+ (if (org-export-footnote-first-reference-p
+ footnote-reference info)
+ ""
+ ".100"))))
+ (format
+ (plist-get info :html-footnote-format)
+ (org-html--anchor
+ id n (format " class=\"footref\" href=\"#fn.%d\"" n) info)))))
+
+;;;; Headline
+
+(defun org-html-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to HTML.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((numberedp (org-export-numbered-headline-p headline info))
+ (numbers (org-export-get-headline-number headline info))
+ (level (+ (org-export-get-relative-level headline info)
+ (1- (plist-get info :html-toplevel-hlevel))))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ (text (org-export-data (org-element-property :title headline) info))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (full-text (funcall (plist-get info :html-format-headline-function)
+ todo todo-type priority text tags info))
+ (contents (or contents ""))
+ (ids (delq nil
+ (list (org-element-property :CUSTOM_ID headline)
+ (org-export-get-reference headline info)
+ (org-element-property :ID headline))))
+ (preferred-id (car ids))
+ (extra-ids
+ (mapconcat
+ (lambda (id)
+ (org-html--anchor
+ (if (org-uuidgen-p id) (concat "ID-" id) id)
+ nil nil info))
+ (cdr ids) "")))
+ (if (org-export-low-level-p headline info)
+ ;; This is a deep sub-tree: export it as a list item.
+ (let* ((type (if numberedp 'ordered 'unordered))
+ (itemized-body
+ (org-html-format-list-item
+ contents type nil info nil
+ (concat (org-html--anchor preferred-id nil nil info)
+ extra-ids
+ full-text))))
+ (concat (and (org-export-first-sibling-p headline info)
+ (org-html-begin-plain-list type))
+ itemized-body
+ (and (org-export-last-sibling-p headline info)
+ (org-html-end-plain-list type))))
+ (let ((extra-class (org-element-property :HTML_CONTAINER_CLASS headline))
+ (first-content (car (org-element-contents headline))))
+ ;; Standard headline. Export it as a section.
+ (format "<%s id=\"%s\" class=\"%s\">%s%s</%s>\n"
+ (org-html--container headline info)
+ (concat "outline-container-"
+ (org-export-get-reference headline info))
+ (concat (format "outline-%d" level)
+ (and extra-class " ")
+ extra-class)
+ (format "\n<h%d id=\"%s\">%s%s</h%d>\n"
+ level
+ preferred-id
+ extra-ids
+ (concat
+ (and numberedp
+ (format
+ "<span class=\"section-number-%d\">%s</span> "
+ level
+ (mapconcat #'number-to-string numbers ".")))
+ full-text)
+ level)
+ ;; When there is no section, pretend there is an
+ ;; empty one to get the correct <div
+ ;; class="outline-...> which is needed by
+ ;; `org-info.js'.
+ (if (eq (org-element-type first-content) 'section) contents
+ (concat (org-html-section first-content "" info) contents))
+ (org-html--container headline info)))))))
+
+(defun org-html-format-headline-default-function
+ (todo _todo-type priority text tags info)
+ "Default format function for a headline.
+See `org-html-format-headline-function' for details."
+ (let ((todo (org-html--todo todo info))
+ (priority (org-html--priority priority info))
+ (tags (org-html--tags tags info)))
+ (concat todo (and todo " ")
+ priority (and priority " ")
+ text
+ (and tags "&#xa0;&#xa0;&#xa0;") tags)))
+
+(defun org-html--container (headline info)
+ (or (org-element-property :HTML_CONTAINER headline)
+ (if (= 1 (org-export-get-relative-level headline info))
+ (plist-get info :html-container)
+ "div")))
+
+;;;; Horizontal Rule
+
+(defun org-html-horizontal-rule (_horizontal-rule _contents info)
+ "Transcode an HORIZONTAL-RULE object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-html-close-tag "hr" nil info))
+
+;;;; Inline Src Block
+
+(defun org-html-inline-src-block (inline-src-block _contents info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((lang (org-element-property :language inline-src-block))
+ (code (org-html-fontify-code
+ (org-element-property :value inline-src-block)
+ lang))
+ (label
+ (let ((lbl (and (org-element-property :name inline-src-block)
+ (org-export-get-reference inline-src-block info))))
+ (if (not lbl) "" (format " id=\"%s\"" lbl)))))
+ (format "<code class=\"src src-%s\"%s>%s</code>" lang label code)))
+
+;;;; Inlinetask
+
+(defun org-html-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type inlinetask)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask)))
+ (text (org-export-data (org-element-property :title inlinetask) info))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags inlinetask info))))
+ (funcall (plist-get info :html-format-inlinetask-function)
+ todo todo-type priority text tags contents info)))
+
+(defun org-html-format-inlinetask-default-function
+ (todo todo-type priority text tags contents info)
+ "Default format function for a inlinetasks.
+See `org-html-format-inlinetask-function' for details."
+ (format "<div class=\"inlinetask\">\n<b>%s</b>%s\n%s</div>"
+ (org-html-format-headline-default-function
+ todo todo-type priority text tags info)
+ (org-html-close-tag "br" nil info)
+ contents))
+
+;;;; Italic
+
+(defun org-html-italic (_italic contents info)
+ "Transcode ITALIC from Org to HTML.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (format
+ (or (cdr (assq 'italic (plist-get info :html-text-markup-alist))) "%s")
+ contents))
+
+;;;; Item
+
+(defun org-html-checkbox (checkbox info)
+ "Format CHECKBOX into HTML.
+INFO is a plist holding contextual information. See
+`org-html-checkbox-type' for customization options."
+ (cdr (assq checkbox
+ (cdr (assq (plist-get info :html-checkbox-type)
+ org-html-checkbox-types)))))
+
+(defun org-html-format-list-item (contents type checkbox info
+ &optional term-counter-id
+ headline)
+ "Format a list item into HTML."
+ (let ((class (if checkbox
+ (format " class=\"%s\""
+ (symbol-name checkbox)) ""))
+ (checkbox (concat (org-html-checkbox checkbox info)
+ (and checkbox " ")))
+ (br (org-html-close-tag "br" nil info)))
+ (concat
+ (pcase type
+ (`ordered
+ (let* ((counter term-counter-id)
+ (extra (if counter (format " value=\"%s\"" counter) "")))
+ (concat
+ (format "<li%s%s>" class extra)
+ (when headline (concat headline br)))))
+ (`unordered
+ (let* ((id term-counter-id)
+ (extra (if id (format " id=\"%s\"" id) "")))
+ (concat
+ (format "<li%s%s>" class extra)
+ (when headline (concat headline br)))))
+ (`descriptive
+ (let* ((term term-counter-id))
+ (setq term (or term "(no term)"))
+ ;; Check-boxes in descriptive lists are associated to tag.
+ (concat (format "<dt%s>%s</dt>"
+ class (concat checkbox term))
+ "<dd>"))))
+ (unless (eq type 'descriptive) checkbox)
+ (and contents (org-trim contents))
+ (pcase type
+ (`ordered "</li>")
+ (`unordered "</li>")
+ (`descriptive "</dd>")))))
+
+(defun org-html-item (item contents info)
+ "Transcode an ITEM element from Org to HTML.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((plain-list (org-export-get-parent item))
+ (type (org-element-property :type plain-list))
+ (counter (org-element-property :counter item))
+ (checkbox (org-element-property :checkbox item))
+ (tag (let ((tag (org-element-property :tag item)))
+ (and tag (org-export-data tag info)))))
+ (org-html-format-list-item
+ contents type checkbox info (or tag counter))))
+
+;;;; Keyword
+
+(defun org-html-keyword (keyword _contents info)
+ "Transcode a KEYWORD element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "HTML") value)
+ ((string= key "TOC")
+ (let ((case-fold-search t))
+ (cond
+ ((string-match "\\<headlines\\>" value)
+ (let ((depth (and (string-match "\\<[0-9]+\\>" value)
+ (string-to-number (match-string 0 value))))
+ (localp (string-match-p "\\<local\\>" value)))
+ (org-html-toc depth info (and localp keyword))))
+ ((string= "listings" value) (org-html-list-of-listings info))
+ ((string= "tables" value) (org-html-list-of-tables info))))))))
+
+;;;; Latex Environment
+
+(defun org-html-format-latex (latex-frag processing-type info)
+ "Format a LaTeX fragment LATEX-FRAG into HTML.
+PROCESSING-TYPE designates the tool used for conversion. It can
+be `mathjax', `verbatim', nil, t or symbols in
+`org-preview-latex-process-alist', e.g., `dvipng', `dvisvgm' or
+`imagemagick'. See `org-html-with-latex' for more information.
+INFO is a plist containing export properties."
+ (let ((cache-relpath "") (cache-dir ""))
+ (unless (eq processing-type 'mathjax)
+ (let ((bfn (or (buffer-file-name)
+ (make-temp-name
+ (expand-file-name "latex" temporary-file-directory))))
+ (latex-header
+ (let ((header (plist-get info :latex-header)))
+ (and header
+ (concat (mapconcat
+ (lambda (line) (concat "#+LATEX_HEADER: " line))
+ (org-split-string header "\n")
+ "\n")
+ "\n")))))
+ (setq cache-relpath
+ (concat (file-name-as-directory org-preview-latex-image-directory)
+ (file-name-sans-extension
+ (file-name-nondirectory bfn)))
+ cache-dir (file-name-directory bfn))
+ ;; Re-create LaTeX environment from original buffer in
+ ;; temporary buffer so that dvipng/imagemagick can properly
+ ;; turn the fragment into an image.
+ (setq latex-frag (concat latex-header latex-frag))))
+ (with-temp-buffer
+ (insert latex-frag)
+ (org-format-latex cache-relpath nil nil cache-dir nil
+ "Creating LaTeX Image..." nil processing-type)
+ (buffer-string))))
+
+(defun org-html-latex-environment (latex-environment _contents info)
+ "Transcode a LATEX-ENVIRONMENT element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((processing-type (plist-get info :with-latex))
+ (latex-frag (org-remove-indentation
+ (org-element-property :value latex-environment)))
+ (attributes (org-export-read-attribute :attr_html latex-environment)))
+ (cond
+ ((memq processing-type '(t mathjax))
+ (org-html-format-latex latex-frag 'mathjax info))
+ ((assq processing-type org-preview-latex-process-alist)
+ (let ((formula-link
+ (org-html-format-latex latex-frag processing-type info)))
+ (when (and formula-link (string-match "file:\\([^]]*\\)" formula-link))
+ ;; Do not provide a caption or a name to be consistent with
+ ;; `mathjax' handling.
+ (org-html--wrap-image
+ (org-html--format-image
+ (match-string 1 formula-link) attributes info) info))))
+ (t latex-frag))))
+
+;;;; Latex Fragment
+
+(defun org-html-latex-fragment (latex-fragment _contents info)
+ "Transcode a LATEX-FRAGMENT object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((latex-frag (org-element-property :value latex-fragment))
+ (processing-type (plist-get info :with-latex)))
+ (cond
+ ((memq processing-type '(t mathjax))
+ (org-html-format-latex latex-frag 'mathjax info))
+ ((assq processing-type org-preview-latex-process-alist)
+ (let ((formula-link
+ (org-html-format-latex latex-frag processing-type info)))
+ (when (and formula-link (string-match "file:\\([^]]*\\)" formula-link))
+ (org-html--format-image (match-string 1 formula-link) nil info))))
+ (t latex-frag))))
+
+;;;; Line Break
+
+(defun org-html-line-break (_line-break _contents info)
+ "Transcode a LINE-BREAK object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (concat (org-html-close-tag "br" nil info) "\n"))
+
+;;;; Link
+
+(defun org-html-inline-image-p (link info)
+ "Non-nil when LINK is meant to appear as an image.
+INFO is a plist used as a communication channel. LINK is an
+inline image when it has no description and targets an image
+file (see `org-html-inline-image-rules' for more information), or
+if its description is a single link targeting an image file."
+ (if (not (org-element-contents link))
+ (org-export-inline-image-p
+ link (plist-get info :html-inline-image-rules))
+ (not
+ (let ((link-count 0))
+ (org-element-map (org-element-contents link)
+ (cons 'plain-text org-element-all-objects)
+ (lambda (obj)
+ (pcase (org-element-type obj)
+ (`plain-text (org-string-nw-p obj))
+ (`link (if (= link-count 1) t
+ (cl-incf link-count)
+ (not (org-export-inline-image-p
+ obj (plist-get info :html-inline-image-rules)))))
+ (_ t)))
+ info t)))))
+
+(defvar org-html-standalone-image-predicate)
+(defun org-html-standalone-image-p (element info)
+ "Non-nil if ELEMENT is a standalone image.
+
+INFO is a plist holding contextual information.
+
+An element or object is a standalone image when
+
+ - its type is `paragraph' and its sole content, save for white
+ spaces, is a link that qualifies as an inline image;
+
+ - its type is `link' and its containing paragraph has no other
+ content save white spaces.
+
+Bind `org-html-standalone-image-predicate' to constrain paragraph
+further. For example, to check for only captioned standalone
+images, set it to:
+
+ (lambda (paragraph) (org-element-property :caption paragraph))"
+ (let ((paragraph (pcase (org-element-type element)
+ (`paragraph element)
+ (`link (org-export-get-parent element)))))
+ (and (eq (org-element-type paragraph) 'paragraph)
+ (or (not (fboundp 'org-html-standalone-image-predicate))
+ (funcall org-html-standalone-image-predicate paragraph))
+ (catch 'exit
+ (let ((link-count 0))
+ (org-element-map (org-element-contents paragraph)
+ (cons 'plain-text org-element-all-objects)
+ (lambda (obj)
+ (when (pcase (org-element-type obj)
+ (`plain-text (org-string-nw-p obj))
+ (`link (or (> (cl-incf link-count) 1)
+ (not (org-html-inline-image-p obj info))))
+ (_ t))
+ (throw 'exit nil)))
+ info nil 'link)
+ (= link-count 1))))))
+
+(defun org-html-link (link desc info)
+ "Transcode a LINK object from Org to HTML.
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+ (let* ((home (when (plist-get info :html-link-home)
+ (org-trim (plist-get info :html-link-home))))
+ (use-abs-url (plist-get info :html-link-use-abs-url))
+ (link-org-files-as-html-maybe
+ (lambda (raw-path info)
+ ;; Treat links to `file.org' as links to `file.html', if
+ ;; needed. See `org-html-link-org-files-as-html'.
+ (cond
+ ((and (plist-get info :html-link-org-files-as-html)
+ (string= ".org"
+ (downcase (file-name-extension raw-path "."))))
+ (concat (file-name-sans-extension raw-path) "."
+ (plist-get info :html-extension)))
+ (t raw-path))))
+ (type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (org-string-nw-p desc))
+ (path
+ (cond
+ ((member type '("http" "https" "ftp" "mailto" "news"))
+ (url-encode-url (org-link-unescape (concat type ":" raw-path))))
+ ((string= type "file")
+ ;; Treat links to ".org" files as ".html", if needed.
+ (setq raw-path
+ (funcall link-org-files-as-html-maybe raw-path info))
+ ;; If file path is absolute, prepend it with protocol
+ ;; component - "file://".
+ (cond
+ ((file-name-absolute-p raw-path)
+ (setq raw-path (org-export-file-uri raw-path)))
+ ((and home use-abs-url)
+ (setq raw-path (concat (file-name-as-directory home) raw-path))))
+ ;; Add search option, if any. A search option can be
+ ;; relative to a custom-id, a headline title, a name or
+ ;; a target.
+ (let ((option (org-element-property :search-option link)))
+ (cond ((not option) raw-path)
+ ;; Since HTML back-end use custom-id value as-is,
+ ;; resolving is them is trivial.
+ ((eq (string-to-char option) ?#) (concat raw-path option))
+ (t
+ (concat raw-path
+ "#"
+ (org-publish-resolve-external-link
+ option
+ (org-element-property :path link)))))))
+ (t raw-path)))
+ ;; Extract attributes from parent's paragraph. HACK: Only do
+ ;; this for the first link in parent (inner image link for
+ ;; inline images). This is needed as long as attributes
+ ;; cannot be set on a per link basis.
+ (attributes-plist
+ (let* ((parent (org-export-get-parent-element link))
+ (link (let ((container (org-export-get-parent link)))
+ (if (and (eq (org-element-type container) 'link)
+ (org-html-inline-image-p link info))
+ container
+ link))))
+ (and (eq (org-element-map parent 'link 'identity info t) link)
+ (org-export-read-attribute :attr_html parent))))
+ (attributes
+ (let ((attr (org-html--make-attribute-string attributes-plist)))
+ (if (org-string-nw-p attr) (concat " " attr) ""))))
+ (cond
+ ;; Link type is handled by a special function.
+ ((org-export-custom-protocol-maybe link desc 'html))
+ ;; Image file.
+ ((and (plist-get info :html-inline-images)
+ (org-export-inline-image-p
+ link (plist-get info :html-inline-image-rules)))
+ (org-html--format-image path attributes-plist info))
+ ;; Radio target: Transcode target's contents and use them as
+ ;; link's description.
+ ((string= type "radio")
+ (let ((destination (org-export-resolve-radio-link link info)))
+ (if (not destination) desc
+ (format "<a href=\"#%s\"%s>%s</a>"
+ (org-export-get-reference destination info)
+ attributes
+ desc))))
+ ;; Links pointing to a headline: Find destination and build
+ ;; appropriate referencing command.
+ ((member type '("custom-id" "fuzzy" "id"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (pcase (org-element-type destination)
+ ;; ID link points to an external file.
+ (`plain-text
+ (let ((fragment (concat "ID-" path))
+ ;; Treat links to ".org" files as ".html", if needed.
+ (path (funcall link-org-files-as-html-maybe
+ destination info)))
+ (format "<a href=\"%s#%s\"%s>%s</a>"
+ path fragment attributes (or desc destination))))
+ ;; Fuzzy link points nowhere.
+ (`nil
+ (format "<i>%s</i>"
+ (or desc
+ (org-export-data
+ (org-element-property :raw-link link) info))))
+ ;; Link points to a headline.
+ (`headline
+ (let ((href (or (org-element-property :CUSTOM_ID destination)
+ (org-export-get-reference destination info)))
+ ;; What description to use?
+ (desc
+ ;; Case 1: Headline is numbered and LINK has no
+ ;; description. Display section number.
+ (if (and (org-export-numbered-headline-p destination info)
+ (not desc))
+ (mapconcat #'number-to-string
+ (org-export-get-headline-number
+ destination info) ".")
+ ;; Case 2: Either the headline is un-numbered or
+ ;; LINK has a custom description. Display LINK's
+ ;; description or headline's title.
+ (or desc
+ (org-export-data
+ (org-element-property :title destination) info)))))
+ (format "<a href=\"#%s\"%s>%s</a>" href attributes desc)))
+ ;; Fuzzy link points to a target or an element.
+ (_
+ (let* ((ref (org-export-get-reference destination info))
+ (org-html-standalone-image-predicate
+ #'org-html--has-caption-p)
+ (number (cond
+ (desc nil)
+ ((org-html-standalone-image-p destination info)
+ (org-export-get-ordinal
+ (org-element-map destination 'link
+ #'identity info t)
+ info 'link 'org-html-standalone-image-p))
+ (t (org-export-get-ordinal
+ destination info nil 'org-html--has-caption-p))))
+ (desc (cond (desc)
+ ((not number) "No description for this link")
+ ((numberp number) (number-to-string number))
+ (t (mapconcat #'number-to-string number ".")))))
+ (format "<a href=\"#%s\"%s>%s</a>" ref attributes desc))))))
+ ;; Coderef: replace link with the reference name or the
+ ;; equivalent line number.
+ ((string= type "coderef")
+ (let ((fragment (concat "coderef-" (org-html-encode-plain-text path))))
+ (format "<a href=\"#%s\" %s%s>%s</a>"
+ fragment
+ (format "class=\"coderef\" onmouseover=\"CodeHighlightOn(this, \
+'%s');\" onmouseout=\"CodeHighlightOff(this, '%s');\""
+ fragment fragment)
+ attributes
+ (format (org-export-get-coderef-format path desc)
+ (org-export-resolve-coderef path info)))))
+ ;; External link with a description part.
+ ((and path desc) (format "<a href=\"%s\"%s>%s</a>"
+ (org-html-encode-plain-text path)
+ attributes
+ desc))
+ ;; External link without a description part.
+ (path (let ((path (org-html-encode-plain-text path)))
+ (format "<a href=\"%s\"%s>%s</a>"
+ path
+ attributes
+ (org-link-unescape path))))
+ ;; No path, only description. Try to do something useful.
+ (t (format "<i>%s</i>" desc)))))
+
+;;;; Node Property
+
+(defun org-html-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+;;;; Paragraph
+
+(defun org-html-paragraph (paragraph contents info)
+ "Transcode a PARAGRAPH element from Org to HTML.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ (let* ((parent (org-export-get-parent paragraph))
+ (parent-type (org-element-type parent))
+ (style '((footnote-definition " class=\"footpara\"")
+ (org-data " class=\"footpara\"")))
+ (attributes (org-html--make-attribute-string
+ (org-export-read-attribute :attr_html paragraph)))
+ (extra (or (cadr (assq parent-type style)) "")))
+ (cond
+ ((and (eq parent-type 'item)
+ (not (org-export-get-previous-element paragraph info))
+ (let ((followers (org-export-get-next-element paragraph info 2)))
+ (and (not (cdr followers))
+ (memq (org-element-type (car followers)) '(nil plain-list)))))
+ ;; First paragraph in an item has no tag if it is alone or
+ ;; followed, at most, by a sub-list.
+ contents)
+ ((org-html-standalone-image-p paragraph info)
+ ;; Standalone image.
+ (let ((caption
+ (let ((raw (org-export-data
+ (org-export-get-caption paragraph) info))
+ (org-html-standalone-image-predicate
+ #'org-html--has-caption-p))
+ (if (not (org-string-nw-p raw)) raw
+ (concat "<span class=\"figure-number\">"
+ (format (org-html--translate "Figure %d:" info)
+ (org-export-get-ordinal
+ (org-element-map paragraph 'link
+ #'identity info t)
+ info nil #'org-html-standalone-image-p))
+ " </span>"
+ raw))))
+ (label (and (org-element-property :name paragraph)
+ (org-export-get-reference paragraph info))))
+ (org-html--wrap-image contents info caption label)))
+ ;; Regular paragraph.
+ (t (format "<p%s%s>\n%s</p>"
+ (if (org-string-nw-p attributes)
+ (concat " " attributes) "")
+ extra contents)))))
+
+;;;; Plain List
+
+;; FIXME Maybe arg1 is not needed because <li value="20"> already sets
+;; the correct value for the item counter
+(defun org-html-begin-plain-list (type &optional arg1)
+ "Insert the beginning of the HTML list depending on TYPE.
+When ARG1 is a string, use it as the start parameter for ordered
+lists."
+ (pcase type
+ (`ordered
+ (format "<ol class=\"org-ol\"%s>"
+ (if arg1 (format " start=\"%d\"" arg1) "")))
+ (`unordered "<ul class=\"org-ul\">")
+ (`descriptive "<dl class=\"org-dl\">")))
+
+(defun org-html-end-plain-list (type)
+ "Insert the end of the HTML list depending on TYPE."
+ (pcase type
+ (`ordered "</ol>")
+ (`unordered "</ul>")
+ (`descriptive "</dl>")))
+
+(defun org-html-plain-list (plain-list contents _info)
+ "Transcode a PLAIN-LIST element from Org to HTML.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let ((type (org-element-property :type plain-list)))
+ (format "%s\n%s%s"
+ (org-html-begin-plain-list type)
+ contents (org-html-end-plain-list type))))
+
+;;;; Plain Text
+
+(defun org-html-convert-special-strings (string)
+ "Convert special characters in STRING to HTML."
+ (dolist (a org-html-special-string-regexps string)
+ (let ((re (car a))
+ (rpl (cdr a)))
+ (setq string (replace-regexp-in-string re rpl string t)))))
+
+(defun org-html-encode-plain-text (text)
+ "Convert plain text characters from TEXT to HTML equivalent.
+Possible conversions are set in `org-html-protect-char-alist'."
+ (dolist (pair org-html-protect-char-alist text)
+ (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t))))
+
+(defun org-html-plain-text (text info)
+ "Transcode a TEXT string from Org to HTML.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ (let ((output text))
+ ;; Protect following characters: <, >, &.
+ (setq output (org-html-encode-plain-text output))
+ ;; Handle smart quotes. Be sure to provide original string since
+ ;; OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output (org-export-activate-smart-quotes output :html info text)))
+ ;; Handle special strings.
+ (when (plist-get info :with-special-strings)
+ (setq output (org-html-convert-special-strings output)))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output
+ (replace-regexp-in-string
+ "\\(\\\\\\\\\\)?[ \t]*\n"
+ (concat (org-html-close-tag "br" nil info) "\n") output)))
+ ;; Return value.
+ output))
+
+
+;; Planning
+
+(defun org-html-planning (planning _contents info)
+ "Transcode a PLANNING element from Org to HTML.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format
+ "<p><span class=\"timestamp-wrapper\">%s</span></p>"
+ (org-trim
+ (mapconcat
+ (lambda (pair)
+ (let ((timestamp (cdr pair)))
+ (when timestamp
+ (let ((string (car pair)))
+ (format "<span class=\"timestamp-kwd\">%s</span> \
+<span class=\"timestamp\">%s</span> "
+ string
+ (org-html-plain-text (org-timestamp-translate timestamp)
+ info))))))
+ `((,org-closed-string . ,(org-element-property :closed planning))
+ (,org-deadline-string . ,(org-element-property :deadline planning))
+ (,org-scheduled-string . ,(org-element-property :scheduled planning)))
+ ""))))
+
+;;;; Property Drawer
+
+(defun org-html-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element from Org to HTML.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format "<pre class=\"example\">\n%s</pre>" contents)))
+
+;;;; Quote Block
+
+(defun org-html-quote-block (quote-block contents _info)
+ "Transcode a QUOTE-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (format "<blockquote%s>\n%s</blockquote>"
+ (let* ((name (org-element-property :name quote-block))
+ (attributes (org-export-read-attribute :attr_html quote-block))
+ (a (org-html--make-attribute-string
+ (if (or (not name) (plist-member attributes :id))
+ attributes
+ (plist-put attributes :id name)))))
+ (if (org-string-nw-p a) (concat " " a) ""))
+ contents))
+
+;;;; Section
+
+(defun org-html-section (section contents info)
+ "Transcode a SECTION element from Org to HTML.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ (let ((parent (org-export-get-parent-headline section)))
+ ;; Before first headline: no container, just return CONTENTS.
+ (if (not parent) contents
+ ;; Get div's class and id references.
+ (let* ((class-num (+ (org-export-get-relative-level parent info)
+ (1- (plist-get info :html-toplevel-hlevel))))
+ (section-number
+ (and (org-export-numbered-headline-p parent info)
+ (mapconcat
+ #'number-to-string
+ (org-export-get-headline-number parent info) "-"))))
+ ;; Build return value.
+ (format "<div class=\"outline-text-%d\" id=\"text-%s\">\n%s</div>"
+ class-num
+ (or (org-element-property :CUSTOM_ID parent)
+ section-number
+ (org-export-get-reference parent info))
+ (or contents ""))))))
+
+;;;; Radio Target
+
+(defun org-html-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object from Org to HTML.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (let ((ref (org-export-get-reference radio-target info)))
+ (org-html--anchor ref text nil info)))
+
+;;;; Special Block
+
+(defun org-html-special-block (special-block contents info)
+ "Transcode a SPECIAL-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((block-type (org-element-property :type special-block))
+ (html5-fancy (and (org-html--html5-fancy-p info)
+ (member block-type org-html-html5-elements)))
+ (attributes (org-export-read-attribute :attr_html special-block)))
+ (unless html5-fancy
+ (let ((class (plist-get attributes :class)))
+ (setq attributes (plist-put attributes :class
+ (if class (concat class " " block-type)
+ block-type)))))
+ (let* ((contents (or contents ""))
+ (name (org-element-property :name special-block))
+ (a (org-html--make-attribute-string
+ (if (or (not name) (plist-member attributes :id))
+ attributes
+ (plist-put attributes :id name))))
+ (str (if (org-string-nw-p a) (concat " " a) "")))
+ (if html5-fancy
+ (format "<%s%s>\n%s</%s>" block-type str contents block-type)
+ (format "<div%s>\n%s\n</div>" str contents)))))
+
+;;;; Src Block
+
+(defun org-html-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to HTML.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (if (org-export-read-attribute :attr_html src-block :textarea)
+ (org-html--textarea-block src-block)
+ (let ((lang (org-element-property :language src-block))
+ (code (org-html-format-code src-block info))
+ (label (let ((lbl (and (org-element-property :name src-block)
+ (org-export-get-reference src-block info))))
+ (if lbl (format " id=\"%s\"" lbl) ""))))
+ (if (not lang) (format "<pre class=\"example\"%s>\n%s</pre>" label code)
+ (format "<div class=\"org-src-container\">\n%s%s\n</div>"
+ ;; Build caption.
+ (let ((caption (org-export-get-caption src-block)))
+ (if (not caption) ""
+ (let ((listing-number
+ (format
+ "<span class=\"listing-number\">%s </span>"
+ (format
+ (org-html--translate "Listing %d:" info)
+ (org-export-get-ordinal
+ src-block info nil #'org-html--has-caption-p)))))
+ (format "<label class=\"org-src-name\">%s%s</label>"
+ listing-number
+ (org-trim (org-export-data caption info))))))
+ ;; Contents.
+ (format "<pre class=\"src src-%s\"%s>%s</pre>"
+ lang label code))))))
+
+;;;; Statistics Cookie
+
+(defun org-html-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((cookie-value (org-element-property :value statistics-cookie)))
+ (format "<code>%s</code>" cookie-value)))
+
+;;;; Strike-Through
+
+(defun org-html-strike-through (_strike-through contents info)
+ "Transcode STRIKE-THROUGH from Org to HTML.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (format
+ (or (cdr (assq 'strike-through (plist-get info :html-text-markup-alist)))
+ "%s")
+ contents))
+
+;;;; Subscript
+
+(defun org-html-subscript (_subscript contents _info)
+ "Transcode a SUBSCRIPT object from Org to HTML.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "<sub>%s</sub>" contents))
+
+;;;; Superscript
+
+(defun org-html-superscript (_superscript contents _info)
+ "Transcode a SUPERSCRIPT object from Org to HTML.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "<sup>%s</sup>" contents))
+
+;;;; Table Cell
+
+(defun org-html-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to HTML.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let* ((table-row (org-export-get-parent table-cell))
+ (table (org-export-get-parent-table table-cell))
+ (cell-attrs
+ (if (not (plist-get info :html-table-align-individual-fields)) ""
+ (format (if (and (boundp 'org-html-format-table-no-css)
+ org-html-format-table-no-css)
+ " align=\"%s\"" " class=\"org-%s\"")
+ (org-export-table-cell-alignment table-cell info)))))
+ (when (or (not contents) (string= "" (org-trim contents)))
+ (setq contents "&#xa0;"))
+ (cond
+ ((and (org-export-table-has-header-p table info)
+ (= 1 (org-export-table-row-group table-row info)))
+ (let ((header-tags (plist-get info :html-table-header-tags)))
+ (concat "\n" (format (car header-tags) "col" cell-attrs)
+ contents
+ (cdr header-tags))))
+ ((and (plist-get info :html-table-use-header-tags-for-first-column)
+ (zerop (cdr (org-export-table-cell-address table-cell info))))
+ (let ((header-tags (plist-get info :html-table-header-tags)))
+ (concat "\n" (format (car header-tags) "row" cell-attrs)
+ contents
+ (cdr header-tags))))
+ (t (let ((data-tags (plist-get info :html-table-data-tags)))
+ (concat "\n" (format (car data-tags) cell-attrs)
+ contents
+ (cdr data-tags)))))))
+
+;;;; Table Row
+
+(defun org-html-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to HTML.
+CONTENTS is the contents of the row. INFO is a plist used as a
+communication channel."
+ ;; Rules are ignored since table separators are deduced from
+ ;; borders of the current row.
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let* ((group (org-export-table-row-group table-row info))
+ (number (org-export-table-row-number table-row info))
+ (start-group-p
+ (org-export-table-row-starts-rowgroup-p table-row info))
+ (end-group-p
+ (org-export-table-row-ends-rowgroup-p table-row info))
+ (topp (and (equal start-group-p '(top))
+ (equal end-group-p '(below top))))
+ (bottomp (and (equal start-group-p '(above))
+ (equal end-group-p '(bottom above))))
+ (row-open-tag
+ (pcase (plist-get info :html-table-row-open-tag)
+ ((and accessor (pred functionp))
+ (funcall accessor
+ number group start-group-p end-group-p topp bottomp))
+ (accessor accessor)))
+ (row-close-tag
+ (pcase (plist-get info :html-table-row-close-tag)
+ ((and accessor (pred functionp))
+ (funcall accessor
+ number group start-group-p end-group-p topp bottomp))
+ (accessor accessor)))
+ (group-tags
+ (cond
+ ;; Row belongs to second or subsequent groups.
+ ((not (= 1 group)) '("<tbody>" . "\n</tbody>"))
+ ;; Row is from first group. Table has >=1 groups.
+ ((org-export-table-has-header-p
+ (org-export-get-parent-table table-row) info)
+ '("<thead>" . "\n</thead>"))
+ ;; Row is from first and only group.
+ (t '("<tbody>" . "\n</tbody>")))))
+ (concat (and start-group-p (car group-tags))
+ (concat "\n"
+ row-open-tag
+ contents
+ "\n"
+ row-close-tag)
+ (and end-group-p (cdr group-tags))))))
+
+;;;; Table
+
+(defun org-html-table-first-row-data-cells (table info)
+ "Transcode the first row of TABLE.
+INFO is a plist used as a communication channel."
+ (let ((table-row
+ (org-element-map table 'table-row
+ (lambda (row)
+ (unless (eq (org-element-property :type row) 'rule) row))
+ info 'first-match))
+ (special-column-p (org-export-table-has-special-column-p table)))
+ (if (not special-column-p) (org-element-contents table-row)
+ (cdr (org-element-contents table-row)))))
+
+(defun org-html-table--table.el-table (table _info)
+ "Format table.el tables into HTML.
+INFO is a plist used as a communication channel."
+ (when (eq (org-element-property :type table) 'table.el)
+ (require 'table)
+ (let ((outbuf (with-current-buffer
+ (get-buffer-create "*org-export-table*")
+ (erase-buffer) (current-buffer))))
+ (with-temp-buffer
+ (insert (org-element-property :value table))
+ (goto-char 1)
+ (re-search-forward "^[ \t]*|[^|]" nil t)
+ (table-generate-source 'html outbuf))
+ (with-current-buffer outbuf
+ (prog1 (org-trim (buffer-string))
+ (kill-buffer) )))))
+
+(defun org-html-table (table contents info)
+ "Transcode a TABLE element from Org to HTML.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (if (eq (org-element-property :type table) 'table.el)
+ ;; "table.el" table. Convert it using appropriate tools.
+ (org-html-table--table.el-table table info)
+ ;; Standard table.
+ (let* ((caption (org-export-get-caption table))
+ (number (org-export-get-ordinal
+ table info nil #'org-html--has-caption-p))
+ (attributes
+ (org-html--make-attribute-string
+ (org-combine-plists
+ (and (org-element-property :name table)
+ (list :id (org-export-get-reference table info)))
+ (and (not (org-html-html5-p info))
+ (plist-get info :html-table-attributes))
+ (org-export-read-attribute :attr_html table))))
+ (alignspec
+ (if (bound-and-true-p org-html-format-table-no-css)
+ "align=\"%s\""
+ "class=\"org-%s\""))
+ (table-column-specs
+ (lambda (table info)
+ (mapconcat
+ (lambda (table-cell)
+ (let ((alignment (org-export-table-cell-alignment
+ table-cell info)))
+ (concat
+ ;; Begin a colgroup?
+ (when (org-export-table-cell-starts-colgroup-p
+ table-cell info)
+ "\n<colgroup>")
+ ;; Add a column. Also specify its alignment.
+ (format "\n%s"
+ (org-html-close-tag
+ "col" (concat " " (format alignspec alignment)) info))
+ ;; End a colgroup?
+ (when (org-export-table-cell-ends-colgroup-p
+ table-cell info)
+ "\n</colgroup>"))))
+ (org-html-table-first-row-data-cells table info) "\n"))))
+ (format "<table%s>\n%s\n%s\n%s</table>"
+ (if (equal attributes "") "" (concat " " attributes))
+ (if (not caption) ""
+ (format (if (plist-get info :html-table-caption-above)
+ "<caption class=\"t-above\">%s</caption>"
+ "<caption class=\"t-bottom\">%s</caption>")
+ (concat
+ "<span class=\"table-number\">"
+ (format (org-html--translate "Table %d:" info) number)
+ "</span> " (org-export-data caption info))))
+ (funcall table-column-specs table info)
+ contents))))
+
+;;;; Target
+
+(defun org-html-target (target _contents info)
+ "Transcode a TARGET object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((ref (org-export-get-reference target info)))
+ (org-html--anchor ref nil nil info)))
+
+;;;; Timestamp
+
+(defun org-html-timestamp (timestamp _contents info)
+ "Transcode a TIMESTAMP object from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((value (org-html-plain-text (org-timestamp-translate timestamp) info)))
+ (format "<span class=\"timestamp-wrapper\"><span class=\"timestamp\">%s</span></span>"
+ (replace-regexp-in-string "--" "&#x2013;" value))))
+
+;;;; Underline
+
+(defun org-html-underline (_underline contents info)
+ "Transcode UNDERLINE from Org to HTML.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (format (or (cdr (assq 'underline (plist-get info :html-text-markup-alist)))
+ "%s")
+ contents))
+
+;;;; Verbatim
+
+(defun org-html-verbatim (verbatim _contents info)
+ "Transcode VERBATIM from Org to HTML.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format (or (cdr (assq 'verbatim (plist-get info :html-text-markup-alist))) "%s")
+ (org-html-encode-plain-text (org-element-property :value verbatim))))
+
+;;;; Verse Block
+
+(defun org-html-verse-block (_verse-block contents info)
+ "Transcode a VERSE-BLOCK element from Org to HTML.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (format "<p class=\"verse\">\n%s</p>"
+ ;; Replace leading white spaces with non-breaking spaces.
+ (replace-regexp-in-string
+ "^[ \t]+" (lambda (m) (org-html--make-string (length m) "&#xa0;"))
+ ;; Replace each newline character with line break. Also
+ ;; remove any trailing "br" close-tag so as to avoid
+ ;; duplicates.
+ (let* ((br (org-html-close-tag "br" nil info))
+ (re (format "\\(?:%s\\)?[ \t]*\n" (regexp-quote br))))
+ (replace-regexp-in-string re (concat br "\n") contents)))))
+
+
+;;; Filter Functions
+
+(defun org-html-final-function (contents _backend info)
+ "Filter to indent the HTML and convert HTML entities."
+ (with-temp-buffer
+ (insert contents)
+ (set-auto-mode t)
+ (if (plist-get info :html-indent)
+ (indent-region (point-min) (point-max)))
+ (buffer-substring-no-properties (point-min) (point-max))))
+
+
+;;; End-user functions
+
+;;;###autoload
+(defun org-html-export-as-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to an HTML buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org HTML Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'html "*Org HTML Export*"
+ async subtreep visible-only body-only ext-plist
+ (lambda () (set-auto-mode t))))
+
+;;;###autoload
+(defun org-html-convert-region-to-html ()
+ "Assume the current region has Org syntax, and convert it to HTML.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an HTML buffer and use this command
+to convert it."
+ (interactive)
+ (org-export-replace-region-by 'html))
+
+;;;###autoload
+(defun org-html-export-to-html
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a HTML file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"<body>\" and \"</body>\" tags.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let* ((extension (concat "." (or (plist-get ext-plist :html-extension)
+ org-html-extension
+ "html")))
+ (file (org-export-output-file-name extension subtreep))
+ (org-export-coding-system org-html-coding-system))
+ (org-export-to-file 'html file
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-html-publish-to-html (plist filename pub-dir)
+ "Publish an org file to HTML.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'html filename
+ (concat "." (or (plist-get plist :html-extension)
+ org-html-extension
+ "html"))
+ plist pub-dir))
+
+
+(provide 'ox-html)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-html.el ends here
diff --git a/lisp/ox-icalendar.el b/lisp/ox-icalendar.el
new file mode 100644
index 0000000..9ccbb27
--- /dev/null
+++ b/lisp/ox-icalendar.el
@@ -0,0 +1,960 @@
+;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
+
+;; Author: Carsten Dominik <carsten at orgmode dot org>
+;; Nicolas Goaziou <n dot goaziou at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements an iCalendar back-end for Org generic
+;; exporter. See Org manual for more information.
+;;
+;; It is expected to conform to RFC 5545.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox-ascii)
+(declare-function org-bbdb-anniv-export-ical "org-bbdb" nil)
+
+
+
+;;; User-Configurable Variables
+
+(defgroup org-export-icalendar nil
+ "Options specific for iCalendar export back-end."
+ :tag "Org Export iCalendar"
+ :group 'org-export)
+
+(defcustom org-icalendar-combined-agenda-file "~/org.ics"
+ "The file name for the iCalendar file covering all agenda files.
+This file is created with the command `\\[org-icalendar-combine-agenda-files]'.
+The file name should be absolute. It will be overwritten without warning."
+ :group 'org-export-icalendar
+ :type 'file)
+
+(defcustom org-icalendar-alarm-time 0
+ "Number of minutes for triggering an alarm for exported timed events.
+
+A zero value (the default) turns off the definition of an alarm trigger
+for timed events. If non-zero, alarms are created.
+
+- a single alarm per entry is defined
+- The alarm will go off N minutes before the event
+- only a DISPLAY action is defined."
+ :group 'org-export-icalendar
+ :version "24.1"
+ :type 'integer)
+
+(defcustom org-icalendar-combined-name "OrgMode"
+ "Calendar name for the combined iCalendar representing all agenda files."
+ :group 'org-export-icalendar
+ :type 'string)
+
+(defcustom org-icalendar-combined-description ""
+ "Calendar description for the combined iCalendar (all agenda files)."
+ :group 'org-export-icalendar
+ :type 'string)
+
+(defcustom org-icalendar-exclude-tags nil
+ "Tags that exclude a tree from export.
+This variable allows specifying different exclude tags from other
+back-ends. It can also be set with the ICALENDAR_EXCLUDE_TAGS
+keyword."
+ :group 'org-export-icalendar
+ :type '(repeat (string :tag "Tag")))
+
+(defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due)
+ "Contexts where iCalendar export should use a deadline time stamp.
+
+This is a list with possibly several symbols in it. Valid symbols are:
+
+`event-if-todo' Deadlines in TODO entries become calendar events.
+`event-if-not-todo' Deadlines in non-TODO entries become calendar events.
+`todo-due' Use deadlines in TODO entries as due-dates."
+ :group 'org-export-icalendar
+ :type '(set :greedy t
+ (const :tag "Deadlines in non-TODO entries become events"
+ event-if-not-todo)
+ (const :tag "Deadline in TODO entries become events"
+ event-if-todo)
+ (const :tag "Deadlines in TODO entries become due-dates"
+ todo-due)))
+
+(defcustom org-icalendar-use-scheduled '(todo-start)
+ "Contexts where iCalendar export should use a scheduling time stamp.
+
+This is a list with possibly several symbols in it. Valid symbols are:
+
+`event-if-todo' Scheduling time stamps in TODO entries become an event.
+`event-if-not-todo' Scheduling time stamps in non-TODO entries become an event.
+`todo-start' Scheduling time stamps in TODO entries become start date.
+ Some calendar applications show TODO entries only after
+ that date."
+ :group 'org-export-icalendar
+ :type '(set :greedy t
+ (const :tag
+ "SCHEDULED timestamps in non-TODO entries become events"
+ event-if-not-todo)
+ (const :tag "SCHEDULED timestamps in TODO entries become events"
+ event-if-todo)
+ (const :tag "SCHEDULED in TODO entries become start date"
+ todo-start)))
+
+(defcustom org-icalendar-categories '(local-tags category)
+ "Items that should be entered into the \"categories\" field.
+
+This is a list of symbols, the following are valid:
+`category' The Org mode category of the current file or tree
+`todo-state' The todo state, if any
+`local-tags' The tags, defined in the current line
+`all-tags' All tags, including inherited ones."
+ :group 'org-export-icalendar
+ :type '(repeat
+ (choice
+ (const :tag "The file or tree category" category)
+ (const :tag "The TODO state" todo-state)
+ (const :tag "Tags defined in current line" local-tags)
+ (const :tag "All tags, including inherited ones" all-tags))))
+
+(defcustom org-icalendar-with-timestamps 'active
+ "Non-nil means make an event from plain time stamps.
+
+It can be set to `active', `inactive', t or nil, in order to make
+an event from, respectively, only active timestamps, only
+inactive ones, all of them or none.
+
+This variable has precedence over `org-export-with-timestamps'.
+It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
+ :group 'org-export-icalendar
+ :type '(choice
+ (const :tag "All timestamps" t)
+ (const :tag "Only active timestamps" active)
+ (const :tag "Only inactive timestamps" inactive)
+ (const :tag "No timestamp" nil)))
+
+(defcustom org-icalendar-include-todo nil
+ "Non-nil means create VTODO components from TODO items.
+
+Valid values are:
+nil don't include any task.
+t include tasks that are not in DONE state.
+`unblocked' include all TODO items that are not blocked.
+`all' include both done and not done items."
+ :group 'org-export-icalendar
+ :type '(choice
+ (const :tag "None" nil)
+ (const :tag "Unfinished" t)
+ (const :tag "Unblocked" unblocked)
+ (const :tag "All" all)
+ (repeat :tag "Specific TODO keywords"
+ (string :tag "Keyword"))))
+
+(defcustom org-icalendar-include-bbdb-anniversaries nil
+ "Non-nil means a combined iCalendar file should include anniversaries.
+The anniversaries are defined in the BBDB database."
+ :group 'org-export-icalendar
+ :type 'boolean)
+
+(defcustom org-icalendar-include-sexps t
+ "Non-nil means export to iCalendar files should also cover sexp entries.
+These are entries like in the diary, but directly in an Org file."
+ :group 'org-export-icalendar
+ :type 'boolean)
+
+(defcustom org-icalendar-include-body t
+ "Amount of text below headline to be included in iCalendar export.
+This is a number of characters that should maximally be included.
+Properties, scheduling and clocking lines will always be removed.
+The text will be inserted into the DESCRIPTION field."
+ :group 'org-export-icalendar
+ :type '(choice
+ (const :tag "Nothing" nil)
+ (const :tag "Everything" t)
+ (integer :tag "Max characters")))
+
+(defcustom org-icalendar-store-UID nil
+ "Non-nil means store any created UIDs in properties.
+
+The iCalendar standard requires that all entries have a unique identifier.
+Org will create these identifiers as needed. When this variable is non-nil,
+the created UIDs will be stored in the ID property of the entry. Then the
+next time this entry is exported, it will be exported with the same UID,
+superseding the previous form of it. This is essential for
+synchronization services.
+
+This variable is not turned on by default because we want to avoid creating
+a property drawer in every entry if people are only playing with this feature,
+or if they are only using it locally."
+ :group 'org-export-icalendar
+ :type 'boolean)
+
+(defcustom org-icalendar-timezone (getenv "TZ")
+ "The time zone string for iCalendar export.
+When nil or the empty string, use output
+from (current-time-zone)."
+ :group 'org-export-icalendar
+ :type '(choice
+ (const :tag "Unspecified" nil)
+ (string :tag "Time zone")))
+
+(defcustom org-icalendar-date-time-format ":%Y%m%dT%H%M%S"
+ "Format-string for exporting icalendar DATE-TIME.
+
+See `format-time-string' for a full documentation. The only
+difference is that `org-icalendar-timezone' is used for %Z.
+
+Interesting value are:
+ - \":%Y%m%dT%H%M%S\" for local time
+ - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
+ - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
+ :group 'org-export-icalendar
+ :version "24.1"
+ :type '(choice
+ (const :tag "Local time" ":%Y%m%dT%H%M%S")
+ (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
+ (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
+ (string :tag "Explicit format")))
+
+(defvar org-icalendar-after-save-hook nil
+ "Hook run after an iCalendar file has been saved.
+This hook is run with the name of the file as argument. A good
+way to use this is to tell a desktop calendar application to
+re-read the iCalendar file.")
+
+
+
+;;; Define Back-End
+
+(org-export-define-derived-backend 'icalendar 'ascii
+ :translate-alist '((clock . ignore)
+ (footnote-definition . ignore)
+ (footnote-reference . ignore)
+ (headline . org-icalendar-entry)
+ (inlinetask . ignore)
+ (planning . ignore)
+ (section . ignore)
+ (inner-template . (lambda (c i) c))
+ (template . org-icalendar-template))
+ :options-alist
+ '((:exclude-tags
+ "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split)
+ (:with-timestamps nil "<" org-icalendar-with-timestamps)
+ ;; Other variables.
+ (:icalendar-alarm-time nil nil org-icalendar-alarm-time)
+ (:icalendar-categories nil nil org-icalendar-categories)
+ (:icalendar-date-time-format nil nil org-icalendar-date-time-format)
+ (:icalendar-include-bbdb-anniversaries nil nil org-icalendar-include-bbdb-anniversaries)
+ (:icalendar-include-body nil nil org-icalendar-include-body)
+ (:icalendar-include-sexps nil nil org-icalendar-include-sexps)
+ (:icalendar-include-todo nil nil org-icalendar-include-todo)
+ (:icalendar-store-UID nil nil org-icalendar-store-UID)
+ (:icalendar-timezone nil nil org-icalendar-timezone)
+ (:icalendar-use-deadline nil nil org-icalendar-use-deadline)
+ (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled))
+ :filters-alist
+ '((:filter-headline . org-icalendar-clear-blank-lines))
+ :menu-entry
+ '(?c "Export to iCalendar"
+ ((?f "Current file" org-icalendar-export-to-ics)
+ (?a "All agenda files"
+ (lambda (a s v b) (org-icalendar-export-agenda-files a)))
+ (?c "Combine all agenda files"
+ (lambda (a s v b) (org-icalendar-combine-agenda-files a))))))
+
+
+
+;;; Internal Functions
+
+(defun org-icalendar-create-uid (file &optional bell)
+ "Set ID property on headlines missing it in FILE.
+When optional argument BELL is non-nil, inform the user with
+a message if the file was modified."
+ (let (modified-flag)
+ (org-map-entries
+ (lambda ()
+ (let ((entry (org-element-at-point)))
+ (unless (org-element-property :ID entry)
+ (org-id-get-create)
+ (setq modified-flag t)
+ (forward-line))))
+ nil nil 'comment)
+ (when (and bell modified-flag)
+ (message "ID properties created in file \"%s\"" file)
+ (sit-for 2))))
+
+(defun org-icalendar-blocked-headline-p (headline info)
+ "Non-nil when HEADLINE is considered to be blocked.
+
+INFO is a plist used as a communication channel.
+
+A headline is blocked when either
+
+ - it has children which are not all in a completed state;
+
+ - it has a parent with the property :ORDERED:, and there are
+ siblings prior to it with incomplete status;
+
+ - its parent is blocked because it has siblings that should be
+ done first or is a child of a blocked grandparent entry."
+ (or
+ ;; Check if any child is not done.
+ (org-element-map headline 'headline
+ (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
+ info 'first-match)
+ ;; Check :ORDERED: node property.
+ (catch 'blockedp
+ (let ((current headline))
+ (dolist (parent (org-element-lineage headline))
+ (cond
+ ((not (org-element-property :todo-keyword parent))
+ (throw 'blockedp nil))
+ ((org-not-nil (org-element-property :ORDERED parent))
+ (let ((sibling current))
+ (while (setq sibling (org-export-get-previous-element
+ sibling info))
+ (when (eq (org-element-property :todo-type sibling) 'todo)
+ (throw 'blockedp t)))))
+ (t (setq current parent))))))))
+
+(defun org-icalendar-use-UTC-date-time-p ()
+ "Non-nil when `org-icalendar-date-time-format' requires UTC time."
+ (char-equal (elt org-icalendar-date-time-format
+ (1- (length org-icalendar-date-time-format))) ?Z))
+
+(defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
+(defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
+ "Convert TIMESTAMP to iCalendar format.
+
+TIMESTAMP is a timestamp object. KEYWORD is added in front of
+it, in order to make a complete line (e.g. \"DTSTART\").
+
+When optional argument END is non-nil, use end of time range.
+Also increase the hour by two (if time string contains a time),
+or the day by one (if it does not contain a time) when no
+explicit ending time is specified.
+
+When optional argument UTC is non-nil, time will be expressed in
+Universal Time, ignoring `org-icalendar-date-time-format'."
+ (let* ((year-start (org-element-property :year-start timestamp))
+ (year-end (org-element-property :year-end timestamp))
+ (month-start (org-element-property :month-start timestamp))
+ (month-end (org-element-property :month-end timestamp))
+ (day-start (org-element-property :day-start timestamp))
+ (day-end (org-element-property :day-end timestamp))
+ (hour-start (org-element-property :hour-start timestamp))
+ (hour-end (org-element-property :hour-end timestamp))
+ (minute-start (org-element-property :minute-start timestamp))
+ (minute-end (org-element-property :minute-end timestamp))
+ (with-time-p minute-start)
+ (equal-bounds-p
+ (equal (list year-start month-start day-start hour-start minute-start)
+ (list year-end month-end day-end hour-end minute-end)))
+ (mi (cond ((not with-time-p) 0)
+ ((not end) minute-start)
+ ((and org-agenda-default-appointment-duration equal-bounds-p)
+ (+ minute-end org-agenda-default-appointment-duration))
+ (t minute-end)))
+ (h (cond ((not with-time-p) 0)
+ ((not end) hour-start)
+ ((or (not equal-bounds-p)
+ org-agenda-default-appointment-duration)
+ hour-end)
+ (t (+ hour-end 2))))
+ (d (cond ((not end) day-start)
+ ((not with-time-p) (1+ day-end))
+ (t day-end)))
+ (m (if end month-end month-start))
+ (y (if end year-end year-start)))
+ (concat
+ keyword
+ (format-time-string
+ (cond (utc ":%Y%m%dT%H%M%SZ")
+ ((not with-time-p) ";VALUE=DATE:%Y%m%d")
+ (t (replace-regexp-in-string "%Z"
+ org-icalendar-timezone
+ org-icalendar-date-time-format
+ t)))
+ ;; Convert timestamp into internal time in order to use
+ ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
+ (encode-time 0 mi h d m y)
+ (and (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))
+ t)))))
+
+(defun org-icalendar-dtstamp ()
+ "Return DTSTAMP property, as a string."
+ (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
+
+(defun org-icalendar-get-categories (entry info)
+ "Return categories according to `org-icalendar-categories'.
+ENTRY is a headline or an inlinetask element. INFO is a plist
+used as a communication channel."
+ (mapconcat
+ #'identity
+ (org-uniquify
+ (let (categories)
+ (dolist (type org-icalendar-categories (nreverse categories))
+ (cl-case type
+ (category
+ (push (org-export-get-category entry info) categories))
+ (todo-state
+ (let ((todo (org-element-property :todo-keyword entry)))
+ (and todo (push todo categories))))
+ (local-tags
+ (setq categories
+ (append (nreverse (org-export-get-tags entry info))
+ categories)))
+ (all-tags
+ (setq categories
+ (append (nreverse (org-export-get-tags entry info nil t))
+ categories)))))))
+ ","))
+
+(defun org-icalendar-transcode-diary-sexp (sexp uid summary)
+ "Transcode a diary sexp into iCalendar format.
+SEXP is the diary sexp being transcoded, as a string. UID is the
+unique identifier for the entry. SUMMARY defines a short summary
+or subject for the event."
+ (when (require 'icalendar nil t)
+ (org-element-normalize-string
+ (with-temp-buffer
+ (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
+ (concat (substring sexp 1 -1) " " summary))))
+ (put-text-property 0 1 'uid uid sexp)
+ (insert sexp "\n"))
+ (org-diary-to-ical-string (current-buffer))))))
+
+(defun org-icalendar-cleanup-string (s)
+ "Cleanup string S according to RFC 5545."
+ (when s
+ ;; Protect "\", "," and ";" characters. and replace newline
+ ;; characters with literal \n.
+ (replace-regexp-in-string
+ "[ \t]*\n" "\\n"
+ (replace-regexp-in-string "[\\,;]" "\\\\\\&" s)
+ nil t)))
+
+(defun org-icalendar-fold-string (s)
+ "Fold string S according to RFC 5545."
+ (org-element-normalize-string
+ (mapconcat
+ (lambda (line)
+ ;; Limit each line to a maximum of 75 characters. If it is
+ ;; longer, fold it by using "\r\n " as a continuation marker.
+ (let ((len (length line)))
+ (if (<= len 75) line
+ (let ((folded-line (substring line 0 75))
+ (chunk-start 75)
+ chunk-end)
+ ;; Since continuation marker takes up one character on the
+ ;; line, real contents must be split at 74 chars.
+ (while (< (setq chunk-end (+ chunk-start 74)) len)
+ (setq folded-line
+ (concat folded-line "\r\n "
+ (substring line chunk-start chunk-end))
+ chunk-start chunk-end))
+ (concat folded-line "\r\n " (substring line chunk-start))))))
+ (org-split-string s "\n") "\r\n")))
+
+
+
+;;; Filters
+
+(defun org-icalendar-clear-blank-lines (headline _back-end _info)
+ "Remove blank lines in HEADLINE export.
+HEADLINE is a string representing a transcoded headline.
+BACK-END and INFO are ignored."
+ (replace-regexp-in-string "^\\(?:[ \t]*\n\\)+" "" headline))
+
+
+
+;;; Transcode Functions
+
+;;;; Headline and Inlinetasks
+
+;; The main function is `org-icalendar-entry', which extracts
+;; information from a headline or an inlinetask (summary,
+;; description...) and then delegates code generation to
+;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
+;; on the component needed.
+
+;; Obviously, `org-icalendar--valarm' handles alarms, which can
+;; happen within a VTODO component.
+
+(defun org-icalendar-entry (entry contents info)
+ "Transcode ENTRY element into iCalendar format.
+
+ENTRY is either a headline or an inlinetask. CONTENTS is
+ignored. INFO is a plist used as a communication channel.
+
+This function is called on every headline, the section below
+it (minus inlinetasks) being its contents. It tries to create
+VEVENT and VTODO components out of scheduled date, deadline date,
+plain timestamps, diary sexps. It also calls itself on every
+inlinetask within the section."
+ (unless (org-element-property :footnote-section-p entry)
+ (let* ((type (org-element-type entry))
+ ;; Determine contents really associated to the entry. For
+ ;; a headline, limit them to section, if any. For an
+ ;; inlinetask, this is every element within the task.
+ (inside
+ (if (eq type 'inlinetask)
+ (cons 'org-data (cons nil (org-element-contents entry)))
+ (let ((first (car (org-element-contents entry))))
+ (and (eq (org-element-type first) 'section)
+ (cons 'org-data
+ (cons nil (org-element-contents first))))))))
+ (concat
+ (let ((todo-type (org-element-property :todo-type entry))
+ (uid (or (org-element-property :ID entry) (org-id-new)))
+ (summary (org-icalendar-cleanup-string
+ (or (org-element-property :SUMMARY entry)
+ (org-export-data
+ (org-element-property :title entry) info))))
+ (loc (org-icalendar-cleanup-string
+ (org-element-property :LOCATION entry)))
+ ;; Build description of the entry from associated section
+ ;; (headline) or contents (inlinetask).
+ (desc
+ (org-icalendar-cleanup-string
+ (or (org-element-property :DESCRIPTION entry)
+ (let ((contents (org-export-data inside info)))
+ (cond
+ ((not (org-string-nw-p contents)) nil)
+ ((wholenump org-icalendar-include-body)
+ (let ((contents (org-trim contents)))
+ (substring
+ contents 0 (min (length contents)
+ org-icalendar-include-body))))
+ (org-icalendar-include-body (org-trim contents)))))))
+ (cat (org-icalendar-get-categories entry info)))
+ (concat
+ ;; Events: Delegate to `org-icalendar--vevent' to generate
+ ;; "VEVENT" component from scheduled, deadline, or any
+ ;; timestamp in the entry.
+ (let ((deadline (org-element-property :deadline entry)))
+ (and deadline
+ (memq (if todo-type 'event-if-todo 'event-if-not-todo)
+ org-icalendar-use-deadline)
+ (org-icalendar--vevent
+ entry deadline (concat "DL-" uid)
+ (concat "DL: " summary) loc desc cat)))
+ (let ((scheduled (org-element-property :scheduled entry)))
+ (and scheduled
+ (memq (if todo-type 'event-if-todo 'event-if-not-todo)
+ org-icalendar-use-scheduled)
+ (org-icalendar--vevent
+ entry scheduled (concat "SC-" uid)
+ (concat "S: " summary) loc desc cat)))
+ ;; When collecting plain timestamps from a headline and its
+ ;; title, skip inlinetasks since collection will happen once
+ ;; ENTRY is one of them.
+ (let ((counter 0))
+ (mapconcat
+ #'identity
+ (org-element-map (cons (org-element-property :title entry)
+ (org-element-contents inside))
+ 'timestamp
+ (lambda (ts)
+ (when (let ((type (org-element-property :type ts)))
+ (cl-case (plist-get info :with-timestamps)
+ (active (memq type '(active active-range)))
+ (inactive (memq type '(inactive inactive-range)))
+ ((t) t)))
+ (let ((uid (format "TS%d-%s" (cl-incf counter) uid)))
+ (org-icalendar--vevent
+ entry ts uid summary loc desc cat))))
+ info nil (and (eq type 'headline) 'inlinetask))
+ ""))
+ ;; Task: First check if it is appropriate to export it. If
+ ;; so, call `org-icalendar--vtodo' to transcode it into
+ ;; a "VTODO" component.
+ (when (and todo-type
+ (cl-case (plist-get info :icalendar-include-todo)
+ (all t)
+ (unblocked
+ (and (eq type 'headline)
+ (not (org-icalendar-blocked-headline-p
+ entry info))))
+ ((t) (eq todo-type 'todo))))
+ (org-icalendar--vtodo entry uid summary loc desc cat))
+ ;; Diary-sexp: Collect every diary-sexp element within ENTRY
+ ;; and its title, and transcode them. If ENTRY is
+ ;; a headline, skip inlinetasks: they will be handled
+ ;; separately.
+ (when org-icalendar-include-sexps
+ (let ((counter 0))
+ (mapconcat #'identity
+ (org-element-map
+ (cons (org-element-property :title entry)
+ (org-element-contents inside))
+ 'diary-sexp
+ (lambda (sexp)
+ (org-icalendar-transcode-diary-sexp
+ (org-element-property :value sexp)
+ (format "DS%d-%s" (cl-incf counter) uid)
+ summary))
+ info nil (and (eq type 'headline) 'inlinetask))
+ "")))))
+ ;; If ENTRY is a headline, call current function on every
+ ;; inlinetask within it. In agenda export, this is independent
+ ;; from the mark (or lack thereof) on the entry.
+ (when (eq type 'headline)
+ (mapconcat #'identity
+ (org-element-map inside 'inlinetask
+ (lambda (task) (org-icalendar-entry task nil info))
+ info) ""))
+ ;; Don't forget components from inner entries.
+ contents))))
+
+(defun org-icalendar--vevent
+ (entry timestamp uid summary location description categories)
+ "Create a VEVENT component.
+
+ENTRY is either a headline or an inlinetask element. TIMESTAMP
+is a timestamp object defining the date-time of the event. UID
+is the unique identifier for the event. SUMMARY defines a short
+summary or subject for the event. LOCATION defines the intended
+venue for the event. DESCRIPTION provides the complete
+description of the event. CATEGORIES defines the categories the
+event belongs to.
+
+Return VEVENT component as a string."
+ (org-icalendar-fold-string
+ (if (eq (org-element-property :type timestamp) 'diary)
+ (org-icalendar-transcode-diary-sexp
+ (org-element-property :raw-value timestamp) uid summary)
+ (concat "BEGIN:VEVENT\n"
+ (org-icalendar-dtstamp) "\n"
+ "UID:" uid "\n"
+ (org-icalendar-convert-timestamp timestamp "DTSTART") "\n"
+ (org-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
+ ;; RRULE.
+ (when (org-element-property :repeater-type timestamp)
+ (format "RRULE:FREQ=%s;INTERVAL=%d\n"
+ (cl-case (org-element-property :repeater-unit timestamp)
+ (hour "HOURLY") (day "DAILY") (week "WEEKLY")
+ (month "MONTHLY") (year "YEARLY"))
+ (org-element-property :repeater-value timestamp)))
+ "SUMMARY:" summary "\n"
+ (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
+ (and (org-string-nw-p description)
+ (format "DESCRIPTION:%s\n" description))
+ "CATEGORIES:" categories "\n"
+ ;; VALARM.
+ (org-icalendar--valarm entry timestamp summary)
+ "END:VEVENT"))))
+
+(defun org-icalendar--vtodo
+ (entry uid summary location description categories)
+ "Create a VTODO component.
+
+ENTRY is either a headline or an inlinetask element. UID is the
+unique identifier for the task. SUMMARY defines a short summary
+or subject for the task. LOCATION defines the intended venue for
+the task. DESCRIPTION provides the complete description of the
+task. CATEGORIES defines the categories the task belongs to.
+
+Return VTODO component as a string."
+ (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
+ (org-element-property :scheduled entry))
+ ;; If we can't use a scheduled time for some
+ ;; reason, start task now.
+ (let ((now (decode-time)))
+ (list 'timestamp
+ (list :type 'active
+ :minute-start (nth 1 now)
+ :hour-start (nth 2 now)
+ :day-start (nth 3 now)
+ :month-start (nth 4 now)
+ :year-start (nth 5 now)))))))
+ (org-icalendar-fold-string
+ (concat "BEGIN:VTODO\n"
+ "UID:TODO-" uid "\n"
+ (org-icalendar-dtstamp) "\n"
+ (org-icalendar-convert-timestamp start "DTSTART") "\n"
+ (and (memq 'todo-due org-icalendar-use-deadline)
+ (org-element-property :deadline entry)
+ (concat (org-icalendar-convert-timestamp
+ (org-element-property :deadline entry) "DUE")
+ "\n"))
+ "SUMMARY:" summary "\n"
+ (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
+ (and (org-string-nw-p description)
+ (format "DESCRIPTION:%s\n" description))
+ "CATEGORIES:" categories "\n"
+ "SEQUENCE:1\n"
+ (format "PRIORITY:%d\n"
+ (let ((pri (or (org-element-property :priority entry)
+ org-default-priority)))
+ (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
+ (- org-lowest-priority
+ org-highest-priority)))))))
+ (format "STATUS:%s\n"
+ (if (eq (org-element-property :todo-type entry) 'todo)
+ "NEEDS-ACTION"
+ "COMPLETED"))
+ "END:VTODO"))))
+
+(defun org-icalendar--valarm (entry timestamp summary)
+ "Create a VALARM component.
+
+ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
+the start date-time of the entry. SUMMARY defines a short
+summary or subject for the task.
+
+Return VALARM component as a string, or nil if it isn't allowed."
+ ;; Create a VALARM entry if the entry is timed. This is not very
+ ;; general in that:
+ ;; (a) only one alarm per entry is defined,
+ ;; (b) only minutes are allowed for the trigger period ahead of the
+ ;; start time,
+ ;; (c) only a DISPLAY action is defined. [ESF]
+ (let ((alarm-time
+ (let ((warntime
+ (org-element-property :APPT_WARNTIME entry)))
+ (if warntime (string-to-number warntime) 0))))
+ (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
+ (org-element-property :hour-start timestamp)
+ (format "BEGIN:VALARM
+ACTION:DISPLAY
+DESCRIPTION:%s
+TRIGGER:-P0DT0H%dM0S
+END:VALARM\n"
+ summary
+ (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
+
+
+;;;; Template
+
+(defun org-icalendar-template (contents info)
+ "Return complete document string after iCalendar conversion.
+CONTENTS is the transcoded contents string. INFO is a plist used
+as a communication channel."
+ (org-icalendar--vcalendar
+ ;; Name.
+ (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
+ (file-name-nondirectory
+ (file-name-sans-extension (plist-get info :input-file))))
+ ;; Owner.
+ (if (not (plist-get info :with-author)) ""
+ (org-export-data (plist-get info :author) info))
+ ;; Timezone.
+ (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
+ (cadr (current-time-zone)))
+ ;; Description.
+ (org-export-data (plist-get info :title) info)
+ contents))
+
+(defun org-icalendar--vcalendar (name owner tz description contents)
+ "Create a VCALENDAR component.
+NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
+respectively, the name of the calendar, its owner, the timezone
+used, a short description and the other components included."
+ (concat (format "BEGIN:VCALENDAR
+VERSION:2.0
+X-WR-CALNAME:%s
+PRODID:-//%s//Emacs with Org mode//EN
+X-WR-TIMEZONE:%s
+X-WR-CALDESC:%s
+CALSCALE:GREGORIAN\n"
+ (org-icalendar-cleanup-string name)
+ (org-icalendar-cleanup-string owner)
+ (org-icalendar-cleanup-string tz)
+ (org-icalendar-cleanup-string description))
+ contents
+ "END:VCALENDAR\n"))
+
+
+
+;;; Interactive Functions
+
+;;;###autoload
+(defun org-icalendar-export-to-ics
+ (&optional async subtreep visible-only body-only)
+ "Export current buffer to an iCalendar file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
+
+Return ICS file name."
+ (interactive)
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (when (and file org-icalendar-store-UID)
+ (org-icalendar-create-uid file 'warn-user)))
+ ;; Export part. Since this back-end is backed up by `ascii', ensure
+ ;; links will not be collected at the end of sections.
+ (let ((outfile (org-export-output-file-name ".ics" subtreep)))
+ (org-export-to-file 'icalendar outfile
+ async subtreep visible-only body-only
+ '(:ascii-charset utf-8 :ascii-links-to-notes nil)
+ (lambda (file)
+ (run-hook-with-args 'org-icalendar-after-save-hook file) nil))))
+
+;;;###autoload
+(defun org-icalendar-export-agenda-files (&optional async)
+ "Export all agenda files to iCalendar files.
+When optional argument ASYNC is non-nil, export happens in an
+external process."
+ (interactive)
+ (if async
+ ;; Asynchronous export is not interactive, so we will not call
+ ;; `org-check-agenda-file'. Instead we remove any non-existent
+ ;; agenda file from the list.
+ (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
+ (org-export-async-start
+ (lambda (results)
+ (dolist (f results) (org-export-add-to-stack f 'icalendar)))
+ `(let (output-files)
+ (dolist (file ',files outputfiles)
+ (with-current-buffer (org-get-agenda-file-buffer file)
+ (push (expand-file-name (org-icalendar-export-to-ics))
+ output-files))))))
+ (let ((files (org-agenda-files t)))
+ (org-agenda-prepare-buffers files)
+ (unwind-protect
+ (dolist (file files)
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (with-current-buffer (org-get-agenda-file-buffer file)
+ (org-icalendar-export-to-ics))))
+ (org-release-buffers org-agenda-new-buffers)))))
+
+;;;###autoload
+(defun org-icalendar-combine-agenda-files (&optional async)
+ "Combine all agenda files into a single iCalendar file.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+The file is stored under the name chosen in
+`org-icalendar-combined-agenda-file'."
+ (interactive)
+ (if async
+ (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
+ (org-export-async-start
+ (lambda (_)
+ (org-export-add-to-stack
+ (expand-file-name org-icalendar-combined-agenda-file)
+ 'icalendar))
+ `(apply #'org-icalendar--combine-files ',files)))
+ (apply #'org-icalendar--combine-files (org-agenda-files t))))
+
+(defun org-icalendar-export-current-agenda (file)
+ "Export current agenda view to an iCalendar FILE.
+This function assumes major mode for current buffer is
+`org-agenda-mode'."
+ (let* ((org-export-babel-evaluate) ; Don't evaluate Babel block.
+ (contents
+ (org-export-string-as
+ (with-output-to-string
+ (save-excursion
+ (let ((p (point-min)))
+ (while (setq p (next-single-property-change p 'org-hd-marker))
+ (let ((m (get-text-property p 'org-hd-marker)))
+ (when m
+ (with-current-buffer (marker-buffer m)
+ (org-with-wide-buffer
+ (goto-char (marker-position m))
+ (princ
+ (org-element-normalize-string
+ (buffer-substring
+ (point) (progn (outline-next-heading) (point)))))))))
+ (forward-line)))))
+ 'icalendar t
+ '(:ascii-charset utf-8 :ascii-links-to-notes nil
+ :icalendar-include-todo all))))
+ (with-temp-file file
+ (insert
+ (org-icalendar--vcalendar
+ org-icalendar-combined-name
+ user-full-name
+ (or (org-string-nw-p org-icalendar-timezone) (cadr (current-time-zone)))
+ org-icalendar-combined-description
+ contents)))
+ (run-hook-with-args 'org-icalendar-after-save-hook file)))
+
+(defun org-icalendar--combine-files (&rest files)
+ "Combine entries from multiple files into an iCalendar file.
+FILES is a list of files to build the calendar from."
+ (org-agenda-prepare-buffers files)
+ (unwind-protect
+ (progn
+ (with-temp-file org-icalendar-combined-agenda-file
+ (insert
+ (org-icalendar--vcalendar
+ ;; Name.
+ org-icalendar-combined-name
+ ;; Owner.
+ user-full-name
+ ;; Timezone.
+ (or (org-string-nw-p org-icalendar-timezone)
+ (cadr (current-time-zone)))
+ ;; Description.
+ org-icalendar-combined-description
+ ;; Contents.
+ (concat
+ ;; Agenda contents.
+ (mapconcat
+ (lambda (file)
+ (catch 'nextfile
+ (org-check-agenda-file file)
+ (with-current-buffer (org-get-agenda-file-buffer file)
+ ;; Create ID if necessary.
+ (when org-icalendar-store-UID
+ (org-icalendar-create-uid file t))
+ (org-export-as
+ 'icalendar nil nil t
+ '(:ascii-charset utf-8 :ascii-links-to-notes nil)))))
+ files "")
+ ;; BBDB anniversaries.
+ (when (and org-icalendar-include-bbdb-anniversaries
+ (require 'org-bbdb nil t))
+ (with-output-to-string (org-bbdb-anniv-export-ical)))))))
+ (run-hook-with-args 'org-icalendar-after-save-hook
+ org-icalendar-combined-agenda-file))
+ (org-release-buffers org-agenda-new-buffers)))
+
+
+(provide 'ox-icalendar)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-icalendar.el ends here
diff --git a/lisp/ox-latex.el b/lisp/ox-latex.el
new file mode 100644
index 0000000..f11a8a6
--- /dev/null
+++ b/lisp/ox-latex.el
@@ -0,0 +1,3711 @@
+;;; ox-latex.el --- LaTeX Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; See Org manual for details.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox)
+(require 'ox-publish)
+
+(defvar org-latex-default-packages-alist)
+(defvar org-latex-packages-alist)
+(defvar orgtbl-exp-regexp)
+
+
+
+;;; Define Back-End
+
+(org-export-define-backend 'latex
+ '((bold . org-latex-bold)
+ (center-block . org-latex-center-block)
+ (clock . org-latex-clock)
+ (code . org-latex-code)
+ (drawer . org-latex-drawer)
+ (dynamic-block . org-latex-dynamic-block)
+ (entity . org-latex-entity)
+ (example-block . org-latex-example-block)
+ (export-block . org-latex-export-block)
+ (export-snippet . org-latex-export-snippet)
+ (fixed-width . org-latex-fixed-width)
+ (footnote-definition . org-latex-footnote-definition)
+ (footnote-reference . org-latex-footnote-reference)
+ (headline . org-latex-headline)
+ (horizontal-rule . org-latex-horizontal-rule)
+ (inline-src-block . org-latex-inline-src-block)
+ (inlinetask . org-latex-inlinetask)
+ (italic . org-latex-italic)
+ (item . org-latex-item)
+ (keyword . org-latex-keyword)
+ (latex-environment . org-latex-latex-environment)
+ (latex-fragment . org-latex-latex-fragment)
+ (line-break . org-latex-line-break)
+ (link . org-latex-link)
+ (node-property . org-latex-node-property)
+ (paragraph . org-latex-paragraph)
+ (plain-list . org-latex-plain-list)
+ (plain-text . org-latex-plain-text)
+ (planning . org-latex-planning)
+ (property-drawer . org-latex-property-drawer)
+ (quote-block . org-latex-quote-block)
+ (radio-target . org-latex-radio-target)
+ (section . org-latex-section)
+ (special-block . org-latex-special-block)
+ (src-block . org-latex-src-block)
+ (statistics-cookie . org-latex-statistics-cookie)
+ (strike-through . org-latex-strike-through)
+ (subscript . org-latex-subscript)
+ (superscript . org-latex-superscript)
+ (table . org-latex-table)
+ (table-cell . org-latex-table-cell)
+ (table-row . org-latex-table-row)
+ (target . org-latex-target)
+ (template . org-latex-template)
+ (timestamp . org-latex-timestamp)
+ (underline . org-latex-underline)
+ (verbatim . org-latex-verbatim)
+ (verse-block . org-latex-verse-block)
+ ;; Pseudo objects and elements.
+ (latex-math-block . org-latex-math-block)
+ (latex-matrices . org-latex-matrices))
+ :menu-entry
+ '(?l "Export to LaTeX"
+ ((?L "As LaTeX buffer" org-latex-export-as-latex)
+ (?l "As LaTeX file" org-latex-export-to-latex)
+ (?p "As PDF file" org-latex-export-to-pdf)
+ (?o "As PDF file and open"
+ (lambda (a s v b)
+ (if a (org-latex-export-to-pdf t s v b)
+ (org-open-file (org-latex-export-to-pdf nil s v b)))))))
+ :filters-alist '((:filter-options . org-latex-math-block-options-filter)
+ (:filter-paragraph . org-latex-clean-invalid-line-breaks)
+ (:filter-parse-tree org-latex-math-block-tree-filter
+ org-latex-matrices-tree-filter)
+ (:filter-verse-block . org-latex-clean-invalid-line-breaks))
+ :options-alist
+ '((:latex-class "LATEX_CLASS" nil org-latex-default-class t)
+ (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
+ (:latex-header "LATEX_HEADER" nil nil newline)
+ (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline)
+ (:description "DESCRIPTION" nil nil parse)
+ (:keywords "KEYWORDS" nil nil parse)
+ (:subtitle "SUBTITLE" nil nil parse)
+ ;; Other variables.
+ (:latex-active-timestamp-format nil nil org-latex-active-timestamp-format)
+ (:latex-caption-above nil nil org-latex-caption-above)
+ (:latex-classes nil nil org-latex-classes)
+ (:latex-default-figure-position nil nil org-latex-default-figure-position)
+ (:latex-default-table-environment nil nil org-latex-default-table-environment)
+ (:latex-default-table-mode nil nil org-latex-default-table-mode)
+ (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format)
+ (:latex-footnote-defined-format nil nil org-latex-footnote-defined-format)
+ (:latex-footnote-separator nil nil org-latex-footnote-separator)
+ (:latex-format-drawer-function nil nil org-latex-format-drawer-function)
+ (:latex-format-headline-function nil nil org-latex-format-headline-function)
+ (:latex-format-inlinetask-function nil nil org-latex-format-inlinetask-function)
+ (:latex-hyperref-template nil nil org-latex-hyperref-template t)
+ (:latex-image-default-height nil nil org-latex-image-default-height)
+ (:latex-image-default-option nil nil org-latex-image-default-option)
+ (:latex-image-default-width nil nil org-latex-image-default-width)
+ (:latex-images-centered nil nil org-latex-images-centered)
+ (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format)
+ (:latex-inline-image-rules nil nil org-latex-inline-image-rules)
+ (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format)
+ (:latex-listings nil nil org-latex-listings)
+ (:latex-listings-langs nil nil org-latex-listings-langs)
+ (:latex-listings-options nil nil org-latex-listings-options)
+ (:latex-minted-langs nil nil org-latex-minted-langs)
+ (:latex-minted-options nil nil org-latex-minted-options)
+ (:latex-prefer-user-labels nil nil org-latex-prefer-user-labels)
+ (:latex-subtitle-format nil nil org-latex-subtitle-format)
+ (:latex-subtitle-separate nil nil org-latex-subtitle-separate)
+ (:latex-table-scientific-notation nil nil org-latex-table-scientific-notation)
+ (:latex-tables-booktabs nil nil org-latex-tables-booktabs)
+ (:latex-tables-centered nil nil org-latex-tables-centered)
+ (:latex-text-markup-alist nil nil org-latex-text-markup-alist)
+ (:latex-title-command nil nil org-latex-title-command)
+ (:latex-toc-command nil nil org-latex-toc-command)
+ (:latex-compiler "LATEX_COMPILER" nil org-latex-compiler)
+ ;; Redefine regular options.
+ (:date "DATE" nil "\\today" parse)))
+
+
+
+;;; Internal Variables
+
+(defconst org-latex-babel-language-alist
+ '(("af" . "afrikaans")
+ ("bg" . "bulgarian")
+ ("bt-br" . "brazilian")
+ ("ca" . "catalan")
+ ("cs" . "czech")
+ ("cy" . "welsh")
+ ("da" . "danish")
+ ("de" . "germanb")
+ ("de-at" . "naustrian")
+ ("de-de" . "ngerman")
+ ("el" . "greek")
+ ("en" . "english")
+ ("en-au" . "australian")
+ ("en-ca" . "canadian")
+ ("en-gb" . "british")
+ ("en-ie" . "irish")
+ ("en-nz" . "newzealand")
+ ("en-us" . "american")
+ ("es" . "spanish")
+ ("et" . "estonian")
+ ("eu" . "basque")
+ ("fi" . "finnish")
+ ("fr" . "frenchb")
+ ("fr-ca" . "canadien")
+ ("gl" . "galician")
+ ("hr" . "croatian")
+ ("hu" . "hungarian")
+ ("id" . "indonesian")
+ ("is" . "icelandic")
+ ("it" . "italian")
+ ("la" . "latin")
+ ("ms" . "malay")
+ ("nl" . "dutch")
+ ("nb" . "norsk")
+ ("nn" . "nynorsk")
+ ("no" . "norsk")
+ ("pl" . "polish")
+ ("pt" . "portuguese")
+ ("ro" . "romanian")
+ ("ru" . "russian")
+ ("sa" . "sanskrit")
+ ("sb" . "uppersorbian")
+ ("sk" . "slovak")
+ ("sl" . "slovene")
+ ("sq" . "albanian")
+ ("sr" . "serbian")
+ ("sv" . "swedish")
+ ("ta" . "tamil")
+ ("tr" . "turkish")
+ ("uk" . "ukrainian"))
+ "Alist between language code and corresponding Babel option.")
+
+(defconst org-latex-polyglossia-language-alist
+ '(("am" "amharic")
+ ("ast" "asturian")
+ ("ar" "arabic")
+ ("bo" "tibetan")
+ ("bn" "bengali")
+ ("bg" "bulgarian")
+ ("br" "breton")
+ ("bt-br" "brazilian")
+ ("ca" "catalan")
+ ("cop" "coptic")
+ ("cs" "czech")
+ ("cy" "welsh")
+ ("da" "danish")
+ ("de" "german" "german")
+ ("de-at" "german" "austrian")
+ ("de-de" "german" "german")
+ ("dv" "divehi")
+ ("el" "greek")
+ ("en" "english" "usmax")
+ ("en-au" "english" "australian")
+ ("en-gb" "english" "uk")
+ ("en-nz" "english" "newzealand")
+ ("en-us" "english" "usmax")
+ ("eo" "esperanto")
+ ("es" "spanish")
+ ("et" "estonian")
+ ("eu" "basque")
+ ("fa" "farsi")
+ ("fi" "finnish")
+ ("fr" "french")
+ ("fu" "friulan")
+ ("ga" "irish")
+ ("gd" "scottish")
+ ("gl" "galician")
+ ("he" "hebrew")
+ ("hi" "hindi")
+ ("hr" "croatian")
+ ("hu" "magyar")
+ ("hy" "armenian")
+ ("id" "bahasai")
+ ("ia" "interlingua")
+ ("is" "icelandic")
+ ("it" "italian")
+ ("kn" "kannada")
+ ("la" "latin" "modern")
+ ("la-modern" "latin" "modern")
+ ("la-classic" "latin" "classic")
+ ("la-medieval" "latin" "medieval")
+ ("lo" "lao")
+ ("lt" "lithuanian")
+ ("lv" "latvian")
+ ("mr" "maranthi")
+ ("ml" "malayalam")
+ ("nl" "dutch")
+ ("nb" "norsk")
+ ("nn" "nynorsk")
+ ("nko" "nko")
+ ("no" "norsk")
+ ("oc" "occitan")
+ ("pl" "polish")
+ ("pms" "piedmontese")
+ ("pt" "portuges")
+ ("rm" "romansh")
+ ("ro" "romanian")
+ ("ru" "russian")
+ ("sa" "sanskrit")
+ ("hsb" "usorbian")
+ ("dsb" "lsorbian")
+ ("sk" "slovak")
+ ("sl" "slovenian")
+ ("se" "samin")
+ ("sq" "albanian")
+ ("sr" "serbian")
+ ("sv" "swedish")
+ ("syr" "syriac")
+ ("ta" "tamil")
+ ("te" "telugu")
+ ("th" "thai")
+ ("tk" "turkmen")
+ ("tr" "turkish")
+ ("uk" "ukrainian")
+ ("ur" "urdu")
+ ("vi" "vietnamese"))
+ "Alist between language code and corresponding Polyglossia option")
+
+
+
+(defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
+ ("qbordermatrix" . "\\cr")
+ ("kbordermatrix" . "\\\\"))
+ "Alist between matrix macros and their row ending.")
+
+(defconst org-latex-math-environments-re
+ (format
+ "\\`[ \t]*\\\\begin{%s\\*?}"
+ (regexp-opt
+ '("equation" "eqnarray" "math" "displaymath"
+ "align" "gather" "multline" "flalign" "alignat"
+ "xalignat" "xxalignat"
+ "subequations"
+ ;; breqn
+ "dmath" "dseries" "dgroup" "darray"
+ ;; empheq
+ "empheq")))
+ "Regexp of LaTeX math environments.")
+
+
+;;; User Configurable Variables
+
+(defgroup org-export-latex nil
+ "Options for exporting Org mode files to LaTeX."
+ :tag "Org Export LaTeX"
+ :group 'org-export)
+
+;;;; Generic
+
+(defcustom org-latex-caption-above '(table)
+ "When non-nil, place caption string at the beginning of elements.
+Otherwise, place it near the end. When value is a list of
+symbols, put caption above selected elements only. Allowed
+symbols are: `image', `table', `src-block' and `special-block'."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "For all elements" t)
+ (const :tag "For no element" nil)
+ (set :tag "For the following elements only" :greedy t
+ (const :tag "Images" image)
+ (const :tag "Tables" table)
+ (const :tag "Source code" src-block)
+ (const :tag "Special blocks" special-block))))
+
+(defcustom org-latex-prefer-user-labels nil
+ "Use user-provided labels instead of internal ones when non-nil.
+
+When this variable is non-nil, Org will use the value of
+CUSTOM_ID property, NAME keyword or Org target as the key for the
+\\label commands generated.
+
+By default, Org generates its own internal labels during LaTeX
+export. This process ensures that the \\label keys are unique
+and valid, but it means the keys are not available in advance of
+the export process.
+
+Setting this variable gives you control over how Org generates
+labels during LaTeX export, so that you may know their keys in
+advance. One reason to do this is that it allows you to refer to
+various elements using a single label both in Org's link syntax
+and in embedded LaTeX code.
+
+For example, when this variable is non-nil, a headline like this:
+
+ ** Some section
+ :PROPERTIES:
+ :CUSTOM_ID: sec:foo
+ :END:
+ This is section [[#sec:foo]].
+ #+BEGIN_EXPORT latex
+ And this is still section \\ref{sec:foo}.
+ #+END_EXPORT
+
+will be exported to LaTeX as:
+
+ \\subsection{Some section}
+ \\label{sec:foo}
+ This is section \\ref{sec:foo}.
+ And this is still section \\ref{sec:foo}.
+
+Note, however, that setting this variable introduces a limitation
+on the possible values for CUSTOM_ID and NAME. When this
+variable is non-nil, Org passes their value to \\label unchanged.
+You are responsible for ensuring that the value is a valid LaTeX
+\\label key, and that no other \\label commands with the same key
+appear elsewhere in your document. (Keys may contain letters,
+numbers, and the following punctuation: '_' '.' '-' ':'.) There
+are no such limitations on CUSTOM_ID and NAME when this variable
+is nil.
+
+For headlines that do not define the CUSTOM_ID property or
+elements without a NAME, Org will continue to use its default
+labeling scheme to generate labels and resolve links into proper
+references."
+ :group 'org-export-latex
+ :type 'boolean
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+;;;; Preamble
+
+(defcustom org-latex-default-class "article"
+ "The default LaTeX class."
+ :group 'org-export-latex
+ :type '(string :tag "LaTeX class"))
+
+(defcustom org-latex-classes
+ '(("article"
+ "\\documentclass[11pt]{article}"
+ ("\\section{%s}" . "\\section*{%s}")
+ ("\\subsection{%s}" . "\\subsection*{%s}")
+ ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
+ ("\\paragraph{%s}" . "\\paragraph*{%s}")
+ ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
+ ("report"
+ "\\documentclass[11pt]{report}"
+ ("\\part{%s}" . "\\part*{%s}")
+ ("\\chapter{%s}" . "\\chapter*{%s}")
+ ("\\section{%s}" . "\\section*{%s}")
+ ("\\subsection{%s}" . "\\subsection*{%s}")
+ ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
+ ("book"
+ "\\documentclass[11pt]{book}"
+ ("\\part{%s}" . "\\part*{%s}")
+ ("\\chapter{%s}" . "\\chapter*{%s}")
+ ("\\section{%s}" . "\\section*{%s}")
+ ("\\subsection{%s}" . "\\subsection*{%s}")
+ ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
+ "Alist of LaTeX classes and associated header and structure.
+If #+LATEX_CLASS is set in the buffer, use its value and the
+associated information. Here is the structure of each cell:
+
+ (class-name
+ header-string
+ (numbered-section . unnumbered-section)
+ ...)
+
+The header string
+-----------------
+
+The HEADER-STRING is the header that will be inserted into the
+LaTeX file. It should contain the \\documentclass macro, and
+anything else that is needed for this setup. To this header, the
+following commands will be added:
+
+- Calls to \\usepackage for all packages mentioned in the
+ variables `org-latex-default-packages-alist' and
+ `org-latex-packages-alist'. Thus, your header definitions
+ should avoid to also request these packages.
+
+- Lines specified via \"#+LATEX_HEADER:\" and
+ \"#+LATEX_HEADER_EXTRA:\" keywords.
+
+If you need more control about the sequence in which the header
+is built up, or if you want to exclude one of these building
+blocks for a particular class, you can use the following
+macro-like placeholders.
+
+ [DEFAULT-PACKAGES] \\usepackage statements for default packages
+ [NO-DEFAULT-PACKAGES] do not include any of the default packages
+ [PACKAGES] \\usepackage statements for packages
+ [NO-PACKAGES] do not include the packages
+ [EXTRA] the stuff from #+LATEX_HEADER(_EXTRA)
+ [NO-EXTRA] do not include #+LATEX_HEADER(_EXTRA) stuff
+
+So a header like
+
+ \\documentclass{article}
+ [NO-DEFAULT-PACKAGES]
+ [EXTRA]
+ \\providecommand{\\alert}[1]{\\textbf{#1}}
+ [PACKAGES]
+
+will omit the default packages, and will include the
+#+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call
+to \\providecommand, and then place \\usepackage commands based
+on the content of `org-latex-packages-alist'.
+
+If your header, `org-latex-default-packages-alist' or
+`org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\",
+AUTO will automatically be replaced with a coding system derived
+from `buffer-file-coding-system'. See also the variable
+`org-latex-inputenc-alist' for a way to influence this mechanism.
+
+Likewise, if your header contains \"\\usepackage[AUTO]{babel}\"
+or \"\\usepackage[AUTO]{polyglossia}\", AUTO will be replaced
+with the language related to the language code specified by
+`org-export-default-language'. Note that constructions such as
+\"\\usepackage[french,AUTO,english]{babel}\" are permitted. For
+Polyglossia the language will be set via the macros
+\"\\setmainlanguage\" and \"\\setotherlanguage\". See also
+`org-latex-guess-babel-language' and
+`org-latex-guess-polyglossia-language'.
+
+The sectioning structure
+------------------------
+
+The sectioning structure of the class is given by the elements
+following the header string. For each sectioning level, a number
+of strings is specified. A %s formatter is mandatory in each
+section string and will be replaced by the title of the section.
+
+Instead of a cons cell (numbered . unnumbered), you can also
+provide a list of 2 or 4 elements,
+
+ (numbered-open numbered-close)
+
+or
+
+ (numbered-open numbered-close unnumbered-open unnumbered-close)
+
+providing opening and closing strings for a LaTeX environment
+that should represent the document section. The opening clause
+should have a %s to represent the section title.
+
+Instead of a list of sectioning commands, you can also specify
+a function name. That function will be called with two
+parameters, the (reduced) level of the headline, and a predicate
+non-nil when the headline should be numbered. It must return
+a format string in which the section title will be added."
+ :group 'org-export-latex
+ :type '(repeat
+ (list (string :tag "LaTeX class")
+ (string :tag "LaTeX header")
+ (repeat :tag "Levels" :inline t
+ (choice
+ (cons :tag "Heading"
+ (string :tag " numbered")
+ (string :tag "unnumbered"))
+ (list :tag "Environment"
+ (string :tag "Opening (numbered)")
+ (string :tag "Closing (numbered)")
+ (string :tag "Opening (unnumbered)")
+ (string :tag "Closing (unnumbered)"))
+ (function :tag "Hook computing sectioning"))))))
+
+(defcustom org-latex-inputenc-alist nil
+ "Alist of inputenc coding system names, and what should really be used.
+For example, adding an entry
+
+ (\"utf8\" . \"utf8x\")
+
+will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
+are written as utf8 files."
+ :group 'org-export-latex
+ :type '(repeat
+ (cons
+ (string :tag "Derived from buffer")
+ (string :tag "Use this instead"))))
+
+(defcustom org-latex-title-command "\\maketitle"
+ "The command used to insert the title just after \\begin{document}.
+
+This format string may contain these elements:
+
+ %a for AUTHOR keyword
+ %t for TITLE keyword
+ %s for SUBTITLE keyword
+ %k for KEYWORDS line
+ %d for DESCRIPTION line
+ %c for CREATOR line
+ %l for Language keyword
+ %L for capitalized language keyword
+ %D for DATE keyword
+
+If you need to use a \"%\" character, you need to escape it
+like that: \"%%\".
+
+Setting :latex-title-command in publishing projects will take
+precedence over this variable."
+ :group 'org-export-latex
+ :type '(string :tag "Format string"))
+
+(defcustom org-latex-subtitle-format "\\\\\\medskip\n\\large %s"
+ "Format string used for transcoded subtitle.
+The format string should have at most one \"%s\"-expression,
+which is replaced with the subtitle."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(string :tag "Format string"))
+
+(defcustom org-latex-subtitle-separate nil
+ "Non-nil means the subtitle is not typeset as part of title."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'boolean)
+
+(defcustom org-latex-toc-command "\\tableofcontents\n\n"
+ "LaTeX command to set the table of contents, list of figures, etc.
+This command only applies to the table of contents generated with
+the toc:nil option, not to those generated with #+TOC keyword."
+ :group 'org-export-latex
+ :type 'string)
+
+(defcustom org-latex-hyperref-template
+ "\\hypersetup{\n pdfauthor={%a},\n pdftitle={%t},\n pdfkeywords={%k},
+ pdfsubject={%d},\n pdfcreator={%c}, \n pdflang={%L}}\n"
+ "Template for hyperref package options.
+
+This format string may contain these elements:
+
+ %a for AUTHOR keyword
+ %t for TITLE keyword
+ %s for SUBTITLE keyword
+ %k for KEYWORDS line
+ %d for DESCRIPTION line
+ %c for CREATOR line
+ %l for Language keyword
+ %L for capitalized language keyword
+ %D for DATE keyword
+
+If you need to use a \"%\" character, you need to escape it
+like that: \"%%\".
+
+As a special case, a nil value prevents template from being
+inserted.
+
+Setting :latex-hyperref-template in publishing projects will take
+precedence over this variable."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice (const :tag "No template" nil)
+ (string :tag "Format string")))
+
+;;;; Headline
+
+(defcustom org-latex-format-headline-function
+ 'org-latex-format-headline-default-function
+ "Function for formatting the headline's text.
+
+This function will be called with six arguments:
+TODO the todo keyword (string or nil)
+TODO-TYPE the type of todo (symbol: `todo', `done', nil)
+PRIORITY the priority of the headline (integer or nil)
+TEXT the main headline text (string)
+TAGS the tags (list of strings or nil)
+INFO the export options (plist)
+
+The function result will be used in the section format string."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'function)
+
+
+;;;; Footnotes
+
+(defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
+ "Text used to separate footnotes."
+ :group 'org-export-latex
+ :type 'string)
+
+(defcustom org-latex-footnote-defined-format "\\textsuperscript{\\ref{%s}}"
+ "Format string used to format reference to footnote already defined.
+%s will be replaced by the label of the referred footnote."
+ :group 'org-export-latex
+ :type '(choice
+ (const :tag "Use plain superscript (default)" "\\textsuperscript{\\ref{%s}}")
+ (const :tag "Use Memoir/KOMA-Script footref" "\\footref{%s}")
+ (string :tag "Other format string"))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+;;;; Timestamps
+
+(defcustom org-latex-active-timestamp-format "\\textit{%s}"
+ "A printf format string to be applied to active timestamps."
+ :group 'org-export-latex
+ :type 'string)
+
+(defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
+ "A printf format string to be applied to inactive timestamps."
+ :group 'org-export-latex
+ :type 'string)
+
+(defcustom org-latex-diary-timestamp-format "\\textit{%s}"
+ "A printf format string to be applied to diary timestamps."
+ :group 'org-export-latex
+ :type 'string)
+
+
+;;;; Links
+
+(defcustom org-latex-images-centered t
+ "When non-nil, images are centered."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-latex-image-default-option ""
+ "Default option for images."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-latex-image-default-width ".9\\linewidth"
+ "Default width for images.
+This value will not be used if a height is provided."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-latex-image-default-height ""
+ "Default height for images.
+This value will not be used if a width is provided, or if the
+image is wrapped within a \"figure\" or \"wrapfigure\"
+environment."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-latex-default-figure-position "htbp"
+ "Default position for LaTeX figures."
+ :group 'org-export-latex
+ :type 'string
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :safe #'stringp)
+
+(defcustom org-latex-inline-image-rules
+ '(("file" . "\\.\\(pdf\\|jpeg\\|jpg\\|png\\|ps\\|eps\\|tikz\\|pgf\\|svg\\)\\'"))
+ "Rules characterizing image files that can be inlined into LaTeX.
+
+A rule consists in an association whose key is the type of link
+to consider, and value is a regexp that will be matched against
+link's path.
+
+Note that, by default, the image extension *actually* allowed
+depend on the way the LaTeX file is processed. When used with
+pdflatex, pdf, jpg and png images are OK. When processing
+through dvi to Postscript, only ps and eps are allowed. The
+default we use here encompasses both."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(alist :key-type (string :tag "Type")
+ :value-type (regexp :tag "Path")))
+
+(defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
+ "Format string for links with unknown path type."
+ :group 'org-export-latex
+ :type 'string)
+
+
+;;;; Tables
+
+(defcustom org-latex-default-table-environment "tabular"
+ "Default environment used to build tables."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'string)
+
+(defcustom org-latex-default-table-mode 'table
+ "Default mode for tables.
+
+Value can be a symbol among:
+
+ `table' Regular LaTeX table.
+
+ `math' In this mode, every cell is considered as being in math
+ mode and the complete table will be wrapped within a math
+ environment. It is particularly useful to write matrices.
+
+ `inline-math' This mode is almost the same as `math', but the
+ math environment will be inlined.
+
+ `verbatim' The table is exported as it appears in the Org
+ buffer, within a verbatim environment.
+
+This value can be overridden locally with, i.e. \":mode math\" in
+LaTeX attributes.
+
+When modifying this variable, it may be useful to change
+`org-latex-default-table-environment' accordingly."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice (const :tag "Table" table)
+ (const :tag "Matrix" math)
+ (const :tag "Inline matrix" inline-math)
+ (const :tag "Verbatim" verbatim))
+ :safe (lambda (s) (memq s '(table math inline-math verbatim))))
+
+(defcustom org-latex-tables-centered t
+ "When non-nil, tables are exported in a center environment."
+ :group 'org-export-latex
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-latex-tables-booktabs nil
+ "When non-nil, display tables in a formal \"booktabs\" style.
+This option assumes that the \"booktabs\" package is properly
+loaded in the header of the document. This value can be ignored
+locally with \":booktabs t\" and \":booktabs nil\" LaTeX
+attributes."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-latex-table-scientific-notation "%s\\,(%s)"
+ "Format string to display numbers in scientific notation.
+The format should have \"%s\" twice, for mantissa and exponent
+\(i.e., \"%s\\\\times10^{%s}\").
+
+When nil, no transformation is made."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (string :tag "Format string")
+ (const :tag "No formatting" nil)))
+
+;;;; Text markup
+
+(defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
+ (code . protectedtexttt)
+ (italic . "\\emph{%s}")
+ (strike-through . "\\sout{%s}")
+ (underline . "\\uline{%s}")
+ (verbatim . protectedtexttt))
+ "Alist of LaTeX expressions to convert text markup.
+
+The key must be a symbol among `bold', `code', `italic',
+`strike-through', `underline' and `verbatim'. The value is
+a formatting string to wrap fontified text with.
+
+Value can also be set to the following symbols: `verb' and
+`protectedtexttt'. For the former, Org will use \"\\verb\" to
+create a format string and select a delimiter character that
+isn't in the string. For the latter, Org will use \"\\texttt\"
+to typeset and try to protect special characters.
+
+If no association can be found for a given markup, text will be
+returned as-is."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'alist
+ :options '(bold code italic strike-through underline verbatim))
+
+
+;;;; Drawers
+
+(defcustom org-latex-format-drawer-function (lambda (_ contents) contents)
+ "Function called to format a drawer in LaTeX code.
+
+The function must accept two parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+
+The function should return the string to be exported.
+
+The default function simply returns the value of CONTENTS."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+
+;;;; Inlinetasks
+
+(defcustom org-latex-format-inlinetask-function
+ 'org-latex-format-inlinetask-default-function
+ "Function called to format an inlinetask in LaTeX code.
+
+The function must accept seven parameters:
+ TODO the todo keyword (string or nil)
+ TODO-TYPE the todo type (symbol: `todo', `done', nil)
+ PRIORITY the inlinetask priority (integer or nil)
+ NAME the inlinetask name (string)
+ TAGS the inlinetask tags (list of strings or nil)
+ CONTENTS the contents of the inlinetask (string or nil)
+ INFO the export options (plist)
+
+The function should return the string to be exported."
+ :group 'org-export-latex
+ :type 'function
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+
+;; Src blocks
+
+(defcustom org-latex-listings nil
+ "Non-nil means export source code using the listings package.
+
+This package will fontify source code, possibly even with color.
+If you want to use this, you also need to make LaTeX use the
+listings package, and if you want to have color, the color
+package. Just add these to `org-latex-packages-alist', for
+example using customize, or with something like:
+
+ (require \\='ox-latex)
+ (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
+ (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
+
+Alternatively,
+
+ (setq org-latex-listings \\='minted)
+
+causes source code to be exported using the minted package as
+opposed to listings. If you want to use minted, you need to add
+the minted package to `org-latex-packages-alist', for example
+using customize, or with
+
+ (require \\='ox-latex)
+ (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
+
+In addition, it is necessary to install pygments
+\(http://pygments.org), and to configure the variable
+`org-latex-pdf-process' so that the -shell-escape option is
+passed to pdflatex.
+
+The minted choice has possible repercussions on the preview of
+latex fragments (see `org-preview-latex-fragment'). If you run
+into previewing problems, please consult
+
+ http://orgmode.org/worg/org-tutorials/org-latex-preview.html"
+ :group 'org-export-latex
+ :type '(choice
+ (const :tag "Use listings" t)
+ (const :tag "Use minted" minted)
+ (const :tag "Export verbatim" nil))
+ :safe (lambda (s) (memq s '(t nil minted))))
+
+(defcustom org-latex-listings-langs
+ '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
+ (c "C") (cc "C++")
+ (fortran "fortran")
+ (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
+ (html "HTML") (xml "XML")
+ (tex "TeX") (latex "[LaTeX]TeX")
+ (shell-script "bash")
+ (gnuplot "Gnuplot")
+ (ocaml "Caml") (caml "Caml")
+ (sql "SQL") (sqlite "sql")
+ (makefile "make")
+ (R "r"))
+ "Alist mapping languages to their listing language counterpart.
+The key is a symbol, the major mode symbol without the \"-mode\".
+The value is the string that should be inserted as the language
+parameter for the listings package. If the mode name and the
+listings name are the same, the language does not need an entry
+in this list - but it does not hurt if it is present."
+ :group 'org-export-latex
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type '(repeat
+ (list
+ (symbol :tag "Major mode ")
+ (string :tag "Listings language"))))
+
+(defcustom org-latex-listings-options nil
+ "Association list of options for the latex listings package.
+
+These options are supplied as a comma-separated list to the
+\\lstset command. Each element of the association list should be
+a list containing two strings: the name of the option, and the
+value. For example,
+
+ (setq org-latex-listings-options
+ \\='((\"basicstyle\" \"\\\\small\")
+ (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
+
+will typeset the code in a small size font with underlined, bold
+black keywords.
+
+Note that the same options will be applied to blocks of all
+languages. If you need block-specific options, you may use the
+following syntax:
+
+ #+ATTR_LATEX: :options key1=value1,key2=value2
+ #+BEGIN_SRC <LANG>
+ ...
+ #+END_SRC"
+ :group 'org-export-latex
+ :type '(repeat
+ (list
+ (string :tag "Listings option name ")
+ (string :tag "Listings option value"))))
+
+(defcustom org-latex-minted-langs
+ '((emacs-lisp "common-lisp")
+ (cc "c++")
+ (cperl "perl")
+ (shell-script "bash")
+ (caml "ocaml"))
+ "Alist mapping languages to their minted language counterpart.
+The key is a symbol, the major mode symbol without the \"-mode\".
+The value is the string that should be inserted as the language
+parameter for the minted package. If the mode name and the
+listings name are the same, the language does not need an entry
+in this list - but it does not hurt if it is present.
+
+Note that minted uses all lower case for language identifiers,
+and that the full list of language identifiers can be obtained
+with:
+
+ pygmentize -L lexers"
+ :group 'org-export-latex
+ :type '(repeat
+ (list
+ (symbol :tag "Major mode ")
+ (string :tag "Minted language"))))
+
+(defcustom org-latex-minted-options nil
+ "Association list of options for the latex minted package.
+
+These options are supplied within square brackets in
+\\begin{minted} environments. Each element of the alist should
+be a list containing two strings: the name of the option, and the
+value. For example,
+
+ (setq org-latex-minted-options
+ \\='((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
+
+will result in src blocks being exported with
+
+\\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
+
+as the start of the minted environment. Note that the same
+options will be applied to blocks of all languages. If you need
+block-specific options, you may use the following syntax:
+
+ #+ATTR_LATEX: :options key1=value1,key2=value2
+ #+BEGIN_SRC <LANG>
+ ...
+ #+END_SRC"
+ :group 'org-export-latex
+ :type '(repeat
+ (list
+ (string :tag "Minted option name ")
+ (string :tag "Minted option value"))))
+
+(defcustom org-latex-custom-lang-environments nil
+ "Alist mapping languages to language-specific LaTeX environments.
+
+It is used during export of src blocks by the listings and minted
+latex packages. The environment may be a simple string, composed of
+only letters and numbers. In this case, the string is directly the
+name of the latex environment to use. The environment may also be
+a format string. In this case the format string will be directly
+exported. This format string may contain these elements:
+
+ %s for the formatted source
+ %c for the caption
+ %f for the float attribute
+ %l for an appropriate label
+ %o for the LaTeX attributes
+
+For example,
+
+ (setq org-latex-custom-lang-environments
+ \\='((python \"pythoncode\")
+ (ocaml \"\\\\begin{listing}
+\\\\begin{minted}[%o]{ocaml}
+%s\\\\end{minted}
+\\\\caption{%c}
+\\\\label{%l}\")))
+
+would have the effect that if Org encounters a Python source block
+during LaTeX export it will produce
+
+ \\begin{pythoncode}
+ <src block body>
+ \\end{pythoncode}
+
+and if Org encounters an Ocaml source block during LaTeX export it
+will produce
+
+ \\begin{listing}
+ \\begin{minted}[<attr_latex options>]{ocaml}
+ <src block body>
+ \\end{minted}
+ \\caption{<caption>}
+ \\label{<label>}
+ \\end{listing}"
+ :group 'org-export-latex
+ :type '(repeat
+ (list
+ (symbol :tag "Language name ")
+ (string :tag "Environment name or format string")))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+
+;;;; Compilation
+
+(defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
+ "LaTeX compiler format-string.
+See also `org-latex-compiler'."
+ :group 'org-export-latex
+ :type '(choice
+ (const :tag "Comment" "%% Intended LaTeX compiler: %s\n")
+ (const :tag "latex-mode file variable" "%% -*- latex-run-command: %s -*-\n")
+ (const :tag "AUCTeX file variable" "%% -*- LaTeX-command: %s -*-\n")
+ (string :tag "custom format" "%% %s"))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defcustom org-latex-compiler "pdflatex"
+ "LaTeX compiler to use.
+
+Must be an element in `org-latex-compilers' or the empty quote.
+Can also be set in buffers via #+LATEX_COMPILER. See also
+`org-latex-compiler-file-string'."
+ :group 'org-export-latex
+ :type '(choice
+ (const :tag "pdfLaTeX" "pdflatex")
+ (const :tag "XeLaTeX" "xelatex")
+ (const :tag "LuaLaTeX" "lualatex")
+ (const :tag "Unset" ""))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defconst org-latex-compilers '("pdflatex" "xelatex" "lualatex")
+ "Known LaTeX compilers.
+See also `org-latex-compiler'.")
+
+(defcustom org-latex-bib-compiler "bibtex"
+ "Command to process a LaTeX file's bibliography.
+
+The shorthand %bib in `org-latex-pdf-process' is replaced with
+this value.
+
+A better approach is to use a compiler suit such as `latexmk'."
+ :group 'org-export-latex
+ :type '(choice (const :tag "BibTeX" "bibtex")
+ (const :tag "Biber" "biber")
+ (string :tag "Other process"))
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defcustom org-latex-pdf-process
+ '("%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f")
+ "Commands to process a LaTeX file to a PDF file.
+
+This is a list of strings, each of them will be given to the
+shell as a command. %f in the command will be replaced by the
+relative file name, %F by the absolute file name, %b by the file
+base name (i.e. without directory and extension parts), %o by the
+base directory of the file, %O by the absolute file name of the
+output file, %latex is the LaTeX compiler (see
+`org-latex-compiler'), and %bib is the BibTeX-like compiler (see
+`org-latex-bib-compiler').
+
+The reason why this is a list is that it usually takes several
+runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
+does not have a clever mechanism to detect which of these
+commands have to be run to get to a stable result, and it also
+does not do any error checking.
+
+Consider a smart LaTeX compiler such as `texi2dvi' or `latexmk',
+which calls the \"correct\" combinations of auxiliary programs.
+
+Alternatively, this may be a Lisp function that does the
+processing, so you could use this to apply the machinery of
+AUCTeX or the Emacs LaTeX mode. This function should accept the
+file name as its single argument."
+ :group 'org-export-pdf
+ :type '(choice
+ (repeat :tag "Shell command sequence"
+ (string :tag "Shell command"))
+ (const :tag "2 runs of latex"
+ ("%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f"))
+ (const :tag "3 runs of latex"
+ ("%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f"))
+ (const :tag "latex,bibtex,latex,latex"
+ ("%latex -interaction nonstopmode -output-directory %o %f"
+ "%bib %b"
+ "%latex -interaction nonstopmode -output-directory %o %f"
+ "%latex -interaction nonstopmode -output-directory %o %f"))
+ (const :tag "texi2dvi"
+ ("cd %o; LATEX=\"%latex\" texi2dvi -p -b -V %b.tex"))
+ (const :tag "latexmk"
+ ("latexmk -g -pdf -pdflatex=\"%latex\" -outdir=%o %f"))
+ (function)))
+
+(defcustom org-latex-logfiles-extensions
+ '("aux" "bcf" "blg" "fdb_latexmk" "fls" "figlist" "idx" "log" "nav" "out"
+ "ptc" "run.xml" "snm" "toc" "vrb" "xdv")
+ "The list of file extensions to consider as LaTeX logfiles.
+The logfiles will be removed if `org-latex-remove-logfiles' is
+non-nil."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-latex-remove-logfiles t
+ "Non-nil means remove the logfiles produced by PDF production.
+By default, logfiles are files with these extensions: .aux, .idx,
+.log, .out, .toc, .nav, .snm and .vrb. To define the set of
+logfiles to remove, set `org-latex-logfiles-extensions'."
+ :group 'org-export-latex
+ :type 'boolean)
+
+(defcustom org-latex-known-warnings
+ '(("Reference.*?undefined" . "[undefined reference]")
+ ("Runaway argument" . "[runaway argument]")
+ ("Underfull \\hbox" . "[underfull hbox]")
+ ("Overfull \\hbox" . "[overfull hbox]")
+ ("Citation.*?undefined" . "[undefined citation]")
+ ("Undefined control sequence" . "[undefined control sequence]"))
+ "Alist of regular expressions and associated messages for the user.
+The regular expressions are used to find possible warnings in the
+log of a latex-run. These warnings will be reported after
+calling `org-latex-compile'."
+ :group 'org-export-latex
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(repeat
+ (cons
+ (string :tag "Regexp")
+ (string :tag "Message"))))
+
+
+
+;;; Internal Functions
+
+(defun org-latex--caption-above-p (element info)
+ "Non nil when caption is expected to be located above ELEMENT.
+INFO is a plist holding contextual information."
+ (let ((above (plist-get info :latex-caption-above)))
+ (if (symbolp above) above
+ (let ((type (org-element-type element)))
+ (memq (if (eq type 'link) 'image type) above)))))
+
+(defun org-latex--label (datum info &optional force full)
+ "Return an appropriate label for DATUM.
+DATUM is an element or a `target' type object. INFO is the
+current export state, as a plist.
+
+Return nil if element DATUM has no NAME or VALUE affiliated
+keyword or no CUSTOM_ID property, unless FORCE is non-nil. In
+this case always return a unique label.
+
+Eventually, if FULL is non-nil, wrap label within \"\\label{}\"."
+ (let* ((type (org-element-type datum))
+ (user-label
+ (org-element-property
+ (cl-case type
+ ((headline inlinetask) :CUSTOM_ID)
+ (target :value)
+ (otherwise :name))
+ datum))
+ (label
+ (and (or user-label force)
+ (if (and user-label (plist-get info :latex-prefer-user-labels))
+ user-label
+ (concat (cl-case type
+ (headline "sec:")
+ (table "tab:")
+ (latex-environment
+ (and (string-match-p
+ org-latex-math-environments-re
+ (org-element-property :value datum))
+ "eq:"))
+ (paragraph
+ (and (org-element-property :caption datum)
+ "fig:")))
+ (org-export-get-reference datum info))))))
+ (cond ((not full) label)
+ (label (format "\\label{%s}%s"
+ label
+ (if (eq type 'target) "" "\n")))
+ (t ""))))
+
+(defun org-latex--caption/label-string (element info)
+ "Return caption and label LaTeX string for ELEMENT.
+
+INFO is a plist holding contextual information. If there's no
+caption nor label, return the empty string.
+
+For non-floats, see `org-latex--wrap-label'."
+ (let* ((label (org-latex--label element info nil t))
+ (main (org-export-get-caption element))
+ (attr (org-export-read-attribute :attr_latex element))
+ (type (org-element-type element))
+ (nonfloat (or (and (plist-member attr :float)
+ (not (plist-get attr :float))
+ main)
+ (and (eq type 'src-block)
+ (not (plist-get attr :float))
+ (null (plist-get info :latex-listings)))))
+ (short (org-export-get-caption element t))
+ (caption-from-attr-latex (plist-get attr :caption)))
+ (cond
+ ((org-string-nw-p caption-from-attr-latex)
+ (concat caption-from-attr-latex "\n"))
+ ((and (not main) (equal label "")) "")
+ ((not main) label)
+ ;; Option caption format with short name.
+ (t
+ (format (if nonfloat "\\captionof{%s}%s{%s%s}\n"
+ "\\caption%s%s{%s%s}\n")
+ (if nonfloat
+ (cl-case type
+ (paragraph "figure")
+ (src-block (if (plist-get info :latex-listings)
+ "listing"
+ "figure"))
+ (t (symbol-name type)))
+ "")
+ (if short (format "[%s]" (org-export-data short info)) "")
+ label
+ (org-export-data main info))))))
+
+(defun org-latex-guess-inputenc (header)
+ "Set the coding system in inputenc to what the buffer is.
+
+HEADER is the LaTeX header string. This function only applies
+when specified inputenc option is \"AUTO\".
+
+Return the new header, as a string."
+ (let* ((cs (or (ignore-errors
+ (latexenc-coding-system-to-inputenc
+ (or org-export-coding-system buffer-file-coding-system)))
+ "utf8")))
+ (if (not cs) header
+ ;; First translate if that is requested.
+ (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
+ ;; Then find the \usepackage statement and replace the option.
+ (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
+ cs header t nil 1))))
+
+(defun org-latex-guess-babel-language (header info)
+ "Set Babel's language according to LANGUAGE keyword.
+
+HEADER is the LaTeX header string. INFO is the plist used as
+a communication channel.
+
+Insertion of guessed language only happens when Babel package has
+explicitly been loaded. Then it is added to the rest of
+package's options.
+
+The argument to Babel may be \"AUTO\" which is then replaced with
+the language of the document or `org-export-default-language'
+unless language in question is already loaded.
+
+Return the new header."
+ (let ((language-code (plist-get info :language)))
+ ;; If no language is set or Babel package is not loaded, return
+ ;; HEADER as-is.
+ (if (or (not (stringp language-code))
+ (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
+ header
+ (let ((options (save-match-data
+ (org-split-string (match-string 1 header) ",[ \t]*")))
+ (language (cdr (assoc-string language-code
+ org-latex-babel-language-alist t))))
+ ;; If LANGUAGE is already loaded, return header without AUTO.
+ ;; Otherwise, replace AUTO with language or append language if
+ ;; AUTO is not present.
+ (replace-match
+ (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
+ (cond ((member language options) (delete "AUTO" options))
+ ((member "AUTO" options) options)
+ (t (append options (list language))))
+ ", ")
+ t nil header 1)))))
+
+(defun org-latex-guess-polyglossia-language (header info)
+ "Set the Polyglossia language according to the LANGUAGE keyword.
+
+HEADER is the LaTeX header string. INFO is the plist used as
+a communication channel.
+
+Insertion of guessed language only happens when the Polyglossia
+package has been explicitly loaded.
+
+The argument to Polyglossia may be \"AUTO\" which is then
+replaced with the language of the document or
+`org-export-default-language'. Note, the language is really set
+using \setdefaultlanguage and not as an option to the package.
+
+Return the new header."
+ (let ((language (plist-get info :language)))
+ ;; If no language is set or Polyglossia is not loaded, return
+ ;; HEADER as-is.
+ (if (or (not (stringp language))
+ (not (string-match
+ "\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
+ header)))
+ header
+ (let* ((options (org-string-nw-p (match-string 1 header)))
+ (languages (and options
+ ;; Reverse as the last loaded language is
+ ;; the main language.
+ (nreverse
+ (delete-dups
+ (save-match-data
+ (org-split-string
+ (replace-regexp-in-string
+ "AUTO" language options t)
+ ",[ \t]*"))))))
+ (main-language-set
+ (string-match-p "\\\\setmainlanguage{.*?}" header)))
+ (replace-match
+ (concat "\\usepackage{polyglossia}\n"
+ (mapconcat
+ (lambda (l)
+ (let ((l (or (assoc l org-latex-polyglossia-language-alist)
+ l)))
+ (format (if main-language-set "\\setotherlanguage%s{%s}\n"
+ (setq main-language-set t)
+ "\\setmainlanguage%s{%s}\n")
+ (if (and (consp l) (= (length l) 3))
+ (format "[variant=%s]" (nth 2 l))
+ "")
+ (nth 1 l))))
+ languages
+ ""))
+ t t header 0)))))
+
+(defun org-latex--remove-packages (pkg-alist info)
+ "Remove packages based on the current LaTeX compiler.
+
+If the fourth argument of an element is set in pkg-alist, and it
+is not a member of the LaTeX compiler of the document, the packages
+is removed. See also `org-latex-compiler'.
+
+Return modified pkg-alist."
+ (let ((compiler (or (plist-get info :latex-compiler) "")))
+ (if (member-ignore-case compiler org-latex-compilers)
+ (delq nil
+ (mapcar
+ (lambda (pkg)
+ (unless (and
+ (listp pkg)
+ (let ((third (nth 3 pkg)))
+ (and third
+ (not (member-ignore-case
+ compiler
+ (if (listp third) third (list third)))))))
+ pkg))
+ pkg-alist))
+ pkg-alist)))
+
+(defun org-latex--find-verb-separator (s)
+ "Return a character not used in string S.
+This is used to choose a separator for constructs like \\verb."
+ (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
+ (cl-loop for c across ll
+ when (not (string-match (regexp-quote (char-to-string c)) s))
+ return (char-to-string c))))
+
+(defun org-latex--make-option-string (options)
+ "Return a comma separated string of keywords and values.
+OPTIONS is an alist where the key is the options keyword as
+a string, and the value a list containing the keyword value, or
+nil."
+ (mapconcat (lambda (pair)
+ (pcase-let ((`(,keyword ,value) pair))
+ (concat keyword
+ (and (> (length value) 0)
+ (concat "=" value)))))
+ options
+ ","))
+
+(defun org-latex--wrap-label (element output info)
+ "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
+INFO is the current export state, as a plist. This function
+should not be used for floats. See
+`org-latex--caption/label-string'."
+ (if (not (and (org-string-nw-p output) (org-element-property :name element)))
+ output
+ (concat (format "\\phantomsection\n\\label{%s}\n"
+ (org-latex--label element info))
+ output)))
+
+(defun org-latex--protect-text (text)
+ "Protect special characters in string TEXT and return it."
+ (replace-regexp-in-string "[\\{}$%&_#~^]" "\\\\\\&" text))
+
+(defun org-latex--text-markup (text markup info)
+ "Format TEXT depending on MARKUP text markup.
+INFO is a plist used as a communication channel. See
+`org-latex-text-markup-alist' for details."
+ (let ((fmt (cdr (assq markup (plist-get info :latex-text-markup-alist)))))
+ (cl-case fmt
+ ;; No format string: Return raw text.
+ ((nil) text)
+ ;; Handle the `verb' special case: Find an appropriate separator
+ ;; and use "\\verb" command.
+ (verb
+ (let ((separator (org-latex--find-verb-separator text)))
+ (concat "\\verb"
+ separator
+ (replace-regexp-in-string "\n" " " text)
+ separator)))
+ ;; Handle the `protectedtexttt' special case: Protect some
+ ;; special chars and use "\texttt{%s}" format string.
+ (protectedtexttt
+ (format "\\texttt{%s}"
+ (replace-regexp-in-string
+ "--\\|[\\{}$%&_#~^]"
+ (lambda (m)
+ (cond ((equal m "--") "-{}-")
+ ((equal m "\\") "\\textbackslash{}")
+ ((equal m "~") "\\textasciitilde{}")
+ ((equal m "^") "\\textasciicircum{}")
+ (t (org-latex--protect-text m))))
+ text nil t)))
+ ;; Else use format string.
+ (t (format fmt text)))))
+
+(defun org-latex--delayed-footnotes-definitions (element info)
+ "Return footnotes definitions in ELEMENT as a string.
+
+INFO is a plist used as a communication channel.
+
+Footnotes definitions are returned within \"\\footnotetext{}\"
+commands.
+
+This function is used within constructs that don't support
+\"\\footnote{}\" command (e.g., an item tag). In that case,
+\"\\footnotemark\" is used within the construct and the function
+just outside of it."
+ (mapconcat
+ (lambda (ref)
+ (let ((def (org-export-get-footnote-definition ref info)))
+ (format "\\footnotetext[%d]{%s%s}"
+ (org-export-get-footnote-number ref info)
+ (org-trim (org-latex--label def info t t))
+ (org-trim (org-export-data def info)))))
+ ;; Find every footnote reference in ELEMENT.
+ (letrec ((all-refs nil)
+ (search-refs
+ (lambda (data)
+ ;; Return a list of all footnote references never seen
+ ;; before in DATA.
+ (org-element-map data 'footnote-reference
+ (lambda (ref)
+ (when (org-export-footnote-first-reference-p ref info)
+ (push ref all-refs)
+ (when (eq (org-element-property :type ref) 'standard)
+ (funcall search-refs
+ (org-export-get-footnote-definition ref info)))))
+ info)
+ (reverse all-refs))))
+ (funcall search-refs element))
+ ""))
+
+(defun org-latex--translate (s info)
+ "Translate string S according to specified language.
+INFO is a plist used as a communication channel."
+ (org-export-translate s :latex info))
+
+(defun org-latex--format-spec (info)
+ "Create a format-spec for document meta-data.
+INFO is a plist used as a communication channel."
+ (let ((language (let ((lang (plist-get info :language)))
+ (or (cdr (assoc-string lang org-latex-babel-language-alist t))
+ (nth 1 (assoc-string lang org-latex-polyglossia-language-alist t))
+ lang))))
+ `((?a . ,(org-export-data (plist-get info :author) info))
+ (?t . ,(org-export-data (plist-get info :title) info))
+ (?k . ,(org-export-data (org-latex--wrap-latex-math-block
+ (plist-get info :keywords) info)
+ info))
+ (?d . ,(org-export-data (org-latex--wrap-latex-math-block
+ (plist-get info :description) info)
+ info))
+ (?c . ,(plist-get info :creator))
+ (?l . ,language)
+ (?L . ,(capitalize language))
+ (?D . ,(org-export-get-date info)))))
+
+(defun org-latex--insert-compiler (info)
+ "Insert LaTeX_compiler info into the document.
+INFO is a plist used as a communication channel."
+ (let ((compiler (plist-get info :latex-compiler)))
+ (and (org-string-nw-p org-latex-compiler-file-string)
+ (member (or compiler "") org-latex-compilers)
+ (format org-latex-compiler-file-string compiler))))
+
+
+;;; Filters
+
+(defun org-latex-matrices-tree-filter (tree _backend info)
+ (org-latex--wrap-latex-matrices tree info))
+
+(defun org-latex-math-block-tree-filter (tree _backend info)
+ (org-latex--wrap-latex-math-block tree info))
+
+(defun org-latex-math-block-options-filter (info _backend)
+ (dolist (prop '(:author :date :title) info)
+ (plist-put info prop
+ (org-latex--wrap-latex-math-block (plist-get info prop) info))))
+
+(defun org-latex-clean-invalid-line-breaks (data _backend _info)
+ (replace-regexp-in-string
+ "\\(\\end{[A-Za-z0-9*]+}\\|^\\)[ \t]*\\\\\\\\[ \t]*$" "\\1"
+ data))
+
+
+;;; Template
+
+;;;###autoload
+(defun org-latex-make-preamble (info &optional template snippet?)
+ "Return a formatted LaTeX preamble.
+INFO is a plist used as a communication channel. Optional
+argument TEMPLATE, when non-nil, is the header template string,
+as expected by `org-splice-latex-header'. When SNIPPET? is
+non-nil, only includes packages relevant to image generation, as
+specified in `org-latex-default-packages-alist' or
+`org-latex-packages-alist'."
+ (let* ((class (plist-get info :latex-class))
+ (class-options (plist-get info :latex-class-options))
+ (header (nth 1 (assoc class (plist-get info :latex-classes))))
+ (class-template
+ (or template
+ (and (stringp header)
+ (if (not class-options) header
+ (replace-regexp-in-string
+ "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
+ class-options header t nil 1)))
+ (user-error "Unknown LaTeX class `%s'" class))))
+ (org-latex-guess-polyglossia-language
+ (org-latex-guess-babel-language
+ (org-latex-guess-inputenc
+ (org-element-normalize-string
+ (org-splice-latex-header
+ class-template
+ (org-latex--remove-packages org-latex-default-packages-alist info)
+ (org-latex--remove-packages org-latex-packages-alist info)
+ snippet?
+ (mapconcat #'org-element-normalize-string
+ (list (plist-get info :latex-header)
+ (plist-get info :latex-header-extra)) ""))))
+ info)
+ info)))
+
+(defun org-latex-template (contents info)
+ "Return complete document string after LaTeX conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((title (org-export-data (plist-get info :title) info))
+ (spec (org-latex--format-spec info)))
+ (concat
+ ;; Time-stamp.
+ (and (plist-get info :time-stamp-file)
+ (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
+ ;; LaTeX compiler.
+ (org-latex--insert-compiler info)
+ ;; Document class and packages.
+ (org-latex-make-preamble info)
+ ;; Possibly limit depth for headline numbering.
+ (let ((sec-num (plist-get info :section-numbers)))
+ (when (integerp sec-num)
+ (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
+ ;; Author.
+ (let ((author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (and (plist-get info :with-email)
+ (org-export-data (plist-get info :email) info))))
+ (cond ((and author email (not (string= "" email)))
+ (format "\\author{%s\\thanks{%s}}\n" author email))
+ ((or author email) (format "\\author{%s}\n" (or author email)))))
+ ;; Date.
+ (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
+ (format "\\date{%s}\n" (org-export-data date info)))
+ ;; Title and subtitle.
+ (let* ((subtitle (plist-get info :subtitle))
+ (formatted-subtitle
+ (when subtitle
+ (format (plist-get info :latex-subtitle-format)
+ (org-export-data subtitle info))))
+ (separate (plist-get info :latex-subtitle-separate)))
+ (concat
+ (format "\\title{%s%s}\n" title
+ (if separate "" (or formatted-subtitle "")))
+ (when (and separate subtitle)
+ (concat formatted-subtitle "\n"))))
+ ;; Hyperref options.
+ (let ((template (plist-get info :latex-hyperref-template)))
+ (and (stringp template)
+ (format-spec template spec)))
+ ;; Document start.
+ "\\begin{document}\n\n"
+ ;; Title command.
+ (let* ((title-command (plist-get info :latex-title-command))
+ (command (and (stringp title-command)
+ (format-spec title-command spec))))
+ (org-element-normalize-string
+ (cond ((not (plist-get info :with-title)) nil)
+ ((string= "" title) nil)
+ ((not (stringp command)) nil)
+ ((string-match "\\(?:[^%]\\|^\\)%s" command)
+ (format command title))
+ (t command))))
+ ;; Table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth
+ (concat (when (wholenump depth)
+ (format "\\setcounter{tocdepth}{%d}\n" depth))
+ (plist-get info :latex-toc-command))))
+ ;; Document's body.
+ contents
+ ;; Creator.
+ (and (plist-get info :with-creator)
+ (concat (plist-get info :creator) "\n"))
+ ;; Document end.
+ "\\end{document}")))
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-latex-bold (_bold contents info)
+ "Transcode BOLD from Org to LaTeX.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (org-latex--text-markup contents 'bold info))
+
+
+;;;; Center Block
+
+(defun org-latex-center-block (center-block contents info)
+ "Transcode a CENTER-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the center block. INFO is a plist
+holding contextual information."
+ (org-latex--wrap-label
+ center-block (format "\\begin{center}\n%s\\end{center}" contents) info))
+
+
+;;;; Clock
+
+(defun org-latex-clock (clock _contents info)
+ "Transcode a CLOCK element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ "\\noindent"
+ (format "\\textbf{%s} " org-clock-string)
+ (format (plist-get info :latex-inactive-timestamp-format)
+ (concat (org-timestamp-translate (org-element-property :value clock))
+ (let ((time (org-element-property :duration clock)))
+ (and time (format " (%s)" time)))))
+ "\\\\"))
+
+
+;;;; Code
+
+(defun org-latex-code (code _contents info)
+ "Transcode a CODE object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-latex--text-markup (org-element-property :value code) 'code info))
+
+
+;;;; Drawer
+
+(defun org-latex-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to LaTeX.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((name (org-element-property :drawer-name drawer))
+ (output (funcall (plist-get info :latex-format-drawer-function)
+ name contents)))
+ (org-latex--wrap-label drawer output info)))
+
+
+;;;; Dynamic Block
+
+(defun org-latex-dynamic-block (dynamic-block contents info)
+ "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information. See `org-export-data'."
+ (org-latex--wrap-label dynamic-block contents info))
+
+
+;;;; Entity
+
+(defun org-latex-entity (entity _contents _info)
+ "Transcode an ENTITY object from Org to LaTeX.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :latex entity))
+
+
+;;;; Example Block
+
+(defun org-latex-example-block (example-block _contents info)
+ "Transcode an EXAMPLE-BLOCK element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (when (org-string-nw-p (org-element-property :value example-block))
+ (let ((environment (or (org-export-read-attribute
+ :attr_latex example-block :environment)
+ "verbatim")))
+ (org-latex--wrap-label
+ example-block
+ (format "\\begin{%s}\n%s\\end{%s}"
+ environment
+ (org-export-format-code-default example-block info)
+ environment)
+ info))))
+
+
+;;;; Export Block
+
+(defun org-latex-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (member (org-element-property :type export-block) '("LATEX" "TEX"))
+ (org-remove-indentation (org-element-property :value export-block))))
+
+
+;;;; Export Snippet
+
+(defun org-latex-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'latex)
+ (org-element-property :value export-snippet)))
+
+
+;;;; Fixed Width
+
+(defun org-latex-fixed-width (fixed-width _contents info)
+ "Transcode a FIXED-WIDTH element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-latex--wrap-label
+ fixed-width
+ (format "\\begin{verbatim}\n%s\\end{verbatim}"
+ (org-remove-indentation
+ (org-element-property :value fixed-width)))
+ info))
+
+
+;;;; Footnote Reference
+
+(defun org-latex-footnote-reference (footnote-reference _contents info)
+ "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((label (org-element-property :label footnote-reference)))
+ (concat
+ ;; Insert separator between two footnotes in a row.
+ (let ((prev (org-export-get-previous-element footnote-reference info)))
+ (when (eq (org-element-type prev) 'footnote-reference)
+ (plist-get info :latex-footnote-separator)))
+ (cond
+ ;; Use `:latex-footnote-defined-format' if the footnote has
+ ;; already been defined.
+ ((not (org-export-footnote-first-reference-p footnote-reference info))
+ (format (plist-get info :latex-footnote-defined-format)
+ (org-latex--label
+ (org-export-get-footnote-definition footnote-reference info)
+ info t)))
+ ;; Use \footnotemark if reference is within another footnote
+ ;; reference, footnote definition or table cell.
+ ((org-element-lineage footnote-reference
+ '(footnote-reference footnote-definition table-cell))
+ "\\footnotemark")
+ ;; Otherwise, define it with \footnote command.
+ (t
+ (let ((def (org-export-get-footnote-definition footnote-reference info)))
+ (concat
+ (format "\\footnote{%s%s}" (org-trim (org-export-data def info))
+ ;; Only insert a \label if there exist another
+ ;; reference to def.
+ (cond ((not label) "")
+ ((org-element-map (plist-get info :parse-tree) 'footnote-reference
+ (lambda (f)
+ (and (not (eq f footnote-reference))
+ (equal (org-element-property :label f) label)
+ (org-trim (org-latex--label def info t t))))
+ info t))
+ (t "")))
+ ;; Retrieve all footnote references within the footnote and
+ ;; add their definition after it, since LaTeX doesn't support
+ ;; them inside.
+ (org-latex--delayed-footnotes-definitions def info))))))))
+
+
+;;;; Headline
+
+(defun org-latex-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to LaTeX.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((class (plist-get info :latex-class))
+ (level (org-export-get-relative-level headline info))
+ (numberedp (org-export-numbered-headline-p headline info))
+ (class-sectioning (assoc class (plist-get info :latex-classes)))
+ ;; Section formatting will set two placeholders: one for
+ ;; the title and the other for the contents.
+ (section-fmt
+ (let ((sec (if (functionp (nth 2 class-sectioning))
+ (funcall (nth 2 class-sectioning) level numberedp)
+ (nth (1+ level) class-sectioning))))
+ (cond
+ ;; No section available for that LEVEL.
+ ((not sec) nil)
+ ;; Section format directly returned by a function. Add
+ ;; placeholder for contents.
+ ((stringp sec) (concat sec "\n%s"))
+ ;; (numbered-section . unnumbered-section)
+ ((not (consp (cdr sec)))
+ (concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
+ ;; (numbered-open numbered-close)
+ ((= (length sec) 2)
+ (when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
+ ;; (num-in num-out no-num-in no-num-out)
+ ((= (length sec) 4)
+ (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
+ (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
+ ;; Create a temporary export back-end that hard-codes
+ ;; "\underline" within "\section" and alike.
+ (section-back-end
+ (org-export-create-backend
+ :parent 'latex
+ :transcoders
+ '((underline . (lambda (o c i) (format "\\underline{%s}" c))))))
+ (text
+ (org-export-data-with-backend
+ (org-element-property :title headline) section-back-end info))
+ (todo
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ ;; Create the headline text along with a no-tag version.
+ ;; The latter is required to remove tags from toc.
+ (full-text (funcall (plist-get info :latex-format-headline-function)
+ todo todo-type priority text tags info))
+ ;; Associate \label to the headline for internal links.
+ (headline-label (org-latex--label headline info t t))
+ (pre-blanks
+ (make-string (org-element-property :pre-blank headline) ?\n)))
+ (if (or (not section-fmt) (org-export-low-level-p headline info))
+ ;; This is a deep sub-tree: export it as a list item. Also
+ ;; export as items headlines for which no section format has
+ ;; been found.
+ (let ((low-level-body
+ (concat
+ ;; If headline is the first sibling, start a list.
+ (when (org-export-first-sibling-p headline info)
+ (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
+ ;; Itemize headline
+ "\\item"
+ (and full-text
+ (string-match-p "\\`[ \t]*\\[" full-text)
+ "\\relax")
+ " " full-text "\n"
+ headline-label
+ pre-blanks
+ contents)))
+ ;; If headline is not the last sibling simply return
+ ;; LOW-LEVEL-BODY. Otherwise, also close the list, before
+ ;; any blank line.
+ (if (not (org-export-last-sibling-p headline info)) low-level-body
+ (replace-regexp-in-string
+ "[ \t\n]*\\'"
+ (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
+ low-level-body)))
+ ;; This is a standard headline. Export it as a section. Add
+ ;; an alternative heading when possible, and when this is not
+ ;; identical to the usual heading.
+ (let ((opt-title
+ (funcall (plist-get info :latex-format-headline-function)
+ todo todo-type priority
+ (org-export-data-with-backend
+ (org-export-get-alt-title headline info)
+ section-back-end info)
+ (and (eq (plist-get info :with-tags) t) tags)
+ info))
+ ;; Maybe end local TOC (see `org-latex-keyword').
+ (contents
+ (concat
+ contents
+ (let ((case-fold-search t)
+ (section
+ (let ((first (car (org-element-contents headline))))
+ (and (eq (org-element-type first) 'section) first))))
+ (org-element-map section 'keyword
+ (lambda (k)
+ (and (equal (org-element-property :key k) "TOC")
+ (let ((v (org-element-property :value k)))
+ (and (string-match-p "\\<headlines\\>" v)
+ (string-match-p "\\<local\\>" v)
+ (format "\\stopcontents[level-%d]" level)))))
+ info t)))))
+ (if (and opt-title
+ (not (equal opt-title full-text))
+ (string-match "\\`\\\\\\(.+?\\){" section-fmt))
+ (format (replace-match "\\1[%s]" nil nil section-fmt 1)
+ ;; Replace square brackets with parenthesis
+ ;; since square brackets are not supported in
+ ;; optional arguments.
+ (replace-regexp-in-string
+ "\\[" "(" (replace-regexp-in-string "\\]" ")" opt-title))
+ full-text
+ (concat headline-label pre-blanks contents))
+ ;; Impossible to add an alternative heading. Fallback to
+ ;; regular sectioning format string.
+ (format section-fmt full-text
+ (concat headline-label pre-blanks contents))))))))
+
+(defun org-latex-format-headline-default-function
+ (todo _todo-type priority text tags _info)
+ "Default format function for a headline.
+See `org-latex-format-headline-function' for details."
+ (concat
+ (and todo (format "{\\bfseries\\sffamily %s} " todo))
+ (and priority (format "\\framebox{\\#%c} " priority))
+ text
+ (and tags
+ (format "\\hfill{}\\textsc{%s}"
+ (mapconcat #'org-latex--protect-text tags ":")))))
+
+
+;;;; Horizontal Rule
+
+(defun org-latex-horizontal-rule (horizontal-rule _contents info)
+ "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((attr (org-export-read-attribute :attr_latex horizontal-rule))
+ (prev (org-export-get-previous-element horizontal-rule info)))
+ (concat
+ ;; Make sure the rule doesn't start at the end of the current
+ ;; line by separating it with a blank line from previous element.
+ (when (and prev
+ (let ((prev-blank (org-element-property :post-blank prev)))
+ (or (not prev-blank) (zerop prev-blank))))
+ "\n")
+ (org-latex--wrap-label
+ horizontal-rule
+ (format "\\noindent\\rule{%s}{%s}"
+ (or (plist-get attr :width) "\\textwidth")
+ (or (plist-get attr :thickness) "0.5pt"))
+ info))))
+
+
+;;;; Inline Src Block
+
+(defun org-latex-inline-src-block (inline-src-block _contents info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((code (org-element-property :value inline-src-block))
+ (separator (org-latex--find-verb-separator code)))
+ (cl-case (plist-get info :latex-listings)
+ ;; Do not use a special package: transcode it verbatim.
+ ((nil) (format "\\texttt{%s}" (org-latex--text-markup code 'code info)))
+ ;; Use minted package.
+ (minted
+ (let* ((org-lang (org-element-property :language inline-src-block))
+ (mint-lang (or (cadr (assq (intern org-lang)
+ (plist-get info :latex-minted-langs)))
+ (downcase org-lang)))
+ (options (org-latex--make-option-string
+ (plist-get info :latex-minted-options))))
+ (format "\\mintinline%s{%s}{%s}"
+ (if (string= options "") "" (format "[%s]" options))
+ mint-lang
+ code)))
+ ;; Use listings package.
+ (otherwise
+ ;; Maybe translate language's name.
+ (let* ((org-lang (org-element-property :language inline-src-block))
+ (lst-lang (or (cadr (assq (intern org-lang)
+ (plist-get info :latex-listings-langs)))
+ org-lang))
+ (options (org-latex--make-option-string
+ (append (plist-get info :latex-listings-options)
+ `(("language" ,lst-lang))))))
+ (concat (format "\\lstinline[%s]" options)
+ separator code separator))))))
+
+
+;;;; Inlinetask
+
+(defun org-latex-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to LaTeX.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((title (org-export-data (org-element-property :title inlinetask) info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (org-element-property :todo-type inlinetask))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags inlinetask info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask)))
+ (contents (concat (org-latex--label inlinetask info) contents)))
+ (funcall (plist-get info :latex-format-inlinetask-function)
+ todo todo-type priority title tags contents info)))
+
+(defun org-latex-format-inlinetask-default-function
+ (todo _todo-type priority title tags contents _info)
+ "Default format function for a inlinetasks.
+See `org-latex-format-inlinetask-function' for details."
+ (let ((full-title
+ (concat (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
+ (when priority (format "\\framebox{\\#%c} " priority))
+ title
+ (when tags
+ (format "\\hfill{}\\textsc{:%s:}"
+ (mapconcat #'org-latex--protect-text tags ":"))))))
+ (concat "\\begin{center}\n"
+ "\\fbox{\n"
+ "\\begin{minipage}[c]{.6\\textwidth}\n"
+ full-title "\n\n"
+ (and (org-string-nw-p contents)
+ (concat "\\rule[.8em]{\\textwidth}{2pt}\n\n" contents))
+ "\\end{minipage}\n"
+ "}\n"
+ "\\end{center}")))
+
+
+;;;; Italic
+
+(defun org-latex-italic (_italic contents info)
+ "Transcode ITALIC from Org to LaTeX.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (org-latex--text-markup contents 'italic info))
+
+
+;;;; Item
+
+(defun org-latex-item (item contents info)
+ "Transcode an ITEM element from Org to LaTeX.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((counter
+ (let ((count (org-element-property :counter item))
+ (level
+ ;; Determine level of current item to determine the
+ ;; correct LaTeX counter to use (enumi, enumii...).
+ (let ((parent item) (level 0))
+ (while (memq (org-element-type
+ (setq parent (org-export-get-parent parent)))
+ '(plain-list item))
+ (when (and (eq (org-element-type parent) 'plain-list)
+ (eq (org-element-property :type parent)
+ 'ordered))
+ (cl-incf level)))
+ level)))
+ (and count
+ (< level 5)
+ (format "\\setcounter{enum%s}{%s}\n"
+ (nth (1- level) '("i" "ii" "iii" "iv"))
+ (1- count)))))
+ (checkbox (cl-case (org-element-property :checkbox item)
+ (on "$\\boxtimes$ ")
+ (off "$\\square$ ")
+ (trans "$\\boxminus$ ")))
+ (tag (let ((tag (org-element-property :tag item)))
+ ;; Check-boxes must belong to the tag.
+ (and tag (format "[{%s}] "
+ (concat checkbox
+ (org-export-data tag info)))))))
+ (concat counter
+ "\\item"
+ (cond
+ (tag)
+ (checkbox (concat " " checkbox))
+ ;; Without a tag or a check-box, if CONTENTS starts with
+ ;; an opening square bracket, add "\relax" to "\item",
+ ;; unless the brackets comes from an initial export
+ ;; snippet (i.e. it is inserted willingly by the user).
+ ((and contents
+ (string-match-p "\\`[ \t]*\\[" contents)
+ (not (let ((e (car (org-element-contents item))))
+ (and (eq (org-element-type e) 'paragraph)
+ (let ((o (car (org-element-contents e))))
+ (and (eq (org-element-type o) 'export-snippet)
+ (eq (org-export-snippet-backend o)
+ 'latex)))))))
+ "\\relax ")
+ (t " "))
+ (and contents (org-trim contents))
+ ;; If there are footnotes references in tag, be sure to
+ ;; add their definition at the end of the item. This
+ ;; workaround is necessary since "\footnote{}" command is
+ ;; not supported in tags.
+ (and tag
+ (org-latex--delayed-footnotes-definitions
+ (org-element-property :tag item) info)))))
+
+
+;;;; Keyword
+
+(defun org-latex-keyword (keyword _contents info)
+ "Transcode a KEYWORD element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "LATEX") value)
+ ((string= key "INDEX") (format "\\index{%s}" value))
+ ((string= key "TOC")
+ (let ((case-fold-search t))
+ (cond
+ ((string-match-p "\\<headlines\\>" value)
+ (let* ((localp (string-match-p "\\<local\\>" value))
+ (parent (org-element-lineage keyword '(headline)))
+ (level (if (not (and localp parent)) 0
+ (org-export-get-relative-level parent info)))
+ (depth
+ (and (string-match "\\<[0-9]+\\>" value)
+ (format
+ "\\setcounter{tocdepth}{%d}"
+ (+ (string-to-number (match-string 0 value)) level)))))
+ (if (and localp parent)
+ ;; Start local TOC, assuming package "titletoc" is
+ ;; required.
+ (format "\\startcontents[level-%d]
+\\printcontents[level-%d]{}{0}{%s}"
+ level level (or depth ""))
+ (concat depth (and depth "\n") "\\tableofcontents"))))
+ ((string-match-p "\\<tables\\>" value) "\\listoftables")
+ ((string-match-p "\\<listings\\>" value)
+ (cl-case (plist-get info :latex-listings)
+ ((nil) "\\listoffigures")
+ (minted "\\listoflistings")
+ (otherwise "\\lstlistoflistings")))))))))
+
+
+;;;; Latex Environment
+
+(defun org-latex-latex-environment (latex-environment _contents info)
+ "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (plist-get info :with-latex)
+ (let ((value (org-remove-indentation
+ (org-element-property :value latex-environment))))
+ (if (not (org-element-property :name latex-environment)) value
+ ;; Environment is labeled: label must be within the environment
+ ;; (otherwise, a reference pointing to that element will count
+ ;; the section instead).
+ (with-temp-buffer
+ (insert value)
+ (goto-char (point-min))
+ (forward-line)
+ (insert (org-latex--label latex-environment info nil t))
+ (buffer-string))))))
+
+
+;;;; Latex Fragment
+
+(defun org-latex-latex-fragment (latex-fragment _contents _info)
+ "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((value (org-element-property :value latex-fragment)))
+ ;; Trim math markers since the fragment is enclosed within
+ ;; a latex-math-block object anyway.
+ (cond ((string-match-p "\\`\\$[^$]" value) (substring value 1 -1))
+ ((string-prefix-p "\\(" value) (substring value 2 -2))
+ (t value))))
+
+
+;;;; Line Break
+
+(defun org-latex-line-break (_line-break _contents _info)
+ "Transcode a LINE-BREAK object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ "\\\\\n")
+
+
+;;;; Link
+
+(defun org-latex--inline-image (link info)
+ "Return LaTeX code for an inline image.
+LINK is the link pointing to the inline image. INFO is a plist
+used as a communication channel."
+ (let* ((parent (org-export-get-parent-element link))
+ (path (let ((raw-path (org-element-property :path link)))
+ (if (not (file-name-absolute-p raw-path)) raw-path
+ (expand-file-name raw-path))))
+ (filetype (file-name-extension path))
+ (caption (org-latex--caption/label-string parent info))
+ (caption-above-p (org-latex--caption-above-p link info))
+ ;; Retrieve latex attributes from the element around.
+ (attr (org-export-read-attribute :attr_latex parent))
+ (float (let ((float (plist-get attr :float)))
+ (cond ((string= float "wrap") 'wrap)
+ ((string= float "sideways") 'sideways)
+ ((string= float "multicolumn") 'multicolumn)
+ ((and (plist-member attr :float) (not float)) 'nonfloat)
+ ((or float
+ (org-element-property :caption parent)
+ (org-string-nw-p (plist-get attr :caption)))
+ 'figure)
+ (t 'nonfloat))))
+ (placement
+ (let ((place (plist-get attr :placement)))
+ (cond
+ (place (format "%s" place))
+ ((eq float 'wrap) "{l}{0.5\\textwidth}")
+ ((eq float 'figure)
+ (format "[%s]" (plist-get info :latex-default-figure-position)))
+ (t ""))))
+ (center
+ (if (plist-member attr :center) (plist-get attr :center)
+ (plist-get info :latex-images-centered)))
+ (comment-include (if (plist-get attr :comment-include) "%" ""))
+ ;; It is possible to specify width and height in the
+ ;; ATTR_LATEX line, and also via default variables.
+ (width (cond ((plist-get attr :width))
+ ((plist-get attr :height) "")
+ ((eq float 'wrap) "0.48\\textwidth")
+ (t (plist-get info :latex-image-default-width))))
+ (height (cond ((plist-get attr :height))
+ ((or (plist-get attr :width)
+ (memq float '(figure wrap))) "")
+ (t (plist-get info :latex-image-default-height))))
+ (options (let ((opt (or (plist-get attr :options)
+ (plist-get info :latex-image-default-option))))
+ (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
+ (match-string 1 opt))))
+ image-code)
+ (if (member filetype '("tikz" "pgf"))
+ ;; For tikz images:
+ ;; - use \input to read in image file.
+ ;; - if options are present, wrap in a tikzpicture environment.
+ ;; - if width or height are present, use \resizebox to change
+ ;; the image size.
+ (progn
+ (setq image-code (format "\\input{%s}" path))
+ (when (org-string-nw-p options)
+ (setq image-code
+ (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
+ options
+ image-code)))
+ (when (or (org-string-nw-p width) (org-string-nw-p height))
+ (setq image-code (format "\\resizebox{%s}{%s}{%s}"
+ (if (org-string-nw-p width) width "!")
+ (if (org-string-nw-p height) height "!")
+ image-code))))
+ ;; For other images:
+ ;; - add width and height to options.
+ ;; - include the image with \includegraphics.
+ (when (org-string-nw-p width)
+ (setq options (concat options ",width=" width)))
+ (when (org-string-nw-p height)
+ (setq options (concat options ",height=" height)))
+ (let ((search-option (org-element-property :search-option link)))
+ (when (and search-option
+ (equal filetype "pdf")
+ (string-match-p "\\`[0-9]+\\'" search-option)
+ (not (string-match-p "page=" options)))
+ (setq options (concat options ",page=" search-option))))
+ (setq image-code
+ (format "\\includegraphics%s{%s}"
+ (cond ((not (org-string-nw-p options)) "")
+ ((string-prefix-p "," options)
+ (format "[%s]" (substring options 1)))
+ (t (format "[%s]" options)))
+ path))
+ (when (equal filetype "svg")
+ (setq image-code (replace-regexp-in-string "^\\\\includegraphics"
+ "\\includesvg"
+ image-code
+ nil t))
+ (setq image-code (replace-regexp-in-string "\\.svg}"
+ "}"
+ image-code
+ nil t))))
+ ;; Return proper string, depending on FLOAT.
+ (pcase float
+ (`wrap (format "\\begin{wrapfigure}%s
+%s%s
+%s%s
+%s\\end{wrapfigure}"
+ placement
+ (if caption-above-p caption "")
+ (if center "\\centering" "")
+ comment-include image-code
+ (if caption-above-p "" caption)))
+ (`sideways (format "\\begin{sidewaysfigure}
+%s%s
+%s%s
+%s\\end{sidewaysfigure}"
+ (if caption-above-p caption "")
+ (if center "\\centering" "")
+ comment-include image-code
+ (if caption-above-p "" caption)))
+ (`multicolumn (format "\\begin{figure*}%s
+%s%s
+%s%s
+%s\\end{figure*}"
+ placement
+ (if caption-above-p caption "")
+ (if center "\\centering" "")
+ comment-include image-code
+ (if caption-above-p "" caption)))
+ (`figure (format "\\begin{figure}%s
+%s%s
+%s%s
+%s\\end{figure}"
+ placement
+ (if caption-above-p caption "")
+ (if center "\\centering" "")
+ comment-include image-code
+ (if caption-above-p "" caption)))
+ ((guard center)
+ (format "\\begin{center}
+%s%s
+%s\\end{center}"
+ (if caption-above-p caption "")
+ image-code
+ (if caption-above-p "" caption)))
+ (_
+ (concat (if caption-above-p caption "")
+ image-code
+ (if caption-above-p caption ""))))))
+
+(defun org-latex-link (link desc info)
+ "Transcode a LINK object from Org to LaTeX.
+
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+ (let* ((type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (and (not (string= desc "")) desc))
+ (imagep (org-export-inline-image-p
+ link (plist-get info :latex-inline-image-rules)))
+ (path (org-latex--protect-text
+ (cond ((member type '("http" "https" "ftp" "mailto" "doi"))
+ (concat type ":" raw-path))
+ ((string= type "file") (org-export-file-uri raw-path))
+ (t raw-path)))))
+ (cond
+ ;; Link type is handled by a special function.
+ ((org-export-custom-protocol-maybe link desc 'latex))
+ ;; Image file.
+ (imagep (org-latex--inline-image link info))
+ ;; Radio link: Transcode target's contents and use them as link's
+ ;; description.
+ ((string= type "radio")
+ (let ((destination (org-export-resolve-radio-link link info)))
+ (if (not destination) desc
+ (format "\\hyperref[%s]{%s}"
+ (org-export-get-reference destination info)
+ desc))))
+ ;; Links pointing to a headline: Find destination and build
+ ;; appropriate referencing command.
+ ((member type '("custom-id" "fuzzy" "id"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (cl-case (org-element-type destination)
+ ;; Id link points to an external file.
+ (plain-text
+ (if desc (format "\\href{%s}{%s}" destination desc)
+ (format "\\url{%s}" destination)))
+ ;; Fuzzy link points nowhere.
+ ((nil)
+ (format (plist-get info :latex-link-with-unknown-path-format)
+ (or desc
+ (org-export-data
+ (org-element-property :raw-link link) info))))
+ ;; LINK points to a headline. If headlines are numbered
+ ;; and the link has no description, display headline's
+ ;; number. Otherwise, display description or headline's
+ ;; title.
+ (headline
+ (let ((label (org-latex--label destination info t)))
+ (if (and (not desc)
+ (org-export-numbered-headline-p destination info))
+ (format "\\ref{%s}" label)
+ (format "\\hyperref[%s]{%s}" label
+ (or desc
+ (org-export-data
+ (org-element-property :title destination) info))))))
+ ;; Fuzzy link points to a target. Do as above.
+ (otherwise
+ (let ((ref (org-latex--label destination info t)))
+ (if (not desc) (format "\\ref{%s}" ref)
+ (format "\\hyperref[%s]{%s}" ref desc)))))))
+ ;; Coderef: replace link with the reference name or the
+ ;; equivalent line number.
+ ((string= type "coderef")
+ (format (org-export-get-coderef-format path desc)
+ (org-export-resolve-coderef path info)))
+ ;; External link with a description part.
+ ((and path desc) (format "\\href{%s}{%s}" path desc))
+ ;; External link without a description part.
+ (path (format "\\url{%s}" path))
+ ;; No path, only description. Try to do something useful.
+ (t (format (plist-get info :latex-link-with-unknown-path-format) desc)))))
+
+
+;;;; Node Property
+
+(defun org-latex-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+
+;;;; Paragraph
+
+(defun org-latex-paragraph (_paragraph contents _info)
+ "Transcode a PARAGRAPH element from Org to LaTeX.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ contents)
+
+
+;;;; Plain List
+
+(defun org-latex-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element from Org to LaTeX.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let* ((type (org-element-property :type plain-list))
+ (attr (org-export-read-attribute :attr_latex plain-list))
+ (latex-type (let ((env (plist-get attr :environment)))
+ (cond (env (format "%s" env))
+ ((eq type 'ordered) "enumerate")
+ ((eq type 'descriptive) "description")
+ (t "itemize")))))
+ (org-latex--wrap-label
+ plain-list
+ (format "\\begin{%s}%s\n%s\\end{%s}"
+ latex-type
+ (or (plist-get attr :options) "")
+ contents
+ latex-type)
+ info)))
+
+
+;;;; Plain Text
+
+(defun org-latex-plain-text (text info)
+ "Transcode a TEXT string from Org to LaTeX.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ (let* ((specialp (plist-get info :with-special-strings))
+ (output
+ ;; Turn LaTeX into \LaTeX{} and TeX into \TeX{}.
+ (let ((case-fold-search nil))
+ (replace-regexp-in-string
+ "\\<\\(?:La\\)?TeX\\>" "\\\\\\&{}"
+ ;; Protect ^, ~, %, #, &, $, _, { and }. Also protect \.
+ ;; However, if special strings are used, be careful not
+ ;; to protect "\" in "\-" constructs.
+ (replace-regexp-in-string
+ (concat "[%$#&{}_~^]\\|\\\\" (and specialp "\\([^-]\\|$\\)"))
+ (lambda (m)
+ (cl-case (string-to-char m)
+ (?\\ "$\\\\backslash$\\1")
+ (?~ "\\\\textasciitilde{}")
+ (?^ "\\\\^{}")
+ (t "\\\\\\&")))
+ text)))))
+ ;; Activate smart quotes. Be sure to provide original TEXT string
+ ;; since OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output (org-export-activate-smart-quotes output :latex info text)))
+ ;; Convert special strings.
+ (when specialp
+ (setq output (replace-regexp-in-string "\\.\\.\\." "\\\\ldots{}" output)))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output (replace-regexp-in-string
+ "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
+ ;; Return value.
+ output))
+
+
+;;;; Planning
+
+(defun org-latex-planning (planning _contents info)
+ "Transcode a PLANNING element from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ "\\noindent"
+ (mapconcat
+ 'identity
+ (delq nil
+ (list
+ (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat
+ (format "\\textbf{%s} " org-closed-string)
+ (format (plist-get info :latex-inactive-timestamp-format)
+ (org-timestamp-translate closed)))))
+ (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat
+ (format "\\textbf{%s} " org-deadline-string)
+ (format (plist-get info :latex-active-timestamp-format)
+ (org-timestamp-translate deadline)))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat
+ (format "\\textbf{%s} " org-scheduled-string)
+ (format (plist-get info :latex-active-timestamp-format)
+ (org-timestamp-translate scheduled)))))))
+ " ")
+ "\\\\"))
+
+
+;;;; Property Drawer
+
+(defun org-latex-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format "\\begin{verbatim}\n%s\\end{verbatim}" contents)))
+
+
+;;;; Pseudo Element: LaTeX Matrices
+
+;; `latex-matrices' elements have the following properties:
+;; `:caption', `:post-blank' and `:markup' (`inline', `equation' or
+;; `math').
+
+(defun org-latex--wrap-latex-matrices (data info)
+ "Merge contiguous tables with the same mode within a pseudo-element.
+DATA is a parse tree or a secondary string. INFO is a plist
+containing export options. Modify DATA by side-effect and return
+it."
+ (org-element-map data 'table
+ (lambda (table)
+ (when (eq (org-element-property :type table) 'org)
+ (let ((mode (or (org-export-read-attribute :attr_latex table :mode)
+ (plist-get info :latex-default-table-mode))))
+ (when (and (member mode '("inline-math" "math"))
+ ;; Do not wrap twice the same table.
+ (not (eq (org-element-type
+ (org-element-property :parent table))
+ 'latex-matrices)))
+ (let* ((caption (and (not (string= mode "inline-math"))
+ (org-element-property :caption table)))
+ (matrices
+ (list 'latex-matrices
+ (list :caption caption
+ :markup
+ (cond ((string= mode "inline-math") 'inline)
+ (caption 'equation)
+ (t 'math)))))
+ (previous table)
+ (next (org-export-get-next-element table info)))
+ (org-element-insert-before matrices table)
+ ;; Swallow all contiguous tables sharing the same mode.
+ (while (and
+ (zerop (or (org-element-property :post-blank previous) 0))
+ (setq next (org-export-get-next-element previous info))
+ (eq (org-element-type next) 'table)
+ (eq (org-element-property :type next) 'org)
+ (string= (or (org-export-read-attribute
+ :attr_latex next :mode)
+ (plist-get info :latex-default-table-mode))
+ mode))
+ (org-element-extract-element previous)
+ (org-element-adopt-elements matrices previous)
+ (setq previous next))
+ ;; Inherit `:post-blank' from the value of the last
+ ;; swallowed table. Set the latter's `:post-blank'
+ ;; value to 0 so as to not duplicate empty lines.
+ (org-element-put-property
+ matrices :post-blank (org-element-property :post-blank previous))
+ (org-element-put-property previous :post-blank 0)
+ (org-element-extract-element previous)
+ (org-element-adopt-elements matrices previous))))))
+ info)
+ data)
+
+(defun org-latex-matrices (matrices contents _info)
+ "Transcode a MATRICES element from Org to LaTeX.
+CONTENTS is a string. INFO is a plist used as a communication
+channel."
+ (format (cl-case (org-element-property :markup matrices)
+ (inline "\\(%s\\)")
+ (equation "\\begin{equation}\n%s\\end{equation}")
+ (t "\\[\n%s\\]"))
+ contents))
+
+
+;;;; Pseudo Object: LaTeX Math Block
+
+;; `latex-math-block' objects have the following property:
+;; `:post-blank'.
+
+(defun org-latex--wrap-latex-math-block (data info)
+ "Merge contiguous math objects in a pseudo-object container.
+DATA is a parse tree or a secondary string. INFO is a plist
+containing export options. Modify DATA by side-effect and return it."
+ (let ((valid-object-p
+ ;; Non-nil when OBJ can be added to the latex math block B.
+ (lambda (obj b)
+ (pcase (org-element-type obj)
+ (`entity (org-element-property :latex-math-p obj))
+ (`latex-fragment
+ (let ((value (org-element-property :value obj)))
+ (or (string-prefix-p "\\(" value)
+ (string-match-p "\\`\\$[^$]" value))))
+ ((and type (or `subscript `superscript))
+ (not (memq type (mapcar #'org-element-type
+ (org-element-contents b)))))))))
+ (org-element-map data '(entity latex-fragment subscript superscript)
+ (lambda (object)
+ ;; Skip objects already wrapped.
+ (when (and (not (eq (org-element-type
+ (org-element-property :parent object))
+ 'latex-math-block))
+ (funcall valid-object-p object nil))
+ (let ((math-block (list 'latex-math-block nil))
+ (next-elements (org-export-get-next-element object info t))
+ (last object))
+ ;; Wrap MATH-BLOCK around OBJECT in DATA.
+ (org-element-insert-before math-block object)
+ (org-element-extract-element object)
+ (org-element-adopt-elements math-block object)
+ (when (zerop (or (org-element-property :post-blank object) 0))
+ ;; MATH-BLOCK swallows consecutive math objects.
+ (catch 'exit
+ (dolist (next next-elements)
+ (unless (funcall valid-object-p next math-block)
+ (throw 'exit nil))
+ (org-element-extract-element next)
+ (org-element-adopt-elements math-block next)
+ ;; Eschew the case: \beta$x$ -> \(\betax\).
+ (unless (memq (org-element-type next)
+ '(subscript superscript))
+ (org-element-put-property last :post-blank 1))
+ (setq last next)
+ (when (> (or (org-element-property :post-blank next) 0) 0)
+ (throw 'exit nil)))))
+ (org-element-put-property
+ math-block :post-blank (org-element-property :post-blank last)))))
+ info nil '(subscript superscript latex-math-block) t)
+ ;; Return updated DATA.
+ data))
+
+(defun org-latex-math-block (_math-block contents _info)
+ "Transcode a MATH-BLOCK object from Org to LaTeX.
+CONTENTS is a string. INFO is a plist used as a communication
+channel."
+ (when (org-string-nw-p contents)
+ (format "\\(%s\\)" (org-trim contents))))
+
+;;;; Quote Block
+
+(defun org-latex-quote-block (quote-block contents info)
+ "Transcode a QUOTE-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (org-latex--wrap-label
+ quote-block (format "\\begin{quote}\n%s\\end{quote}" contents) info))
+
+
+;;;; Radio Target
+
+(defun org-latex-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object from Org to LaTeX.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (format "\\label{%s}%s" (org-export-get-reference radio-target info) text))
+
+
+;;;; Section
+
+(defun org-latex-section (_section contents _info)
+ "Transcode a SECTION element from Org to LaTeX.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ contents)
+
+
+;;;; Special Block
+
+(defun org-latex-special-block (special-block contents info)
+ "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((type (org-element-property :type special-block))
+ (opt (org-export-read-attribute :attr_latex special-block :options))
+ (caption (org-latex--caption/label-string special-block info))
+ (caption-above-p (org-latex--caption-above-p special-block info)))
+ (concat (format "\\begin{%s}%s\n" type (or opt ""))
+ (and caption-above-p caption)
+ contents
+ (and (not caption-above-p) caption)
+ (format "\\end{%s}" type))))
+
+
+;;;; Src Block
+
+(defun org-latex-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to LaTeX.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (when (org-string-nw-p (org-element-property :value src-block))
+ (let* ((lang (org-element-property :language src-block))
+ (caption (org-element-property :caption src-block))
+ (caption-above-p (org-latex--caption-above-p src-block info))
+ (label (org-element-property :name src-block))
+ (custom-env (and lang
+ (cadr (assq (intern lang)
+ org-latex-custom-lang-environments))))
+ (num-start (org-export-get-loc src-block info))
+ (retain-labels (org-element-property :retain-labels src-block))
+ (attributes (org-export-read-attribute :attr_latex src-block))
+ (float (plist-get attributes :float))
+ (listings (plist-get info :latex-listings)))
+ (cond
+ ;; Case 1. No source fontification.
+ ((not listings)
+ (let* ((caption-str (org-latex--caption/label-string src-block info))
+ (float-env
+ (cond ((string= "multicolumn" float)
+ (format "\\begin{figure*}[%s]\n%s%%s\n%s\\end{figure*}"
+ (plist-get info :latex-default-figure-position)
+ (if caption-above-p caption-str "")
+ (if caption-above-p "" caption-str)))
+ (caption (concat
+ (if caption-above-p caption-str "")
+ "%s"
+ (if caption-above-p "" (concat "\n" caption-str))))
+ (t "%s"))))
+ (format
+ float-env
+ (concat (format "\\begin{verbatim}\n%s\\end{verbatim}"
+ (org-export-format-code-default src-block info))))))
+ ;; Case 2. Custom environment.
+ (custom-env
+ (let ((caption-str (org-latex--caption/label-string src-block info))
+ (formatted-src (org-export-format-code-default src-block info)))
+ (if (string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
+ (format "\\begin{%s}\n%s\\end{%s}\n"
+ custom-env
+ (concat (and caption-above-p caption-str)
+ formatted-src
+ (and (not caption-above-p) caption-str))
+ custom-env)
+ (format-spec custom-env
+ `((?s . ,formatted-src)
+ (?c . ,caption)
+ (?f . ,float)
+ (?l . ,(org-latex--label src-block info))
+ (?o . ,(or (plist-get attributes :options) "")))))))
+ ;; Case 3. Use minted package.
+ ((eq listings 'minted)
+ (let* ((caption-str (org-latex--caption/label-string src-block info))
+ (float-env
+ (cond
+ ((string= "multicolumn" float)
+ (format "\\begin{listing*}[%s]\n%s%%s\n%s\\end{listing*}"
+ (plist-get info :latex-default-figure-position)
+ (if caption-above-p caption-str "")
+ (if caption-above-p "" caption-str)))
+ (caption
+ (format "\\begin{listing}[%s]\n%s%%s\n%s\\end{listing}"
+ (plist-get info :latex-default-figure-position)
+ (if caption-above-p caption-str "")
+ (if caption-above-p "" caption-str)))
+ ((string= "t" float)
+ (concat (format "\\begin{listing}[%s]\n"
+ (plist-get info :latex-default-figure-position))
+ "%s\n\\end{listing}"))
+ (t "%s")))
+ (options (plist-get info :latex-minted-options))
+ (body
+ (format
+ "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
+ ;; Options.
+ (concat
+ (org-latex--make-option-string
+ (if (or (not num-start) (assoc "linenos" options))
+ options
+ (append
+ `(("linenos")
+ ("firstnumber" ,(number-to-string (1+ num-start))))
+ options)))
+ (let ((local-options (plist-get attributes :options)))
+ (and local-options (concat "," local-options))))
+ ;; Language.
+ (or (cadr (assq (intern lang)
+ (plist-get info :latex-minted-langs)))
+ (downcase lang))
+ ;; Source code.
+ (let* ((code-info (org-export-unravel-code src-block))
+ (max-width
+ (apply 'max
+ (mapcar 'length
+ (org-split-string (car code-info)
+ "\n")))))
+ (org-export-format-code
+ (car code-info)
+ (lambda (loc _num ref)
+ (concat
+ loc
+ (when ref
+ ;; Ensure references are flushed to the right,
+ ;; separated with 6 spaces from the widest line
+ ;; of code.
+ (concat (make-string (+ (- max-width (length loc)) 6)
+ ?\s)
+ (format "(%s)" ref)))))
+ nil (and retain-labels (cdr code-info)))))))
+ ;; Return value.
+ (format float-env body)))
+ ;; Case 4. Use listings package.
+ (t
+ (let ((lst-lang
+ (or (cadr (assq (intern lang)
+ (plist-get info :latex-listings-langs)))
+ lang))
+ (caption-str
+ (when caption
+ (let ((main (org-export-get-caption src-block))
+ (secondary (org-export-get-caption src-block t)))
+ (if (not secondary)
+ (format "{%s}" (org-export-data main info))
+ (format "{[%s]%s}"
+ (org-export-data secondary info)
+ (org-export-data main info))))))
+ (lst-opt (plist-get info :latex-listings-options)))
+ (concat
+ ;; Options.
+ (format
+ "\\lstset{%s}\n"
+ (concat
+ (org-latex--make-option-string
+ (append
+ lst-opt
+ (cond
+ ((and (not float) (plist-member attributes :float)) nil)
+ ((string= "multicolumn" float) '(("float" "*")))
+ ((and float (not (assoc "float" lst-opt)))
+ `(("float" ,(plist-get info :latex-default-figure-position)))))
+ `(("language" ,lst-lang))
+ (if label
+ `(("label" ,(org-latex--label src-block info)))
+ '(("label" " ")))
+ (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
+ `(("captionpos" ,(if caption-above-p "t" "b")))
+ (cond ((assoc "numbers" lst-opt) nil)
+ ((not num-start) '(("numbers" "none")))
+ (t `(("firstnumber" ,(number-to-string (1+ num-start)))
+ ("numbers" "left"))))))
+ (let ((local-options (plist-get attributes :options)))
+ (and local-options (concat "," local-options)))))
+ ;; Source code.
+ (format
+ "\\begin{lstlisting}\n%s\\end{lstlisting}"
+ (let* ((code-info (org-export-unravel-code src-block))
+ (max-width
+ (apply 'max
+ (mapcar 'length
+ (org-split-string (car code-info) "\n")))))
+ (org-export-format-code
+ (car code-info)
+ (lambda (loc _num ref)
+ (concat
+ loc
+ (when ref
+ ;; Ensure references are flushed to the right,
+ ;; separated with 6 spaces from the widest line of
+ ;; code
+ (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
+ (format "(%s)" ref)))))
+ nil (and retain-labels (cdr code-info))))))))))))
+
+
+;;;; Statistics Cookie
+
+(defun org-latex-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (replace-regexp-in-string
+ "%" "\\%" (org-element-property :value statistics-cookie) nil t))
+
+
+;;;; Strike-Through
+
+(defun org-latex-strike-through (_strike-through contents info)
+ "Transcode STRIKE-THROUGH from Org to LaTeX.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (org-latex--text-markup contents 'strike-through info))
+
+
+;;;; Subscript
+
+(defun org-latex--script-size (object info)
+ "Transcode a subscript or superscript object.
+OBJECT is an Org object. INFO is a plist used as a communication
+channel."
+ (let ((output ""))
+ (org-element-map (org-element-contents object)
+ (cons 'plain-text org-element-all-objects)
+ (lambda (obj)
+ (cl-case (org-element-type obj)
+ ((entity latex-fragment)
+ (let ((data (org-trim (org-export-data obj info))))
+ (string-match
+ "\\`\\(?:\\\\[([]\\|\\$+\\)?\\(.*?\\)\\(?:\\\\[])]\\|\\$+\\)?\\'"
+ data)
+ (setq output
+ (concat output
+ (match-string 1 data)
+ (let ((blank (org-element-property :post-blank obj)))
+ (and blank (> blank 0) "\\ "))))))
+ (plain-text
+ (setq output
+ (format "%s\\text{%s}" output (org-export-data obj info))))
+ (otherwise
+ (setq output
+ (concat output
+ (org-export-data obj info)
+ (let ((blank (org-element-property :post-blank obj)))
+ (and blank (> blank 0) "\\ ")))))))
+ info nil org-element-recursive-objects)
+ ;; Result. Do not wrap into curly brackets if OUTPUT is a single
+ ;; character.
+ (concat (if (eq (org-element-type object) 'subscript) "_" "^")
+ (and (> (length output) 1) "{")
+ output
+ (and (> (length output) 1) "}"))))
+
+(defun org-latex-subscript (subscript _contents info)
+ "Transcode a SUBSCRIPT object from Org to LaTeX.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (org-latex--script-size subscript info))
+
+
+;;;; Superscript
+
+(defun org-latex-superscript (superscript _contents info)
+ "Transcode a SUPERSCRIPT object from Org to LaTeX.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (org-latex--script-size superscript info))
+
+
+;;;; Table
+;;
+;; `org-latex-table' is the entry point for table transcoding. It
+;; takes care of tables with a "verbatim" mode. Otherwise, it
+;; delegates the job to either `org-latex--table.el-table',
+;; `org-latex--org-table' or `org-latex--math-table' functions,
+;; depending of the type of the table and the mode requested.
+;;
+;; `org-latex--align-string' is a subroutine used to build alignment
+;; string for Org tables.
+
+(defun org-latex-table (table contents info)
+ "Transcode a TABLE element from Org to LaTeX.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (if (eq (org-element-property :type table) 'table.el)
+ ;; "table.el" table. Convert it using appropriate tools.
+ (org-latex--table.el-table table info)
+ (let ((type (or (org-export-read-attribute :attr_latex table :mode)
+ (plist-get info :latex-default-table-mode))))
+ (cond
+ ;; Case 1: Verbatim table.
+ ((string= type "verbatim")
+ (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
+ ;; Re-create table, without affiliated keywords.
+ (org-trim (org-element-interpret-data
+ `(table nil ,@(org-element-contents table))))))
+ ;; Case 2: Matrix.
+ ((or (string= type "math") (string= type "inline-math"))
+ (org-latex--math-table table info))
+ ;; Case 3: Standard table.
+ (t (concat (org-latex--org-table table contents info)
+ ;; When there are footnote references within the
+ ;; table, insert their definition just after it.
+ (org-latex--delayed-footnotes-definitions table info)))))))
+
+(defun org-latex--align-string (table info &optional math?)
+ "Return an appropriate LaTeX alignment string.
+TABLE is the considered table. INFO is a plist used as
+a communication channel. When optional argument MATH? is
+non-nil, TABLE is meant to be a matrix, where all cells are
+centered."
+ (or (org-export-read-attribute :attr_latex table :align)
+ (let (align)
+ ;; Extract column groups and alignment from first (non-rule)
+ ;; row.
+ (org-element-map
+ (org-element-map table 'table-row
+ (lambda (row)
+ (and (eq (org-element-property :type row) 'standard) row))
+ info 'first-match)
+ 'table-cell
+ (lambda (cell)
+ (let ((borders (org-export-table-cell-borders cell info)))
+ ;; Check left border for the first cell only.
+ (when (and (memq 'left borders) (not align))
+ (push "|" align))
+ (push (if math? "c" ;center cells in matrices
+ (cl-case (org-export-table-cell-alignment cell info)
+ (left "l")
+ (right "r")
+ (center "c")))
+ align)
+ (when (memq 'right borders) (push "|" align))))
+ info)
+ (apply 'concat (nreverse align)))))
+
+(defun org-latex--org-table (table contents info)
+ "Return appropriate LaTeX code for an Org table.
+
+TABLE is the table type element to transcode. CONTENTS is its
+contents, as a string. INFO is a plist used as a communication
+channel.
+
+This function assumes TABLE has `org' as its `:type' property and
+`table' as its `:mode' attribute."
+ (let* ((caption (org-latex--caption/label-string table info))
+ (attr (org-export-read-attribute :attr_latex table))
+ ;; Determine alignment string.
+ (alignment (org-latex--align-string table info))
+ ;; Determine environment for the table: longtable, tabular...
+ (table-env (or (plist-get attr :environment)
+ (plist-get info :latex-default-table-environment)))
+ ;; If table is a float, determine environment: table, table*
+ ;; or sidewaystable.
+ (float-env (unless (member table-env '("longtable" "longtabu"))
+ (let ((float (plist-get attr :float)))
+ (cond
+ ((and (not float) (plist-member attr :float)) nil)
+ ((or (string= float "sidewaystable")
+ (string= float "sideways")) "sidewaystable")
+ ((string= float "multicolumn") "table*")
+ ((or float
+ (org-element-property :caption table)
+ (org-string-nw-p (plist-get attr :caption)))
+ "table")))))
+ ;; Extract others display options.
+ (fontsize (let ((font (plist-get attr :font)))
+ (and font (concat font "\n"))))
+ ;; "tabular" environment doesn't allow to define a width.
+ (width (and (not (equal table-env "tabular")) (plist-get attr :width)))
+ (spreadp (plist-get attr :spread))
+ (placement
+ (or (plist-get attr :placement)
+ (format "[%s]" (plist-get info :latex-default-figure-position))))
+ (centerp (if (plist-member attr :center) (plist-get attr :center)
+ (plist-get info :latex-tables-centered)))
+ (caption-above-p (org-latex--caption-above-p table info)))
+ ;; Prepare the final format string for the table.
+ (cond
+ ;; Longtable.
+ ((equal "longtable" table-env)
+ (concat (and fontsize (concat "{" fontsize))
+ (format "\\begin{longtable}{%s}\n" alignment)
+ (and caption-above-p
+ (org-string-nw-p caption)
+ (concat caption "\\\\\n"))
+ contents
+ (and (not caption-above-p)
+ (org-string-nw-p caption)
+ (concat caption "\\\\\n"))
+ "\\end{longtable}\n"
+ (and fontsize "}")))
+ ;; Longtabu
+ ((equal "longtabu" table-env)
+ (concat (and fontsize (concat "{" fontsize))
+ (format "\\begin{longtabu}%s{%s}\n"
+ (if width
+ (format " %s %s "
+ (if spreadp "spread" "to") width) "")
+ alignment)
+ (and caption-above-p
+ (org-string-nw-p caption)
+ (concat caption "\\\\\n"))
+ contents
+ (and (not caption-above-p)
+ (org-string-nw-p caption)
+ (concat caption "\\\\\n"))
+ "\\end{longtabu}\n"
+ (and fontsize "}")))
+ ;; Others.
+ (t (concat (cond
+ (float-env
+ (concat (format "\\begin{%s}%s\n" float-env placement)
+ (if caption-above-p caption "")
+ (when centerp "\\centering\n")
+ fontsize))
+ ((and (not float-env) caption)
+ (concat
+ (and centerp "\\begin{center}\n" )
+ (if caption-above-p caption "")
+ (cond ((and fontsize centerp) fontsize)
+ (fontsize (concat "{" fontsize)))))
+ (centerp (concat "\\begin{center}\n" fontsize))
+ (fontsize (concat "{" fontsize)))
+ (cond ((equal "tabu" table-env)
+ (format "\\begin{tabu}%s{%s}\n%s\\end{tabu}"
+ (if width (format
+ (if spreadp " spread %s " " to %s ")
+ width) "")
+ alignment
+ contents))
+ (t (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
+ table-env
+ (if width (format "{%s}" width) "")
+ alignment
+ contents
+ table-env)))
+ (cond
+ (float-env
+ (concat (if caption-above-p "" (concat "\n" caption))
+ (format "\n\\end{%s}" float-env)))
+ ((and (not float-env) caption)
+ (concat
+ (if caption-above-p "" (concat "\n" caption))
+ (and centerp "\n\\end{center}")
+ (and fontsize (not centerp) "}")))
+ (centerp "\n\\end{center}")
+ (fontsize "}")))))))
+
+(defun org-latex--table.el-table (table info)
+ "Return appropriate LaTeX code for a table.el table.
+
+TABLE is the table type element to transcode. INFO is a plist
+used as a communication channel.
+
+This function assumes TABLE has `table.el' as its `:type'
+property."
+ (require 'table)
+ ;; Ensure "*org-export-table*" buffer is empty.
+ (with-current-buffer (get-buffer-create "*org-export-table*")
+ (erase-buffer))
+ (let ((output (with-temp-buffer
+ (insert (org-element-property :value table))
+ (goto-char 1)
+ (re-search-forward "^[ \t]*|[^|]" nil t)
+ (table-generate-source 'latex "*org-export-table*")
+ (with-current-buffer "*org-export-table*"
+ (org-trim (buffer-string))))))
+ (kill-buffer (get-buffer "*org-export-table*"))
+ ;; Remove left out comments.
+ (while (string-match "^%.*\n" output)
+ (setq output (replace-match "" t t output)))
+ (let ((attr (org-export-read-attribute :attr_latex table)))
+ (when (plist-get attr :rmlines)
+ ;; When the "rmlines" attribute is provided, remove all hlines
+ ;; but the the one separating heading from the table body.
+ (let ((n 0) (pos 0))
+ (while (and (< (length output) pos)
+ (setq pos (string-match "^\\\\hline\n?" output pos)))
+ (cl-incf n)
+ (unless (= n 2) (setq output (replace-match "" nil nil output))))))
+ (let ((centerp (if (plist-member attr :center) (plist-get attr :center)
+ (plist-get info :latex-tables-centered))))
+ (if (not centerp) output
+ (format "\\begin{center}\n%s\n\\end{center}" output))))))
+
+(defun org-latex--math-table (table info)
+ "Return appropriate LaTeX code for a matrix.
+
+TABLE is the table type element to transcode. INFO is a plist
+used as a communication channel.
+
+This function assumes TABLE has `org' as its `:type' property and
+`inline-math' or `math' as its `:mode' attribute."
+ (let* ((attr (org-export-read-attribute :attr_latex table))
+ (env (or (plist-get attr :environment)
+ (plist-get info :latex-default-table-environment)))
+ (contents
+ (mapconcat
+ (lambda (row)
+ ;; Ignore horizontal rules.
+ (when (eq (org-element-property :type row) 'standard)
+ ;; Return each cell unmodified.
+ (concat
+ (mapconcat
+ (lambda (cell)
+ (substring (org-element-interpret-data cell) 0 -1))
+ (org-element-map row 'table-cell #'identity info) "&")
+ (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
+ "\n")))
+ (org-element-map table 'table-row #'identity info) "")))
+ (concat
+ ;; Prefix.
+ (plist-get attr :math-prefix)
+ ;; Environment. Also treat special cases.
+ (cond ((member env '("array" "tabular"))
+ (format "\\begin{%s}{%s}\n%s\\end{%s}"
+ env (org-latex--align-string table info t) contents env))
+ ((assoc env org-latex-table-matrix-macros)
+ (format "\\%s%s{\n%s}"
+ env
+ (or (plist-get attr :math-arguments) "")
+ contents))
+ (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
+ ;; Suffix.
+ (plist-get attr :math-suffix))))
+
+
+;;;; Table Cell
+
+(defun org-latex-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to LaTeX.
+CONTENTS is the cell contents. INFO is a plist used as
+a communication channel."
+ (concat
+ (let ((scientific-format (plist-get info :latex-table-scientific-notation)))
+ (if (and contents
+ scientific-format
+ (string-match orgtbl-exp-regexp contents))
+ ;; Use appropriate format string for scientific
+ ;; notation.
+ (format scientific-format
+ (match-string 1 contents)
+ (match-string 2 contents))
+ contents))
+ (when (org-export-get-next-element table-cell info) " & ")))
+
+
+;;;; Table Row
+
+(defun org-latex-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to LaTeX.
+CONTENTS is the contents of the row. INFO is a plist used as
+a communication channel."
+ (let* ((attr (org-export-read-attribute :attr_latex
+ (org-export-get-parent table-row)))
+ (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
+ (plist-get info :latex-tables-booktabs)))
+ (longtablep
+ (member (or (plist-get attr :environment)
+ (plist-get info :latex-default-table-environment))
+ '("longtable" "longtabu"))))
+ (if (eq (org-element-property :type table-row) 'rule)
+ (cond
+ ((not booktabsp) "\\hline")
+ ((not (org-export-get-previous-element table-row info)) "\\toprule")
+ ((not (org-export-get-next-element table-row info)) "\\bottomrule")
+ ((and longtablep
+ (org-export-table-row-ends-header-p
+ (org-export-get-previous-element table-row info) info))
+ "")
+ (t "\\midrule"))
+ (concat
+ ;; When BOOKTABS are activated enforce top-rule even when no
+ ;; hline was specifically marked.
+ (and booktabsp (not (org-export-get-previous-element table-row info))
+ "\\toprule\n")
+ contents "\\\\\n"
+ (cond
+ ;; Special case for long tables. Define header and footers.
+ ((and longtablep (org-export-table-row-ends-header-p table-row info))
+ (let ((columns (cdr (org-export-table-dimensions
+ (org-export-get-parent-table table-row) info))))
+ (format "%s
+\\endfirsthead
+\\multicolumn{%d}{l}{%s} \\\\
+%s
+%s \\\\\n
+%s
+\\endhead
+%s\\multicolumn{%d}{r}{%s} \\\\
+\\endfoot
+\\endlastfoot"
+ (if booktabsp "\\midrule" "\\hline")
+ columns
+ (org-latex--translate "Continued from previous page" info)
+ (cond
+ ((not (org-export-table-row-starts-header-p table-row info))
+ "")
+ (booktabsp "\\toprule\n")
+ (t "\\hline\n"))
+ contents
+ (if booktabsp "\\midrule" "\\hline")
+ (if booktabsp "\\midrule" "\\hline")
+ columns
+ (org-latex--translate "Continued on next page" info))))
+ ;; When BOOKTABS are activated enforce bottom rule even when
+ ;; no hline was specifically marked.
+ ((and booktabsp (not (org-export-get-next-element table-row info)))
+ "\\bottomrule"))))))
+
+
+;;;; Target
+
+(defun org-latex-target (target _contents info)
+ "Transcode a TARGET object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "\\label{%s}" (org-latex--label target info)))
+
+
+;;;; Timestamp
+
+(defun org-latex-timestamp (timestamp _contents info)
+ "Transcode a TIMESTAMP object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((value (org-latex-plain-text (org-timestamp-translate timestamp) info)))
+ (format
+ (plist-get info
+ (cl-case (org-element-property :type timestamp)
+ ((active active-range) :latex-active-timestamp-format)
+ ((inactive inactive-range) :latex-inactive-timestamp-format)
+ (otherwise :latex-diary-timestamp-format)))
+ value)))
+
+
+;;;; Underline
+
+(defun org-latex-underline (_underline contents info)
+ "Transcode UNDERLINE from Org to LaTeX.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (org-latex--text-markup contents 'underline info))
+
+
+;;;; Verbatim
+
+(defun org-latex-verbatim (verbatim _contents info)
+ "Transcode a VERBATIM object from Org to LaTeX.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-latex--text-markup
+ (org-element-property :value verbatim) 'verbatim info))
+
+
+;;;; Verse Block
+
+(defun org-latex-verse-block (verse-block contents info)
+ "Transcode a VERSE-BLOCK element from Org to LaTeX.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (org-latex--wrap-label
+ verse-block
+ ;; In a verse environment, add a line break to each newline
+ ;; character and change each white space at beginning of a line
+ ;; into a space of 1 em. Also change each blank line with
+ ;; a vertical space of 1 em.
+ (format "\\begin{verse}\n%s\\end{verse}"
+ (replace-regexp-in-string
+ "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
+ (replace-regexp-in-string
+ "^[ \t]*\\\\\\\\$" "\\vspace*{1em}"
+ (replace-regexp-in-string
+ "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
+ contents nil t) nil t) nil t))
+ info))
+
+
+
+;;; End-user functions
+
+;;;###autoload
+(defun org-latex-export-as-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer as a LaTeX buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org LATEX Export*\", which
+will be displayed when `org-export-show-temporary-export-buffer'
+is non-nil."
+ (interactive)
+ (org-export-to-buffer 'latex "*Org LATEX Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
+
+;;;###autoload
+(defun org-latex-convert-region-to-latex ()
+ "Assume the current region has Org syntax, and convert it to LaTeX.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an LaTeX buffer and use this
+command to convert it."
+ (interactive)
+ (org-export-replace-region-by 'latex))
+
+;;;###autoload
+(defun org-latex-export-to-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a LaTeX file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".tex" subtreep)))
+ (org-export-to-file 'latex outfile
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-latex-export-to-pdf
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to LaTeX then process through to PDF.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".tex" subtreep)))
+ (org-export-to-file 'latex outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))))
+
+(defun org-latex-compile (texfile &optional snippet)
+ "Compile a TeX file.
+
+TEXFILE is the name of the file being compiled. Processing is
+done through the command specified in `org-latex-pdf-process',
+which see. Output is redirected to \"*Org PDF LaTeX Output*\"
+buffer.
+
+When optional argument SNIPPET is non-nil, TEXFILE is a temporary
+file used to preview a LaTeX snippet. In this case, do not
+create a log buffer and do not remove log files.
+
+Return PDF file name or raise an error if it couldn't be
+produced."
+ (unless snippet (message "Processing LaTeX file %s..." texfile))
+ (let* ((compiler
+ (or (with-temp-buffer
+ (save-excursion (insert-file-contents texfile))
+ (and (search-forward-regexp (regexp-opt org-latex-compilers)
+ (line-end-position 2)
+ t)
+ (progn (beginning-of-line) (looking-at-p "%"))
+ (match-string 0)))
+ "pdflatex"))
+ (process (if (functionp org-latex-pdf-process) org-latex-pdf-process
+ ;; Replace "%latex" and "%bibtex" with,
+ ;; respectively, "%L" and "%B" so as to adhere to
+ ;; `format-spec' specifications.
+ (mapcar (lambda (command)
+ (replace-regexp-in-string
+ "%\\(?:bib\\|la\\)tex\\>"
+ (lambda (m) (upcase (substring m 0 2)))
+ command))
+ org-latex-pdf-process)))
+ (spec `((?B . ,(shell-quote-argument org-latex-bib-compiler))
+ (?L . ,(shell-quote-argument compiler))))
+ (log-buf-name "*Org PDF LaTeX Output*")
+ (log-buf (and (not snippet) (get-buffer-create log-buf-name)))
+ (outfile (org-compile-file texfile process "pdf"
+ (format "See %S for details" log-buf-name)
+ log-buf spec)))
+ (unless snippet
+ (when org-latex-remove-logfiles
+ (mapc #'delete-file
+ (directory-files
+ (file-name-directory outfile)
+ t
+ (concat (regexp-quote (file-name-base outfile))
+ "\\(?:\\.[0-9]+\\)?\\."
+ (regexp-opt org-latex-logfiles-extensions))
+ t)))
+ (let ((warnings (org-latex--collect-warnings log-buf)))
+ (message (concat "PDF file produced"
+ (cond
+ ((eq warnings 'error) " with errors.")
+ (warnings (concat " with warnings: " warnings))
+ (t "."))))))
+ ;; Return output file name.
+ outfile))
+
+(defun org-latex--collect-warnings (buffer)
+ "Collect some warnings from \"pdflatex\" command output.
+BUFFER is the buffer containing output. Return collected
+warnings types as a string, `error' if a LaTeX error was
+encountered or nil if there was none."
+ (with-current-buffer buffer
+ (save-excursion
+ (goto-char (point-max))
+ (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
+ (if (re-search-forward "^!" nil t) 'error
+ (let ((case-fold-search t)
+ (warnings ""))
+ (dolist (warning org-latex-known-warnings)
+ (when (save-excursion (re-search-forward (car warning) nil t))
+ (setq warnings (concat warnings " " (cdr warning)))))
+ (org-string-nw-p (org-trim warnings))))))))
+
+;;;###autoload
+(defun org-latex-publish-to-latex (plist filename pub-dir)
+ "Publish an Org file to LaTeX.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'latex filename ".tex" plist pub-dir))
+
+;;;###autoload
+(defun org-latex-publish-to-pdf (plist filename pub-dir)
+ "Publish an Org file to PDF (via LaTeX).
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
+ ;; in working directory and then moved to publishing directory.
+ (org-publish-attachment
+ plist
+ ;; Default directory could be anywhere when this function is
+ ;; called. We ensure it is set to source file directory during
+ ;; compilation so as to not break links to external documents.
+ (let ((default-directory (file-name-directory filename)))
+ (org-latex-compile
+ (org-publish-org-to
+ 'latex filename ".tex" plist (file-name-directory filename))))
+ pub-dir))
+
+
+(provide 'ox-latex)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-latex.el ends here
diff --git a/lisp/ox-man.el b/lisp/ox-man.el
new file mode 100644
index 0000000..71718ab
--- /dev/null
+++ b/lisp/ox-man.el
@@ -0,0 +1,1141 @@
+;; ox-man.el --- Man Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2011-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Luis R Anaya <papoanaya aroba hot mail punto com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements a Man back-end for Org generic exporter.
+;;
+;; To test it, run
+;;
+;; M-: (org-export-to-buffer 'man "*Test Man*") RET
+;;
+;; in an Org buffer then switch to the buffer to see the Man export.
+;; See ox.el for more details on how this exporter works.
+;;
+;; It introduces one new buffer keywords:
+;; "MAN_CLASS_OPTIONS".
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox)
+
+(defvar org-export-man-default-packages-alist)
+(defvar org-export-man-packages-alist)
+(defvar orgtbl-exp-regexp)
+
+
+
+;;; Define Back-End
+
+(org-export-define-backend 'man
+ '((babel-call . org-man-babel-call)
+ (bold . org-man-bold)
+ (center-block . org-man-center-block)
+ (code . org-man-code)
+ (drawer . org-man-drawer)
+ (dynamic-block . org-man-dynamic-block)
+ (entity . org-man-entity)
+ (example-block . org-man-example-block)
+ (export-block . org-man-export-block)
+ (export-snippet . org-man-export-snippet)
+ (fixed-width . org-man-fixed-width)
+ (footnote-definition . org-man-footnote-definition)
+ (footnote-reference . org-man-footnote-reference)
+ (headline . org-man-headline)
+ (horizontal-rule . org-man-horizontal-rule)
+ (inline-babel-call . org-man-inline-babel-call)
+ (inline-src-block . org-man-inline-src-block)
+ (inlinetask . org-man-inlinetask)
+ (italic . org-man-italic)
+ (item . org-man-item)
+ (keyword . org-man-keyword)
+ (line-break . org-man-line-break)
+ (link . org-man-link)
+ (node-property . org-man-node-property)
+ (paragraph . org-man-paragraph)
+ (plain-list . org-man-plain-list)
+ (plain-text . org-man-plain-text)
+ (planning . org-man-planning)
+ (property-drawer . org-man-property-drawer)
+ (quote-block . org-man-quote-block)
+ (radio-target . org-man-radio-target)
+ (section . org-man-section)
+ (special-block . org-man-special-block)
+ (src-block . org-man-src-block)
+ (statistics-cookie . org-man-statistics-cookie)
+ (strike-through . org-man-strike-through)
+ (subscript . org-man-subscript)
+ (superscript . org-man-superscript)
+ (table . org-man-table)
+ (table-cell . org-man-table-cell)
+ (table-row . org-man-table-row)
+ (target . org-man-target)
+ (template . org-man-template)
+ (timestamp . org-man-timestamp)
+ (underline . org-man-underline)
+ (verbatim . org-man-verbatim)
+ (verse-block . org-man-verse-block))
+ :menu-entry
+ '(?M "Export to MAN"
+ ((?m "As MAN file" org-man-export-to-man)
+ (?p "As PDF file" org-man-export-to-pdf)
+ (?o "As PDF file and open"
+ (lambda (a s v b)
+ (if a (org-man-export-to-pdf t s v b)
+ (org-open-file (org-man-export-to-pdf nil s v b)))))))
+ :options-alist
+ '((:man-class "MAN_CLASS" nil nil t)
+ (:man-class-options "MAN_CLASS_OPTIONS" nil nil t)
+ (:man-header-extra "MAN_HEADER" nil nil newline)
+ ;; Other variables.
+ (:man-tables-centered nil nil org-man-tables-centered)
+ (:man-tables-verbatim nil nil org-man-tables-verbatim)
+ (:man-table-scientific-notation nil nil org-man-table-scientific-notation)
+ (:man-source-highlight nil nil org-man-source-highlight)
+ (:man-source-highlight-langs nil nil org-man-source-highlight-langs)))
+
+
+
+;;; User Configurable Variables
+
+(defgroup org-export-man nil
+ "Options for exporting Org mode files to Man."
+ :tag "Org Export Man"
+ :group 'org-export)
+
+;;; Tables
+
+(defcustom org-man-tables-centered t
+ "When non-nil, tables are exported in a center environment."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-man-tables-verbatim nil
+ "When non-nil, tables are exported verbatim."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+
+(defcustom org-man-table-scientific-notation "%sE%s"
+ "Format string to display numbers in scientific notation.
+The format should have \"%s\" twice, for mantissa and exponent
+\(i.e. \"%s\\\\times10^{%s}\").
+
+When nil, no transformation is made."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (string :tag "Format string")
+ (const :tag "No formatting")))
+
+
+;;; Inlinetasks
+;; Src blocks
+
+(defcustom org-man-source-highlight nil
+ "Use GNU source highlight to embellish source blocks "
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+
+(defcustom org-man-source-highlight-langs
+ '((emacs-lisp "lisp") (lisp "lisp") (clojure "lisp")
+ (scheme "scheme")
+ (c "c") (cc "cpp") (csharp "csharp") (d "d")
+ (fortran "fortran") (cobol "cobol") (pascal "pascal")
+ (ada "ada") (asm "asm")
+ (perl "perl") (cperl "perl")
+ (python "python") (ruby "ruby") (tcl "tcl") (lua "lua")
+ (java "java") (javascript "javascript")
+ (tex "latex")
+ (shell-script "sh") (awk "awk") (diff "diff") (m4 "m4")
+ (ocaml "caml") (caml "caml")
+ (sql "sql") (sqlite "sql")
+ (html "html") (css "css") (xml "xml")
+ (bat "bat") (bison "bison") (clipper "clipper")
+ (ldap "ldap") (opa "opa")
+ (php "php") (postscript "postscript") (prolog "prolog")
+ (properties "properties") (makefile "makefile")
+ (tml "tml") (vala "vala") (vbscript "vbscript") (xorg "xorg"))
+ "Alist mapping languages to their listing language counterpart.
+The key is a symbol, the major mode symbol without the \"-mode\".
+The value is the string that should be inserted as the language
+parameter for the listings package. If the mode name and the
+listings name are the same, the language does not need an entry
+in this list - but it does not hurt if it is present."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(repeat
+ (list
+ (symbol :tag "Major mode ")
+ (string :tag "Listings language"))))
+
+
+;;; Compilation
+
+(defcustom org-man-pdf-process
+ '("tbl %f | eqn | groff -man | ps2pdf - > %b.pdf"
+ "tbl %f | eqn | groff -man | ps2pdf - > %b.pdf"
+ "tbl %f | eqn | groff -man | ps2pdf - > %b.pdf")
+
+ "Commands to process a Man file to a PDF file.
+
+This is a list of strings, each of them will be given to the
+shell as a command. %f in the command will be replaced by the
+relative file name, %F by the absolute file name, %b by the file
+base name (i.e. without directory and extension parts), %o by the
+base directory of the file and %O by the absolute file name of
+the output file.
+
+By default, Org uses 3 runs of to do the processing.
+
+Alternatively, this may be a Lisp function that does the
+processing. This function should accept the file name as
+its single argument."
+ :group 'org-export-pdf
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (repeat :tag "Shell command sequence"
+ (string :tag "Shell command"))
+ (const :tag "2 runs of pdfgroff"
+ ("tbl %f | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "tbl %f | eqn | groff -mm | ps2pdf - > %b.pdf" ))
+ (const :tag "3 runs of pdfgroff"
+ ("tbl %f | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "tbl %f | eqn | groff -mm | ps2pdf - > %b.pdf"
+ "tbl %f | eqn | groff -mm | ps2pdf - > %b.pdf"))
+ (function)))
+
+(defcustom org-man-logfiles-extensions
+ '("log" "out" "toc")
+ "The list of file extensions to consider as Man logfiles."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-man-remove-logfiles t
+ "Non-nil means remove the logfiles produced by PDF production.
+These are the .aux, .log, .out, and .toc files."
+ :group 'org-export-man
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+
+
+;;; Internal Functions
+
+(defun org-man--caption/label-string (element info)
+ "Return caption and label Man string for ELEMENT.
+
+INFO is a plist holding contextual information. If there's no
+caption nor label, return the empty string.
+
+For non-floats, see `org-man--wrap-label'."
+ (let ((label (org-element-property :label element))
+ (main (org-export-get-caption element))
+ (short (org-export-get-caption element t)))
+ (cond ((and (not main) (not label)) "")
+ ((not main) (format "\\fI%s\\fP" label))
+ ;; Option caption format with short name.
+ (short (format "\\fR%s\\fP - \\fI\\P - %s\n"
+ (org-export-data short info)
+ (org-export-data main info)))
+ ;; Standard caption format.
+ (t (format "\\fR%s\\fP" (org-export-data main info))))))
+
+(defun org-man--wrap-label (element output)
+ "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
+This function shouldn't be used for floats. See
+`org-man--caption/label-string'."
+ (let ((label (org-element-property :name element)))
+ (if (or (not output) (not label) (string= output "") (string= label ""))
+ output
+ (concat (format "%s\n.br\n" label) output))))
+
+
+
+;;; Template
+
+(defun org-man-template (contents info)
+ "Return complete document string after Man conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let* ((title (when (plist-get info :with-title)
+ (org-export-data (plist-get info :title) info)))
+ (attr (read (format "(%s)"
+ (mapconcat
+ #'identity
+ (list (plist-get info :man-class-options))
+ " "))))
+ (section-item (plist-get attr :section-id)))
+
+ (concat
+
+ (cond
+ ((and title (stringp section-item))
+ (format ".TH \"%s\" \"%s\" \n" title section-item))
+ ((and (string= "" title) (stringp section-item))
+ (format ".TH \"%s\" \"%s\" \n" " " section-item))
+ (title
+ (format ".TH \"%s\" \"1\" \n" title))
+ (t
+ ".TH \" \" \"1\" "))
+ contents)))
+
+
+
+
+;;; Transcode Functions
+
+;;; Babel Call
+;;
+;; Babel Calls are ignored.
+
+
+;;; Bold
+
+(defun org-man-bold (_bold contents _info)
+ "Transcode BOLD from Org to Man.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (format "\\fB%s\\fP" contents))
+
+
+;;; Center Block
+
+(defun org-man-center-block (center-block contents _info)
+ "Transcode a CENTER-BLOCK element from Org to Man.
+CONTENTS holds the contents of the center block. INFO is a plist
+holding contextual information."
+ (org-man--wrap-label
+ center-block
+ (format ".ce %d\n.nf\n%s\n.fi"
+ (- (length (split-string contents "\n")) 1 )
+ contents)))
+
+
+;;; Code
+
+(defun org-man-code (code _contents _info)
+ "Transcode a CODE object from Org to Man.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format "\\fC%s\\fP" code))
+
+
+;;; Drawer
+
+(defun org-man-drawer (_drawer contents _info)
+ "Transcode a DRAWER element from Org to Man.
+ DRAWER holds the drawer information
+ CONTENTS holds the contents of the block.
+ INFO is a plist holding contextual information. "
+ contents)
+
+
+;;; Dynamic Block
+
+(defun org-man-dynamic-block (dynamic-block contents _info)
+ "Transcode a DYNAMIC-BLOCK element from Org to Man.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information. See `org-export-data'."
+ (org-man--wrap-label dynamic-block contents))
+
+
+;;; Entity
+
+(defun org-man-entity (entity _contents _info)
+ "Transcode an ENTITY object from Org to Man.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :utf-8 entity))
+
+
+;;; Example Block
+
+(defun org-man-example-block (example-block _contents info)
+ "Transcode an EXAMPLE-BLOCK element from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-man--wrap-label
+ example-block
+ (format ".RS\n.nf\n%s\n.fi\n.RE"
+ (org-export-format-code-default example-block info))))
+
+
+;;; Export Block
+
+(defun org-man-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "MAN")
+ (org-remove-indentation (org-element-property :value export-block))))
+
+
+;;; Export Snippet
+
+(defun org-man-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'man)
+ (org-element-property :value export-snippet)))
+
+
+;;; Fixed Width
+
+(defun org-man-fixed-width (fixed-width _contents _info)
+ "Transcode a FIXED-WIDTH element from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-man--wrap-label
+ fixed-width
+ (format "\\fC\n%s\\fP"
+ (org-remove-indentation
+ (org-element-property :value fixed-width)))))
+
+
+;;; Footnote Definition
+;;
+;; Footnote Definitions are ignored.
+
+;;; Footnote References
+;;
+;; Footnote References are Ignored
+
+
+;;; Headline
+
+(defun org-man-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to Man.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ (let* ((level (org-export-get-relative-level headline info))
+ ;; Section formatting will set two placeholders: one for the
+ ;; title and the other for the contents.
+ (section-fmt
+ (pcase level
+ (1 ".SH \"%s\"\n%s")
+ (2 ".SS \"%s\"\n%s")
+ (3 ".SS \"%s\"\n%s")
+ (_ nil)))
+ (text (org-export-data (org-element-property :title headline) info)))
+
+ (cond
+ ;; Case 1: This is a footnote section: ignore it.
+ ((org-element-property :footnote-section-p headline) nil)
+
+ ;; Case 2. This is a deep sub-tree: export it as a list item.
+ ;; Also export as items headlines for which no section
+ ;; format has been found.
+ ((or (not section-fmt) (org-export-low-level-p headline info))
+ ;; Build the real contents of the sub-tree.
+ (let ((low-level-body
+ (concat
+ ;; If the headline is the first sibling, start a list.
+ (when (org-export-first-sibling-p headline info)
+ (format "%s\n" ".RS"))
+ ;; Itemize headline
+ ".TP\n.ft I\n" text "\n.ft\n"
+ contents ".RE")))
+ ;; If headline is not the last sibling simply return
+ ;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
+ ;; blank line.
+ (if (not (org-export-last-sibling-p headline info)) low-level-body
+ (replace-regexp-in-string
+ "[ \t\n]*\\'" ""
+ low-level-body))))
+
+ ;; Case 3. Standard headline. Export it as a section.
+ (t (format section-fmt text contents )))))
+
+;;; Horizontal Rule
+;; Not supported
+
+;;; Inline Babel Call
+;;
+;; Inline Babel Calls are ignored.
+
+;;; Inline Src Block
+
+(defun org-man-inline-src-block (inline-src-block _contents info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to Man.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((code (org-element-property :value inline-src-block)))
+ (cond
+ ((plist-get info :man-source-highlight)
+ (let* ((tmpdir temporary-file-directory)
+ (in-file (make-temp-name
+ (expand-file-name "srchilite" tmpdir)))
+ (out-file (make-temp-name
+ (expand-file-name "reshilite" tmpdir)))
+ (org-lang (org-element-property :language inline-src-block))
+ (lst-lang
+ (cadr (assq (intern org-lang)
+ (plist-get info :man-source-highlight-langs))))
+
+ (cmd (concat (expand-file-name "source-highlight")
+ " -s " lst-lang
+ " -f groff_man"
+ " -i " in-file
+ " -o " out-file )))
+
+ (if lst-lang
+ (let ((code-block "" ))
+ (with-temp-file in-file (insert code))
+ (shell-command cmd)
+ (setq code-block (org-file-contents out-file))
+ (delete-file in-file)
+ (delete-file out-file)
+ code-block)
+ (format ".RS\n.nf\n\\fC\\m[black]%s\\m[]\\fP\n.fi\n.RE\n"
+ code))))
+
+ ;; Do not use a special package: transcode it verbatim.
+ (t
+ (concat ".RS\n.nf\n" "\\fC" "\n" code "\n"
+ "\\fP\n.fi\n.RE\n")))))
+
+
+;;; Inlinetask
+;;; Italic
+
+(defun org-man-italic (_italic contents _info)
+ "Transcode ITALIC from Org to Man.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (format "\\fI%s\\fP" contents))
+
+
+;;; Item
+
+
+(defun org-man-item (item contents info)
+ "Transcode an ITEM element from Org to Man.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((bullet (org-element-property :bullet item))
+ (type (org-element-property :type (org-element-property :parent item)))
+ (checkbox (pcase (org-element-property :checkbox item)
+ (`on "\\o'\\(sq\\(mu'")
+ (`off "\\(sq ")
+ (`trans "\\o'\\(sq\\(mi'")))
+
+ (tag (let ((tag (org-element-property :tag item)))
+ ;; Check-boxes must belong to the tag.
+ (and tag (format "\\fB%s\\fP"
+ (concat checkbox
+ (org-export-data tag info)))))))
+
+ (if (and (null tag) (null checkbox))
+ (let* ((bullet (org-trim bullet))
+ (marker (cond ((string= "-" bullet) "\\(em")
+ ((string= "*" bullet) "\\(bu")
+ ((eq type 'ordered)
+ (format "%s " (org-trim bullet)))
+ (t "\\(dg"))))
+ (concat ".IP " marker " 4\n"
+ (org-trim (or contents " " ))))
+ (concat ".TP\n" (or tag (concat " " checkbox)) "\n"
+ (org-trim (or contents " " ))))))
+
+;;; Keyword
+
+
+(defun org-man-keyword (keyword _contents _info)
+ "Transcode a KEYWORD element from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "MAN") value)
+ ((string= key "INDEX") nil)
+ ((string= key "TOC" ) nil))))
+
+
+;;; Line Break
+
+(defun org-man-line-break (_line-break _contents _info)
+ "Transcode a LINE-BREAK object from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ "\n.br\n")
+
+
+;;; Link
+
+
+(defun org-man-link (link desc _info)
+ "Transcode a LINK object from Org to Man.
+
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+ (let* ((type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (and (not (string= desc "")) desc))
+ (path (cond
+ ((member type '("http" "https" "ftp" "mailto"))
+ (concat type ":" raw-path))
+ ((string= type "file") (org-export-file-uri raw-path))
+ (t raw-path))))
+ (cond
+ ;; Link type is handled by a special function.
+ ((org-export-custom-protocol-maybe link desc 'man))
+ ;; External link with a description part.
+ ((and path desc) (format "%s \\fBat\\fP \\fI%s\\fP" path desc))
+ ;; External link without a description part.
+ (path (format "\\fI%s\\fP" path))
+ ;; No path, only description. Try to do something useful.
+ (t (format "\\fI%s\\fP" desc)))))
+
+;;;; Node Property
+
+(defun org-man-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+;;; Paragraph
+
+(defun org-man-paragraph (paragraph contents _info)
+ "Transcode a PARAGRAPH element from Org to Man.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ (let ((parent (plist-get (nth 1 paragraph) :parent)))
+ (when parent
+ (let ((parent-type (car parent))
+ (fixed-paragraph ""))
+ (cond ((and (eq parent-type 'item)
+ (plist-get (nth 1 parent) :bullet ))
+ (setq fixed-paragraph (concat "" contents)))
+ ((eq parent-type 'section)
+ (setq fixed-paragraph (concat ".PP\n" contents)))
+ ((eq parent-type 'footnote-definition)
+ (setq fixed-paragraph contents))
+ (t (setq fixed-paragraph (concat "" contents))))
+ fixed-paragraph ))))
+
+
+;;; Plain List
+
+(defun org-man-plain-list (_plain-list contents _info)
+ "Transcode a PLAIN-LIST element from Org to Man.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ contents)
+
+;;; Plain Text
+
+(defun org-man-plain-text (text info)
+ "Transcode a TEXT string from Org to Man.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ (let ((output text))
+ ;; Protect various chars.
+ (setq output (replace-regexp-in-string
+ "\\(?:[^\\]\\|^\\)\\(\\\\\\)\\(?:[^%$#&{}~^_\\]\\|$\\)"
+ "$\\" output nil t 1))
+ ;; Activate smart quotes. Be sure to provide original TEXT string
+ ;; since OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output (replace-regexp-in-string "\\(\\\\\\\\\\)?[ \t]*\n" ".br\n"
+ output)))
+ ;; Return value.
+ output))
+
+
+
+;;; Planning
+
+
+;;; Property Drawer
+
+(defun org-man-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element from Org to Man.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format ".RS\n.nf\n%s\n.fi\n.RE" contents)))
+
+;;; Quote Block
+
+(defun org-man-quote-block (quote-block contents _info)
+ "Transcode a QUOTE-BLOCK element from Org to Man.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (org-man--wrap-label
+ quote-block
+ (format ".RS\n%s\n.RE" contents)))
+
+
+;;; Radio Target
+
+(defun org-man-radio-target (_radio-target text _info)
+ "Transcode a RADIO-TARGET object from Org to Man.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ text)
+
+
+;;; Section
+
+(defun org-man-section (_section contents _info)
+ "Transcode a SECTION element from Org to Man.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ contents)
+
+
+;;; Special Block
+
+(defun org-man-special-block (special-block contents _info)
+ "Transcode a SPECIAL-BLOCK element from Org to Man.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (org-man--wrap-label special-block (format "%s\n" contents)))
+
+
+;;; Src Block
+
+(defun org-man-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to Man.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (if (not (plist-get info :man-source-highlight))
+ (format ".RS\n.nf\n\\fC%s\\fP\n.fi\n.RE\n\n"
+ (org-export-format-code-default src-block info))
+ (let* ((tmpdir temporary-file-directory)
+ (in-file (make-temp-name (expand-file-name "srchilite" tmpdir)))
+ (out-file (make-temp-name (expand-file-name "reshilite" tmpdir)))
+ (code (org-element-property :value src-block))
+ (org-lang (org-element-property :language src-block))
+ (lst-lang
+ (cadr (assq (intern org-lang)
+ (plist-get info :man-source-highlight-langs))))
+ (cmd (concat "source-highlight"
+ " -s " lst-lang
+ " -f groff_man "
+ " -i " in-file
+ " -o " out-file)))
+ (if lst-lang
+ (let ((code-block ""))
+ (with-temp-file in-file (insert code))
+ (shell-command cmd)
+ (setq code-block (org-file-contents out-file))
+ (delete-file in-file)
+ (delete-file out-file)
+ code-block)
+ (format ".RS\n.nf\n\\fC\\m[black]%s\\m[]\\fP\n.fi\n.RE" code)))))
+
+
+;;; Statistics Cookie
+
+(defun org-man-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-element-property :value statistics-cookie))
+
+
+;;; Strike-Through
+
+(defun org-man-strike-through (_strike-through contents _info)
+ "Transcode STRIKE-THROUGH from Org to Man.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (format "\\fI%s\\fP" contents))
+
+;;; Subscript
+
+(defun org-man-subscript (_subscript contents _info)
+ "Transcode a SUBSCRIPT object from Org to Man.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "\\d\\s-2%s\\s+2\\u" contents))
+
+;;; Superscript "^_%s$
+
+(defun org-man-superscript (_superscript contents _info)
+ "Transcode a SUPERSCRIPT object from Org to Man.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "\\u\\s-2%s\\s+2\\d" contents))
+
+
+;;; Table
+;;
+;; `org-man-table' is the entry point for table transcoding. It
+;; takes care of tables with a "verbatim" attribute. Otherwise, it
+;; delegates the job to either `org-man-table--table.el-table' or
+;; `org-man-table--org-table' functions, depending of the type of
+;; the table.
+;;
+;; `org-man-table--align-string' is a subroutine used to build
+;; alignment string for Org tables.
+
+(defun org-man-table (table contents info)
+ "Transcode a TABLE element from Org to Man.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (cond
+ ;; Case 1: verbatim table.
+ ((or (plist-get info :man-tables-verbatim)
+ (let ((attr (read (format "(%s)"
+ (mapconcat
+ #'identity
+ (org-element-property :attr_man table)
+ " ")))))
+
+ (and attr (plist-get attr :verbatim))))
+
+ (format ".nf\n\\fC%s\\fP\n.fi"
+ ;; Re-create table, without affiliated keywords.
+ (org-trim
+ (org-element-interpret-data
+ `(table nil ,@(org-element-contents table))))))
+ ;; Case 2: Standard table.
+ (t (org-man-table--org-table table contents info))))
+
+(defun org-man-table--align-string (divider table info)
+ "Return an appropriate Man alignment string.
+TABLE is the considered table. INFO is a plist used as
+a communication channel."
+ (let (alignment)
+ ;; Extract column groups and alignment from first (non-rule) row.
+ (org-element-map
+ (org-element-map table 'table-row
+ (lambda (row)
+ (and (eq (org-element-property :type row) 'standard) row))
+ info 'first-match)
+ 'table-cell
+ (lambda (cell)
+ (let* ((borders (org-export-table-cell-borders cell info))
+ (raw-width (org-export-table-cell-width cell info))
+ (width-cm (when raw-width (/ raw-width 5)))
+ (width (if raw-width (format "w(%dc)"
+ (if (< width-cm 1) 1 width-cm)) "")))
+ ;; Check left border for the first cell only.
+ (when (and (memq 'left borders) (not alignment))
+ (push "|" alignment))
+ (push
+ (concat (pcase (org-export-table-cell-alignment cell info)
+ (`left "l") (`right "r") (`center "c"))
+ width
+ divider)
+ alignment)
+ (when (memq 'right borders) (push "|" alignment))))
+ info)
+ (apply #'concat (reverse alignment))))
+
+(defun org-man-table--org-table (table contents info)
+ "Return appropriate Man code for an Org table.
+
+TABLE is the table type element to transcode. CONTENTS is its
+contents, as a string. INFO is a plist used as a communication
+channel.
+
+This function assumes TABLE has `org' as its `:type' attribute."
+ (let* ((attr (org-export-read-attribute :attr_man table))
+ (caption (and (not (plist-get attr :disable-caption))
+ (org-man--caption/label-string table info)))
+ (divider (if (plist-get attr :divider) "|" " "))
+
+ ;; Determine alignment string.
+ (alignment (org-man-table--align-string divider table info))
+ ;; Extract others display options.
+
+ (lines (org-split-string contents "\n"))
+
+ (attr-list
+ (delq nil
+ (list
+ (and (plist-get attr :expand) "expand")
+ (let ((placement (plist-get attr :placement)))
+ (cond ((string= placement 'center) "center")
+ ((string= placement 'left) nil)
+ ((plist-get info :man-tables-centered) "center")
+ (t "")))
+ (or (plist-get attr :boxtype) "box"))))
+
+ (title-line (plist-get attr :title-line))
+ (long-cells (plist-get attr :long-cells))
+
+ (table-format (concat
+ (format "%s" (or (car attr-list) "" ))
+ (or
+ (let ((output-list '()))
+ (when (cdr attr-list)
+ (dolist (attr-item (cdr attr-list))
+ (setq output-list (concat output-list (format ",%s" attr-item)))))
+ output-list)
+ "")))
+
+ (first-line (when lines (org-split-string (car lines) "\t"))))
+ ;; Prepare the final format string for the table.
+
+
+ (cond
+ ;; Others.
+ (lines (concat ".TS\n " table-format ";\n"
+
+ (format "%s.\n"
+ (let ((final-line ""))
+ (when title-line
+ (dotimes (_ (length first-line))
+ (setq final-line (concat final-line "cb" divider))))
+
+ (setq final-line (concat final-line "\n"))
+
+ (if alignment
+ (setq final-line (concat final-line alignment))
+ (dotimes (_ (length first-line))
+ (setq final-line (concat final-line "c" divider))))
+ final-line ))
+
+ (format "%s.TE\n"
+ (let ((final-line "")
+ (long-line "")
+ (lines (org-split-string contents "\n")))
+
+ (dolist (line-item lines)
+ (setq long-line "")
+
+ (if long-cells
+ (progn
+ (if (string= line-item "_")
+ (setq long-line (format "%s\n" line-item))
+ ;; else string =
+ (let ((cell-item-list (org-split-string line-item "\t")))
+ (dolist (cell-item cell-item-list)
+
+ (cond ((eq cell-item (car (last cell-item-list)))
+ (setq long-line (concat long-line
+ (format "T{\n%s\nT}\t\n" cell-item ))))
+ (t
+ (setq long-line (concat long-line
+ (format "T{\n%s\nT}\t" cell-item ))))))
+ long-line))
+ ;; else long cells
+ (setq final-line (concat final-line long-line )))
+
+ (setq final-line (concat final-line line-item "\n"))))
+ final-line))
+
+ (and caption (format ".TB \"%s\"" caption)))))))
+
+;;; Table Cell
+
+(defun org-man-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to Man
+CONTENTS is the cell contents. INFO is a plist used as
+a communication channel."
+ (concat
+ (let ((scientific-format (plist-get info :man-table-scientific-notation)))
+ (if (and contents
+ scientific-format
+ (string-match orgtbl-exp-regexp contents))
+ ;; Use appropriate format string for scientific notation.
+ (format scientific-format
+ (match-string 1 contents)
+ (match-string 2 contents))
+ contents))
+ (when (org-export-get-next-element table-cell info) "\t")))
+
+
+;;; Table Row
+
+(defun org-man-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to Man.
+CONTENTS is the contents of the row. INFO is a plist used as
+a communication channel."
+ ;; Rules are ignored since table separators are deduced from borders
+ ;; of the current row.
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let ((borders
+ ;; TABLE-ROW's borders are extracted from its first cell.
+ (org-export-table-cell-borders
+ (car (org-element-contents table-row)) info)))
+ (concat
+ (cond ((and (memq 'top borders) (memq 'above borders)) "_\n"))
+ contents
+ (cond ((and (memq 'bottom borders) (memq 'below borders)) "\n_")
+ ((memq 'below borders) "\n_"))))))
+
+
+;;; Target
+
+(defun org-man-target (target _contents info)
+ "Transcode a TARGET object from Org to Man.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "\\fI%s\\fP" (org-export-get-reference target info)))
+
+
+;;; Timestamp
+
+(defun org-man-timestamp (_timestamp _contents _info)
+ "Transcode a TIMESTAMP object from Org to Man.
+ONTENTS is nil. INFO is a plist holding contextual information."
+ "")
+
+
+;;; Underline
+
+(defun org-man-underline (_underline contents _info)
+ "Transcode UNDERLINE from Org to Man.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (format "\\fI%s\\fP" contents))
+
+
+;;; Verbatim
+
+(defun org-man-verbatim (_verbatim contents _info)
+ "Transcode a VERBATIM object from Org to Man.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format ".nf\n%s\n.fi" contents))
+
+
+;;; Verse Block
+
+(defun org-man-verse-block (_verse-block contents _info)
+ "Transcode a VERSE-BLOCK element from Org to Man.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (format ".RS\n.ft I\n%s\n.ft\n.RE" contents))
+
+
+
+;;; Interactive functions
+
+(defun org-man-export-to-man
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a Man file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only the body
+without any markers.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".man" subtreep)))
+ (org-export-to-file 'man outfile
+ async subtreep visible-only body-only ext-plist)))
+
+(defun org-man-export-to-pdf
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to Groff then process through to PDF.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write between
+markers.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return PDF file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".man" subtreep)))
+ (org-export-to-file 'man outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))))
+
+(defun org-man-compile (file)
+ "Compile a Groff file.
+
+FILE is the name of the file being compiled. Processing is done
+through the command specified in `org-man-pdf-process'.
+
+Return PDF file name or an error if it couldn't be produced."
+ (message "Processing Groff file %s..." file)
+ (let ((output (org-compile-file file org-man-pdf-process "pdf")))
+ (when org-man-remove-logfiles
+ (let ((base (file-name-sans-extension output)))
+ (dolist (ext org-man-logfiles-extensions)
+ (let ((file (concat base "." ext)))
+ (when (file-exists-p file) (delete-file file))))))
+ (message "Process completed.")
+ output))
+
+(provide 'ox-man)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-man.el ends here
diff --git a/lisp/ox-md.el b/lisp/ox-md.el
new file mode 100644
index 0000000..c8ea1fa
--- /dev/null
+++ b/lisp/ox-md.el
@@ -0,0 +1,647 @@
+;;; ox-md.el --- Markdown Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
+;; Keywords: org, wp, markdown
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This library implements a Markdown back-end (vanilla flavor) for
+;; Org exporter, based on `html' back-end. See Org manual for more
+;; information.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox-html)
+(require 'ox-publish)
+
+
+;;; User-Configurable Variables
+
+(defgroup org-export-md nil
+ "Options specific to Markdown export back-end."
+ :tag "Org Markdown"
+ :group 'org-export
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defcustom org-md-headline-style 'atx
+ "Style used to format headlines.
+This variable can be set to either `atx' or `setext'."
+ :group 'org-export-md
+ :type '(choice
+ (const :tag "Use \"atx\" style" atx)
+ (const :tag "Use \"Setext\" style" setext)))
+
+
+;;;; Footnotes
+
+(defcustom org-md-footnotes-section "%s%s"
+ "Format string for the footnotes section.
+The first %s placeholder will be replaced with the localized Footnotes section
+heading, the second with the contents of the Footnotes section."
+ :group 'org-export-md
+ :type 'string
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+(defcustom org-md-footnote-format "<sup>%s</sup>"
+ "Format string for the footnote reference.
+The %s will be replaced by the footnote reference itself."
+ :group 'org-export-md
+ :type 'string
+ :version "26.1"
+ :package-version '(Org . "9.0"))
+
+
+;;; Define Back-End
+
+(org-export-define-derived-backend 'md 'html
+ :filters-alist '((:filter-parse-tree . org-md-separate-elements))
+ :menu-entry
+ '(?m "Export to Markdown"
+ ((?M "To temporary buffer"
+ (lambda (a s v b) (org-md-export-as-markdown a s v)))
+ (?m "To file" (lambda (a s v b) (org-md-export-to-markdown a s v)))
+ (?o "To file and open"
+ (lambda (a s v b)
+ (if a (org-md-export-to-markdown t s v)
+ (org-open-file (org-md-export-to-markdown nil s v)))))))
+ :translate-alist '((bold . org-md-bold)
+ (code . org-md-verbatim)
+ (example-block . org-md-example-block)
+ (export-block . org-md-export-block)
+ (fixed-width . org-md-example-block)
+ (headline . org-md-headline)
+ (horizontal-rule . org-md-horizontal-rule)
+ (inline-src-block . org-md-verbatim)
+ (inner-template . org-md-inner-template)
+ (italic . org-md-italic)
+ (item . org-md-item)
+ (keyword . org-md-keyword)
+ (line-break . org-md-line-break)
+ (link . org-md-link)
+ (node-property . org-md-node-property)
+ (paragraph . org-md-paragraph)
+ (plain-list . org-md-plain-list)
+ (plain-text . org-md-plain-text)
+ (property-drawer . org-md-property-drawer)
+ (quote-block . org-md-quote-block)
+ (section . org-md-section)
+ (src-block . org-md-example-block)
+ (template . org-md-template)
+ (verbatim . org-md-verbatim))
+ :options-alist
+ '((:md-footnote-format nil nil org-md-footnote-format)
+ (:md-footnotes-section nil nil org-md-footnotes-section)
+ (:md-headline-style nil nil org-md-headline-style)))
+
+
+;;; Filters
+
+(defun org-md-separate-elements (tree _backend info)
+ "Fix blank lines between elements.
+
+TREE is the parse tree being exported. BACKEND is the export
+back-end used. INFO is a plist used as a communication channel.
+
+Enforce a blank line between elements. There are two exceptions
+to this rule:
+
+ 1. Preserve blank lines between sibling items in a plain list,
+
+ 2. In an item, remove any blank line before the very first
+ paragraph and the next sub-list when the latter ends the
+ current item.
+
+Assume BACKEND is `md'."
+ (org-element-map tree (remq 'item org-element-all-elements)
+ (lambda (e)
+ (org-element-put-property
+ e :post-blank
+ (if (and (eq (org-element-type e) 'paragraph)
+ (eq (org-element-type (org-element-property :parent e)) 'item)
+ (org-export-first-sibling-p e info)
+ (let ((next (org-export-get-next-element e info)))
+ (and (eq (org-element-type next) 'plain-list)
+ (not (org-export-get-next-element next info)))))
+ 0
+ 1))))
+ ;; Return updated tree.
+ tree)
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-md-bold (_bold contents _info)
+ "Transcode BOLD object into Markdown format.
+CONTENTS is the text within bold markup. INFO is a plist used as
+a communication channel."
+ (format "**%s**" contents))
+
+
+;;;; Code and Verbatim
+
+(defun org-md-verbatim (verbatim _contents _info)
+ "Transcode VERBATIM object into Markdown format.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((value (org-element-property :value verbatim)))
+ (format (cond ((not (string-match "`" value)) "`%s`")
+ ((or (string-prefix-p "`" value)
+ (string-suffix-p "`" value))
+ "`` %s ``")
+ (t "``%s``"))
+ value)))
+
+
+;;;; Example Block, Src Block and export Block
+
+(defun org-md-example-block (example-block _contents info)
+ "Transcode EXAMPLE-BLOCK element into Markdown format.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (replace-regexp-in-string
+ "^" " "
+ (org-remove-indentation
+ (org-export-format-code-default example-block info))))
+
+(defun org-md-export-block (export-block contents info)
+ "Transcode a EXPORT-BLOCK element from Org to Markdown.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (if (member (org-element-property :type export-block) '("MARKDOWN" "MD"))
+ (org-remove-indentation (org-element-property :value export-block))
+ ;; Also include HTML export blocks.
+ (org-export-with-backend 'html export-block contents info)))
+
+
+;;;; Headline
+
+(defun org-md-headline (headline contents info)
+ "Transcode HEADLINE element into Markdown format.
+CONTENTS is the headline contents. INFO is a plist used as
+a communication channel."
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((level (org-export-get-relative-level headline info))
+ (title (org-export-data (org-element-property :title headline) info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword
+ headline)))
+ (and todo (concat (org-export-data todo info) " ")))))
+ (tags (and (plist-get info :with-tags)
+ (let ((tag-list (org-export-get-tags headline info)))
+ (and tag-list
+ (format " :%s:"
+ (mapconcat 'identity tag-list ":"))))))
+ (priority
+ (and (plist-get info :with-priority)
+ (let ((char (org-element-property :priority headline)))
+ (and char (format "[#%c] " char)))))
+ ;; Headline text without tags.
+ (heading (concat todo priority title))
+ (style (plist-get info :md-headline-style)))
+ (cond
+ ;; Cannot create a headline. Fall-back to a list.
+ ((or (org-export-low-level-p headline info)
+ (not (memq style '(atx setext)))
+ (and (eq style 'atx) (> level 6))
+ (and (eq style 'setext) (> level 2)))
+ (let ((bullet
+ (if (not (org-export-numbered-headline-p headline info)) "-"
+ (concat (number-to-string
+ (car (last (org-export-get-headline-number
+ headline info))))
+ "."))))
+ (concat bullet (make-string (- 4 (length bullet)) ?\s) heading tags "\n\n"
+ (and contents (replace-regexp-in-string "^" " " contents)))))
+ (t
+ (let ((anchor
+ (and (org-md--headline-referred-p headline info)
+ (format "<a id=\"%s\"></a>"
+ (or (org-element-property :CUSTOM_ID headline)
+ (org-export-get-reference headline info))))))
+ (concat (org-md--headline-title style level title anchor tags)
+ contents)))))))
+
+
+(defun org-md--headline-referred-p (headline info)
+ "Non-nil when HEADLINE is being referred to.
+INFO is a plist used as a communication channel. Links and table
+of contents can refer to headlines."
+ (or (plist-get info :with-toc)
+ (org-element-map (plist-get info :parse-tree) 'link
+ (lambda (link)
+ (eq headline
+ (pcase (org-element-property :type link)
+ ((or "custom-id" "id") (org-export-resolve-id-link link info))
+ ("fuzzy" (org-export-resolve-fuzzy-link link info))
+ (_ nil))))
+ info t)))
+
+(defun org-md--headline-title (style level title &optional anchor tags)
+ "Generate a headline title in the preferred Markdown headline style.
+STYLE is the preferred style (`atx' or `setext'). LEVEL is the
+header level. TITLE is the headline title. ANCHOR is the HTML
+anchor tag for the section as a string. TAGS are the tags set on
+the section."
+ (let ((anchor-lines (and anchor (concat anchor "\n\n"))))
+ ;; Use "Setext" style
+ (if (and (eq style 'setext) (< level 3))
+ (let* ((underline-char (if (= level 1) ?= ?-))
+ (underline (concat (make-string (length title) underline-char)
+ "\n")))
+ (concat "\n" anchor-lines title tags "\n" underline "\n"))
+ ;; Use "Atx" style
+ (let ((level-mark (make-string level ?#)))
+ (concat "\n" anchor-lines level-mark " " title tags "\n\n")))))
+
+;;;; Horizontal Rule
+
+(defun org-md-horizontal-rule (_horizontal-rule _contents _info)
+ "Transcode HORIZONTAL-RULE element into Markdown format.
+CONTENTS is the horizontal rule contents. INFO is a plist used
+as a communication channel."
+ "---")
+
+
+;;;; Italic
+
+(defun org-md-italic (_italic contents _info)
+ "Transcode ITALIC object into Markdown format.
+CONTENTS is the text within italic markup. INFO is a plist used
+as a communication channel."
+ (format "*%s*" contents))
+
+
+;;;; Item
+
+(defun org-md-item (item contents info)
+ "Transcode ITEM element into Markdown format.
+CONTENTS is the item contents. INFO is a plist used as
+a communication channel."
+ (let* ((type (org-element-property :type (org-export-get-parent item)))
+ (struct (org-element-property :structure item))
+ (bullet (if (not (eq type 'ordered)) "-"
+ (concat (number-to-string
+ (car (last (org-list-get-item-number
+ (org-element-property :begin item)
+ struct
+ (org-list-prevs-alist struct)
+ (org-list-parents-alist struct)))))
+ "."))))
+ (concat bullet
+ (make-string (- 4 (length bullet)) ? )
+ (pcase (org-element-property :checkbox item)
+ (`on "[X] ")
+ (`trans "[-] ")
+ (`off "[ ] "))
+ (let ((tag (org-element-property :tag item)))
+ (and tag (format "**%s:** "(org-export-data tag info))))
+ (and contents
+ (org-trim (replace-regexp-in-string "^" " " contents))))))
+
+
+
+;;;; Keyword
+
+(defun org-md-keyword (keyword contents info)
+ "Transcode a KEYWORD element into Markdown format.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (if (member (org-element-property :key keyword) '("MARKDOWN" "MD"))
+ (org-element-property :value keyword)
+ (org-export-with-backend 'html keyword contents info)))
+
+
+;;;; Line Break
+
+(defun org-md-line-break (_line-break _contents _info)
+ "Transcode LINE-BREAK object into Markdown format.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ " \n")
+
+
+;;;; Link
+
+(defun org-md-link (link contents info)
+ "Transcode LINE-BREAK object into Markdown format.
+CONTENTS is the link's description. INFO is a plist used as
+a communication channel."
+ (let ((link-org-files-as-md
+ (lambda (raw-path)
+ ;; Treat links to `file.org' as links to `file.md'.
+ (if (string= ".org" (downcase (file-name-extension raw-path ".")))
+ (concat (file-name-sans-extension raw-path) ".md")
+ raw-path)))
+ (type (org-element-property :type link)))
+ (cond
+ ;; Link type is handled by a special function.
+ ((org-export-custom-protocol-maybe link contents 'md))
+ ((member type '("custom-id" "id" "fuzzy"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (pcase (org-element-type destination)
+ (`plain-text ; External file.
+ (let ((path (funcall link-org-files-as-md destination)))
+ (if (not contents) (format "<%s>" path)
+ (format "[%s](%s)" contents path))))
+ (`headline
+ (format
+ "[%s](#%s)"
+ ;; Description.
+ (cond ((org-string-nw-p contents))
+ ((org-export-numbered-headline-p destination info)
+ (mapconcat #'number-to-string
+ (org-export-get-headline-number destination info)
+ "."))
+ (t (org-export-data (org-element-property :title destination)
+ info)))
+ ;; Reference.
+ (or (org-element-property :CUSTOM_ID destination)
+ (org-export-get-reference destination info))))
+ (_
+ (let ((description
+ (or (org-string-nw-p contents)
+ (let ((number (org-export-get-ordinal destination info)))
+ (cond
+ ((not number) nil)
+ ((atom number) (number-to-string number))
+ (t (mapconcat #'number-to-string number ".")))))))
+ (when description
+ (format "[%s](#%s)"
+ description
+ (org-export-get-reference destination info))))))))
+ ((org-export-inline-image-p link org-html-inline-image-rules)
+ (let ((path (let ((raw-path (org-element-property :path link)))
+ (if (not (file-name-absolute-p raw-path)) raw-path
+ (expand-file-name raw-path))))
+ (caption (org-export-data
+ (org-export-get-caption
+ (org-export-get-parent-element link)) info)))
+ (format "![img](%s)"
+ (if (not (org-string-nw-p caption)) path
+ (format "%s \"%s\"" path caption)))))
+ ((string= type "coderef")
+ (let ((ref (org-element-property :path link)))
+ (format (org-export-get-coderef-format ref contents)
+ (org-export-resolve-coderef ref info))))
+ ((equal type "radio") contents)
+ (t (let* ((raw-path (org-element-property :path link))
+ (path
+ (cond
+ ((member type '("http" "https" "ftp"))
+ (concat type ":" raw-path))
+ ((string= type "file")
+ (org-export-file-uri (funcall link-org-files-as-md raw-path)))
+ (t raw-path))))
+ (if (not contents) (format "<%s>" path)
+ (format "[%s](%s)" contents path)))))))
+
+
+;;;; Node Property
+
+(defun org-md-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element into Markdown syntax.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+
+;;;; Paragraph
+
+(defun org-md-paragraph (paragraph contents _info)
+ "Transcode PARAGRAPH element into Markdown format.
+CONTENTS is the paragraph contents. INFO is a plist used as
+a communication channel."
+ (let ((first-object (car (org-element-contents paragraph))))
+ ;; If paragraph starts with a #, protect it.
+ (if (and (stringp first-object) (string-prefix-p "#" first-object))
+ (concat "\\" contents)
+ contents)))
+
+
+;;;; Plain List
+
+(defun org-md-plain-list (_plain-list contents _info)
+ "Transcode PLAIN-LIST element into Markdown format.
+CONTENTS is the plain-list contents. INFO is a plist used as
+a communication channel."
+ contents)
+
+
+;;;; Plain Text
+
+(defun org-md-plain-text (text info)
+ "Transcode a TEXT string into Markdown format.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ (when (plist-get info :with-smart-quotes)
+ (setq text (org-export-activate-smart-quotes text :html info)))
+ ;; Protect ambiguous #. This will protect # at the beginning of
+ ;; a line, but not at the beginning of a paragraph. See
+ ;; `org-md-paragraph'.
+ (setq text (replace-regexp-in-string "\n#" "\n\\\\#" text))
+ ;; Protect ambiguous !
+ (setq text (replace-regexp-in-string "\\(!\\)\\[" "\\\\!" text nil nil 1))
+ ;; Protect `, *, _ and \
+ (setq text (replace-regexp-in-string "[`*_\\]" "\\\\\\&" text))
+ ;; Handle special strings, if required.
+ (when (plist-get info :with-special-strings)
+ (setq text (org-html-convert-special-strings text)))
+ ;; Handle break preservation, if required.
+ (when (plist-get info :preserve-breaks)
+ (setq text (replace-regexp-in-string "[ \t]*\n" " \n" text)))
+ ;; Return value.
+ text)
+
+
+;;;; Property Drawer
+
+(defun org-md-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element into Markdown format.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (replace-regexp-in-string "^" " " contents)))
+
+
+;;;; Quote Block
+
+(defun org-md-quote-block (_quote-block contents _info)
+ "Transcode QUOTE-BLOCK element into Markdown format.
+CONTENTS is the quote-block contents. INFO is a plist used as
+a communication channel."
+ (replace-regexp-in-string
+ "^" "> "
+ (replace-regexp-in-string "\n\\'" "" contents)))
+
+
+;;;; Section
+
+(defun org-md-section (_section contents _info)
+ "Transcode SECTION element into Markdown format.
+CONTENTS is the section contents. INFO is a plist used as
+a communication channel."
+ contents)
+
+
+;;;; Template
+
+(defun org-md--footnote-formatted (footnote info)
+ "Formats a single footnote entry FOOTNOTE.
+FOOTNOTE is a cons cell of the form (number . definition).
+INFO is a plist with contextual information."
+ (let* ((fn-num (car footnote))
+ (fn-text (cdr footnote))
+ (fn-format (plist-get info :md-footnote-format))
+ (fn-anchor (format "fn.%d" fn-num))
+ (fn-href (format " href=\"#fnr.%d\"" fn-num))
+ (fn-link-to-ref (org-html--anchor fn-anchor fn-num fn-href info)))
+ (concat (format fn-format fn-link-to-ref) " " fn-text "\n")))
+
+(defun org-md--footnote-section (info)
+ "Format the footnote section.
+INFO is a plist used as a communication channel."
+ (let* ((fn-alist (org-export-collect-footnote-definitions info))
+ (fn-alist (cl-loop for (n _type raw) in fn-alist collect
+ (cons n (org-trim (org-export-data raw info)))))
+ (headline-style (plist-get info :md-headline-style))
+ (section-title (org-html--translate "Footnotes" info)))
+ (when fn-alist
+ (format (plist-get info :md-footnotes-section)
+ (org-md--headline-title headline-style 1 section-title)
+ (mapconcat (lambda (fn) (org-md--footnote-formatted fn info))
+ fn-alist
+ "\n")))))
+
+(defun org-md-inner-template (contents info)
+ "Return body of document after converting it to Markdown syntax.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ ;; Make sure CONTENTS is separated from table of contents and
+ ;; footnotes with at least a blank line.
+ (concat
+ ;; Table of contents.
+ (let ((depth (plist-get info :with-toc)))
+ (when depth (org-html-toc depth info)))
+ ;; Document contents.
+ contents
+ "\n"
+ ;; Footnotes section.
+ (org-md--footnote-section info)))
+
+(defun org-md-template (contents _info)
+ "Return complete document string after Markdown conversion.
+CONTENTS is the transcoded contents string. INFO is a plist used
+as a communication channel."
+ contents)
+
+
+
+;;; Interactive function
+
+;;;###autoload
+(defun org-md-export-as-markdown (&optional async subtreep visible-only)
+ "Export current buffer to a Markdown buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Export is done in a buffer named \"*Org MD Export*\", which will
+be displayed when `org-export-show-temporary-export-buffer' is
+non-nil."
+ (interactive)
+ (org-export-to-buffer 'md "*Org MD Export*"
+ async subtreep visible-only nil nil (lambda () (text-mode))))
+
+;;;###autoload
+(defun org-md-convert-region-to-md ()
+ "Assume the current region has Org syntax, and convert it to Markdown.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in a Markdown buffer and use
+this command to convert it."
+ (interactive)
+ (org-export-replace-region-by 'md))
+
+
+;;;###autoload
+(defun org-md-export-to-markdown (&optional async subtreep visible-only)
+ "Export current buffer to a Markdown file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".md" subtreep)))
+ (org-export-to-file 'md outfile async subtreep visible-only)))
+
+;;;###autoload
+(defun org-md-publish-to-md (plist filename pub-dir)
+ "Publish an org file to Markdown.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'md filename ".md" plist pub-dir))
+
+(provide 'ox-md)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-md.el ends here
diff --git a/lisp/ox-odt.el b/lisp/ox-odt.el
new file mode 100644
index 0000000..943a6be
--- /dev/null
+++ b/lisp/ox-odt.el
@@ -0,0 +1,4325 @@
+;;; ox-odt.el --- OpenDocument Text Exporter for Org Mode -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
+
+;; Author: Jambunathan K <kjambunathan at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+;; Homepage: http://orgmode.org
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'format-spec)
+(require 'ox)
+(require 'org-compat)
+(require 'table nil 'noerror)
+
+;;; Define Back-End
+
+(org-export-define-backend 'odt
+ '((bold . org-odt-bold)
+ (center-block . org-odt-center-block)
+ (clock . org-odt-clock)
+ (code . org-odt-code)
+ (drawer . org-odt-drawer)
+ (dynamic-block . org-odt-dynamic-block)
+ (entity . org-odt-entity)
+ (example-block . org-odt-example-block)
+ (export-block . org-odt-export-block)
+ (export-snippet . org-odt-export-snippet)
+ (fixed-width . org-odt-fixed-width)
+ (footnote-definition . org-odt-footnote-definition)
+ (footnote-reference . org-odt-footnote-reference)
+ (headline . org-odt-headline)
+ (horizontal-rule . org-odt-horizontal-rule)
+ (inline-src-block . org-odt-inline-src-block)
+ (inlinetask . org-odt-inlinetask)
+ (italic . org-odt-italic)
+ (item . org-odt-item)
+ (keyword . org-odt-keyword)
+ (latex-environment . org-odt-latex-environment)
+ (latex-fragment . org-odt-latex-fragment)
+ (line-break . org-odt-line-break)
+ (link . org-odt-link)
+ (node-property . org-odt-node-property)
+ (paragraph . org-odt-paragraph)
+ (plain-list . org-odt-plain-list)
+ (plain-text . org-odt-plain-text)
+ (planning . org-odt-planning)
+ (property-drawer . org-odt-property-drawer)
+ (quote-block . org-odt-quote-block)
+ (radio-target . org-odt-radio-target)
+ (section . org-odt-section)
+ (special-block . org-odt-special-block)
+ (src-block . org-odt-src-block)
+ (statistics-cookie . org-odt-statistics-cookie)
+ (strike-through . org-odt-strike-through)
+ (subscript . org-odt-subscript)
+ (superscript . org-odt-superscript)
+ (table . org-odt-table)
+ (table-cell . org-odt-table-cell)
+ (table-row . org-odt-table-row)
+ (target . org-odt-target)
+ (template . org-odt-template)
+ (timestamp . org-odt-timestamp)
+ (underline . org-odt-underline)
+ (verbatim . org-odt-verbatim)
+ (verse-block . org-odt-verse-block))
+ :filters-alist '((:filter-parse-tree
+ . (org-odt--translate-latex-fragments
+ org-odt--translate-description-lists
+ org-odt--translate-list-tables)))
+ :menu-entry
+ '(?o "Export to ODT"
+ ((?o "As ODT file" org-odt-export-to-odt)
+ (?O "As ODT file and open"
+ (lambda (a s v b)
+ (if a (org-odt-export-to-odt t s v)
+ (org-open-file (org-odt-export-to-odt nil s v) 'system))))))
+ :options-alist
+ '((:odt-styles-file "ODT_STYLES_FILE" nil nil t)
+ (:description "DESCRIPTION" nil nil newline)
+ (:keywords "KEYWORDS" nil nil space)
+ (:subtitle "SUBTITLE" nil nil parse)
+ ;; Other variables.
+ (:odt-content-template-file nil nil org-odt-content-template-file)
+ (:odt-display-outline-level nil nil org-odt-display-outline-level)
+ (:odt-fontify-srcblocks nil nil org-odt-fontify-srcblocks)
+ (:odt-format-drawer-function nil nil org-odt-format-drawer-function)
+ (:odt-format-headline-function nil nil org-odt-format-headline-function)
+ (:odt-format-inlinetask-function nil nil org-odt-format-inlinetask-function)
+ (:odt-inline-formula-rules nil nil org-odt-inline-formula-rules)
+ (:odt-inline-image-rules nil nil org-odt-inline-image-rules)
+ (:odt-pixels-per-inch nil nil org-odt-pixels-per-inch)
+ (:odt-styles-file nil nil org-odt-styles-file)
+ (:odt-table-styles nil nil org-odt-table-styles)
+ (:odt-use-date-fields nil nil org-odt-use-date-fields)
+ ;; Redefine regular option.
+ (:with-latex nil "tex" org-odt-with-latex)))
+
+
+;;; Dependencies
+
+;;; Hooks
+
+;;; Function and Dynamically Scoped Variables Declarations
+
+(declare-function hfy-face-to-style "htmlfontify" (fn))
+(declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
+(declare-function archive-zip-extract "arc-mode" (archive name))
+(declare-function org-create-math-formula "org" (latex-frag &optional mathml-file))
+(declare-function browse-url-file-url "browse-url" (file))
+
+(defvar nxml-auto-insert-xml-declaration-flag) ; nxml-mode.el
+(defvar archive-zip-extract) ; arc-mode.el
+(defvar hfy-end-span-handler) ; htmlfontify.el
+(defvar hfy-begin-span-handler) ; htmlfontify.el
+(defvar hfy-face-to-css) ; htmlfontify.el
+(defvar hfy-html-quote-map) ; htmlfontify.el
+(defvar hfy-html-quote-regex) ; htmlfontify.el
+
+
+;;; Internal Variables
+
+(defconst org-odt-lib-dir
+ (file-name-directory (or load-file-name (buffer-file-name)))
+ "Location of ODT exporter.
+Use this to infer values of `org-odt-styles-dir' and
+`org-odt-schema-dir'.")
+
+(defvar org-odt-data-dir
+ (expand-file-name "../../etc/" org-odt-lib-dir)
+ "Data directory for ODT exporter.
+Use this to infer values of `org-odt-styles-dir' and
+`org-odt-schema-dir'.")
+
+(defconst org-odt-special-string-regexps
+ '(("\\\\-" . "&#x00ad;\\1") ; shy
+ ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
+ ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
+ ("\\.\\.\\." . "&#x2026;")) ; hellip
+ "Regular expressions for special string conversion.")
+
+(defconst org-odt-schema-dir-list
+ (list
+ (and org-odt-data-dir
+ (expand-file-name "./schema/" org-odt-data-dir)) ; bail out
+ (eval-when-compile
+ (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
+ (expand-file-name "./schema/" org-odt-data-dir))))
+ "List of directories to search for OpenDocument schema files.
+Use this list to set the default value of
+`org-odt-schema-dir'. The entries in this list are
+populated heuristically based on the values of `org-odt-lib-dir'
+and `org-odt-data-dir'.")
+
+(defconst org-odt-styles-dir-list
+ (list
+ (and org-odt-data-dir
+ (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
+ (eval-when-compile
+ (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
+ (expand-file-name "./styles/" org-odt-data-dir)))
+ (expand-file-name "../etc/styles/" org-odt-lib-dir) ; git
+ (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
+ (expand-file-name "./org/" data-directory) ; system
+ )
+ "List of directories to search for OpenDocument styles files.
+See `org-odt-styles-dir'. The entries in this list are populated
+heuristically based on the values of `org-odt-lib-dir' and
+`org-odt-data-dir'.")
+
+(defconst org-odt-styles-dir
+ (let ((styles-dir
+ (cl-find-if
+ (lambda (dir)
+ (and dir
+ (file-readable-p
+ (expand-file-name "OrgOdtContentTemplate.xml" dir))
+ (file-readable-p (expand-file-name "OrgOdtStyles.xml" dir))))
+ org-odt-styles-dir-list)))
+ (unless styles-dir
+ (error "Error (ox-odt): Cannot find factory styles files, aborting"))
+ styles-dir)
+ "Directory that holds auxiliary XML files used by the ODT exporter.
+
+This directory contains the following XML files -
+ \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
+ XML files are used as the default values of
+ `org-odt-styles-file' and `org-odt-content-template-file'.
+
+The default value of this variable varies depending on the
+version of Org in use and is initialized from
+`org-odt-styles-dir-list'. Note that the user could be using Org
+from one of: Org own private git repository, GNU ELPA tar or
+standard Emacs.")
+
+(defconst org-odt-bookmark-prefix "OrgXref.")
+
+(defconst org-odt-manifest-file-entry-tag
+ "\n<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
+
+(defconst org-odt-file-extensions
+ '(("odt" . "OpenDocument Text")
+ ("ott" . "OpenDocument Text Template")
+ ("odm" . "OpenDocument Master Document")
+ ("ods" . "OpenDocument Spreadsheet")
+ ("ots" . "OpenDocument Spreadsheet Template")
+ ("odg" . "OpenDocument Drawing (Graphics)")
+ ("otg" . "OpenDocument Drawing Template")
+ ("odp" . "OpenDocument Presentation")
+ ("otp" . "OpenDocument Presentation Template")
+ ("odi" . "OpenDocument Image")
+ ("odf" . "OpenDocument Formula")
+ ("odc" . "OpenDocument Chart")))
+
+(defconst org-odt-table-style-format
+ "
+<style:style style:name=\"%s\" style:family=\"table\">
+ <style:table-properties style:rel-width=\"%s%%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>
+</style:style>
+"
+ "Template for auto-generated Table styles.")
+
+(defvar org-odt-automatic-styles '()
+ "Registry of automatic styles for various OBJECT-TYPEs.
+The variable has the following form:
+ ((OBJECT-TYPE-A
+ ((OBJECT-NAME-A.1 OBJECT-PROPS-A.1)
+ (OBJECT-NAME-A.2 OBJECT-PROPS-A.2) ...))
+ (OBJECT-TYPE-B
+ ((OBJECT-NAME-B.1 OBJECT-PROPS-B.1)
+ (OBJECT-NAME-B.2 OBJECT-PROPS-B.2) ...))
+ ...).
+
+OBJECT-TYPEs could be \"Section\", \"Table\", \"Figure\" etc.
+OBJECT-PROPS is (typically) a plist created by passing
+\"#+ATTR_ODT: \" option to `org-odt-parse-block-attributes'.
+
+Use `org-odt-add-automatic-style' to add update this variable.'")
+
+(defvar org-odt-object-counters nil
+ "Running counters for various OBJECT-TYPEs.
+Use this to generate automatic names and style-names. See
+`org-odt-add-automatic-style'.")
+
+(defvar org-odt-src-block-paragraph-format
+ "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
+ <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
+ <style:background-image/>
+ </style:paragraph-properties>
+ <style:text-properties fo:color=\"%s\"/>
+ </style:style>"
+ "Custom paragraph style for colorized source and example blocks.
+This style is much the same as that of \"OrgFixedWidthBlock\"
+except that the foreground and background colors are set
+according to the default face identified by the `htmlfontify'.")
+
+(defvar hfy-optimizations)
+(defvar org-odt-embedded-formulas-count 0)
+(defvar org-odt-embedded-images-count 0)
+(defvar org-odt-image-size-probe-method
+ (append (and (executable-find "identify") '(imagemagick)) ; See Bug#10675
+ '(emacs fixed))
+ "Ordered list of methods for determining image sizes.")
+
+(defvar org-odt-default-image-sizes-alist
+ '(("as-char" . (5 . 0.4))
+ ("paragraph" . (5 . 5)))
+ "Hardcoded image dimensions one for each of the anchor
+ methods.")
+
+;; A4 page size is 21.0 by 29.7 cms
+;; The default page settings has 2cm margin on each of the sides. So
+;; the effective text area is 17.0 by 25.7 cm
+(defvar org-odt-max-image-size '(17.0 . 20.0)
+ "Limiting dimensions for an embedded image.")
+
+(defconst org-odt-label-styles
+ '(("math-formula" "%c" "text" "(%n)")
+ ("math-label" "(%n)" "text" "(%n)")
+ ("category-and-value" "%e %n: %c" "category-and-value" "%e %n")
+ ("value" "%e %n: %c" "value" "%n"))
+ "Specify how labels are applied and referenced.
+
+This is an alist where each element is of the form:
+
+ (STYLE-NAME ATTACH-FMT REF-MODE REF-FMT)
+
+ATTACH-FMT controls how labels and captions are attached to an
+entity. It may contain following specifiers - %e and %c. %e is
+replaced with the CATEGORY-NAME. %n is replaced with
+\"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
+with CAPTION.
+
+REF-MODE and REF-FMT controls how label references are generated.
+The following XML is generated for a label reference -
+\"<text:sequence-ref text:reference-format=\"REF-MODE\" ...>
+REF-FMT </text:sequence-ref>\". REF-FMT may contain following
+specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
+%n is replaced with SEQNO.
+
+See also `org-odt-format-label'.")
+
+(defvar org-odt-category-map-alist
+ '(("__Table__" "Table" "value" "Table" org-odt--enumerable-p)
+ ("__Figure__" "Illustration" "value" "Figure" org-odt--enumerable-image-p)
+ ("__MathFormula__" "Text" "math-formula" "Equation" org-odt--enumerable-formula-p)
+ ("__DvipngImage__" "Equation" "value" "Equation" org-odt--enumerable-latex-image-p)
+ ("__Listing__" "Listing" "value" "Listing" org-odt--enumerable-p))
+ "Map a CATEGORY-HANDLE to OD-VARIABLE and LABEL-STYLE.
+
+This is a list where each entry is of the form:
+
+ (CATEGORY-HANDLE OD-VARIABLE LABEL-STYLE CATEGORY-NAME ENUMERATOR-PREDICATE)
+
+CATEGORY_HANDLE identifies the captionable entity in question.
+
+OD-VARIABLE is the OpenDocument sequence counter associated with
+the entity. These counters are declared within
+\"<text:sequence-decls>...</text:sequence-decls>\" block of
+`org-odt-content-template-file'.
+
+LABEL-STYLE is a key into `org-odt-label-styles' and specifies
+how a given entity should be captioned and referenced.
+
+CATEGORY-NAME is used for qualifying captions on export.
+
+ENUMERATOR-PREDICATE is used for assigning a sequence number to
+the entity. See `org-odt--enumerate'.")
+
+(defvar org-odt-manifest-file-entries nil)
+(defvar hfy-user-sheet-assoc)
+
+(defvar org-odt-zip-dir nil
+ "Temporary work directory for OpenDocument exporter.")
+
+
+
+;;; User Configuration Variables
+
+(defgroup org-export-odt nil
+ "Options for exporting Org mode files to ODT."
+ :tag "Org Export ODT"
+ :group 'org-export)
+
+
+;;;; Debugging
+
+(defcustom org-odt-prettify-xml nil
+ "Specify whether or not the xml output should be prettified.
+When this option is turned on, `indent-region' is run on all
+component xml buffers before they are saved. Turn this off for
+regular use. Turn this on if you need to examine the xml
+visually."
+ :group 'org-export-odt
+ :version "24.1"
+ :type 'boolean)
+
+
+;;;; Document schema
+
+(require 'rng-loc)
+(defcustom org-odt-schema-dir
+ (cl-find-if
+ (lambda (dir)
+ (and dir
+ (file-expand-wildcards
+ (expand-file-name "od-manifest-schema*.rnc" dir))
+ (file-expand-wildcards (expand-file-name "od-schema*.rnc" dir))
+ (file-readable-p (expand-file-name "schemas.xml" dir))))
+ org-odt-schema-dir-list)
+ "Directory that contains OpenDocument schema files.
+
+This directory contains:
+1. rnc files for OpenDocument schema
+2. a \"schemas.xml\" file that specifies locating rules needed
+ for auto validation of OpenDocument XML files.
+
+Use the customize interface to set this variable. This ensures
+that `rng-schema-locating-files' is updated and auto-validation
+of OpenDocument XML takes place based on the value
+`rng-nxml-auto-validate-flag'.
+
+The default value of this variable varies depending on the
+version of org in use and is initialized from
+`org-odt-schema-dir-list'. The OASIS schema files are available
+only in the org's private git repository. It is *not* bundled
+with GNU ELPA tar or standard Emacs distribution."
+ :type '(choice
+ (const :tag "Not set" nil)
+ (directory :tag "Schema directory"))
+ :group 'org-export-odt
+ :version "24.1"
+ :set
+ (lambda (var value)
+ "Set `org-odt-schema-dir'.
+Also add it to `rng-schema-locating-files'."
+ (let ((schema-dir value))
+ (set var
+ (if (and
+ (file-expand-wildcards
+ (expand-file-name "od-manifest-schema*.rnc" schema-dir))
+ (file-expand-wildcards
+ (expand-file-name "od-schema*.rnc" schema-dir))
+ (file-readable-p
+ (expand-file-name "schemas.xml" schema-dir)))
+ schema-dir
+ (when value
+ (message "Error (ox-odt): %s has no OpenDocument schema files"
+ value))
+ nil)))
+ (when org-odt-schema-dir
+ (eval-after-load 'rng-loc
+ '(add-to-list 'rng-schema-locating-files
+ (expand-file-name "schemas.xml"
+ org-odt-schema-dir))))))
+
+
+;;;; Document styles
+
+(defcustom org-odt-content-template-file nil
+ "Template file for \"content.xml\".
+The exporter embeds the exported content just before
+\"</office:text>\" element.
+
+If unspecified, the file named \"OrgOdtContentTemplate.xml\"
+under `org-odt-styles-dir' is used."
+ :type '(choice (const nil)
+ (file))
+ :group 'org-export-odt
+ :version "24.3")
+
+(defcustom org-odt-styles-file nil
+ "Default styles file for use with ODT export.
+Valid values are one of:
+1. nil
+2. path to a styles.xml file
+3. path to a *.odt or a *.ott file
+4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
+...))
+
+In case of option 1, an in-built styles.xml is used. See
+`org-odt-styles-dir' for more information.
+
+In case of option 3, the specified file is unzipped and the
+styles.xml embedded therein is used.
+
+In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
+and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
+generated odt file. Use relative path for specifying the
+FILE-MEMBERS. styles.xml must be specified as one of the
+FILE-MEMBERS.
+
+Use options 1, 2 or 3 only if styles.xml alone suffices for
+achieving the desired formatting. Use option 4, if the styles.xml
+references additional files like header and footer images for
+achieving the desired formatting.
+
+Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
+a per-file basis. For example,
+
+#+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
+#+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
+ :group 'org-export-odt
+ :version "24.1"
+ :type
+ '(choice
+ (const :tag "Factory settings" nil)
+ (file :must-match t :tag "styles.xml")
+ (file :must-match t :tag "ODT or OTT file")
+ (list :tag "ODT or OTT file + Members"
+ (file :must-match t :tag "ODF Text or Text Template file")
+ (cons :tag "Members"
+ (file :tag " Member" "styles.xml")
+ (repeat (file :tag "Member"))))))
+
+(defcustom org-odt-display-outline-level 2
+ "Outline levels considered for enumerating captioned entities."
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'integer)
+
+;;;; Document conversion
+
+(defcustom org-odt-convert-processes
+ '(("LibreOffice"
+ "soffice --headless --convert-to %f%x --outdir %d %i")
+ ("unoconv"
+ "unoconv -f %f -o %d %i"))
+ "Specify a list of document converters and their usage.
+The converters in this list are offered as choices while
+customizing `org-odt-convert-process'.
+
+This variable is a list where each element is of the
+form (CONVERTER-NAME CONVERTER-CMD). CONVERTER-NAME is the name
+of the converter. CONVERTER-CMD is the shell command for the
+converter and can contain format specifiers. These format
+specifiers are interpreted as below:
+
+%i input file name in full
+%I input file name as a URL
+%f format of the output file
+%o output file name in full
+%O output file name as a URL
+%d output dir in full
+%D output dir as a URL.
+%x extra options as set in `org-odt-convert-capabilities'."
+ :group 'org-export-odt
+ :version "24.1"
+ :type
+ '(choice
+ (const :tag "None" nil)
+ (alist :tag "Converters"
+ :key-type (string :tag "Converter Name")
+ :value-type (group (string :tag "Command line")))))
+
+(defcustom org-odt-convert-process "LibreOffice"
+ "Use this converter to convert from \"odt\" format to other formats.
+During customization, the list of converter names are populated
+from `org-odt-convert-processes'."
+ :group 'org-export-odt
+ :version "24.1"
+ :type '(choice :convert-widget
+ (lambda (w)
+ (apply 'widget-convert (widget-type w)
+ (eval (car (widget-get w :args)))))
+ `((const :tag "None" nil)
+ ,@(mapcar (lambda (c)
+ `(const :tag ,(car c) ,(car c)))
+ org-odt-convert-processes))))
+
+(defcustom org-odt-convert-capabilities
+ '(("Text"
+ ("odt" "ott" "doc" "rtf" "docx")
+ (("pdf" "pdf") ("odt" "odt") ("rtf" "rtf") ("ott" "ott")
+ ("doc" "doc" ":\"MS Word 97\"") ("docx" "docx") ("html" "html")))
+ ("Web"
+ ("html")
+ (("pdf" "pdf") ("odt" "odt") ("html" "html")))
+ ("Spreadsheet"
+ ("ods" "ots" "xls" "csv" "xlsx")
+ (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv") ("ods" "ods")
+ ("xls" "xls") ("xlsx" "xlsx")))
+ ("Presentation"
+ ("odp" "otp" "ppt" "pptx")
+ (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("otp" "otp") ("ppt" "ppt")
+ ("pptx" "pptx") ("odg" "odg"))))
+ "Specify input and output formats of `org-odt-convert-process'.
+More correctly, specify the set of input and output formats that
+the user is actually interested in.
+
+This variable is an alist where each element is of the
+form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
+INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
+alist where each element is of the form (OUTPUT-FMT
+OUTPUT-FILE-EXTENSION EXTRA-OPTIONS).
+
+The variable is interpreted as follows:
+`org-odt-convert-process' can take any document that is in
+INPUT-FMT-LIST and produce any document that is in the
+OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
+OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
+serves dual purposes:
+- It is used for populating completion candidates during
+ `org-odt-convert' commands.
+- It is used as the value of \"%f\" specifier in
+ `org-odt-convert-process'.
+
+EXTRA-OPTIONS is used as the value of \"%x\" specifier in
+`org-odt-convert-process'.
+
+DOCUMENT-CLASS is used to group a set of file formats in
+INPUT-FMT-LIST in to a single class.
+
+Note that this variable inherently captures how LibreOffice based
+converters work. LibreOffice maps documents of various formats
+to classes like Text, Web, Spreadsheet, Presentation etc and
+allow document of a given class (irrespective of its source
+format) to be converted to any of the export formats associated
+with that class.
+
+See default setting of this variable for an typical
+configuration."
+ :group 'org-export-odt
+ :version "24.1"
+ :type
+ '(choice
+ (const :tag "None" nil)
+ (alist :tag "Capabilities"
+ :key-type (string :tag "Document Class")
+ :value-type
+ (group (repeat :tag "Input formats" (string :tag "Input format"))
+ (alist :tag "Output formats"
+ :key-type (string :tag "Output format")
+ :value-type
+ (group (string :tag "Output file extension")
+ (choice
+ (const :tag "None" nil)
+ (string :tag "Extra options"))))))))
+
+(defcustom org-odt-preferred-output-format nil
+ "Automatically post-process to this format after exporting to \"odt\".
+Command `org-odt-export-to-odt' exports first to \"odt\" format
+and then uses `org-odt-convert-process' to convert the
+resulting document to this format. During customization of this
+variable, the list of valid values are populated based on
+`org-odt-convert-capabilities'.
+
+You can set this option on per-file basis using file local
+values. See Info node `(emacs) File Variables'."
+ :group 'org-export-odt
+ :version "24.1"
+ :type '(choice :convert-widget
+ (lambda (w)
+ (apply 'widget-convert (widget-type w)
+ (eval (car (widget-get w :args)))))
+ `((const :tag "None" nil)
+ ,@(mapcar (lambda (c)
+ `(const :tag ,c ,c))
+ (org-odt-reachable-formats "odt")))))
+;;;###autoload
+(put 'org-odt-preferred-output-format 'safe-local-variable 'stringp)
+
+
+;;;; Drawers
+
+(defcustom org-odt-format-drawer-function (lambda (_name contents) contents)
+ "Function called to format a drawer in ODT code.
+
+The function must accept two parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+
+The function should return the string to be exported.
+
+The default value simply returns the value of CONTENTS."
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+
+;;;; Headline
+
+(defcustom org-odt-format-headline-function
+ 'org-odt-format-headline-default-function
+ "Function to format headline text.
+
+This function will be called with 5 arguments:
+TODO the todo keyword (string or nil).
+TODO-TYPE the type of todo (symbol: `todo', `done', nil)
+PRIORITY the priority of the headline (integer or nil)
+TEXT the main headline text (string).
+TAGS the tags string, separated with colons (string or nil).
+
+The function result will be used as headline text."
+ :group 'org-export-odt
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+
+;;;; Inlinetasks
+
+(defcustom org-odt-format-inlinetask-function
+ 'org-odt-format-inlinetask-default-function
+ "Function called to format an inlinetask in ODT code.
+
+The function must accept six parameters:
+ TODO the todo keyword, as a string
+ TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
+ PRIORITY the inlinetask priority, as a string
+ NAME the inlinetask name, as a string.
+ TAGS the inlinetask tags, as a string.
+ CONTENTS the contents of the inlinetask, as a string.
+
+The function should return the string to be exported."
+ :group 'org-export-odt
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'function)
+
+
+;;;; LaTeX
+
+(defcustom org-odt-with-latex org-export-with-latex
+ "Non-nil means process LaTeX math snippets.
+
+When set, the exporter will process LaTeX environments and
+fragments.
+
+This option can also be set with the +OPTIONS line,
+e.g. \"tex:mathjax\". Allowed values are:
+
+nil Ignore math snippets.
+`verbatim' Keep everything in verbatim
+`dvipng' Process the LaTeX fragments to images. This will also
+ include processing of non-math environments.
+`imagemagick' Convert the LaTeX fragments to pdf files and use
+ imagemagick to convert pdf files to png files.
+`mathjax' Do MathJax preprocessing and arrange for MathJax.js to
+ be loaded.
+t Synonym for `mathjax'."
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Do not process math in any way" nil)
+ (const :tag "Use dvipng to make images" dvipng)
+ (const :tag "Use imagemagick to make images" imagemagick)
+ (const :tag "Use MathJax to display math" mathjax)
+ (const :tag "Leave math verbatim" verbatim)))
+
+
+;;;; Links
+
+(defcustom org-odt-inline-formula-rules
+ '(("file" . "\\.\\(mathml\\|mml\\|odf\\)\\'"))
+ "Rules characterizing formula files that can be inlined into ODT.
+
+A rule consists in an association whose key is the type of link
+to consider, and value is a regexp that will be matched against
+link's path."
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(alist :key-type (string :tag "Type")
+ :value-type (regexp :tag "Path")))
+
+(defcustom org-odt-inline-image-rules
+ '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'"))
+ "Rules characterizing image files that can be inlined into ODT.
+
+A rule consists in an association whose key is the type of link
+to consider, and value is a regexp that will be matched against
+link's path."
+ :group 'org-export-odt
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(alist :key-type (string :tag "Type")
+ :value-type (regexp :tag "Path")))
+
+(defcustom org-odt-pixels-per-inch 96.0
+ "Scaling factor for converting images pixels to inches.
+Use this for sizing of embedded images. See Info node `(org)
+Images in ODT export' for more information."
+ :type 'float
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.1"))
+
+
+;;;; Src Block
+
+(defcustom org-odt-create-custom-styles-for-srcblocks t
+ "Whether custom styles for colorized source blocks be automatically created.
+When this option is turned on, the exporter creates custom styles
+for source blocks based on the advice of `htmlfontify'. Creation
+of custom styles happen as part of `org-odt-hfy-face-to-css'.
+
+When this option is turned off exporter does not create such
+styles.
+
+Use the latter option if you do not want the custom styles to be
+based on your current display settings. It is necessary that the
+styles.xml already contains needed styles for colorizing to work.
+
+This variable is effective only if `org-odt-fontify-srcblocks' is
+turned on."
+ :group 'org-export-odt
+ :version "24.1"
+ :type 'boolean)
+
+(defcustom org-odt-fontify-srcblocks t
+ "Specify whether or not source blocks need to be fontified.
+Turn this option on if you want to colorize the source code
+blocks in the exported file. For colorization to work, you need
+to make available an enhanced version of `htmlfontify' library."
+ :type 'boolean
+ :group 'org-export-odt
+ :version "24.1")
+
+
+;;;; Table
+
+(defcustom org-odt-table-styles
+ '(("OrgEquation" "OrgEquation"
+ ((use-first-column-styles . t)
+ (use-last-column-styles . t)))
+ ("TableWithHeaderRowAndColumn" "Custom"
+ ((use-first-row-styles . t)
+ (use-first-column-styles . t)))
+ ("TableWithFirstRowandLastRow" "Custom"
+ ((use-first-row-styles . t)
+ (use-last-row-styles . t)))
+ ("GriddedTable" "Custom" nil))
+ "Specify how Table Styles should be derived from a Table Template.
+This is a list where each element is of the
+form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
+
+TABLE-STYLE-NAME is the style associated with the table through
+\"#+ATTR_ODT: :style TABLE-STYLE-NAME\" line.
+
+TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
+TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
+below) that is included in `org-odt-content-template-file'.
+
+TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
+ \"TableCell\"
+PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
+ \"TableParagraph\"
+TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
+ \"FirstRow\" | \"LastRow\" |
+ \"EvenRow\" | \"OddRow\" |
+ \"EvenColumn\" | \"OddColumn\" | \"\"
+where \"+\" above denotes string concatenation.
+
+TABLE-CELL-OPTIONS is an alist where each element is of the
+form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
+TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
+ `use-last-row-styles' |
+ `use-first-column-styles' |
+ `use-last-column-styles' |
+ `use-banding-rows-styles' |
+ `use-banding-columns-styles' |
+ `use-first-row-styles'
+ON-OR-OFF := t | nil
+
+For example, with the following configuration
+
+\(setq org-odt-table-styles
+ \\='((\"TableWithHeaderRowsAndColumns\" \"Custom\"
+ ((use-first-row-styles . t)
+ (use-first-column-styles . t)))
+ (\"TableWithHeaderColumns\" \"Custom\"
+ ((use-first-column-styles . t)))))
+
+1. A table associated with \"TableWithHeaderRowsAndColumns\"
+ style will use the following table-cell styles -
+ \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
+ \"CustomTableCell\" and the following paragraph styles
+ \"CustomFirstRowTableParagraph\",
+ \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
+ as appropriate.
+
+2. A table associated with \"TableWithHeaderColumns\" style will
+ use the following table-cell styles -
+ \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
+ following paragraph styles
+ \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
+ as appropriate..
+
+Note that TABLE-TEMPLATE-NAME corresponds to the
+\"<table:table-template>\" elements contained within
+\"<office:styles>\". The entries (TABLE-STYLE-NAME
+TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
+\"table:template-name\" and \"table:use-first-row-styles\" etc
+attributes of \"<table:table>\" element. Refer ODF-1.2
+specification for more information. Also consult the
+implementation filed under `org-odt-get-table-cell-styles'.
+
+The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
+formatting of numbered display equations. Do not delete this
+style from the list."
+ :group 'org-export-odt
+ :version "24.1"
+ :type '(choice
+ (const :tag "None" nil)
+ (repeat :tag "Table Styles"
+ (list :tag "Table Style Specification"
+ (string :tag "Table Style Name")
+ (string :tag "Table Template Name")
+ (alist :options (use-first-row-styles
+ use-last-row-styles
+ use-first-column-styles
+ use-last-column-styles
+ use-banding-rows-styles
+ use-banding-columns-styles)
+ :key-type symbol
+ :value-type (const :tag "True" t))))))
+
+;;;; Timestamps
+
+(defcustom org-odt-use-date-fields nil
+ "Non-nil, if timestamps should be exported as date fields.
+
+When nil, export timestamps as plain text.
+
+When non-nil, map `org-time-stamp-custom-formats' to a pair of
+OpenDocument date-styles with names \"OrgDate1\" and \"OrgDate2\"
+respectively. A timestamp with no time component is formatted
+with style \"OrgDate1\" while one with explicit hour and minutes
+is formatted with style \"OrgDate2\".
+
+This feature is experimental. Most (but not all) of the common
+%-specifiers in `format-time-string' are supported.
+Specifically, locale-dependent specifiers like \"%c\", \"%x\" are
+formatted as canonical Org timestamps. For finer control, avoid
+these %-specifiers.
+
+Textual specifiers like \"%b\", \"%h\", \"%B\", \"%a\", \"%A\"
+etc., are displayed by the application in the default language
+and country specified in `org-odt-styles-file'. Note that the
+default styles file uses language \"en\" and country \"GB\". You
+can localize the week day and month strings in the exported
+document by setting the default language and country either using
+the application UI or through a custom styles file.
+
+See `org-odt--build-date-styles' for implementation details."
+ :group 'org-export-odt
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+
+
+;;; Internal functions
+
+;;;; Date
+
+(defun org-odt--format-timestamp (timestamp &optional end iso-date-p)
+ (let* ((format-timestamp
+ (lambda (timestamp format &optional end utc)
+ (if timestamp
+ (org-timestamp-format timestamp format end utc)
+ (format-time-string format nil utc))))
+ (has-time-p (or (not timestamp)
+ (org-timestamp-has-time-p timestamp)))
+ (iso-date (let ((format (if has-time-p "%Y-%m-%dT%H:%M:%S"
+ "%Y-%m-%dT%H:%M:%S")))
+ (funcall format-timestamp timestamp format end))))
+ (if iso-date-p iso-date
+ (let* ((style (if has-time-p "OrgDate2" "OrgDate1"))
+ ;; LibreOffice does not care about end goes as content
+ ;; within the "<text:date>...</text:date>" field. The
+ ;; displayed date is automagically corrected to match the
+ ;; format requested by "style:data-style-name" attribute. So
+ ;; don't bother about formatting the date contents to be
+ ;; compatible with "OrgDate1" and "OrgDateTime" styles. A
+ ;; simple Org-style date should suffice.
+ (date (let* ((formats
+ (if org-display-custom-times
+ (cons (substring
+ (car org-time-stamp-custom-formats) 1 -1)
+ (substring
+ (cdr org-time-stamp-custom-formats) 1 -1))
+ '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")))
+ (format (if has-time-p (cdr formats) (car formats))))
+ (funcall format-timestamp timestamp format end)))
+ (repeater (let ((repeater-type (org-element-property
+ :repeater-type timestamp))
+ (repeater-value (org-element-property
+ :repeater-value timestamp))
+ (repeater-unit (org-element-property
+ :repeater-unit timestamp)))
+ (concat
+ (cl-case repeater-type
+ (catchup "++") (restart ".+") (cumulate "+"))
+ (when repeater-value
+ (number-to-string repeater-value))
+ (cl-case repeater-unit
+ (hour "h") (day "d") (week "w") (month "m")
+ (year "y"))))))
+ (concat
+ (format "<text:date text:date-value=\"%s\" style:data-style-name=\"%s\" text:fixed=\"true\">%s</text:date>"
+ iso-date style date)
+ (and (not (string= repeater "")) " ")
+ repeater)))))
+
+;;;; Frame
+
+(defun org-odt--frame (text width height style &optional extra
+ anchor-type &rest title-and-desc)
+ (let ((frame-attrs
+ (concat
+ (if width (format " svg:width=\"%0.2fcm\"" width) "")
+ (if height (format " svg:height=\"%0.2fcm\"" height) "")
+ extra
+ (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph"))
+ (format " draw:name=\"%s\""
+ (car (org-odt-add-automatic-style "Frame"))))))
+ (format
+ "\n<draw:frame draw:style-name=\"%s\"%s>\n%s\n</draw:frame>"
+ style frame-attrs
+ (concat text
+ (let ((title (car title-and-desc))
+ (desc (cadr title-and-desc)))
+ (concat (when title
+ (format "<svg:title>%s</svg:title>"
+ (org-odt--encode-plain-text title t)))
+ (when desc
+ (format "<svg:desc>%s</svg:desc>"
+ (org-odt--encode-plain-text desc t)))))))))
+
+
+;;;; Library wrappers
+
+(defun org-odt--zip-extract (archive members target)
+ (when (atom members) (setq members (list members)))
+ (require 'arc-mode)
+ (dolist (member members)
+ (let* ((--quote-file-name
+ ;; This is shamelessly stolen from `archive-zip-extract'.
+ (lambda (name)
+ (if (or (not (memq system-type '(windows-nt ms-dos)))
+ (and (boundp 'w32-quote-process-args)
+ (null w32-quote-process-args)))
+ (shell-quote-argument name)
+ name)))
+ (target (funcall --quote-file-name target))
+ (archive (expand-file-name archive))
+ (archive-zip-extract
+ (list "unzip" "-qq" "-o" "-d" target))
+ exit-code command-output)
+ (setq command-output
+ (with-temp-buffer
+ (setq exit-code (archive-zip-extract archive member))
+ (buffer-string)))
+ (unless (zerop exit-code)
+ (message command-output)
+ (error "Extraction failed")))))
+
+;;;; Target
+
+(defun org-odt--target (text id)
+ (if (not id) text
+ (concat
+ (format "\n<text:bookmark-start text:name=\"OrgXref.%s\"/>" id)
+ (format "\n<text:bookmark text:name=\"%s\"/>" id) text
+ (format "\n<text:bookmark-end text:name=\"OrgXref.%s\"/>" id))))
+
+;;;; Textbox
+
+(defun org-odt--textbox (text width height style &optional
+ extra anchor-type)
+ (org-odt--frame
+ (format "\n<draw:text-box %s>%s\n</draw:text-box>"
+ (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
+ (and (not width)
+ (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
+ text)
+ width nil style extra anchor-type))
+
+
+
+;;;; Table of Contents
+
+(defun org-odt--format-toc (title entries depth)
+ "Return a table of contents.
+TITLE is the title of the table, as a string, or nil. ENTRIES is
+the contents of the table, as a string. DEPTH is an integer
+specifying the depth of the table."
+ (concat
+ "
+<text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">\n"
+ (format " <text:table-of-content-source text:outline-level=\"%d\">" depth)
+ (and title
+ (format "
+ <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
+"
+ title))
+
+ (let ((levels (number-sequence 1 10)))
+ (mapconcat
+ (lambda (level)
+ (format
+ "
+ <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
+ <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
+ <text:index-entry-chapter/>
+ <text:index-entry-text/>
+ <text:index-entry-link-end/>
+ </text:table-of-content-entry-template>\n"
+ level level)) levels ""))
+ "
+ </text:table-of-content-source>
+ <text:index-body>"
+ (and title
+ (format "
+ <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
+ <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
+ </text:index-title>\n"
+ title))
+ entries
+ "
+ </text:index-body>
+</text:table-of-content>"))
+
+(cl-defun org-odt-format-toc-headline
+ (todo _todo-type priority text tags
+ &key _level section-number headline-label &allow-other-keys)
+ (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
+ headline-label
+ (concat
+ ;; Section number.
+ (and section-number (concat section-number ". "))
+ ;; Todo.
+ (when todo
+ (let ((style (if (member todo org-done-keywords)
+ "OrgDone" "OrgTodo")))
+ (format "<text:span text:style-name=\"%s\">%s</text:span> "
+ style todo)))
+ (when priority
+ (let* ((style (format "OrgPriority-%s" priority))
+ (priority (format "[#%c]" priority)))
+ (format "<text:span text:style-name=\"%s\">%s</text:span> "
+ style priority)))
+ ;; Title.
+ text
+ ;; Tags.
+ (when tags
+ (concat
+ (format " <text:span text:style-name=\"%s\">[%s]</text:span>"
+ "OrgTags"
+ (mapconcat
+ (lambda (tag)
+ (format
+ "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgTag" tag)) tags " : ")))))))
+
+(defun org-odt-toc (depth info &optional scope)
+ "Build a table of contents.
+DEPTH is an integer specifying the depth of the table. INFO is
+a plist containing current export properties. Optional argument
+SCOPE, when non-nil, defines the scope of the table. Return the
+table of contents as a string, or nil."
+ (cl-assert (wholenump depth))
+ ;; When a headline is marked as a radio target, as in the example below:
+ ;;
+ ;; ** <<<Some Heading>>>
+ ;; Some text.
+ ;;
+ ;; suppress generation of radio targets. i.e., Radio targets are to
+ ;; be marked as targets within /document body/ and *not* within
+ ;; /TOC/, as otherwise there will be duplicated anchors one in TOC
+ ;; and one in the document body.
+ ;;
+ ;; Likewise, links, footnote references and regular targets are also
+ ;; suppressed.
+ (let* ((headlines (org-export-collect-headlines info depth scope))
+ (backend (org-export-create-backend
+ :parent (org-export-backend-name (plist-get info :back-end))
+ :transcoders '((footnote-reference . ignore)
+ (link . (lambda (object c i) c))
+ (radio-target . (lambda (object c i) c))
+ (target . ignore)))))
+ (when headlines
+ (org-odt--format-toc
+ (and (not scope) (org-export-translate "Table of Contents" :utf-8 info))
+ (mapconcat
+ (lambda (headline)
+ (let* ((entry (org-odt-format-headline--wrap
+ headline backend info 'org-odt-format-toc-headline))
+ (level (org-export-get-relative-level headline info))
+ (style (format "Contents_20_%d" level)))
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ style entry)))
+ headlines "\n")
+ depth))))
+
+
+;;;; Document styles
+
+(defun org-odt-add-automatic-style (object-type &optional object-props)
+ "Create an automatic style of type OBJECT-TYPE with param OBJECT-PROPS.
+OBJECT-PROPS is (typically) a plist created by passing
+\"#+ATTR_ODT: \" option of the object in question to
+`org-odt-parse-block-attributes'.
+
+Use `org-odt-object-counters' to generate an automatic
+OBJECT-NAME and STYLE-NAME. If OBJECT-PROPS is non-nil, add a
+new entry in `org-odt-automatic-styles'. Return (OBJECT-NAME
+. STYLE-NAME)."
+ (cl-assert (stringp object-type))
+ (let* ((object (intern object-type))
+ (seqvar object)
+ (seqno (1+ (or (plist-get org-odt-object-counters seqvar) 0)))
+ (object-name (format "%s%d" object-type seqno)) style-name)
+ (setq org-odt-object-counters
+ (plist-put org-odt-object-counters seqvar seqno))
+ (when object-props
+ (setq style-name (format "Org%s" object-name))
+ (setq org-odt-automatic-styles
+ (plist-put org-odt-automatic-styles object
+ (append (list (list style-name object-props))
+ (plist-get org-odt-automatic-styles object)))))
+ (cons object-name style-name)))
+
+;;;; Checkbox
+
+(defun org-odt--checkbox (item)
+ "Return check-box string associated to ITEM."
+ (let ((checkbox (org-element-property :checkbox item)))
+ (if (not checkbox) ""
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgCode" (cl-case checkbox
+ (on "[&#x2713;] ") ; CHECK MARK
+ (off "[ ] ")
+ (trans "[-] "))))))
+
+;;; Template
+
+(defun org-odt--build-date-styles (fmt style)
+ ;; In LibreOffice 3.4.6, there doesn't seem to be a convenient way
+ ;; to modify the date fields. A date could be modified by
+ ;; offsetting in days. That's about it. Also, date and time may
+ ;; have to be emitted as two fields - a date field and a time field
+ ;; - separately.
+
+ ;; One can add Form Controls to date and time fields so that they
+ ;; can be easily modified. But then, the exported document will
+ ;; become tightly coupled with LibreOffice and may not function
+ ;; properly with other OpenDocument applications.
+
+ ;; I have a strange feeling that Date styles are a bit flaky at the
+ ;; moment.
+
+ ;; The feature is experimental.
+ (when (and fmt style)
+ (let* ((fmt-alist
+ '(("%A" . "<number:day-of-week number:style=\"long\"/>")
+ ("%B" . "<number:month number:textual=\"true\" number:style=\"long\"/>")
+ ("%H" . "<number:hours number:style=\"long\"/>")
+ ("%M" . "<number:minutes number:style=\"long\"/>")
+ ("%S" . "<number:seconds number:style=\"long\"/>")
+ ("%V" . "<number:week-of-year/>")
+ ("%Y" . "<number:year number:style=\"long\"/>")
+ ("%a" . "<number:day-of-week number:style=\"short\"/>")
+ ("%b" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
+ ("%d" . "<number:day number:style=\"long\"/>")
+ ("%e" . "<number:day number:style=\"short\"/>")
+ ("%h" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
+ ("%k" . "<number:hours number:style=\"short\"/>")
+ ("%m" . "<number:month number:style=\"long\"/>")
+ ("%p" . "<number:am-pm/>")
+ ("%y" . "<number:year number:style=\"short\"/>")))
+ (case-fold-search nil)
+ (re (mapconcat 'identity (mapcar 'car fmt-alist) "\\|"))
+ match rpl (start 0) (filler-beg 0) filler-end filler output)
+ (dolist (pair
+ '(("\\(?:%[[:digit:]]*N\\)" . "") ; strip ns, us and ns
+ ("%C" . "Y") ; replace century with year
+ ("%D" . "%m/%d/%y")
+ ("%G" . "Y") ; year corresponding to iso week
+ ("%I" . "%H") ; hour on a 12-hour clock
+ ("%R" . "%H:%M")
+ ("%T" . "%H:%M:%S")
+ ("%U\\|%W" . "%V") ; week no. starting on Sun./Mon.
+ ("%Z" . "") ; time zone name
+ ("%c" . "%Y-%M-%d %a %H:%M" ) ; locale's date and time format
+ ("%g" . "%y")
+ ("%X" . "%x" ) ; locale's pref. time format
+ ("%j" . "") ; day of the year
+ ("%l" . "%k") ; like %I blank-padded
+ ("%s" . "") ; no. of secs since 1970-01-01 00:00:00 +0000
+ ("%n" . "<text:line-break/>")
+ ("%r" . "%I:%M:%S %p")
+ ("%t" . "<text:tab/>")
+ ("%u\\|%w" . "") ; numeric day of week - Mon (1-7), Sun(0-6)
+ ("%x" . "%Y-%M-%d %a") ; locale's pref. time format
+ ("%z" . "") ; time zone in numeric form
+ ))
+ (setq fmt (replace-regexp-in-string (car pair) (cdr pair) fmt t t)))
+ (while (string-match re fmt start)
+ (setq match (match-string 0 fmt))
+ (setq rpl (assoc-default match fmt-alist))
+ (setq start (match-end 0))
+ (setq filler-end (match-beginning 0))
+ (setq filler (substring fmt (prog1 filler-beg
+ (setq filler-beg (match-end 0)))
+ filler-end))
+ (setq filler (and (not (string= filler ""))
+ (format "<number:text>%s</number:text>"
+ (org-odt--encode-plain-text filler))))
+ (setq output (concat output "\n" filler "\n" rpl)))
+ (setq filler (substring fmt filler-beg))
+ (unless (string= filler "")
+ (setq output (concat output
+ (format "\n<number:text>%s</number:text>"
+ (org-odt--encode-plain-text filler)))))
+ (format "\n<number:date-style style:name=\"%s\" %s>%s\n</number:date-style>"
+ style
+ (concat " number:automatic-order=\"true\""
+ " number:format-source=\"fixed\"")
+ output ))))
+
+(defun org-odt-template (contents info)
+ "Return complete document string after ODT conversion.
+CONTENTS is the transcoded contents string. RAW-DATA is the
+original parsed data. INFO is a plist holding export options."
+ ;; Write meta file.
+ (let ((title (org-export-data (plist-get info :title) info))
+ (subtitle (org-export-data (plist-get info :subtitle) info))
+ (author (let ((author (plist-get info :author)))
+ (if (not author) "" (org-export-data author info))))
+ (keywords (or (plist-get info :keywords) ""))
+ (description (or (plist-get info :description) "")))
+ (write-region
+ (concat
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ <office:document-meta
+ xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
+ xmlns:xlink=\"http://www.w3.org/1999/xlink\"
+ xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
+ xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
+ xmlns:ooo=\"http://openoffice.org/2004/office\"
+ office:version=\"1.2\">
+ <office:meta>\n"
+ (format "<dc:creator>%s</dc:creator>\n" author)
+ (format "<meta:initial-creator>%s</meta:initial-creator>\n" author)
+ ;; Date, if required.
+ (when (plist-get info :with-date)
+ ;; Check if DATE is specified as an Org-timestamp. If yes,
+ ;; include it as meta information. Otherwise, just use
+ ;; today's date.
+ (let* ((date (let ((date (plist-get info :date)))
+ (and (not (cdr date))
+ (eq (org-element-type (car date)) 'timestamp)
+ (car date)))))
+ (let ((iso-date (org-odt--format-timestamp date nil 'iso-date)))
+ (concat
+ (format "<dc:date>%s</dc:date>\n" iso-date)
+ (format "<meta:creation-date>%s</meta:creation-date>\n"
+ iso-date)))))
+ (format "<meta:generator>%s</meta:generator>\n"
+ (plist-get info :creator))
+ (format "<meta:keyword>%s</meta:keyword>\n" keywords)
+ (format "<dc:subject>%s</dc:subject>\n" description)
+ (format "<dc:title>%s</dc:title>\n" title)
+ (when (org-string-nw-p subtitle)
+ (format
+ "<meta:user-defined meta:name=\"subtitle\">%s</meta:user-defined>\n"
+ subtitle))
+ "\n"
+ " </office:meta>\n" "</office:document-meta>")
+ nil (concat org-odt-zip-dir "meta.xml"))
+ ;; Add meta.xml in to manifest.
+ (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
+
+ ;; Update styles file.
+ ;; Copy styles.xml. Also dump htmlfontify styles, if there is any.
+ ;; Write styles file.
+ (let* ((styles-file (plist-get info :odt-styles-file))
+ (styles-file (and (org-string-nw-p styles-file)
+ (read (org-trim styles-file))))
+ ;; Non-availability of styles.xml is not a critical
+ ;; error. For now, throw an error.
+ (styles-file (or styles-file
+ (plist-get info :odt-styles-file)
+ (expand-file-name "OrgOdtStyles.xml"
+ org-odt-styles-dir)
+ (error "org-odt: Missing styles file?"))))
+ (cond
+ ((listp styles-file)
+ (let ((archive (nth 0 styles-file))
+ (members (nth 1 styles-file)))
+ (org-odt--zip-extract archive members org-odt-zip-dir)
+ (dolist (member members)
+ (when (org-file-image-p member)
+ (let* ((image-type (file-name-extension member))
+ (media-type (format "image/%s" image-type)))
+ (org-odt-create-manifest-file-entry media-type member))))))
+ ((and (stringp styles-file) (file-exists-p styles-file))
+ (let ((styles-file-type (file-name-extension styles-file)))
+ (cond
+ ((string= styles-file-type "xml")
+ (copy-file styles-file (concat org-odt-zip-dir "styles.xml") t))
+ ((member styles-file-type '("odt" "ott"))
+ (org-odt--zip-extract styles-file "styles.xml" org-odt-zip-dir)))))
+ (t
+ (error "Invalid specification of styles.xml file: %S"
+ (plist-get info :odt-styles-file))))
+
+ ;; create a manifest entry for styles.xml
+ (org-odt-create-manifest-file-entry "text/xml" "styles.xml")
+
+ ;; FIXME: Who is opening an empty styles.xml before this point?
+ (with-current-buffer
+ (find-file-noselect (concat org-odt-zip-dir "styles.xml") t)
+ (revert-buffer t t)
+
+ ;; Write custom styles for source blocks
+ ;; Save STYLES used for colorizing of source blocks.
+ ;; Update styles.xml with styles that were collected as part of
+ ;; `org-odt-hfy-face-to-css' callbacks.
+ (let ((styles (mapconcat (lambda (style) (format " %s\n" (cddr style)))
+ hfy-user-sheet-assoc "")))
+ (when styles
+ (goto-char (point-min))
+ (when (re-search-forward "</office:styles>" nil t)
+ (goto-char (match-beginning 0))
+ (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n"))))
+
+ ;; Update styles.xml - take care of outline numbering
+
+ ;; Don't make automatic backup of styles.xml file. This setting
+ ;; prevents the backed-up styles.xml file from being zipped in to
+ ;; odt file. This is more of a hackish fix. Better alternative
+ ;; would be to fix the zip command so that the output odt file
+ ;; includes only the needed files and excludes any auto-generated
+ ;; extra files like backups and auto-saves etc etc. Note that
+ ;; currently the zip command zips up the entire temp directory so
+ ;; that any auto-generated files created under the hood ends up in
+ ;; the resulting odt file.
+ (setq-local backup-inhibited t)
+
+ ;; Outline numbering is retained only upto LEVEL.
+ ;; To disable outline numbering pass a LEVEL of 0.
+
+ (goto-char (point-min))
+ (let ((regex
+ "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
+ (replacement
+ "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
+ (while (re-search-forward regex nil t)
+ (unless (let ((sec-num (plist-get info :section-numbers))
+ (level (string-to-number (match-string 2))))
+ (if (wholenump sec-num) (<= level sec-num) sec-num))
+ (replace-match replacement t nil))))
+ (save-buffer 0)))
+ ;; Update content.xml.
+
+ (let* ( ;; `org-display-custom-times' should be accessed right
+ ;; within the context of the Org buffer. So obtain its
+ ;; value before moving on to temp-buffer context down below.
+ (custom-time-fmts
+ (if org-display-custom-times
+ (cons (substring (car org-time-stamp-custom-formats) 1 -1)
+ (substring (cdr org-time-stamp-custom-formats) 1 -1))
+ '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
+ (with-temp-buffer
+ (insert-file-contents
+ (or (plist-get info :odt-content-template-file)
+ (expand-file-name "OrgOdtContentTemplate.xml"
+ org-odt-styles-dir)))
+ ;; Write automatic styles.
+ ;; - Position the cursor.
+ (goto-char (point-min))
+ (re-search-forward " </office:automatic-styles>" nil t)
+ (goto-char (match-beginning 0))
+ ;; - Dump automatic table styles.
+ (cl-loop for (style-name props) in
+ (plist-get org-odt-automatic-styles 'Table) do
+ (when (setq props (or (plist-get props :rel-width) "96"))
+ (insert (format org-odt-table-style-format style-name props))))
+ ;; - Dump date-styles.
+ (when (plist-get info :odt-use-date-fields)
+ (insert (org-odt--build-date-styles (car custom-time-fmts)
+ "OrgDate1")
+ (org-odt--build-date-styles (cdr custom-time-fmts)
+ "OrgDate2")))
+ ;; Update display level.
+ ;; - Remove existing sequence decls. Also position the cursor.
+ (goto-char (point-min))
+ (when (re-search-forward "<text:sequence-decls" nil t)
+ (delete-region (match-beginning 0)
+ (re-search-forward "</text:sequence-decls>" nil nil)))
+ ;; Update sequence decls according to user preference.
+ (insert
+ (format
+ "\n<text:sequence-decls>\n%s\n</text:sequence-decls>"
+ (mapconcat
+ (lambda (x)
+ (format
+ "<text:sequence-decl text:display-outline-level=\"%d\" text:name=\"%s\"/>"
+ (plist-get info :odt-display-outline-level)
+ (nth 1 x)))
+ org-odt-category-map-alist "\n")))
+ ;; Position the cursor to document body.
+ (goto-char (point-min))
+ (re-search-forward "</office:text>" nil nil)
+ (goto-char (match-beginning 0))
+
+ ;; Preamble - Title, Author, Date etc.
+ (insert
+ (let* ((title (and (plist-get info :with-title)
+ (org-export-data (plist-get info :title) info)))
+ (subtitle (when title
+ (org-export-data (plist-get info :subtitle) info)))
+ (author (and (plist-get info :with-author)
+ (let ((auth (plist-get info :author)))
+ (and auth (org-export-data auth info)))))
+ (email (plist-get info :email))
+ ;; Switch on or off above vars based on user settings
+ (author (and (plist-get info :with-author) (or author email)))
+ (email (and (plist-get info :with-email) email)))
+ (concat
+ ;; Title.
+ (when (org-string-nw-p title)
+ (concat
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>\n"
+ "OrgTitle" (format "\n<text:title>%s</text:title>" title))
+ ;; Separator.
+ "\n<text:p text:style-name=\"OrgTitle\"/>\n"
+ ;; Subtitle.
+ (when (org-string-nw-p subtitle)
+ (concat
+ (format "<text:p text:style-name=\"OrgSubtitle\">\n%s\n</text:p>\n"
+ (concat
+ "<text:user-defined style:data-style-name=\"N0\" text:name=\"subtitle\">\n"
+ subtitle
+ "</text:user-defined>\n"))
+ ;; Separator.
+ "<text:p text:style-name=\"OrgSubtitle\"/>\n"))))
+ (cond
+ ((and author (not email))
+ ;; Author only.
+ (concat
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "OrgSubtitle"
+ (format "<text:initial-creator>%s</text:initial-creator>" author))
+ ;; Separator.
+ "\n<text:p text:style-name=\"OrgSubtitle\"/>"))
+ ((and author email)
+ ;; Author and E-mail.
+ (concat
+ (format
+ "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "OrgSubtitle"
+ (format
+ "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
+ (concat "mailto:" email)
+ (format "<text:initial-creator>%s</text:initial-creator>" author)))
+ ;; Separator.
+ "\n<text:p text:style-name=\"OrgSubtitle\"/>")))
+ ;; Date, if required.
+ (when (plist-get info :with-date)
+ (let* ((date (plist-get info :date))
+ ;; Check if DATE is specified as a timestamp.
+ (timestamp (and (not (cdr date))
+ (eq (org-element-type (car date)) 'timestamp)
+ (car date))))
+ (when date
+ (concat
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "OrgSubtitle"
+ (if (and (plist-get info :odt-use-date-fields) timestamp)
+ (org-odt--format-timestamp (car date))
+ (org-export-data date info)))
+ ;; Separator
+ "<text:p text:style-name=\"OrgSubtitle\"/>")))))))
+ ;; Table of Contents
+ (let* ((with-toc (plist-get info :with-toc))
+ (depth (and with-toc (if (wholenump with-toc)
+ with-toc
+ (plist-get info :headline-levels)))))
+ (when depth (insert (or (org-odt-toc depth info) ""))))
+ ;; Contents.
+ (insert contents)
+ ;; Return contents.
+ (buffer-substring-no-properties (point-min) (point-max)))))
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-odt-bold (_bold contents _info)
+ "Transcode BOLD from Org to ODT.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "Bold" contents))
+
+
+;;;; Center Block
+
+(defun org-odt-center-block (_center-block contents _info)
+ "Transcode a CENTER-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the center block. INFO is a plist
+holding contextual information."
+ contents)
+
+
+;;;; Clock
+
+(defun org-odt-clock (clock contents info)
+ "Transcode a CLOCK element from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((timestamp (org-element-property :value clock))
+ (duration (org-element-property :duration clock)))
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ (if (eq (org-element-type (org-export-get-next-element clock info))
+ 'clock) "OrgClock" "OrgClockLastLine")
+ (concat
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgClockKeyword" org-clock-string)
+ (org-odt-timestamp timestamp contents info)
+ (and duration (format " (%s)" duration))))))
+
+
+;;;; Code
+
+(defun org-odt-code (code _contents _info)
+ "Transcode a CODE object from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgCode" (org-odt--encode-plain-text
+ (org-element-property :value code))))
+
+
+;;;; Drawer
+
+(defun org-odt-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to ODT.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((name (org-element-property :drawer-name drawer))
+ (output (funcall (plist-get info :odt-format-drawer-function)
+ name contents)))
+ output))
+
+
+;;;; Dynamic Block
+
+(defun org-odt-dynamic-block (_dynamic-block contents _info)
+ "Transcode a DYNAMIC-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information. See `org-export-data'."
+ contents)
+
+
+;;;; Entity
+
+(defun org-odt-entity (entity _contents _info)
+ "Transcode an ENTITY object from Org to ODT.
+CONTENTS are the definition itself. INFO is a plist holding
+contextual information."
+ (org-element-property :utf-8 entity))
+
+
+;;;; Example Block
+
+(defun org-odt-example-block (example-block _contents info)
+ "Transcode a EXAMPLE-BLOCK element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-odt-format-code example-block info))
+
+
+;;;; Export Snippet
+
+(defun org-odt-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'odt)
+ (org-element-property :value export-snippet)))
+
+
+;;;; Export Block
+
+(defun org-odt-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "ODT")
+ (org-remove-indentation (org-element-property :value export-block))))
+
+
+;;;; Fixed Width
+
+(defun org-odt-fixed-width (fixed-width _contents info)
+ "Transcode a FIXED-WIDTH element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-odt-do-format-code (org-element-property :value fixed-width) info))
+
+
+;;;; Footnote Definition
+
+;; Footnote Definitions are ignored.
+
+
+;;;; Footnote Reference
+
+(defun org-odt-footnote-reference (footnote-reference _contents info)
+ "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((--format-footnote-definition
+ (lambda (n def)
+ (setq n (format "%d" n))
+ (let ((id (concat "fn" n))
+ (note-class "footnote"))
+ (format
+ "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
+ id note-class
+ (concat
+ (format "<text:note-citation>%s</text:note-citation>" n)
+ (format "<text:note-body>%s</text:note-body>" def))))))
+ (--format-footnote-reference
+ (lambda (n)
+ (setq n (format "%d" n))
+ (let ((note-class "footnote")
+ (ref-format "text")
+ (ref-name (concat "fn" n)))
+ (format
+ "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgSuperscript"
+ (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
+ note-class ref-format ref-name n))))))
+ (concat
+ ;; Insert separator between two footnotes in a row.
+ (let ((prev (org-export-get-previous-element footnote-reference info)))
+ (and (eq (org-element-type prev) 'footnote-reference)
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgSuperscript" ",")))
+ ;; Transcode footnote reference.
+ (let ((n (org-export-get-footnote-number footnote-reference info nil t)))
+ (cond
+ ((not
+ (org-export-footnote-first-reference-p footnote-reference info nil t))
+ (funcall --format-footnote-reference n))
+ (t
+ (let* ((raw (org-export-get-footnote-definition
+ footnote-reference info))
+ (def
+ (let ((def (org-trim
+ (org-export-data-with-backend
+ raw
+ (org-export-create-backend
+ :parent 'odt
+ :transcoders
+ '((paragraph . (lambda (p c i)
+ (org-odt--format-paragraph
+ p c i
+ "Footnote"
+ "OrgFootnoteCenter"
+ "OrgFootnoteQuotations")))))
+ info))))
+ ;; Inline definitions are secondary strings. We
+ ;; need to wrap them within a paragraph.
+ (if (eq (org-element-class (car (org-element-contents raw)))
+ 'element)
+ def
+ (format
+ "\n<text:p text:style-name=\"Footnote\">%s</text:p>"
+ def)))))
+ (funcall --format-footnote-definition n def))))))))
+
+
+;;;; Headline
+
+(defun org-odt-format-headline--wrap (headline backend info
+ &optional format-function
+ &rest extra-keys)
+ "Transcode a HEADLINE element using BACKEND.
+INFO is a plist holding contextual information."
+ (setq backend (or backend (plist-get info :back-end)))
+ (let* ((level (+ (org-export-get-relative-level headline info)))
+ (headline-number (org-export-get-headline-number headline info))
+ (section-number (and (org-export-numbered-headline-p headline info)
+ (mapconcat 'number-to-string
+ headline-number ".")))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo
+ (org-export-data-with-backend todo backend info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ (text (org-export-data-with-backend
+ (org-element-property :title headline) backend info))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (headline-label (org-export-get-reference headline info))
+ (format-function
+ (if (functionp format-function) format-function
+ (cl-function
+ (lambda (todo todo-type priority text tags
+ &key _level _section-number _headline-label
+ &allow-other-keys)
+ (funcall (plist-get info :odt-format-headline-function)
+ todo todo-type priority text tags))))))
+ (apply format-function
+ todo todo-type priority text tags
+ :headline-label headline-label
+ :level level
+ :section-number section-number extra-keys)))
+
+(defun org-odt-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to ODT.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ ;; Case 1: This is a footnote section: ignore it.
+ (unless (org-element-property :footnote-section-p headline)
+ (let* ((full-text (org-odt-format-headline--wrap headline nil info))
+ ;; Get level relative to current parsed data.
+ (level (org-export-get-relative-level headline info))
+ (numbered (org-export-numbered-headline-p headline info))
+ ;; Get canonical label for the headline.
+ (id (org-export-get-reference headline info))
+ ;; Extra targets.
+ (extra-targets
+ (let ((id (org-element-property :ID headline)))
+ (if id (org-odt--target "" (concat "ID-" id)) "")))
+ ;; Title.
+ (anchored-title (org-odt--target full-text id)))
+ (cond
+ ;; Case 2. This is a deep sub-tree: export it as a list item.
+ ;; Also export as items headlines for which no section
+ ;; format has been found.
+ ((org-export-low-level-p headline info)
+ ;; Build the real contents of the sub-tree.
+ (concat
+ (and (org-export-first-sibling-p headline info)
+ (format "\n<text:list text:style-name=\"%s\" %s>"
+ ;; Choose style based on list type.
+ (if numbered "OrgNumberedList" "OrgBulletedList")
+ ;; If top-level list, re-start numbering. Otherwise,
+ ;; continue numbering.
+ (format "text:continue-numbering=\"%s\""
+ (let* ((parent (org-export-get-parent-headline
+ headline)))
+ (if (and parent
+ (org-export-low-level-p parent info))
+ "true" "false")))))
+ (let ((headline-has-table-p
+ (let ((section (assq 'section (org-element-contents headline))))
+ (assq 'table (and section (org-element-contents section))))))
+ (format "\n<text:list-item>\n%s\n%s"
+ (concat
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Text_20_body"
+ (concat extra-targets anchored-title))
+ contents)
+ (if headline-has-table-p
+ "</text:list-header>"
+ "</text:list-item>")))
+ (and (org-export-last-sibling-p headline info)
+ "</text:list>")))
+ ;; Case 3. Standard headline. Export it as a section.
+ (t
+ (concat
+ (format
+ "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\" text:is-list-header=\"%s\">%s</text:h>"
+ (format "Heading_20_%s%s"
+ level (if numbered "" "_unnumbered"))
+ level
+ (if numbered "false" "true")
+ (concat extra-targets anchored-title))
+ contents))))))
+
+(defun org-odt-format-headline-default-function
+ (todo todo-type priority text tags)
+ "Default format function for a headline.
+See `org-odt-format-headline-function' for details."
+ (concat
+ ;; Todo.
+ (when todo
+ (let ((style (if (eq todo-type 'done) "OrgDone" "OrgTodo")))
+ (format "<text:span text:style-name=\"%s\">%s</text:span> " style todo)))
+ (when priority
+ (let* ((style (format "OrgPriority-%s" priority))
+ (priority (format "[#%c]" priority)))
+ (format "<text:span text:style-name=\"%s\">%s</text:span> "
+ style priority)))
+ ;; Title.
+ text
+ ;; Tags.
+ (when tags
+ (concat
+ "<text:tab/>"
+ (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
+ "OrgTags" (mapconcat
+ (lambda (tag)
+ (format
+ "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgTag" tag)) tags " : "))))))
+
+
+;;;; Horizontal Rule
+
+(defun org-odt-horizontal-rule (_horizontal-rule _contents _info)
+ "Transcode an HORIZONTAL-RULE object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Horizontal_20_Line" ""))
+
+
+;;;; Inline Babel Call
+
+;; Inline Babel Calls are ignored.
+
+
+;;;; Inline Src Block
+
+(defun org-odt--find-verb-separator (s)
+ "Return a character not used in string S.
+This is used to choose a separator for constructs like \\verb."
+ (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
+ (cl-loop for c across ll
+ when (not (string-match (regexp-quote (char-to-string c)) s))
+ return (char-to-string c))))
+
+(defun org-odt-inline-src-block (_inline-src-block _contents _info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (error "FIXME"))
+
+
+;;;; Inlinetask
+
+(defun org-odt-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to ODT.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((todo
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type inlinetask)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask)))
+ (text (org-export-data (org-element-property :title inlinetask) info))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags inlinetask info))))
+ (funcall (plist-get info :odt-format-inlinetask-function)
+ todo todo-type priority text tags contents)))
+
+(defun org-odt-format-inlinetask-default-function
+ (todo todo-type priority name tags contents)
+ "Default format function for a inlinetasks.
+See `org-odt-format-inlinetask-function' for details."
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Text_20_body"
+ (org-odt--textbox
+ (concat
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "OrgInlineTaskHeading"
+ (org-odt-format-headline-default-function
+ todo todo-type priority name tags))
+ contents)
+ nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))
+
+;;;; Italic
+
+(defun org-odt-italic (_italic contents _info)
+ "Transcode ITALIC from Org to ODT.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "Emphasis" contents))
+
+
+;;;; Item
+
+(defun org-odt-item (item contents info)
+ "Transcode an ITEM element from Org to ODT.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((plain-list (org-export-get-parent item))
+ (type (org-element-property :type plain-list)))
+ (unless (memq type '(ordered unordered descriptive-1 descriptive-2))
+ (error "Unknown list type: %S" type))
+ (format "\n<text:list-item>\n%s\n%s"
+ contents
+ (if (org-element-map item 'table #'identity info 'first-match)
+ "</text:list-header>"
+ "</text:list-item>"))))
+
+;;;; Keyword
+
+(defun org-odt-keyword (keyword _contents info)
+ "Transcode a KEYWORD element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((key (org-element-property :key keyword))
+ (value (org-element-property :value keyword)))
+ (cond
+ ((string= key "ODT") value)
+ ((string= key "INDEX")
+ ;; FIXME
+ (ignore))
+ ((string= key "TOC")
+ (let ((case-fold-search t))
+ (cond
+ ((string-match-p "\\<headlines\\>" value)
+ (let ((depth (or (and (string-match "\\<[0-9]+\\>" value)
+ (string-to-number (match-string 0 value)))
+ (plist-get info :headline-levels)))
+ (localp (string-match-p "\\<local\\>" value)))
+ (org-odt-toc depth info (and localp keyword))))
+ ((string-match-p "tables\\|figures\\|listings" value)
+ ;; FIXME
+ (ignore))))))))
+
+
+;;;; Latex Environment
+
+
+;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
+;; (defadvice org-format-latex-as-mathml ; FIXME
+;; (after org-odt-protect-latex-fragment activate)
+;; "Encode LaTeX fragment as XML.
+;; Do this when translation to MathML fails."
+;; (unless (> (length ad-return-value) 0)
+;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
+
+(defun org-odt-latex-environment (latex-environment _contents info)
+ "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let* ((latex-frag (org-remove-indentation
+ (org-element-property :value latex-environment))))
+ (org-odt-do-format-code latex-frag info)))
+
+
+;;;; Latex Fragment
+
+;; (when latex-frag ; FIXME
+;; (setq href (propertize href :title "LaTeX Fragment"
+;; :description latex-frag)))
+;; handle verbatim
+;; provide descriptions
+
+(defun org-odt-latex-fragment (latex-fragment _contents _info)
+ "Transcode a LATEX-FRAGMENT object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((latex-frag (org-element-property :value latex-fragment)))
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgCode" (org-odt--encode-plain-text latex-frag t))))
+
+
+;;;; Line Break
+
+(defun org-odt-line-break (_line-break _contents _info)
+ "Transcode a LINE-BREAK object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ "<text:line-break/>")
+
+
+;;;; Link
+
+;;;; Links :: Label references
+
+(defun org-odt--enumerate (element info &optional predicate n)
+ (when predicate (cl-assert (funcall predicate element info)))
+ (let* ((--numbered-parent-headline-at-<=-n
+ (lambda (element n info)
+ (cl-loop for x in (org-element-lineage element)
+ thereis (and (eq (org-element-type x) 'headline)
+ (<= (org-export-get-relative-level x info) n)
+ (org-export-numbered-headline-p x info)
+ x))))
+ (--enumerate
+ (lambda (element scope info &optional predicate)
+ (let ((counter 0))
+ (org-element-map (or scope (plist-get info :parse-tree))
+ (org-element-type element)
+ (lambda (el)
+ (and (or (not predicate) (funcall predicate el info))
+ (cl-incf counter)
+ (eq element el)
+ counter))
+ info 'first-match))))
+ (scope (funcall --numbered-parent-headline-at-<=-n
+ element
+ (or n (plist-get info :odt-display-outline-level))
+ info))
+ (ordinal (funcall --enumerate element scope info predicate))
+ (tag
+ (concat
+ ;; Section number.
+ (and scope
+ (mapconcat 'number-to-string
+ (org-export-get-headline-number scope info) "."))
+ ;; Separator.
+ (and scope ".")
+ ;; Ordinal.
+ (number-to-string ordinal))))
+ tag))
+
+(defun org-odt-format-label (element info op)
+ "Return a label for ELEMENT.
+
+ELEMENT is a `link', `table', `src-block' or `paragraph' type
+element. INFO is a plist used as a communication channel. OP is
+either `definition' or `reference', depending on the purpose of
+the generated string.
+
+Return value is a string if OP is set to `reference' or a cons
+cell like CAPTION . SHORT-CAPTION) where CAPTION and
+SHORT-CAPTION are strings."
+ (cl-assert (memq (org-element-type element) '(link table src-block paragraph)))
+ (let* ((element-or-parent
+ (cl-case (org-element-type element)
+ (link (org-export-get-parent-element element))
+ (t element)))
+ ;; Get label and caption.
+ (label (and (or (org-element-property :name element)
+ (org-element-property :name element-or-parent))
+ (org-export-get-reference element-or-parent info)))
+ (caption (let ((c (org-export-get-caption element-or-parent)))
+ (and c (org-export-data c info))))
+ ;; FIXME: We don't use short-caption for now
+ (short-caption nil))
+ (when (or label caption)
+ (let* ((default-category
+ (cl-case (org-element-type element)
+ (table "__Table__")
+ (src-block "__Listing__")
+ ((link paragraph)
+ (cond
+ ((org-odt--enumerable-latex-image-p element info)
+ "__DvipngImage__")
+ ((org-odt--enumerable-image-p element info)
+ "__Figure__")
+ ((org-odt--enumerable-formula-p element info)
+ "__MathFormula__")
+ (t (error "Don't know how to format label for link: %S"
+ element))))
+ (t (error "Don't know how to format label for element type: %s"
+ (org-element-type element)))))
+ seqno)
+ (cl-assert default-category)
+ (pcase-let
+ ((`(,counter ,label-style ,category ,predicate)
+ (assoc-default default-category org-odt-category-map-alist)))
+ ;; Compute sequence number of the element.
+ (setq seqno (org-odt--enumerate element info predicate))
+ ;; Localize category string.
+ (setq category (org-export-translate category :utf-8 info))
+ (cl-case op
+ ;; Case 1: Handle Label definition.
+ (definition
+ (cons
+ (concat
+ ;; Sneak in a bookmark. The bookmark is used when the
+ ;; labeled element is referenced with a link that
+ ;; provides its own description.
+ (format "\n<text:bookmark text:name=\"%s\"/>" label)
+ ;; Label definition: Typically formatted as below:
+ ;; CATEGORY SEQ-NO: LONG CAPTION
+ ;; with translation for correct punctuation.
+ (format-spec
+ (org-export-translate
+ (cadr (assoc-string label-style org-odt-label-styles t))
+ :utf-8 info)
+ `((?e . ,category)
+ (?n . ,(format
+ "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
+ label counter counter seqno))
+ (?c . ,(or caption "")))))
+ short-caption))
+ ;; Case 2: Handle Label reference.
+ (reference
+ (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
+ (fmt1 (car fmt))
+ (fmt2 (cadr fmt)))
+ (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
+ fmt1
+ label
+ (format-spec fmt2 `((?e . ,category) (?n . ,seqno))))))
+ (t (error "Unknown %S on label" op))))))))
+
+
+;;;; Links :: Inline Images
+
+(defun org-odt--copy-image-file (path)
+ "Returns the internal name of the file"
+ (let* ((image-type (file-name-extension path))
+ (media-type (format "image/%s" image-type))
+ (target-dir "Images/")
+ (target-file
+ (format "%s%04d.%s" target-dir
+ (cl-incf org-odt-embedded-images-count) image-type)))
+ (message "Embedding %s as %s..."
+ (substring-no-properties path) target-file)
+
+ (when (= 1 org-odt-embedded-images-count)
+ (make-directory (concat org-odt-zip-dir target-dir))
+ (org-odt-create-manifest-file-entry "" target-dir))
+
+ (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
+ (org-odt-create-manifest-file-entry media-type target-file)
+ target-file))
+
+(defun org-odt--image-size
+ (file info &optional user-width user-height scale dpi embed-as)
+ (let* ((--pixels-to-cms
+ (function (lambda (pixels dpi)
+ (let ((cms-per-inch 2.54)
+ (inches (/ pixels dpi)))
+ (* cms-per-inch inches)))))
+ (--size-in-cms
+ (function
+ (lambda (size-in-pixels dpi)
+ (and size-in-pixels
+ (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
+ (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
+ (dpi (or dpi (plist-get info :odt-pixels-per-inch)))
+ (anchor-type (or embed-as "paragraph"))
+ (user-width (and (not scale) user-width))
+ (user-height (and (not scale) user-height))
+ (size
+ (and
+ (not (and user-height user-width))
+ (or
+ ;; Use Imagemagick.
+ (and (executable-find "identify")
+ (let ((size-in-pixels
+ (let ((dim (shell-command-to-string
+ (format "identify -format \"%%w:%%h\" \"%s\""
+ file))))
+ (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
+ (cons (string-to-number (match-string 1 dim))
+ (string-to-number (match-string 2 dim)))))))
+ (funcall --size-in-cms size-in-pixels dpi)))
+ ;; Use Emacs.
+ (let ((size-in-pixels
+ (ignore-errors ; Emacs could be in batch mode
+ (clear-image-cache)
+ (image-size (create-image file) 'pixels))))
+ (funcall --size-in-cms size-in-pixels dpi))
+ ;; Use hard-coded values.
+ (cdr (assoc-string anchor-type
+ org-odt-default-image-sizes-alist))
+ ;; Error out.
+ (error "Cannot determine image size, aborting"))))
+ (width (car size)) (height (cdr size)))
+ (cond
+ (scale
+ (setq width (* width scale) height (* height scale)))
+ ((and user-height user-width)
+ (setq width user-width height user-height))
+ (user-height
+ (setq width (* user-height (/ width height)) height user-height))
+ (user-width
+ (setq height (* user-width (/ height width)) width user-width))
+ (t (ignore)))
+ ;; ensure that an embedded image fits comfortably within a page
+ (let ((max-width (car org-odt-max-image-size))
+ (max-height (cdr org-odt-max-image-size)))
+ (when (or (> width max-width) (> height max-height))
+ (let* ((scale1 (/ max-width width))
+ (scale2 (/ max-height height))
+ (scale (min scale1 scale2)))
+ (setq width (* scale width) height (* scale height)))))
+ (cons width height)))
+
+(defun org-odt-link--inline-image (element info)
+ "Return ODT code for an inline image.
+LINK is the link pointing to the inline image. INFO is a plist
+used as a communication channel."
+ (cl-assert (eq (org-element-type element) 'link))
+ (let* ((src (let* ((type (org-element-property :type element))
+ (raw-path (org-element-property :path element)))
+ (cond ((member type '("http" "https"))
+ (concat type ":" raw-path))
+ ((file-name-absolute-p raw-path)
+ (expand-file-name raw-path))
+ (t raw-path))))
+ (src-expanded (if (file-name-absolute-p src) src
+ (expand-file-name src (file-name-directory
+ (plist-get info :input-file)))))
+ (href (format
+ "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
+ (org-odt--copy-image-file src-expanded)))
+ ;; Extract attributes from #+ATTR_ODT line.
+ (attr-from (cl-case (org-element-type element)
+ (link (org-export-get-parent-element element))
+ (t element)))
+ ;; Convert attributes to a plist.
+ (attr-plist (org-export-read-attribute :attr_odt attr-from))
+ ;; Handle `:anchor', `:style' and `:attributes' properties.
+ (user-frame-anchor
+ (car (assoc-string (plist-get attr-plist :anchor)
+ '(("as-char") ("paragraph") ("page")) t)))
+ (user-frame-style
+ (and user-frame-anchor (plist-get attr-plist :style)))
+ (user-frame-attrs
+ (and user-frame-anchor (plist-get attr-plist :attributes)))
+ (user-frame-params
+ (list user-frame-style user-frame-attrs user-frame-anchor))
+ ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
+ ;;
+ ;; Handle `:width', `:height' and `:scale' properties. Read
+ ;; them as numbers since we need them for computations.
+ (size (org-odt--image-size
+ src-expanded info
+ (let ((width (plist-get attr-plist :width)))
+ (and width (read width)))
+ (let ((length (plist-get attr-plist :length)))
+ (and length (read length)))
+ (let ((scale (plist-get attr-plist :scale)))
+ (and scale (read scale)))
+ nil ; embed-as
+ "paragraph" ; FIXME
+ ))
+ (width (car size)) (height (cdr size))
+ (standalone-link-p (org-odt--standalone-link-p element info))
+ (embed-as (if standalone-link-p "paragraph" "as-char"))
+ (captions (org-odt-format-label element info 'definition))
+ (caption (car captions))
+ (entity (concat (and caption "Captioned") embed-as "Image"))
+ ;; Check if this link was created by LaTeX-to-PNG converter.
+ (replaces (org-element-property
+ :replaces (if (not standalone-link-p) element
+ (org-export-get-parent-element element))))
+ ;; If yes, note down the type of the element - LaTeX Fragment
+ ;; or LaTeX environment. It will go in to frame title.
+ (title (and replaces (capitalize
+ (symbol-name (org-element-type replaces)))))
+
+ ;; If yes, note down its contents. It will go in to frame
+ ;; description. This quite useful for debugging.
+ (desc (and replaces (org-element-property :value replaces))))
+ (org-odt--render-image/formula entity href width height
+ captions user-frame-params title desc)))
+
+
+;;;; Links :: Math formula
+
+(defun org-odt-link--inline-formula (element info)
+ (let* ((src (let ((raw-path (org-element-property :path element)))
+ (cond
+ ((file-name-absolute-p raw-path)
+ (expand-file-name raw-path))
+ (t raw-path))))
+ (src-expanded (if (file-name-absolute-p src) src
+ (expand-file-name src (file-name-directory
+ (plist-get info :input-file)))))
+ (href
+ (format
+ "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
+ " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
+ (file-name-directory (org-odt--copy-formula-file src-expanded))))
+ (standalone-link-p (org-odt--standalone-link-p element info))
+ (embed-as (if standalone-link-p 'paragraph 'character))
+ (captions (org-odt-format-label element info 'definition))
+ ;; Check if this link was created by LaTeX-to-MathML
+ ;; converter.
+ (replaces (org-element-property
+ :replaces (if (not standalone-link-p) element
+ (org-export-get-parent-element element))))
+ ;; If yes, note down the type of the element - LaTeX Fragment
+ ;; or LaTeX environment. It will go in to frame title.
+ (title (and replaces (capitalize
+ (symbol-name (org-element-type replaces)))))
+
+ ;; If yes, note down its contents. It will go in to frame
+ ;; description. This quite useful for debugging.
+ (desc (and replaces (org-element-property :value replaces)))
+ width height)
+ (cond
+ ((eq embed-as 'character)
+ (org-odt--render-image/formula "InlineFormula" href width height
+ nil nil title desc))
+ (t
+ (let* ((equation (org-odt--render-image/formula
+ "CaptionedDisplayFormula" href width height
+ captions nil title desc))
+ (label
+ (let* ((org-odt-category-map-alist
+ '(("__MathFormula__" "Text" "math-label" "Equation"
+ org-odt--enumerable-formula-p))))
+ (car (org-odt-format-label element info 'definition)))))
+ (concat equation "<text:tab/>" label))))))
+
+(defun org-odt--copy-formula-file (src-file)
+ "Returns the internal name of the file"
+ (let* ((target-dir (format "Formula-%04d/"
+ (cl-incf org-odt-embedded-formulas-count)))
+ (target-file (concat target-dir "content.xml")))
+ ;; Create a directory for holding formula file. Also enter it in
+ ;; to manifest.
+ (make-directory (concat org-odt-zip-dir target-dir))
+ (org-odt-create-manifest-file-entry
+ "application/vnd.oasis.opendocument.formula" target-dir "1.2")
+ ;; Copy over the formula file from user directory to zip
+ ;; directory.
+ (message "Embedding %s as %s..." src-file target-file)
+ (let ((ext (file-name-extension src-file)))
+ (cond
+ ;; Case 1: Mathml.
+ ((member ext '("mathml" "mml"))
+ (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
+ ;; Case 2: OpenDocument formula.
+ ((string= ext "odf")
+ (org-odt--zip-extract src-file "content.xml"
+ (concat org-odt-zip-dir target-dir)))
+ (t (error "%s is not a formula file" src-file))))
+ ;; Enter the formula file in to manifest.
+ (org-odt-create-manifest-file-entry "text/xml" target-file)
+ target-file))
+
+;;;; Targets
+
+(defun org-odt--render-image/formula (cfg-key href width height &optional
+ captions user-frame-params
+ &rest title-and-desc)
+ (let* ((frame-cfg-alist
+ ;; Each element of this alist is of the form (CFG-HANDLE
+ ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
+
+ ;; CFG-HANDLE is the key to the alist.
+
+ ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
+ ;; frame params for INNER-FRAME and OUTER-FRAME
+ ;; respectively. See below.
+
+ ;; Configurations that are meant to be applied to
+ ;; non-captioned image/formula specifies no
+ ;; OUTER-FRAME-PARAMS.
+
+ ;; TERMINOLOGY
+ ;; ===========
+ ;; INNER-FRAME :: Frame that directly surrounds an
+ ;; image/formula.
+
+ ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
+ ;; frame also contains the caption, if any.
+
+ ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
+ ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
+ ;; that these are the last three arguments
+ ;; to `org-odt--frame'.
+
+ ;; Note that an un-captioned image/formula requires just an
+ ;; INNER-FRAME, while a captioned image/formula requires
+ ;; both an INNER and an OUTER-FRAME.
+ '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
+ ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
+ ("PageImage" ("OrgPageImage" nil "page"))
+ ("CaptionedAs-CharImage"
+ ("OrgCaptionedImage"
+ " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
+ ("OrgInlineImage" nil "as-char"))
+ ("CaptionedParagraphImage"
+ ("OrgCaptionedImage"
+ " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
+ ("OrgImageCaptionFrame" nil "paragraph"))
+ ("CaptionedPageImage"
+ ("OrgCaptionedImage"
+ " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
+ ("OrgPageImageCaptionFrame" nil "page"))
+ ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
+ ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
+ ("CaptionedDisplayFormula"
+ ("OrgCaptionedFormula" nil "paragraph")
+ ("OrgFormulaCaptionFrame" nil "paragraph"))))
+ (caption (car captions)) (short-caption (cdr captions))
+ ;; Retrieve inner and outer frame params, from configuration.
+ (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
+ (inner (nth 1 frame-cfg))
+ (outer (nth 2 frame-cfg))
+ ;; User-specified frame params (from #+ATTR_ODT spec)
+ (user user-frame-params)
+ (--merge-frame-params (function
+ (lambda (default user)
+ "Merge default and user frame params."
+ (if (not user) default
+ (cl-assert (= (length default) 3))
+ (cl-assert (= (length user) 3))
+ (cl-loop for u in user
+ for d in default
+ collect (or u d)))))))
+ (cond
+ ;; Case 1: Image/Formula has no caption.
+ ;; There is only one frame, one that surrounds the image
+ ;; or formula.
+ ((not caption)
+ ;; Merge user frame params with that from configuration.
+ (setq inner (funcall --merge-frame-params inner user))
+ (apply 'org-odt--frame href width height
+ (append inner title-and-desc)))
+ ;; Case 2: Image/Formula is captioned or labeled.
+ ;; There are two frames: The inner one surrounds the
+ ;; image or formula. The outer one contains the
+ ;; caption/sequence number.
+ (t
+ ;; Merge user frame params with outer frame params.
+ (setq outer (funcall --merge-frame-params outer user))
+ ;; Short caption, if specified, goes as part of inner frame.
+ (setq inner (let ((frame-params (copy-sequence inner)))
+ (setcar (cdr frame-params)
+ (concat
+ (cadr frame-params)
+ (when short-caption
+ (format " draw:name=\"%s\" " short-caption))))
+ frame-params))
+ (apply 'org-odt--textbox
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Illustration"
+ (concat
+ (apply 'org-odt--frame href width height
+ (append inner title-and-desc))
+ caption))
+ width height outer)))))
+
+(defun org-odt--enumerable-p (element _info)
+ ;; Element should have a caption or label.
+ (or (org-element-property :caption element)
+ (org-element-property :name element)))
+
+(defun org-odt--enumerable-image-p (element info)
+ (org-odt--standalone-link-p
+ element info
+ ;; Paragraph should have a caption or label. It SHOULD NOT be a
+ ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
+ ;; processing.)
+ (lambda (p)
+ (and (not (org-element-property :replaces p))
+ (or (org-element-property :caption p)
+ (org-element-property :name p))))
+ ;; Link should point to an image file.
+ (lambda (l)
+ (cl-assert (eq (org-element-type l) 'link))
+ (org-export-inline-image-p l (plist-get info :odt-inline-image-rules)))))
+
+(defun org-odt--enumerable-latex-image-p (element info)
+ (org-odt--standalone-link-p
+ element info
+ ;; Paragraph should have a caption or label. It SHOULD also be a
+ ;; replacement element. (i.e., It SHOULD be a result of LaTeX
+ ;; processing.)
+ (lambda (p)
+ (and (org-element-property :replaces p)
+ (or (org-element-property :caption p)
+ (org-element-property :name p))))
+ ;; Link should point to an image file.
+ (lambda (l)
+ (cl-assert (eq (org-element-type l) 'link))
+ (org-export-inline-image-p l (plist-get info :odt-inline-image-rules)))))
+
+(defun org-odt--enumerable-formula-p (element info)
+ (org-odt--standalone-link-p
+ element info
+ ;; Paragraph should have a caption or label.
+ (lambda (p)
+ (or (org-element-property :caption p)
+ (org-element-property :name p)))
+ ;; Link should point to a MathML or ODF file.
+ (lambda (l)
+ (cl-assert (eq (org-element-type l) 'link))
+ (org-export-inline-image-p l (plist-get info :odt-inline-formula-rules)))))
+
+(defun org-odt--standalone-link-p (element _info &optional
+ paragraph-predicate
+ link-predicate)
+ "Test if ELEMENT is a standalone link for the purpose ODT export.
+INFO is a plist holding contextual information.
+
+Return non-nil, if ELEMENT is of type paragraph satisfying
+PARAGRAPH-PREDICATE and its sole content, save for whitespaces,
+is a link that satisfies LINK-PREDICATE.
+
+Return non-nil, if ELEMENT is of type link satisfying
+LINK-PREDICATE and its containing paragraph satisfies
+PARAGRAPH-PREDICATE in addition to having no other content save for
+leading and trailing whitespaces.
+
+Return nil, otherwise."
+ (let ((p (cl-case (org-element-type element)
+ (paragraph element)
+ (link (and (or (not link-predicate)
+ (funcall link-predicate element))
+ (org-export-get-parent element)))
+ (t nil))))
+ (when (and p (eq (org-element-type p) 'paragraph))
+ (when (or (not paragraph-predicate)
+ (funcall paragraph-predicate p))
+ (let ((contents (org-element-contents p)))
+ (cl-loop for x in contents
+ with inline-image-count = 0
+ always (cl-case (org-element-type x)
+ (plain-text
+ (not (org-string-nw-p x)))
+ (link
+ (and (or (not link-predicate)
+ (funcall link-predicate x))
+ (= (cl-incf inline-image-count) 1)))
+ (t nil))))))))
+
+(defun org-odt-link--infer-description (destination info)
+ ;; DESTINATION is a headline or an element (like paragraph,
+ ;; verse-block etc) to which a "#+NAME: label" can be attached.
+
+ ;; Note that labels that are attached to captioned entities - inline
+ ;; images, math formulae and tables - get resolved as part of
+ ;; `org-odt-format-label' and `org-odt--enumerate'.
+
+ ;; Create a cross-reference to DESTINATION but make best-efforts to
+ ;; create a *meaningful* description. Check item numbers, section
+ ;; number and section title in that order.
+
+ ;; NOTE: Counterpart of `org-export-get-ordinal'.
+ ;; FIXME: Handle footnote-definition footnote-reference?
+ (let* ((genealogy (org-element-lineage destination))
+ (data (reverse genealogy))
+ (label (let ((type (org-element-type destination)))
+ (if (memq type '(headline target))
+ (org-export-get-reference destination info)
+ (error "FIXME: Unable to resolve %S" destination)))))
+ (or
+ (let* ( ;; Locate top-level list.
+ (top-level-list
+ (cl-loop for x on data
+ when (eq (org-element-type (car x)) 'plain-list)
+ return x))
+ ;; Get list item nos.
+ (item-numbers
+ (cl-loop for (plain-list item . rest) on top-level-list by #'cddr
+ until (not (eq (org-element-type plain-list) 'plain-list))
+ collect (when (eq (org-element-property :type
+ plain-list)
+ 'ordered)
+ (1+ (length (org-export-get-previous-element
+ item info t))))))
+ ;; Locate top-most listified headline.
+ (listified-headlines
+ (cl-loop for x on data
+ when (and (eq (org-element-type (car x)) 'headline)
+ (org-export-low-level-p (car x) info))
+ return x))
+ ;; Get listified headline numbers.
+ (listified-headline-nos
+ (cl-loop for el in listified-headlines
+ when (eq (org-element-type el) 'headline)
+ collect (when (org-export-numbered-headline-p el info)
+ (1+ (length (org-export-get-previous-element
+ el info t)))))))
+ ;; Combine item numbers from both the listified headlines and
+ ;; regular list items.
+
+ ;; Case 1: Check if all the parents of list item are numbered.
+ ;; If yes, link to the item proper.
+ (let ((item-numbers (append listified-headline-nos item-numbers)))
+ (when (and item-numbers (not (memq nil item-numbers)))
+ (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
+ label
+ (mapconcat (lambda (n) (if (not n) " "
+ (concat (number-to-string n) ".")))
+ item-numbers "")))))
+ ;; Case 2: Locate a regular and numbered headline in the
+ ;; hierarchy. Display its section number.
+ (let ((headline
+ (and
+ ;; Test if destination is a numbered headline.
+ (org-export-numbered-headline-p destination info)
+ (cl-loop for el in (cons destination genealogy)
+ when (and (eq (org-element-type el) 'headline)
+ (not (org-export-low-level-p el info))
+ (org-export-numbered-headline-p el info))
+ return el))))
+ ;; We found one.
+ (when headline
+ (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
+ label
+ (mapconcat 'number-to-string (org-export-get-headline-number
+ headline info) "."))))
+ ;; Case 4: Locate a regular headline in the hierarchy. Display
+ ;; its title.
+ (let ((headline (cl-loop for el in (cons destination genealogy)
+ when (and (eq (org-element-type el) 'headline)
+ (not (org-export-low-level-p el info)))
+ return el)))
+ ;; We found one.
+ (when headline
+ (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
+ label
+ (let ((title (org-element-property :title headline)))
+ (org-export-data title info)))))
+ (error "FIXME?"))))
+
+(defun org-odt-link (link desc info)
+ "Transcode a LINK object from Org to ODT.
+
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+ (let* ((type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (and (not (string= desc "")) desc))
+ (imagep (org-export-inline-image-p
+ link (plist-get info :odt-inline-image-rules)))
+ (path (cond
+ ((member type '("http" "https" "ftp" "mailto"))
+ (concat type ":" raw-path))
+ ((string= type "file") (org-export-file-uri raw-path))
+ (t raw-path)))
+ ;; Convert & to &amp; for correct XML representation
+ (path (replace-regexp-in-string "&" "&amp;" path)))
+ (cond
+ ;; Link type is handled by a special function.
+ ((org-export-custom-protocol-maybe link desc 'odt))
+ ;; Image file.
+ ((and (not desc) imagep) (org-odt-link--inline-image link info))
+ ;; Formula file.
+ ((and (not desc)
+ (org-export-inline-image-p
+ link (plist-get info :odt-inline-formula-rules)))
+ (org-odt-link--inline-formula link info))
+ ;; Radio target: Transcode target's contents and use them as
+ ;; link's description.
+ ((string= type "radio")
+ (let ((destination (org-export-resolve-radio-link link info)))
+ (if (not destination) desc
+ (format
+ "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
+ (org-export-get-reference destination info)
+ desc))))
+ ;; Links pointing to a headline: Find destination and build
+ ;; appropriate referencing command.
+ ((member type '("custom-id" "fuzzy" "id"))
+ (let ((destination (if (string= type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (cl-case (org-element-type destination)
+ ;; Fuzzy link points to a headline. If there's
+ ;; a description, create a hyperlink. Otherwise, try to
+ ;; provide a meaningful description.
+ (headline
+ (if (not desc) (org-odt-link--infer-description destination info)
+ (let ((label
+ (or (and (string= type "custom-id")
+ (org-element-property :CUSTOM_ID destination))
+ (org-export-get-reference destination info))))
+ (format
+ "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
+ label desc))))
+ ;; Fuzzy link points to a target. If there's a description,
+ ;; create a hyperlink. Otherwise, try to provide
+ ;; a meaningful description.
+ (target
+ (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
+ (org-export-get-reference destination info)
+ (or desc (org-export-get-ordinal destination info))))
+ ;; Fuzzy link points to some element (e.g., an inline image,
+ ;; a math formula or a table).
+ (otherwise
+ (let ((label-reference
+ (ignore-errors
+ (org-odt-format-label destination info 'reference))))
+ (cond
+ ((not label-reference)
+ (org-odt-link--infer-description destination info))
+ ;; LINK has no description. Create
+ ;; a cross-reference showing entity's sequence
+ ;; number.
+ ((not desc) label-reference)
+ ;; LINK has description. Insert a hyperlink with
+ ;; user-provided description.
+ (t
+ (format
+ "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
+ (org-export-get-reference destination info)
+ desc))))))))
+ ;; Coderef: replace link with the reference name or the
+ ;; equivalent line number.
+ ((string= type "coderef")
+ (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
+ (href (concat "coderef-" path)))
+ (format
+ (org-export-get-coderef-format path desc)
+ (format
+ "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
+ href line-no))))
+ ;; External link with a description part.
+ ((and path desc)
+ (let ((link-contents (org-element-contents link)))
+ ;; Check if description is a link to an inline image.
+ (if (and (not (cdr link-contents))
+ (let ((desc-element (car link-contents)))
+ (and (eq (org-element-type desc-element) 'link)
+ (org-export-inline-image-p
+ desc-element
+ (plist-get info :odt-inline-image-rules)))))
+ ;; Format link as a clickable image.
+ (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
+ path desc)
+ ;; Otherwise, format it as a regular link.
+ (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
+ path desc))))
+ ;; External link without a description part.
+ (path
+ (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
+ path path))
+ ;; No path, only description. Try to do something useful.
+ (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "Emphasis" desc)))))
+
+
+;;;; Node Property
+
+(defun org-odt-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-odt--encode-plain-text
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) "")))))
+
+;;;; Paragraph
+
+(defun org-odt--paragraph-style (paragraph)
+ "Return style of PARAGRAPH.
+Style is a symbol among `quoted', `centered' and nil."
+ (let ((up paragraph))
+ (while (and (setq up (org-element-property :parent up))
+ (not (memq (org-element-type up)
+ '(center-block quote-block section)))))
+ (cl-case (org-element-type up)
+ (center-block 'centered)
+ (quote-block 'quoted))))
+
+(defun org-odt--format-paragraph (paragraph contents info default center quote)
+ "Format paragraph according to given styles.
+PARAGRAPH is a paragraph type element. CONTENTS is the
+transcoded contents of that paragraph, as a string. INFO is
+a plist used as a communication channel. DEFAULT, CENTER and
+QUOTE are, respectively, style to use when paragraph belongs to
+no special environment, a center block, or a quote block."
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ (cl-case (org-odt--paragraph-style paragraph)
+ (quoted quote)
+ (centered center)
+ (otherwise default))
+ ;; If PARAGRAPH is a leading paragraph in an item that has
+ ;; a checkbox, splice checkbox and paragraph contents
+ ;; together.
+ (concat (let ((parent (org-element-property :parent paragraph)))
+ (and (eq (org-element-type parent) 'item)
+ (not (org-export-get-previous-element paragraph info))
+ (org-odt--checkbox parent)))
+ contents)))
+
+(defun org-odt-paragraph (paragraph contents info)
+ "Transcode a PARAGRAPH element from Org to ODT.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ (org-odt--format-paragraph
+ paragraph contents info
+ (or (org-element-property :style paragraph) "Text_20_body")
+ "OrgCenter"
+ "Quotations"))
+
+
+;;;; Plain List
+
+(defun org-odt-plain-list (plain-list contents _info)
+ "Transcode a PLAIN-LIST element from Org to ODT.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
+ ;; Choose style based on list type.
+ (cl-case (org-element-property :type plain-list)
+ (ordered "OrgNumberedList")
+ (unordered "OrgBulletedList")
+ (descriptive-1 "OrgDescriptionList")
+ (descriptive-2 "OrgDescriptionList"))
+ ;; If top-level list, re-start numbering. Otherwise,
+ ;; continue numbering.
+ (format "text:continue-numbering=\"%s\""
+ (let* ((parent (org-export-get-parent plain-list)))
+ (if (and parent (eq (org-element-type parent) 'item))
+ "true" "false")))
+ contents))
+
+;;;; Plain Text
+
+(defun org-odt--encode-tabs-and-spaces (line)
+ (replace-regexp-in-string
+ "\\(\t\\| \\{2,\\}\\)"
+ (lambda (s)
+ (if (string= s "\t") "<text:tab/>"
+ (format " <text:s text:c=\"%d\"/>" (1- (length s)))))
+ line))
+
+(defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
+ (dolist (pair '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
+ (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
+ (if no-whitespace-filling text
+ (org-odt--encode-tabs-and-spaces text)))
+
+(defun org-odt-plain-text (text info)
+ "Transcode a TEXT string from Org to ODT.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ (let ((output text))
+ ;; Protect &, < and >.
+ (setq output (org-odt--encode-plain-text output t))
+ ;; Handle smart quotes. Be sure to provide original string since
+ ;; OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output (org-export-activate-smart-quotes output :utf-8 info text)))
+ ;; Convert special strings.
+ (when (plist-get info :with-special-strings)
+ (dolist (pair org-odt-special-string-regexps)
+ (setq output
+ (replace-regexp-in-string (car pair) (cdr pair) output t nil))))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output (replace-regexp-in-string
+ "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>" output t)))
+ ;; Return value.
+ output))
+
+
+;;;; Planning
+
+(defun org-odt-planning (planning contents info)
+ "Transcode a PLANNING element from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "OrgPlanning"
+ (concat
+ (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgClosedKeyword" org-closed-string)
+ (org-odt-timestamp closed contents info))))
+ (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgDeadlineKeyword" org-deadline-string)
+ (org-odt-timestamp deadline contents info))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgScheduledKeyword" org-deadline-string)
+ (org-odt-timestamp scheduled contents info)))))))
+
+
+;;;; Property Drawer
+
+(defun org-odt-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element from Org to ODT.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format "<text:p text:style-name=\"OrgFixedWidthBlock\">%s</text:p>"
+ contents)))
+
+
+;;;; Quote Block
+
+(defun org-odt-quote-block (_quote-block contents _info)
+ "Transcode a QUOTE-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ contents)
+
+
+;;;; Section
+
+(defun org-odt-format-section (text style &optional name)
+ (let ((default-name (car (org-odt-add-automatic-style "Section"))))
+ (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
+ style
+ (format "text:name=\"%s\"" (or name default-name))
+ text)))
+
+
+(defun org-odt-section (_section contents _info) ; FIXME
+ "Transcode a SECTION element from Org to ODT.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ contents)
+
+;;;; Radio Target
+
+(defun org-odt-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object from Org to ODT.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (org-odt--target text (org-export-get-reference radio-target info)))
+
+
+;;;; Special Block
+
+(defun org-odt-special-block (special-block contents info)
+ "Transcode a SPECIAL-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((type (org-element-property :type special-block))
+ (attributes (org-export-read-attribute :attr_odt special-block)))
+ (cond
+ ;; Annotation.
+ ((string= type "annotation")
+ (let* ((author (or (plist-get attributes :author)
+ (let ((author (plist-get info :author)))
+ (and author (org-export-data author info)))))
+ (date (or (plist-get attributes :date)
+ ;; FIXME: Is `car' right thing to do below?
+ (car (plist-get info :date)))))
+ (format "\n<text:p>%s</text:p>"
+ (format "<office:annotation>\n%s\n</office:annotation>"
+ (concat
+ (and author
+ (format "<dc:creator>%s</dc:creator>" author))
+ (and date
+ (format "<dc:date>%s</dc:date>"
+ (org-odt--format-timestamp date nil 'iso-date)))
+ contents)))))
+ ;; Textbox.
+ ((string= type "textbox")
+ (let ((width (plist-get attributes :width))
+ (height (plist-get attributes :height))
+ (style (plist-get attributes :style))
+ (extra (plist-get attributes :extra))
+ (anchor (plist-get attributes :anchor)))
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Text_20_body" (org-odt--textbox contents width height
+ style extra anchor))))
+ (t contents))))
+
+
+;;;; Src Block
+
+(defun org-odt-hfy-face-to-css (fn)
+ "Create custom style for face FN.
+When FN is the default face, use its foreground and background
+properties to create \"OrgSrcBlock\" paragraph style. Otherwise
+use its color attribute to create a character style whose name
+is obtained from FN. Currently all attributes of FN other than
+color are ignored.
+
+The style name for a face FN is derived using the following
+operations on the face name in that order - de-dash, CamelCase
+and prefix with \"OrgSrc\". For example,
+`font-lock-function-name-face' is associated with
+\"OrgSrcFontLockFunctionNameFace\"."
+ (let* ((css-list (hfy-face-to-style fn))
+ (style-name (concat "OrgSrc"
+ (mapconcat
+ 'capitalize (split-string
+ (hfy-face-or-def-to-name fn) "-")
+ "")))
+ (color-val (cdr (assoc "color" css-list)))
+ (background-color-val (cdr (assoc "background" css-list)))
+ (style (and org-odt-create-custom-styles-for-srcblocks
+ (cond
+ ((eq fn 'default)
+ (format org-odt-src-block-paragraph-format
+ background-color-val color-val))
+ (t
+ (format
+ "
+<style:style style:name=\"%s\" style:family=\"text\">
+ <style:text-properties fo:color=\"%s\"/>
+ </style:style>" style-name color-val))))))
+ (cons style-name style)))
+
+(defun org-odt-htmlfontify-string (line)
+ (let* ((hfy-html-quote-regex "\\([<\"&> \t]\\)")
+ (hfy-html-quote-map '(("\"" "&quot;")
+ ("<" "&lt;")
+ ("&" "&amp;")
+ (">" "&gt;")
+ (" " "<text:s/>")
+ ("\t" "<text:tab/>")))
+ (hfy-face-to-css 'org-odt-hfy-face-to-css)
+ (hfy-optimizations-1 (copy-sequence hfy-optimizations))
+ (hfy-optimizations (cl-pushnew 'body-text-only hfy-optimizations-1))
+ (hfy-begin-span-handler
+ (lambda (style _text-block _text-id _text-begins-block-p)
+ (insert (format "<text:span text:style-name=\"%s\">" style))))
+ (hfy-end-span-handler (lambda () (insert "</text:span>"))))
+ (with-no-warnings (htmlfontify-string line))))
+
+(defun org-odt-do-format-code
+ (code info &optional lang refs retain-labels num-start)
+ (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
+ (lang-mode (and lang (intern (format "%s-mode" lang))))
+ (code-lines (org-split-string code "\n"))
+ (code-length (length code-lines))
+ (use-htmlfontify-p (and (functionp lang-mode)
+ (plist-get info :odt-fontify-srcblocks)
+ (require 'htmlfontify nil t)
+ (fboundp 'htmlfontify-string)))
+ (code (if (not use-htmlfontify-p) code
+ (with-temp-buffer
+ (insert code)
+ (funcall lang-mode)
+ (org-font-lock-ensure)
+ (buffer-string))))
+ (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
+ 'org-odt--encode-plain-text))
+ (par-style (if use-htmlfontify-p "OrgSrcBlock"
+ "OrgFixedWidthBlock"))
+ (i 0))
+ (cl-assert (= code-length (length (org-split-string code "\n"))))
+ (setq code
+ (org-export-format-code
+ code
+ (lambda (loc line-num ref)
+ (setq par-style
+ (concat par-style (and (= (cl-incf i) code-length)
+ "LastLine")))
+
+ (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
+ (setq loc (funcall fontifier loc))
+ (when ref
+ (setq loc (org-odt--target loc (concat "coderef-" ref))))
+ (cl-assert par-style)
+ (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ par-style loc))
+ (if (not line-num) loc
+ (format "\n<text:list-item>%s\n</text:list-item>" loc)))
+ num-start refs))
+ (cond
+ ((not num-start) code)
+ ((= num-start 0)
+ (format
+ "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
+ " text:continue-numbering=\"false\"" code))
+ (t
+ (format
+ "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
+ " text:continue-numbering=\"true\"" code)))))
+
+(defun org-odt-format-code (element info)
+ (let* ((lang (org-element-property :language element))
+ ;; Extract code and references.
+ (code-info (org-export-unravel-code element))
+ (code (car code-info))
+ (refs (cdr code-info))
+ ;; Does the src block contain labels?
+ (retain-labels (org-element-property :retain-labels element))
+ ;; Does it have line numbers?
+ (num-start (org-export-get-loc element info)))
+ (org-odt-do-format-code code info lang refs retain-labels num-start)))
+
+(defun org-odt-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to ODT.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((attributes (org-export-read-attribute :attr_odt src-block))
+ (caption (car (org-odt-format-label src-block info 'definition))))
+ (concat
+ (and caption
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Listing" caption))
+ (let ((--src-block (org-odt-format-code src-block info)))
+ (if (not (plist-get attributes :textbox)) --src-block
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Text_20_body"
+ (org-odt--textbox --src-block nil nil nil)))))))
+
+
+;;;; Statistics Cookie
+
+(defun org-odt-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((cookie-value (org-element-property :value statistics-cookie)))
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgCode" cookie-value)))
+
+
+;;;; Strike-Through
+
+(defun org-odt-strike-through (_strike-through contents _info)
+ "Transcode STRIKE-THROUGH from Org to ODT.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "Strikethrough" contents))
+
+
+;;;; Subscript
+
+(defun org-odt-subscript (_subscript contents _info)
+ "Transcode a SUBSCRIPT object from Org to ODT.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgSubscript" contents))
+
+
+;;;; Superscript
+
+(defun org-odt-superscript (_superscript contents _info)
+ "Transcode a SUPERSCRIPT object from Org to ODT.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgSuperscript" contents))
+
+
+;;;; Table Cell
+
+(defun org-odt-table-style-spec (element info)
+ (let* ((table (org-export-get-parent-table element))
+ (table-attributes (org-export-read-attribute :attr_odt table))
+ (table-style (plist-get table-attributes :style)))
+ (assoc table-style (plist-get info :odt-table-styles))))
+
+(defun org-odt-get-table-cell-styles (table-cell info)
+ "Retrieve styles applicable to a table cell.
+R and C are (zero-based) row and column numbers of the table
+cell. STYLE-SPEC is an entry in `org-odt-table-styles'
+applicable to the current table. It is nil if the table is not
+associated with any style attributes.
+
+Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
+
+When STYLE-SPEC is nil, style the table cell the conventional way
+- choose cell borders based on row and column groupings and
+choose paragraph alignment based on `org-col-cookies' text
+property. See also
+`org-odt-get-paragraph-style-cookie-for-table-cell'.
+
+When STYLE-SPEC is non-nil, ignore the above cookie and return
+styles congruent with the ODF-1.2 specification."
+ (let* ((table-cell-address (org-export-table-cell-address table-cell info))
+ (r (car table-cell-address)) (c (cdr table-cell-address))
+ (style-spec (org-odt-table-style-spec table-cell info))
+ (table-dimensions (org-export-table-dimensions
+ (org-export-get-parent-table table-cell)
+ info)))
+ (when style-spec
+ ;; LibreOffice - particularly the Writer - honors neither table
+ ;; templates nor custom table-cell styles. Inorder to retain
+ ;; inter-operability with LibreOffice, only automatic styles are
+ ;; used for styling of table-cells. The current implementation is
+ ;; congruent with ODF-1.2 specification and hence is
+ ;; future-compatible.
+
+ ;; Additional Note: LibreOffice's AutoFormat facility for tables -
+ ;; which recognizes as many as 16 different cell types - is much
+ ;; richer. Unfortunately it is NOT amenable to easy configuration
+ ;; by hand.
+ (let* ((template-name (nth 1 style-spec))
+ (cell-style-selectors (nth 2 style-spec))
+ (cell-type
+ (cond
+ ((and (cdr (assq 'use-first-column-styles cell-style-selectors))
+ (= c 0)) "FirstColumn")
+ ((and (cdr (assq 'use-last-column-styles cell-style-selectors))
+ (= (1+ c) (cdr table-dimensions)))
+ "LastColumn")
+ ((and (cdr (assq 'use-first-row-styles cell-style-selectors))
+ (= r 0)) "FirstRow")
+ ((and (cdr (assq 'use-last-row-styles cell-style-selectors))
+ (= (1+ r) (car table-dimensions)))
+ "LastRow")
+ ((and (cdr (assq 'use-banding-rows-styles cell-style-selectors))
+ (= (% r 2) 1)) "EvenRow")
+ ((and (cdr (assq 'use-banding-rows-styles cell-style-selectors))
+ (= (% r 2) 0)) "OddRow")
+ ((and (cdr (assq 'use-banding-columns-styles cell-style-selectors))
+ (= (% c 2) 1)) "EvenColumn")
+ ((and (cdr (assq 'use-banding-columns-styles cell-style-selectors))
+ (= (% c 2) 0)) "OddColumn")
+ (t ""))))
+ (concat template-name cell-type)))))
+
+(defun org-odt-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let* ((table-cell-address (org-export-table-cell-address table-cell info))
+ (r (car table-cell-address))
+ (c (cdr table-cell-address))
+ (horiz-span (or (org-export-table-cell-width table-cell info) 0))
+ (table-row (org-export-get-parent table-cell))
+ (custom-style-prefix (org-odt-get-table-cell-styles
+ table-cell info))
+ (paragraph-style
+ (or
+ (and custom-style-prefix
+ (format "%sTableParagraph" custom-style-prefix))
+ (concat
+ (cond
+ ((and (= 1 (org-export-table-row-group table-row info))
+ (org-export-table-has-header-p
+ (org-export-get-parent-table table-row) info))
+ "OrgTableHeading")
+ ((let* ((table (org-export-get-parent-table table-cell))
+ (table-attrs (org-export-read-attribute :attr_odt table))
+ (table-header-columns
+ (let ((cols (plist-get table-attrs :header-columns)))
+ (and cols (read cols)))))
+ (<= c (cond ((wholenump table-header-columns)
+ (- table-header-columns 1))
+ (table-header-columns 0)
+ (t -1))))
+ "OrgTableHeading")
+ (t "OrgTableContents"))
+ (capitalize (symbol-name (org-export-table-cell-alignment
+ table-cell info))))))
+ (cell-style-name
+ (or
+ (and custom-style-prefix (format "%sTableCell"
+ custom-style-prefix))
+ (concat
+ "OrgTblCell"
+ (when (or (org-export-table-row-starts-rowgroup-p table-row info)
+ (zerop r)) "T")
+ (when (org-export-table-row-ends-rowgroup-p table-row info) "B")
+ (when (and (org-export-table-cell-starts-colgroup-p table-cell info)
+ (not (zerop c)) ) "L"))))
+ (cell-attributes
+ (concat
+ (format " table:style-name=\"%s\"" cell-style-name)
+ (and (> horiz-span 0)
+ (format " table:number-columns-spanned=\"%d\""
+ (1+ horiz-span))))))
+ (unless contents (setq contents ""))
+ (concat
+ (cl-assert paragraph-style)
+ (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
+ cell-attributes
+ (let ((table-cell-contents (org-element-contents table-cell)))
+ (if (eq (org-element-class (car table-cell-contents)) 'element)
+ contents
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ paragraph-style contents))))
+ (let (s)
+ (dotimes (_ horiz-span s)
+ (setq s (concat s "\n<table:covered-table-cell/>"))))
+ "\n")))
+
+
+;;;; Table Row
+
+(defun org-odt-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to ODT.
+CONTENTS is the contents of the row. INFO is a plist used as a
+communication channel."
+ ;; Rules are ignored since table separators are deduced from
+ ;; borders of the current row.
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let* ((rowgroup-tags
+ (if (and (= 1 (org-export-table-row-group table-row info))
+ (org-export-table-has-header-p
+ (org-export-get-parent-table table-row) info))
+ ;; If the row belongs to the first rowgroup and the
+ ;; table has more than one row groups, then this row
+ ;; belongs to the header row group.
+ '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
+ ;; Otherwise, it belongs to non-header row group.
+ '("\n<table:table-rows>" . "\n</table:table-rows>"))))
+ (concat
+ ;; Does this row begin a rowgroup?
+ (when (org-export-table-row-starts-rowgroup-p table-row info)
+ (car rowgroup-tags))
+ ;; Actual table row
+ (format "\n<table:table-row>\n%s\n</table:table-row>" contents)
+ ;; Does this row end a rowgroup?
+ (when (org-export-table-row-ends-rowgroup-p table-row info)
+ (cdr rowgroup-tags))))))
+
+
+;;;; Table
+
+(defun org-odt-table-first-row-data-cells (table info)
+ (let ((table-row
+ (org-element-map table 'table-row
+ (lambda (row)
+ (unless (eq (org-element-property :type row) 'rule) row))
+ info 'first-match))
+ (special-column-p (org-export-table-has-special-column-p table)))
+ (if (not special-column-p) (org-element-contents table-row)
+ (cdr (org-element-contents table-row)))))
+
+(defun org-odt--table (table contents info)
+ "Transcode a TABLE element from Org to ODT.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (cl-case (org-element-property :type table)
+ ;; Case 1: table.el doesn't support export to OD format. Strip
+ ;; such tables from export.
+ (table.el
+ (prog1 nil
+ (message
+ (concat
+ "(ox-odt): Found table.el-type table in the source Org file."
+ " table.el doesn't support export to ODT format."
+ " Stripping the table from export."))))
+ ;; Case 2: Native Org tables.
+ (otherwise
+ (let* ((captions (org-odt-format-label table info 'definition))
+ (caption (car captions)) (short-caption (cdr captions))
+ (attributes (org-export-read-attribute :attr_odt table))
+ (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
+ (table-column-specs
+ (lambda (table info)
+ (let* ((table-style (or custom-table-style "OrgTable"))
+ (column-style (format "%sColumn" table-style)))
+ (mapconcat
+ (lambda (table-cell)
+ (let ((width (1+ (or (org-export-table-cell-width
+ table-cell info) 0)))
+ (s (format
+ "\n<table:table-column table:style-name=\"%s\"/>"
+ column-style))
+ out)
+ (dotimes (_ width out) (setq out (concat s out)))))
+ (org-odt-table-first-row-data-cells table info) "\n")))))
+ (concat
+ ;; caption.
+ (when caption
+ (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
+ "Table" caption))
+ ;; begin table.
+ (let* ((automatic-name
+ (org-odt-add-automatic-style "Table" attributes)))
+ (format
+ "\n<table:table table:style-name=\"%s\"%s>"
+ (or custom-table-style (cdr automatic-name) "OrgTable")
+ (concat (when short-caption
+ (format " table:name=\"%s\"" short-caption)))))
+ ;; column specification.
+ (funcall table-column-specs table info)
+ ;; actual contents.
+ "\n" contents
+ ;; end table.
+ "</table:table>")))))
+
+(defun org-odt-table (table contents info)
+ "Transcode a TABLE element from Org to ODT.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information.
+
+Use `org-odt--table' to typeset the table. Handle details
+pertaining to indentation here."
+ (let* ((--element-preceded-by-table-p
+ (lambda (element info)
+ (cl-loop for el in (org-export-get-previous-element element info t)
+ thereis (eq (org-element-type el) 'table))))
+ (--walk-list-genealogy-and-collect-tags
+ (lambda (table info)
+ (let* ((genealogy (org-element-lineage table))
+ (list-genealogy
+ (when (eq (org-element-type (car genealogy)) 'item)
+ (cl-loop for el in genealogy
+ when (memq (org-element-type el)
+ '(item plain-list))
+ collect el)))
+ (llh-genealogy
+ (apply #'nconc
+ (cl-loop
+ for el in genealogy
+ when (and (eq (org-element-type el) 'headline)
+ (org-export-low-level-p el info))
+ collect
+ (list el
+ (assq 'headline
+ (org-element-contents
+ (org-export-get-parent el)))))))
+ parent-list)
+ (nconc
+ ;; Handle list genealogy.
+ (cl-loop
+ for el in list-genealogy collect
+ (cl-case (org-element-type el)
+ (plain-list
+ (setq parent-list el)
+ (cons "</text:list>"
+ (format "\n<text:list text:style-name=\"%s\" %s>"
+ (cl-case (org-element-property :type el)
+ (ordered "OrgNumberedList")
+ (unordered "OrgBulletedList")
+ (descriptive-1 "OrgDescriptionList")
+ (descriptive-2 "OrgDescriptionList"))
+ "text:continue-numbering=\"true\"")))
+ (item
+ (cond
+ ((not parent-list)
+ (if (funcall --element-preceded-by-table-p table info)
+ '("</text:list-header>" . "<text:list-header>")
+ '("</text:list-item>" . "<text:list-header>")))
+ ((funcall --element-preceded-by-table-p
+ parent-list info)
+ '("</text:list-header>" . "<text:list-header>"))
+ (t '("</text:list-item>" . "<text:list-item>"))))))
+ ;; Handle low-level headlines.
+ (cl-loop for el in llh-genealogy
+ with step = 'item collect
+ (cl-case step
+ (plain-list
+ (setq step 'item) ; Flip-flop
+ (setq parent-list el)
+ (cons "</text:list>"
+ (format "\n<text:list text:style-name=\"%s\" %s>"
+ (if (org-export-numbered-headline-p
+ el info)
+ "OrgNumberedList"
+ "OrgBulletedList")
+ "text:continue-numbering=\"true\"")))
+ (item
+ (setq step 'plain-list) ; Flip-flop
+ (cond
+ ((not parent-list)
+ (if (funcall --element-preceded-by-table-p table info)
+ '("</text:list-header>" . "<text:list-header>")
+ '("</text:list-item>" . "<text:list-header>")))
+ ((let ((section? (org-export-get-previous-element
+ parent-list info)))
+ (and section?
+ (eq (org-element-type section?) 'section)
+ (assq 'table (org-element-contents section?))))
+ '("</text:list-header>" . "<text:list-header>"))
+ (t
+ '("</text:list-item>" . "<text:list-item>"))))))))))
+ (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
+ table info)))
+ ;; OpenDocument schema does not permit table to occur within a
+ ;; list item.
+
+ ;; One solution - the easiest and lightweight, in terms of
+ ;; implementation - is to put the table in an indented text box
+ ;; and make the text box part of the list-item. Unfortunately if
+ ;; the table is big and spans multiple pages, the text box could
+ ;; overflow. In this case, the following attribute will come
+ ;; handy.
+
+ ;; ,---- From OpenDocument-v1.1.pdf
+ ;; | 15.27.28 Overflow behavior
+ ;; |
+ ;; | For text boxes contained within text document, the
+ ;; | style:overflow-behavior property specifies the behavior of text
+ ;; | boxes where the containing text does not fit into the text
+ ;; | box.
+ ;; |
+ ;; | If the attribute's value is clip, the text that does not fit
+ ;; | into the text box is not displayed.
+ ;; |
+ ;; | If the attribute value is auto-create-new-frame, a new frame
+ ;; | will be created on the next page, with the same position and
+ ;; | dimensions of the original frame.
+ ;; |
+ ;; | If the style:overflow-behavior property's value is
+ ;; | auto-create-new-frame and the text box has a minimum width or
+ ;; | height specified, then the text box will grow until the page
+ ;; | bounds are reached before a new frame is created.
+ ;; `----
+
+ ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
+ ;; auto-create-new-frame property and always resorts to clipping
+ ;; the text box. This results in table being truncated.
+
+ ;; So we solve the problem the hard (and fun) way using list
+ ;; continuations.
+
+ ;; The problem only becomes more interesting if you take in to
+ ;; account the following facts:
+ ;;
+ ;; - Description lists are simulated as plain lists.
+ ;; - Low-level headlines can be listified.
+ ;; - In Org mode, a table can occur not only as a regular list
+ ;; item, but also within description lists and low-level
+ ;; headlines.
+
+ ;; See `org-odt-translate-description-lists' and
+ ;; `org-odt-translate-low-level-headlines' for how this is
+ ;; tackled.
+
+ (concat "\n"
+ ;; Discontinue the list.
+ (mapconcat 'car close-open-tags "\n")
+ ;; Put the table in an indented section.
+ (let* ((table (org-odt--table table contents info))
+ (level (/ (length (mapcar 'car close-open-tags)) 2))
+ (style (format "OrgIndentedSection-Level-%d" level)))
+ (when table (org-odt-format-section table style)))
+ ;; Continue the list.
+ (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
+
+
+;;;; Target
+
+(defun org-odt-target (target _contents info)
+ "Transcode a TARGET object from Org to ODT.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (org-odt--target "" (org-export-get-reference target info)))
+
+
+;;;; Timestamp
+
+(defun org-odt-timestamp (timestamp _contents info)
+ "Transcode a TIMESTAMP object from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (let ((type (org-element-property :type timestamp)))
+ (if (not (plist-get info :odt-use-date-fields))
+ (let ((value (org-odt-plain-text
+ (org-timestamp-translate timestamp) info)))
+ (cl-case (org-element-property :type timestamp)
+ ((active active-range)
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgActiveTimestamp" value))
+ ((inactive inactive-range)
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgInactiveTimestamp" value))
+ (otherwise value)))
+ (cl-case type
+ (active
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgActiveTimestamp"
+ (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
+ (inactive
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgInactiveTimestamp"
+ (format "[%s]" (org-odt--format-timestamp timestamp))))
+ (active-range
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgActiveTimestamp"
+ (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
+ (org-odt--format-timestamp timestamp)
+ (org-odt--format-timestamp timestamp 'end))))
+ (inactive-range
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgInactiveTimestamp"
+ (format "[%s]&#x2013;[%s]"
+ (org-odt--format-timestamp timestamp)
+ (org-odt--format-timestamp timestamp 'end))))
+ (otherwise
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgDiaryTimestamp"
+ (org-odt-plain-text (org-timestamp-translate timestamp)
+ info)))))))
+
+
+;;;; Underline
+
+(defun org-odt-underline (_underline contents _info)
+ "Transcode UNDERLINE from Org to ODT.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "Underline" contents))
+
+
+;;;; Verbatim
+
+(defun org-odt-verbatim (verbatim _contents _info)
+ "Transcode a VERBATIM object from Org to ODT.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (format "<text:span text:style-name=\"%s\">%s</text:span>"
+ "OrgCode" (org-odt--encode-plain-text
+ (org-element-property :value verbatim))))
+
+
+;;;; Verse Block
+
+(defun org-odt-verse-block (_verse-block contents _info)
+ "Transcode a VERSE-BLOCK element from Org to ODT.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (format "\n<text:p text:style-name=\"OrgVerse\">%s</text:p>"
+ (replace-regexp-in-string
+ ;; Replace leading tabs and spaces.
+ "^[ \t]+" #'org-odt--encode-tabs-and-spaces
+ ;; Add line breaks to each line of verse.
+ (replace-regexp-in-string
+ "\\(<text:line-break/>\\)?[ \t]*$" "<text:line-break/>" contents))))
+
+
+
+;;; Filters
+
+;;;; LaTeX fragments
+
+(defun org-odt--translate-latex-fragments (tree _backend info)
+ (let ((processing-type (plist-get info :with-latex))
+ (count 0))
+ ;; Normalize processing-type to one of dvipng, mathml or verbatim.
+ ;; If the desired converter is not available, force verbatim
+ ;; processing.
+ (cl-case processing-type
+ ((t mathml)
+ (if (and (fboundp 'org-format-latex-mathml-available-p)
+ (org-format-latex-mathml-available-p))
+ (setq processing-type 'mathml)
+ (message "LaTeX to MathML converter not available.")
+ (setq processing-type 'verbatim)))
+ ((dvipng imagemagick)
+ (unless (and (org-check-external-command "latex" "" t)
+ (org-check-external-command
+ (if (eq processing-type 'dvipng) "dvipng" "convert") "" t))
+ (message "LaTeX to PNG converter not available.")
+ (setq processing-type 'verbatim)))
+ (otherwise
+ (message "Unknown LaTeX option. Forcing verbatim.")
+ (setq processing-type 'verbatim)))
+
+ ;; Store normalized value for later use.
+ (when (plist-get info :with-latex)
+ (plist-put info :with-latex processing-type))
+ (message "Formatting LaTeX using %s" processing-type)
+
+ ;; Convert `latex-fragment's and `latex-environment's.
+ (when (memq processing-type '(mathml dvipng imagemagick))
+ (org-element-map tree '(latex-fragment latex-environment)
+ (lambda (latex-*)
+ (cl-incf count)
+ (let* ((latex-frag (org-element-property :value latex-*))
+ (input-file (plist-get info :input-file))
+ (cache-dir (file-name-directory input-file))
+ (cache-subdir (concat
+ (cl-case processing-type
+ ((dvipng imagemagick) "ltxpng/")
+ (mathml "ltxmathml/"))
+ (file-name-sans-extension
+ (file-name-nondirectory input-file))))
+ (display-msg
+ (cl-case processing-type
+ ((dvipng imagemagick)
+ (format "Creating LaTeX Image %d..." count))
+ (mathml (format "Creating MathML snippet %d..." count))))
+ ;; Get an Org-style link to PNG image or the MathML
+ ;; file.
+ (org-link
+ (let ((link (with-temp-buffer
+ (insert latex-frag)
+ (org-format-latex cache-subdir nil nil cache-dir
+ nil display-msg nil
+ processing-type)
+ (buffer-substring-no-properties
+ (point-min) (point-max)))))
+ (if (string-match-p "file:\\([^]]*\\)" link) link
+ (message "LaTeX Conversion failed.")
+ nil))))
+ (when org-link
+ ;; Conversion succeeded. Parse above Org-style link to
+ ;; a `link' object.
+ (let* ((link
+ (org-element-map
+ (org-element-parse-secondary-string org-link '(link))
+ 'link #'identity info t))
+ (replacement
+ (cl-case (org-element-type latex-*)
+ ;; Case 1: LaTeX environment. Mimic
+ ;; a "standalone image or formula" by
+ ;; enclosing the `link' in a `paragraph'.
+ ;; Copy over original attributes, captions to
+ ;; the enclosing paragraph.
+ (latex-environment
+ (org-element-adopt-elements
+ (list 'paragraph
+ (list :style "OrgFormula"
+ :name
+ (org-element-property :name latex-*)
+ :caption
+ (org-element-property :caption latex-*)))
+ link))
+ ;; Case 2: LaTeX fragment. No special action.
+ (latex-fragment link))))
+ ;; Note down the object that link replaces.
+ (org-element-put-property replacement :replaces
+ (list (org-element-type latex-*)
+ (list :value latex-frag)))
+ ;; Restore blank after initial element or object.
+ (org-element-put-property
+ replacement :post-blank
+ (org-element-property :post-blank latex-*))
+ ;; Replace now.
+ (org-element-set-element latex-* replacement)))))
+ info nil nil t)))
+ tree)
+
+
+;;;; Description lists
+
+;; This translator is necessary to handle indented tables in a uniform
+;; manner. See comment in `org-odt--table'.
+
+(defun org-odt--translate-description-lists (tree _backend info)
+ ;; OpenDocument has no notion of a description list. So simulate it
+ ;; using plain lists. Description lists in the exported document
+ ;; are typeset in the same manner as they are in a typical HTML
+ ;; document.
+ ;;
+ ;; Specifically, a description list like this:
+ ;;
+ ;; ,----
+ ;; | - term-1 :: definition-1
+ ;; | - term-2 :: definition-2
+ ;; `----
+ ;;
+ ;; gets translated in to the following form:
+ ;;
+ ;; ,----
+ ;; | - term-1
+ ;; | - definition-1
+ ;; | - term-2
+ ;; | - definition-2
+ ;; `----
+ ;;
+ ;; Further effect is achieved by fixing the OD styles as below:
+ ;;
+ ;; 1. Set the :type property of the simulated lists to
+ ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
+ ;; that has *no* bullets whatsoever.
+ ;;
+ ;; 2. The paragraph containing the definition term is styled to be
+ ;; in bold.
+ ;;
+ (org-element-map tree 'plain-list
+ (lambda (el)
+ (when (eq (org-element-property :type el) 'descriptive)
+ (org-element-set-element
+ el
+ (apply 'org-element-adopt-elements
+ (list 'plain-list (list :type 'descriptive-1))
+ (mapcar
+ (lambda (item)
+ (org-element-adopt-elements
+ (list 'item (list :checkbox (org-element-property
+ :checkbox item)))
+ (list 'paragraph (list :style "Text_20_body_20_bold")
+ (or (org-element-property :tag item) "(no term)"))
+ (org-element-adopt-elements
+ (list 'plain-list (list :type 'descriptive-2))
+ (apply 'org-element-adopt-elements
+ (list 'item nil)
+ (org-element-contents item)))))
+ (org-element-contents el)))))
+ nil)
+ info)
+ tree)
+
+;;;; List tables
+
+;; Lists that are marked with attribute `:list-table' are called as
+;; list tables. They will be rendered as a table within the exported
+;; document.
+
+;; Consider an example. The following list table
+;;
+;; #+attr_odt :list-table t
+;; - Row 1
+;; - 1.1
+;; - 1.2
+;; - 1.3
+;; - Row 2
+;; - 2.1
+;; - 2.2
+;; - 2.3
+;;
+;; will be exported as though it were an Org table like the one show
+;; below.
+;;
+;; | Row 1 | 1.1 | 1.2 | 1.3 |
+;; | Row 2 | 2.1 | 2.2 | 2.3 |
+;;
+;; Note that org-tables are NOT multi-line and each line is mapped to
+;; a unique row in the exported document. So if an exported table
+;; needs to contain a single paragraph (with copious text) it needs to
+;; be typed up in a single line. Editing such long lines using the
+;; table editor will be a cumbersome task. Furthermore inclusion of
+;; multi-paragraph text in a table cell is well-nigh impossible.
+;;
+;; A LIST-TABLE circumvents above problems.
+;;
+;; Note that in the example above the list items could be paragraphs
+;; themselves and the list can be arbitrarily deep.
+;;
+;; Inspired by following thread:
+;; https://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01101.html
+
+;; Translate lists to tables
+
+(defun org-odt--translate-list-tables (tree _backend info)
+ (org-element-map tree 'plain-list
+ (lambda (l1-list)
+ (when (org-export-read-attribute :attr_odt l1-list :list-table)
+ ;; Replace list with table.
+ (org-element-set-element
+ l1-list
+ ;; Build replacement table.
+ (apply 'org-element-adopt-elements
+ (list 'table '(:type org :attr_odt (":style \"GriddedTable\"")))
+ (org-element-map l1-list 'item
+ (lambda (l1-item)
+ (let* ((l1-item-contents (org-element-contents l1-item))
+ l1-item-leading-text l2-list)
+ ;; Remove Level-2 list from the Level-item. It
+ ;; will be subsequently attached as table-cells.
+ (let ((cur l1-item-contents) prev)
+ (while (and cur (not (eq (org-element-type (car cur))
+ 'plain-list)))
+ (setq prev cur)
+ (setq cur (cdr cur)))
+ (when prev
+ (setcdr prev nil)
+ (setq l2-list (car cur)))
+ (setq l1-item-leading-text l1-item-contents))
+ ;; Level-1 items start a table row.
+ (apply 'org-element-adopt-elements
+ (list 'table-row (list :type 'standard))
+ ;; Leading text of level-1 item define
+ ;; the first table-cell.
+ (apply 'org-element-adopt-elements
+ (list 'table-cell nil)
+ l1-item-leading-text)
+ ;; Level-2 items define subsequent
+ ;; table-cells of the row.
+ (org-element-map l2-list 'item
+ (lambda (l2-item)
+ (apply 'org-element-adopt-elements
+ (list 'table-cell nil)
+ (org-element-contents l2-item)))
+ info nil 'item))))
+ info nil 'item))))
+ nil)
+ info)
+ tree)
+
+
+;;; Interactive functions
+
+(defun org-odt-create-manifest-file-entry (&rest args)
+ (push args org-odt-manifest-file-entries))
+
+(defun org-odt-write-manifest-file ()
+ (make-directory (concat org-odt-zip-dir "META-INF"))
+ (let ((manifest-file (concat org-odt-zip-dir "META-INF/manifest.xml")))
+ (with-current-buffer
+ (let ((nxml-auto-insert-xml-declaration-flag nil))
+ (find-file-noselect manifest-file t))
+ (insert
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
+ (dolist (file-entry org-odt-manifest-file-entries)
+ (let* ((version (nth 2 file-entry))
+ (extra (if (not version) ""
+ (format " manifest:version=\"%s\"" version))))
+ (insert
+ (format org-odt-manifest-file-entry-tag
+ (nth 0 file-entry) (nth 1 file-entry) extra))))
+ (insert "\n</manifest:manifest>"))))
+
+(defmacro org-odt--export-wrap (out-file &rest body)
+ `(let* ((--out-file ,out-file)
+ (out-file-type (file-name-extension --out-file))
+ (org-odt-xml-files '("META-INF/manifest.xml" "content.xml"
+ "meta.xml" "styles.xml"))
+ ;; Initialize temporary workarea. All files that end up in
+ ;; the exported document get parked/created here.
+ (org-odt-zip-dir (file-name-as-directory
+ (make-temp-file (format "%s-" out-file-type) t)))
+ (org-odt-manifest-file-entries nil)
+ (--cleanup-xml-buffers
+ (lambda ()
+ ;; Kill all XML buffers.
+ (dolist (file org-odt-xml-files)
+ (let ((buf (find-buffer-visiting
+ (concat org-odt-zip-dir file))))
+ (when buf
+ (with-current-buffer buf
+ (set-buffer-modified-p nil)
+ (kill-buffer buf)))))
+ ;; Delete temporary directory and also other embedded
+ ;; files that get copied there.
+ (delete-directory org-odt-zip-dir t))))
+ (condition-case err
+ (progn
+ (unless (executable-find "zip")
+ ;; Not at all OSes ship with zip by default
+ (error "Executable \"zip\" needed for creating OpenDocument files"))
+ ;; Do export. This creates a bunch of xml files ready to be
+ ;; saved and zipped.
+ (progn ,@body)
+ ;; Create a manifest entry for content.xml.
+ (org-odt-create-manifest-file-entry "text/xml" "content.xml")
+ ;; Write mimetype file
+ (let* ((mimetypes
+ '(("odt" . "application/vnd.oasis.opendocument.text")
+ ("odf" . "application/vnd.oasis.opendocument.formula")))
+ (mimetype (cdr (assoc-string out-file-type mimetypes t))))
+ (unless mimetype
+ (error "Unknown OpenDocument backend %S" out-file-type))
+ (write-region mimetype nil (concat org-odt-zip-dir "mimetype"))
+ (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
+ ;; Write out the manifest entries before zipping
+ (org-odt-write-manifest-file)
+ ;; Save all XML files.
+ (dolist (file org-odt-xml-files)
+ (let ((buf (find-buffer-visiting
+ (concat org-odt-zip-dir file))))
+ (when buf
+ (with-current-buffer buf
+ ;; Prettify output if needed.
+ (when org-odt-prettify-xml
+ (indent-region (point-min) (point-max)))
+ (save-buffer 0)))))
+ ;; Run zip.
+ (let* ((target --out-file)
+ (target-name (file-name-nondirectory target))
+ (cmds `(("zip" "-mX0" ,target-name "mimetype")
+ ("zip" "-rmTq" ,target-name "."))))
+ ;; If a file with same name as the desired output file
+ ;; exists, remove it.
+ (when (file-exists-p target)
+ (delete-file target))
+ ;; Zip up the xml files.
+ (let ((coding-system-for-write 'no-conversion) exitcode err-string)
+ (message "Creating ODT file...")
+ ;; Switch temporarily to content.xml. This way Zip
+ ;; process will inherit `org-odt-zip-dir' as the current
+ ;; directory.
+ (with-current-buffer
+ (find-file-noselect (concat org-odt-zip-dir "content.xml") t)
+ (dolist (cmd cmds)
+ (message "Running %s" (mapconcat 'identity cmd " "))
+ (setq err-string
+ (with-output-to-string
+ (setq exitcode
+ (apply 'call-process (car cmd)
+ nil standard-output nil (cdr cmd)))))
+ (or (zerop exitcode)
+ (error (concat "Unable to create OpenDocument file."
+ " Zip failed with error (%s)")
+ err-string)))))
+ ;; Move the zip file from temporary work directory to
+ ;; user-mandated location.
+ (rename-file (concat org-odt-zip-dir target-name) target)
+ (message "Created %s" (expand-file-name target))
+ ;; Cleanup work directory and work files.
+ (funcall --cleanup-xml-buffers)
+ ;; Open the OpenDocument file in archive-mode for
+ ;; examination.
+ (find-file-noselect target t)
+ ;; Return exported file.
+ (cond
+ ;; Case 1: Conversion desired on exported file. Run the
+ ;; converter on the OpenDocument file. Return the
+ ;; converted file.
+ (org-odt-preferred-output-format
+ (or (org-odt-convert target org-odt-preferred-output-format)
+ target))
+ ;; Case 2: No further conversion. Return exported
+ ;; OpenDocument file.
+ (t target))))
+ (error
+ ;; Cleanup work directory and work files.
+ (funcall --cleanup-xml-buffers)
+ (message "OpenDocument export failed: %s"
+ (error-message-string err))))))
+
+
+;;;; Export to OpenDocument formula
+
+;;;###autoload
+(defun org-odt-export-as-odf (latex-frag &optional odf-file)
+ "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
+Use `org-create-math-formula' to convert LATEX-FRAG first to
+MathML. When invoked as an interactive command, use
+`org-latex-regexps' to infer LATEX-FRAG from currently active
+region. If no LaTeX fragments are found, prompt for it. Push
+MathML source to kill ring depending on the value of
+`org-export-copy-to-kill-ring'."
+ (interactive
+ `(,(let (frag)
+ (setq frag (and (setq frag (and (region-active-p)
+ (buffer-substring (region-beginning)
+ (region-end))))
+ (cl-loop for e in org-latex-regexps
+ thereis (when (string-match (nth 1 e) frag)
+ (match-string (nth 2 e) frag)))))
+ (read-string "LaTeX Fragment: " frag nil frag))
+ ,(let ((odf-filename (expand-file-name
+ (concat
+ (file-name-sans-extension
+ (or (file-name-nondirectory buffer-file-name)))
+ "." "odf")
+ (file-name-directory buffer-file-name))))
+ (read-file-name "ODF filename: " nil odf-filename nil
+ (file-name-nondirectory odf-filename)))))
+ (let ((filename (or odf-file
+ (expand-file-name
+ (concat
+ (file-name-sans-extension
+ (or (file-name-nondirectory buffer-file-name)))
+ "." "odf")
+ (file-name-directory buffer-file-name)))))
+ (org-odt--export-wrap
+ filename
+ (let* ((buffer (progn
+ (require 'nxml-mode)
+ (let ((nxml-auto-insert-xml-declaration-flag nil))
+ (find-file-noselect (concat org-odt-zip-dir
+ "content.xml") t))))
+ (coding-system-for-write 'utf-8)
+ (save-buffer-coding-system 'utf-8))
+ (set-buffer buffer)
+ (set-buffer-file-coding-system coding-system-for-write)
+ (let ((mathml (org-create-math-formula latex-frag)))
+ (unless mathml (error "No Math formula created"))
+ (insert mathml)
+ ;; Add MathML to kill ring, if needed.
+ (when (org-export--copy-to-kill-ring-p)
+ (org-kill-new (buffer-string))))))))
+
+;;;###autoload
+(defun org-odt-export-as-odf-and-open ()
+ "Export LaTeX fragment as OpenDocument formula and immediately open it.
+Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
+formula file."
+ (interactive)
+ (org-open-file (call-interactively 'org-odt-export-as-odf) 'system))
+
+
+;;;; Export to OpenDocument Text
+
+;;;###autoload
+(defun org-odt-export-to-odt (&optional async subtreep visible-only ext-plist)
+ "Export current buffer to a ODT file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".odt" subtreep)))
+ (if async
+ (org-export-async-start (lambda (f) (org-export-add-to-stack f 'odt))
+ `(expand-file-name
+ (org-odt--export-wrap
+ ,outfile
+ (let* ((org-odt-embedded-images-count 0)
+ (org-odt-embedded-formulas-count 0)
+ (org-odt-automatic-styles nil)
+ (org-odt-object-counters nil)
+ ;; Let `htmlfontify' know that we are interested in
+ ;; collecting styles.
+ (hfy-user-sheet-assoc nil))
+ ;; Initialize content.xml and kick-off the export
+ ;; process.
+ (let ((out-buf
+ (progn
+ (require 'nxml-mode)
+ (let ((nxml-auto-insert-xml-declaration-flag nil))
+ (find-file-noselect
+ (concat org-odt-zip-dir "content.xml") t))))
+ (output (org-export-as
+ 'odt ,subtreep ,visible-only nil ,ext-plist)))
+ (with-current-buffer out-buf
+ (erase-buffer)
+ (insert output)))))))
+ (org-odt--export-wrap
+ outfile
+ (let* ((org-odt-embedded-images-count 0)
+ (org-odt-embedded-formulas-count 0)
+ (org-odt-automatic-styles nil)
+ (org-odt-object-counters nil)
+ ;; Let `htmlfontify' know that we are interested in collecting
+ ;; styles.
+ (hfy-user-sheet-assoc nil))
+ ;; Initialize content.xml and kick-off the export process.
+ (let ((output (org-export-as 'odt subtreep visible-only nil ext-plist))
+ (out-buf (progn
+ (require 'nxml-mode)
+ (let ((nxml-auto-insert-xml-declaration-flag nil))
+ (find-file-noselect
+ (concat org-odt-zip-dir "content.xml") t)))))
+ (with-current-buffer out-buf (erase-buffer) (insert output))))))))
+
+
+;;;; Convert between OpenDocument and other formats
+
+(defun org-odt-reachable-p (in-fmt out-fmt)
+ "Return non-nil if IN-FMT can be converted to OUT-FMT."
+ (catch 'done
+ (let ((reachable-formats (org-odt-do-reachable-formats in-fmt)))
+ (dolist (e reachable-formats)
+ (let ((out-fmt-spec (assoc out-fmt (cdr e))))
+ (when out-fmt-spec
+ (throw 'done (cons (car e) out-fmt-spec))))))))
+
+(defun org-odt-do-convert (in-file out-fmt &optional open)
+ "Workhorse routine for `org-odt-convert'."
+ (require 'browse-url)
+ (let* ((in-file (let ((f (expand-file-name (or in-file buffer-file-name))))
+ (if (file-readable-p f) f
+ (error "Cannot read %s" in-file))))
+ (in-fmt (file-name-extension in-file))
+ (out-fmt (or out-fmt (error "Output format unspecified")))
+ (how (or (org-odt-reachable-p in-fmt out-fmt)
+ (error "Cannot convert from %s format to %s format?"
+ in-fmt out-fmt)))
+ (convert-process (car how))
+ (out-file (concat (file-name-sans-extension in-file) "."
+ (nth 1 (or (cdr how) out-fmt))))
+ (extra-options (or (nth 2 (cdr how)) ""))
+ (out-dir (file-name-directory in-file))
+ (cmd (format-spec convert-process
+ `((?i . ,(shell-quote-argument in-file))
+ (?I . ,(browse-url-file-url in-file))
+ (?f . ,out-fmt)
+ (?o . ,out-file)
+ (?O . ,(browse-url-file-url out-file))
+ (?d . , (shell-quote-argument out-dir))
+ (?D . ,(browse-url-file-url out-dir))
+ (?x . ,extra-options)))))
+ (when (file-exists-p out-file)
+ (delete-file out-file))
+
+ (message "Executing %s" cmd)
+ (let ((cmd-output (shell-command-to-string cmd)))
+ (message "%s" cmd-output))
+
+ (cond
+ ((file-exists-p out-file)
+ (message "Exported to %s" out-file)
+ (when open
+ (message "Opening %s..." out-file)
+ (org-open-file out-file 'system))
+ out-file)
+ (t
+ (message "Export to %s failed" out-file)
+ nil))))
+
+(defun org-odt-do-reachable-formats (in-fmt)
+ "Return verbose info about formats to which IN-FMT can be converted.
+Return a list where each element is of the
+form (CONVERTER-PROCESS . OUTPUT-FMT-ALIST). See
+`org-odt-convert-processes' for CONVERTER-PROCESS and see
+`org-odt-convert-capabilities' for OUTPUT-FMT-ALIST."
+ (let* ((converter
+ (and org-odt-convert-process
+ (cadr (assoc-string org-odt-convert-process
+ org-odt-convert-processes t))))
+ (capabilities
+ (and org-odt-convert-process
+ (cadr (assoc-string org-odt-convert-process
+ org-odt-convert-processes t))
+ org-odt-convert-capabilities))
+ reachable-formats)
+ (when converter
+ (dolist (c capabilities)
+ (when (member in-fmt (nth 1 c))
+ (push (cons converter (nth 2 c)) reachable-formats))))
+ reachable-formats))
+
+(defun org-odt-reachable-formats (in-fmt)
+ "Return list of formats to which IN-FMT can be converted.
+The list of the form (OUTPUT-FMT-1 OUTPUT-FMT-2 ...)."
+ (copy-sequence
+ (apply #'append (mapcar
+ (lambda (e) (mapcar #'car (cdr e)))
+ (org-odt-do-reachable-formats in-fmt)))))
+
+(defun org-odt-convert-read-params ()
+ "Return IN-FILE and OUT-FMT params for `org-odt-do-convert'.
+This is a helper routine for interactive use."
+ (let* ((input (if (featurep 'ido) 'ido-completing-read 'completing-read))
+ (in-file (read-file-name "File to be converted: "
+ nil buffer-file-name t))
+ (in-fmt (file-name-extension in-file))
+ (out-fmt-choices (org-odt-reachable-formats in-fmt))
+ (out-fmt
+ (or (and out-fmt-choices
+ (funcall input "Output format: "
+ out-fmt-choices nil nil nil))
+ (error
+ "No known converter or no known output formats for %s files"
+ in-fmt))))
+ (list in-file out-fmt)))
+
+;;;###autoload
+(defun org-odt-convert (&optional in-file out-fmt open)
+ "Convert IN-FILE to format OUT-FMT using a command line converter.
+IN-FILE is the file to be converted. If unspecified, it defaults
+to variable `buffer-file-name'. OUT-FMT is the desired output
+format. Use `org-odt-convert-process' as the converter. If OPEN
+is non-nil then the newly converted file is opened using
+`org-open-file'."
+ (interactive
+ (append (org-odt-convert-read-params) current-prefix-arg))
+ (org-odt-do-convert in-file out-fmt open))
+
+;;; Library Initializations
+
+(dolist (desc org-odt-file-extensions)
+ ;; Let Emacs open all OpenDocument files in archive mode.
+ (add-to-list 'auto-mode-alist
+ (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
+
+(provide 'ox-odt)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-odt.el ends here
diff --git a/lisp/ox-org.el b/lisp/ox-org.el
new file mode 100644
index 0000000..a52ecc8
--- /dev/null
+++ b/lisp/ox-org.el
@@ -0,0 +1,352 @@
+;;; ox-org.el --- Org Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2013-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
+;; Keywords: org, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;;; Code:
+
+(require 'ox)
+(declare-function htmlize-buffer "ext:htmlize" (&optional buffer))
+(defvar htmlize-output-type)
+
+(defgroup org-export-org nil
+ "Options for exporting Org mode files to Org."
+ :tag "Org Export Org"
+ :group 'org-export
+ :version "24.4"
+ :package-version '(Org . "8.0"))
+
+(defcustom org-org-htmlized-css-url nil
+ "URL pointing to the CSS defining colors for htmlized Emacs buffers.
+Normally when creating an htmlized version of an Org buffer,
+htmlize will create the CSS to define the font colors. However,
+this does not work when converting in batch mode, and it also can
+look bad if different people with different fontification setup
+work on the same website. When this variable is non-nil,
+creating an htmlized version of an Org buffer using
+`org-org-export-as-org' will include a link to this URL if the
+setting of `org-html-htmlize-output-type' is `css'."
+ :group 'org-export-org
+ :type '(choice
+ (const :tag "Don't include external stylesheet link" nil)
+ (string :tag "URL or local href")))
+
+(org-export-define-backend 'org
+ '((babel-call . org-org-identity)
+ (bold . org-org-identity)
+ (center-block . org-org-identity)
+ (clock . org-org-identity)
+ (code . org-org-identity)
+ (diary-sexp . org-org-identity)
+ (drawer . org-org-identity)
+ (dynamic-block . org-org-identity)
+ (entity . org-org-identity)
+ (example-block . org-org-identity)
+ (export-block . org-org-export-block)
+ (fixed-width . org-org-identity)
+ (footnote-definition . ignore)
+ (footnote-reference . org-org-identity)
+ (headline . org-org-headline)
+ (horizontal-rule . org-org-identity)
+ (inline-babel-call . org-org-identity)
+ (inline-src-block . org-org-identity)
+ (inlinetask . org-org-identity)
+ (italic . org-org-identity)
+ (item . org-org-identity)
+ (keyword . org-org-keyword)
+ (latex-environment . org-org-identity)
+ (latex-fragment . org-org-identity)
+ (line-break . org-org-identity)
+ (link . org-org-link)
+ (node-property . org-org-identity)
+ (template . org-org-template)
+ (paragraph . org-org-identity)
+ (plain-list . org-org-identity)
+ (planning . org-org-identity)
+ (property-drawer . org-org-identity)
+ (quote-block . org-org-identity)
+ (radio-target . org-org-identity)
+ (section . org-org-section)
+ (special-block . org-org-identity)
+ (src-block . org-org-identity)
+ (statistics-cookie . org-org-identity)
+ (strike-through . org-org-identity)
+ (subscript . org-org-identity)
+ (superscript . org-org-identity)
+ (table . org-org-identity)
+ (table-cell . org-org-identity)
+ (table-row . org-org-identity)
+ (target . org-org-identity)
+ (timestamp . org-org-identity)
+ (underline . org-org-identity)
+ (verbatim . org-org-identity)
+ (verse-block . org-org-identity))
+ :menu-entry
+ '(?O "Export to Org"
+ ((?O "As Org buffer" org-org-export-as-org)
+ (?o "As Org file" org-org-export-to-org)
+ (?v "As Org file and open"
+ (lambda (a s v b)
+ (if a (org-org-export-to-org t s v b)
+ (org-open-file (org-org-export-to-org nil s v b)))))))
+ :filters-alist '((:filter-parse-tree . org-org--add-missing-sections)))
+
+(defun org-org--add-missing-sections (tree _backend _info)
+ "Ensure each headline has an associated section.
+
+TREE is the parse tree being exported.
+
+Footnotes relative to the headline are inserted in the section,
+using `org-org-section'. However, this function is not called if
+the headline doesn't contain any section in the first place, so
+we make sure it is always called."
+ (org-element-map tree 'headline
+ (lambda (h)
+ (let ((first-child (car (org-element-contents h)))
+ (new-section (org-element-create 'section)))
+ (pcase (org-element-type first-child)
+ (`section nil)
+ (`nil (org-element-adopt-elements h new-section))
+ (_ (org-element-insert-before new-section first-child))))))
+ tree)
+
+(defun org-org-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to LaTeX.
+CONTENTS and INFO are ignored."
+ (and (equal (org-element-property :type export-block) "ORG")
+ (org-element-property :value export-block)))
+
+(defun org-org-identity (blob contents _info)
+ "Transcode BLOB element or object back into Org syntax.
+CONTENTS is its contents, as a string or nil. INFO is ignored."
+ (let ((case-fold-search t))
+ (replace-regexp-in-string
+ "^[ \t]*#\\+ATTR_[-_A-Za-z0-9]+:\\(?: .*\\)?\n" ""
+ (org-export-expand blob contents t))))
+
+(defun org-org-headline (headline contents info)
+ "Transcode HEADLINE element back into Org syntax.
+CONTENTS is its contents, as a string or nil. INFO is ignored."
+ (unless (org-element-property :footnote-section-p headline)
+ (unless (plist-get info :with-todo-keywords)
+ (org-element-put-property headline :todo-keyword nil))
+ (unless (plist-get info :with-tags)
+ (org-element-put-property headline :tags nil))
+ (unless (plist-get info :with-priority)
+ (org-element-put-property headline :priority nil))
+ (org-element-put-property headline :level
+ (org-export-get-relative-level headline info))
+ (org-element-headline-interpreter headline contents)))
+
+(defun org-org-keyword (keyword _contents _info)
+ "Transcode KEYWORD element back into Org syntax.
+CONTENTS is nil. INFO is ignored."
+ (let ((key (org-element-property :key keyword)))
+ (unless (member key
+ '("AUTHOR" "CREATOR" "DATE" "EMAIL" "OPTIONS" "TITLE"))
+ (org-element-keyword-interpreter keyword nil))))
+
+(defun org-org-link (link contents _info)
+ "Transcode LINK object back into Org syntax.
+CONTENTS is the description of the link, as a string, or nil.
+INFO is a plist containing current export state."
+ (or (org-export-custom-protocol-maybe link contents 'org)
+ (org-element-link-interpreter link contents)))
+
+(defun org-org-template (contents info)
+ "Return Org document template with document keywords.
+CONTENTS is the transcoded contents string. INFO is a plist used
+as a communication channel."
+ (concat
+ (and (plist-get info :time-stamp-file)
+ (format-time-string "# Created %Y-%m-%d %a %H:%M\n"))
+ (org-element-normalize-string
+ (mapconcat #'identity
+ (org-element-map (plist-get info :parse-tree) 'keyword
+ (lambda (k)
+ (and (string-equal (org-element-property :key k) "OPTIONS")
+ (concat "#+OPTIONS: "
+ (org-element-property :value k)))))
+ "\n"))
+ (and (plist-get info :with-title)
+ (format "#+TITLE: %s\n" (org-export-data (plist-get info :title) info)))
+ (and (plist-get info :with-date)
+ (let ((date (org-export-data (org-export-get-date info) info)))
+ (and (org-string-nw-p date)
+ (format "#+DATE: %s\n" date))))
+ (and (plist-get info :with-author)
+ (let ((author (org-export-data (plist-get info :author) info)))
+ (and (org-string-nw-p author)
+ (format "#+AUTHOR: %s\n" author))))
+ (and (plist-get info :with-email)
+ (let ((email (org-export-data (plist-get info :email) info)))
+ (and (org-string-nw-p email)
+ (format "#+EMAIL: %s\n" email))))
+ (and (plist-get info :with-creator)
+ (org-string-nw-p (plist-get info :creator))
+ (format "#+CREATOR: %s\n" (plist-get info :creator)))
+ contents))
+
+(defun org-org-section (section contents info)
+ "Transcode SECTION element back into Org syntax.
+CONTENTS is the contents of the section. INFO is a plist used as
+a communication channel."
+ (concat
+ (org-element-normalize-string contents)
+ ;; Insert footnote definitions appearing for the first time in this
+ ;; section, or in the relative headline title. Indeed, some of
+ ;; them may not be available to narrowing so we make sure all of
+ ;; them are included in the result.
+ (let ((footnotes
+ (org-element-map
+ (list (org-export-get-parent-headline section) section)
+ 'footnote-reference
+ (lambda (fn)
+ (and (eq (org-element-property :type fn) 'standard)
+ (org-export-footnote-first-reference-p fn info)
+ (org-element-normalize-string
+ (format "[fn:%s] %s"
+ (org-element-property :label fn)
+ (org-export-data
+ (org-export-get-footnote-definition fn info)
+ info)))))
+ info nil 'headline t)))
+ (and footnotes (concat "\n" (mapconcat #'identity footnotes "\n"))))))
+
+;;;###autoload
+(defun org-org-export-as-org
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to an Org buffer.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should be accessible
+through the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip document
+keywords from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Export is done in a buffer named \"*Org ORG Export*\", which will
+be displayed when `org-export-show-temporary-export-buffer' is
+non-nil."
+ (interactive)
+ (org-export-to-buffer 'org "*Org ORG Export*"
+ async subtreep visible-only body-only ext-plist (lambda () (org-mode))))
+
+;;;###autoload
+(defun org-org-export-to-org
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to an org file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, strip document
+keywords from output.
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".org" subtreep)))
+ (org-export-to-file 'org outfile
+ async subtreep visible-only body-only ext-plist)))
+
+;;;###autoload
+(defun org-org-publish-to-org (plist filename pub-dir)
+ "Publish an org file to org.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'org filename ".org" plist pub-dir)
+ (when (plist-get plist :htmlized-source)
+ (require 'htmlize)
+ (require 'ox-html)
+ (let* ((org-inhibit-startup t)
+ (htmlize-output-type 'css)
+ (html-ext (concat "." (or (plist-get plist :html-extension)
+ org-html-extension "html")))
+ (visitingp (find-buffer-visiting filename))
+ (work-buffer (or visitingp (find-file-noselect filename)))
+ newbuf)
+ (with-current-buffer work-buffer
+ (org-font-lock-ensure)
+ (outline-show-all)
+ (org-show-block-all)
+ (setq newbuf (htmlize-buffer)))
+ (with-current-buffer newbuf
+ (when org-org-htmlized-css-url
+ (goto-char (point-min))
+ (and (re-search-forward
+ "<style type=\"text/css\">[^\000]*?\n[ \t]*</style>.*" nil t)
+ (replace-match
+ (format
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">"
+ org-org-htmlized-css-url)
+ t t)))
+ (write-file (concat pub-dir (file-name-nondirectory filename) html-ext)))
+ (kill-buffer newbuf)
+ (unless visitingp (kill-buffer work-buffer)))
+ ;; FIXME: Why? Which buffer is this supposed to apply to?
+ (set-buffer-modified-p nil)))
+
+
+(provide 'ox-org)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-org.el ends here
diff --git a/lisp/ox-publish.el b/lisp/ox-publish.el
new file mode 100644
index 0000000..884d6bf
--- /dev/null
+++ b/lisp/ox-publish.el
@@ -0,0 +1,1333 @@
+;;; ox-publish.el --- Publish Related Org Mode Files as a Website -*- lexical-binding: t; -*-
+;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
+
+;; Author: David O'Toole <dto@gnu.org>
+;; Maintainer: Carsten Dominik <carsten DOT dominik AT gmail DOT com>
+;; Keywords: hypermedia, outlines, wp
+
+;; This file is part of GNU Emacs.
+;;
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+
+;; This program allow configurable publishing of related sets of
+;; Org mode files as a complete website.
+;;
+;; ox-publish.el can do the following:
+;;
+;; + Publish all one's Org files to a given export back-end
+;; + Upload HTML, images, attachments and other files to a web server
+;; + Exclude selected private pages from publishing
+;; + Publish a clickable sitemap of pages
+;; + Manage local timestamps for publishing only changed files
+;; + Accept plugin functions to extend range of publishable content
+;;
+;; Documentation for publishing is in the manual.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'format-spec)
+(require 'ox)
+
+
+
+;;; Variables
+
+(defvar org-publish-temp-files nil
+ "Temporary list of files to be published.")
+
+;; Here, so you find the variable right before it's used the first time:
+(defvar org-publish-cache nil
+ "This will cache timestamps and titles for files in publishing projects.
+Blocks could hash sha1 values here.")
+
+(defvar org-publish-after-publishing-hook nil
+ "Hook run each time a file is published.
+Every function in this hook will be called with two arguments:
+the name of the original file and the name of the file
+produced.")
+
+(defgroup org-publish nil
+ "Options for publishing a set of files."
+ :tag "Org Publishing"
+ :group 'org)
+
+(defcustom org-publish-project-alist nil
+ "Association list to control publishing behavior.
+\\<org-mode-map>
+Each element of the alist is a publishing project. The car of
+each element is a string, uniquely identifying the project. The
+cdr of each element is in one of the following forms:
+
+1. A well-formed property list with an even number of elements,
+ alternating keys and values, specifying parameters for the
+ publishing process.
+
+ (:property value :property value ... )
+
+2. A meta-project definition, specifying of a list of
+ sub-projects:
+
+ (:components (\"project-1\" \"project-2\" ...))
+
+When the CDR of an element of org-publish-project-alist is in
+this second form, the elements of the list after `:components'
+are taken to be components of the project, which group together
+files requiring different publishing options. When you publish
+such a project with `\\[org-publish]', the components all publish.
+
+When a property is given a value in `org-publish-project-alist',
+its setting overrides the value of the corresponding user
+variable (if any) during publishing. However, options set within
+a file override everything.
+
+Most properties are optional, but some should always be set:
+
+ `:base-directory'
+
+ Directory containing publishing source files.
+
+ `:base-extension'
+
+ Extension (without the dot!) of source files. This can be
+ a regular expression. If not given, \"org\" will be used as
+ default extension. If it is `any', include all the files,
+ even without extension.
+
+ `:publishing-directory'
+
+ Directory (possibly remote) where output files will be
+ published.
+
+If `:recursive' is non-nil files in sub-directories of
+`:base-directory' are considered.
+
+The `:exclude' property may be used to prevent certain files from
+being published. Its value may be a string or regexp matching
+file names you don't want to be published.
+
+The `:include' property may be used to include extra files. Its
+value may be a list of filenames to include. The filenames are
+considered relative to the base directory.
+
+When both `:include' and `:exclude' properties are given values,
+the exclusion step happens first.
+
+One special property controls which back-end function to use for
+publishing files in the project. This can be used to extend the
+set of file types publishable by `org-publish', as well as the
+set of output formats.
+
+ `:publishing-function'
+
+ Function to publish file. Each back-end may define its
+ own (i.e. `org-latex-publish-to-pdf',
+ `org-html-publish-to-html'). May be a list of functions, in
+ which case each function in the list is invoked in turn.
+
+Another property allows you to insert code that prepares
+a project for publishing. For example, you could call GNU Make
+on a certain makefile, to ensure published files are built up to
+date.
+
+ `:preparation-function'
+
+ Function to be called before publishing this project. This
+ may also be a list of functions. Preparation functions are
+ called with the project properties list as their sole
+ argument.
+
+ `:completion-function'
+
+ Function to be called after publishing this project. This
+ may also be a list of functions. Completion functions are
+ called with the project properties list as their sole
+ argument.
+
+Some properties control details of the Org publishing process,
+and are equivalent to the corresponding user variables listed in
+the right column. Back-end specific properties may also be
+included. See the back-end documentation for more information.
+
+ :author `user-full-name'
+ :creator `org-export-creator-string'
+ :email `user-mail-address'
+ :exclude-tags `org-export-exclude-tags'
+ :headline-levels `org-export-headline-levels'
+ :language `org-export-default-language'
+ :preserve-breaks `org-export-preserve-breaks'
+ :section-numbers `org-export-with-section-numbers'
+ :select-tags `org-export-select-tags'
+ :time-stamp-file `org-export-time-stamp-file'
+ :with-archived-trees `org-export-with-archived-trees'
+ :with-author `org-export-with-author'
+ :with-creator `org-export-with-creator'
+ :with-date `org-export-with-date'
+ :with-drawers `org-export-with-drawers'
+ :with-email `org-export-with-email'
+ :with-emphasize `org-export-with-emphasize'
+ :with-entities `org-export-with-entities'
+ :with-fixed-width `org-export-with-fixed-width'
+ :with-footnotes `org-export-with-footnotes'
+ :with-inlinetasks `org-export-with-inlinetasks'
+ :with-latex `org-export-with-latex'
+ :with-planning `org-export-with-planning'
+ :with-priority `org-export-with-priority'
+ :with-properties `org-export-with-properties'
+ :with-smart-quotes `org-export-with-smart-quotes'
+ :with-special-strings `org-export-with-special-strings'
+ :with-statistics-cookies' `org-export-with-statistics-cookies'
+ :with-sub-superscript `org-export-with-sub-superscripts'
+ :with-toc `org-export-with-toc'
+ :with-tables `org-export-with-tables'
+ :with-tags `org-export-with-tags'
+ :with-tasks `org-export-with-tasks'
+ :with-timestamps `org-export-with-timestamps'
+ :with-title `org-export-with-title'
+ :with-todo-keywords `org-export-with-todo-keywords'
+
+The following properties may be used to control publishing of
+a site-map of files or summary page for a given project.
+
+ `:auto-sitemap'
+
+ Whether to publish a site-map during
+ `org-publish-current-project' or `org-publish-all'.
+
+ `:sitemap-filename'
+
+ Filename for output of sitemap. Defaults to \"sitemap.org\".
+
+ `:sitemap-title'
+
+ Title of site-map page. Defaults to name of file.
+
+ `:sitemap-function'
+
+ Plugin function to use for generation of site-map. Defaults
+ to `org-publish-org-sitemap', which generates a plain list of
+ links to all files in the project.
+
+ `:sitemap-style'
+
+ Can be `list' (site-map is just an itemized list of the
+ titles of the files involved) or `tree' (the directory
+ structure of the source files is reflected in the site-map).
+ Defaults to `tree'.
+
+ `:sitemap-sans-extension'
+
+ Remove extension from site-map's file-names. Useful to have
+ cool URIs (see http://www.w3.org/Provider/Style/URI).
+ Defaults to nil.
+
+If you create a site-map file, adjust the sorting like this:
+
+ `:sitemap-sort-folders'
+
+ Where folders should appear in the site-map. Set this to
+ `first' (default) or `last' to display folders first or last,
+ respectively. Any other value will mix files and folders.
+
+ `:sitemap-sort-files'
+
+ The site map is normally sorted alphabetically. You can
+ change this behavior setting this to `anti-chronologically',
+ `chronologically', or nil.
+
+ `:sitemap-ignore-case'
+
+ Should sorting be case-sensitive? Default nil.
+
+The following property control the creation of a concept index.
+
+ `:makeindex'
+
+ Create a concept index. The file containing the index has to
+ be called \"theindex.org\". If it doesn't exist in the
+ project, it will be generated. Contents of the index are
+ stored in the file \"theindex.inc\", which can be included in
+ \"theindex.org\".
+
+Other properties affecting publication.
+
+ `:body-only'
+
+ Set this to t to publish only the body of the documents."
+ :group 'org-export-publish
+ :type 'alist)
+
+(defcustom org-publish-use-timestamps-flag t
+ "Non-nil means use timestamp checking to publish only changed files.
+When nil, do no timestamp checking and always publish all files."
+ :group 'org-export-publish
+ :type 'boolean)
+
+(defcustom org-publish-timestamp-directory
+ (convert-standard-filename "~/.org-timestamps/")
+ "Name of directory in which to store publishing timestamps."
+ :group 'org-export-publish
+ :type 'directory)
+
+(defcustom org-publish-list-skipped-files t
+ "Non-nil means show message about files *not* published."
+ :group 'org-export-publish
+ :type 'boolean)
+
+(defcustom org-publish-sitemap-sort-files 'alphabetically
+ "Method to sort files in site-maps.
+Possible values are `alphabetically', `chronologically',
+`anti-chronologically' and nil.
+
+If `alphabetically', files will be sorted alphabetically. If
+`chronologically', files will be sorted with older modification
+time first. If `anti-chronologically', files will be sorted with
+newer modification time first. nil won't sort files.
+
+You can overwrite this default per project in your
+`org-publish-project-alist', using `:sitemap-sort-files'."
+ :group 'org-export-publish
+ :type 'symbol)
+
+(defcustom org-publish-sitemap-sort-folders 'first
+ "A symbol, denoting if folders are sorted first in sitemaps.
+Possible values are `first', `last', and nil.
+If `first', folders will be sorted before files.
+If `last', folders are sorted to the end after the files.
+Any other value will not mix files and folders.
+
+You can overwrite this default per project in your
+`org-publish-project-alist', using `:sitemap-sort-folders'."
+ :group 'org-export-publish
+ :type 'symbol)
+
+(defcustom org-publish-sitemap-sort-ignore-case nil
+ "Non-nil when site-map sorting should ignore case.
+
+You can overwrite this default per project in your
+`org-publish-project-alist', using `:sitemap-ignore-case'."
+ :group 'org-export-publish
+ :type 'boolean)
+
+(defcustom org-publish-sitemap-date-format "%Y-%m-%d"
+ "Format for printing a date in the sitemap.
+See `format-time-string' for allowed formatters."
+ :group 'org-export-publish
+ :type 'string)
+
+(defcustom org-publish-sitemap-file-entry-format "%t"
+ "Format string for site-map file entry.
+You could use brackets to delimit on what part the link will be.
+
+%t is the title.
+%a is the author.
+%d is the date formatted using `org-publish-sitemap-date-format'."
+ :group 'org-export-publish
+ :type 'string)
+
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Timestamp-related functions
+
+(defun org-publish-timestamp-filename (filename &optional pub-dir pub-func)
+ "Return path to timestamp file for filename FILENAME."
+ (setq filename (concat filename "::" (or pub-dir "") "::"
+ (format "%s" (or pub-func ""))))
+ (concat "X" (if (fboundp 'sha1) (sha1 filename) (md5 filename))))
+
+(defun org-publish-needed-p
+ (filename &optional pub-dir pub-func _true-pub-dir base-dir)
+ "Non-nil if FILENAME should be published in PUB-DIR using PUB-FUNC.
+TRUE-PUB-DIR is where the file will truly end up. Currently we
+are not using this - maybe it can eventually be used to check if
+the file is present at the target location, and how old it is.
+Right now we cannot do this, because we do not know under what
+file name the file will be stored - the publishing function can
+still decide about that independently."
+ (let ((rtn (if (not org-publish-use-timestamps-flag) t
+ (org-publish-cache-file-needs-publishing
+ filename pub-dir pub-func base-dir))))
+ (if rtn (message "Publishing file %s using `%s'" filename pub-func)
+ (when org-publish-list-skipped-files
+ (message "Skipping unmodified file %s" filename)))
+ rtn))
+
+(defun org-publish-update-timestamp
+ (filename &optional pub-dir pub-func _base-dir)
+ "Update publishing timestamp for file FILENAME.
+If there is no timestamp, create one."
+ (let ((key (org-publish-timestamp-filename filename pub-dir pub-func))
+ (stamp (org-publish-cache-ctime-of-src filename)))
+ (org-publish-cache-set key stamp)))
+
+(defun org-publish-remove-all-timestamps ()
+ "Remove all files in the timestamp directory."
+ (let ((dir org-publish-timestamp-directory))
+ (when (and (file-exists-p dir) (file-directory-p dir))
+ (mapc #'delete-file (directory-files dir 'full "[^.]\\'"))
+ (org-publish-reset-cache))))
+
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Getting project information out of `org-publish-project-alist'
+
+(defun org-publish-property (property project &optional default)
+ "Return value PROPERTY, as a symbol, in PROJECT.
+DEFAULT is returned when PROPERTY is not actually set in PROJECT
+definition."
+ (let ((properties (cdr project)))
+ (if (plist-member properties property)
+ (plist-get properties property)
+ default)))
+
+(defun org-publish-expand-projects (projects-alist)
+ "Expand projects in PROJECTS-ALIST.
+This splices all the components into the list."
+ (let ((rest projects-alist) rtn p components)
+ (while (setq p (pop rest))
+ (if (setq components (plist-get (cdr p) :components))
+ (setq rest (append
+ (mapcar (lambda (x) (assoc x org-publish-project-alist))
+ components)
+ rest))
+ (push p rtn)))
+ (nreverse (delete-dups (delq nil rtn)))))
+
+(defvar org-publish-sitemap-sort-files)
+(defvar org-publish-sitemap-sort-folders)
+(defvar org-publish-sitemap-ignore-case)
+(defvar org-publish-sitemap-requested)
+(defvar org-publish-sitemap-date-format)
+(defvar org-publish-sitemap-file-entry-format)
+(defun org-publish-compare-directory-files (a b)
+ "Predicate for `sort', that sorts folders and files for sitemap."
+ (let ((retval t))
+ (when (or org-publish-sitemap-sort-files org-publish-sitemap-sort-folders)
+ ;; First we sort files:
+ (when org-publish-sitemap-sort-files
+ (pcase org-publish-sitemap-sort-files
+ (`alphabetically
+ (let* ((adir (file-directory-p a))
+ (aorg (and (string-suffix-p ".org" a) (not adir)))
+ (bdir (file-directory-p b))
+ (borg (and (string-suffix-p ".org" b) (not bdir)))
+ (A (if aorg (concat (file-name-directory a)
+ (org-publish-find-title a)) a))
+ (B (if borg (concat (file-name-directory b)
+ (org-publish-find-title b)) b)))
+ (setq retval (if org-publish-sitemap-ignore-case
+ (not (string-lessp (upcase B) (upcase A)))
+ (not (string-lessp B A))))))
+ ((or `anti-chronologically `chronologically)
+ (let* ((adate (org-publish-find-date a))
+ (bdate (org-publish-find-date b))
+ (A (+ (lsh (car adate) 16) (cadr adate)))
+ (B (+ (lsh (car bdate) 16) (cadr bdate))))
+ (setq retval
+ (if (eq org-publish-sitemap-sort-files 'chronologically)
+ (<= A B)
+ (>= A B)))))))
+ ;; Directory-wise wins:
+ (when org-publish-sitemap-sort-folders
+ ;; a is directory, b not:
+ (cond
+ ((and (file-directory-p a) (not (file-directory-p b)))
+ (setq retval (eq org-publish-sitemap-sort-folders 'first)))
+ ;; a is not a directory, but b is:
+ ((and (not (file-directory-p a)) (file-directory-p b))
+ (setq retval (eq org-publish-sitemap-sort-folders 'last))))))
+ retval))
+
+(defun org-publish-get-base-files-1
+ (base-dir &optional recurse match skip-file skip-dir)
+ "Set `org-publish-temp-files' with files from BASE-DIR directory.
+If RECURSE is non-nil, check BASE-DIR recursively. If MATCH is
+non-nil, restrict this list to the files matching the regexp
+MATCH. If SKIP-FILE is non-nil, skip file matching the regexp
+SKIP-FILE. If SKIP-DIR is non-nil, don't check directories
+matching the regexp SKIP-DIR when recursing through BASE-DIR."
+ (let ((all-files (if (not recurse) (directory-files base-dir t match)
+ ;; If RECURSE is non-nil, we want all files
+ ;; matching MATCH and sub-directories.
+ (cl-remove-if-not
+ (lambda (file)
+ (or (file-directory-p file)
+ (and match (string-match match file))))
+ (directory-files base-dir t)))))
+ (dolist (f (if (not org-publish-sitemap-requested) all-files
+ (sort all-files #'org-publish-compare-directory-files)))
+ (let ((fd-p (file-directory-p f))
+ (fnd (file-name-nondirectory f)))
+ (if (and fd-p recurse
+ (not (string-match "^\\.+$" fnd))
+ (if skip-dir (not (string-match skip-dir fnd)) t))
+ (org-publish-get-base-files-1
+ f recurse match skip-file skip-dir)
+ (unless (or fd-p ; This is a directory.
+ (and skip-file (string-match skip-file fnd))
+ (not (file-exists-p (file-truename f)))
+ (not (string-match match fnd)))
+ (cl-pushnew f org-publish-temp-files)))))))
+
+(defun org-publish-get-base-files (project &optional exclude-regexp)
+ "Return a list of all files in PROJECT.
+If EXCLUDE-REGEXP is set, this will be used to filter out
+matching filenames."
+ (let* ((project-plist (cdr project))
+ (base-dir (file-name-as-directory
+ (plist-get project-plist :base-directory)))
+ (include-list (plist-get project-plist :include))
+ (recurse (plist-get project-plist :recursive))
+ (extension (or (plist-get project-plist :base-extension) "org"))
+ ;; sitemap-... variables are dynamically scoped for
+ ;; org-publish-compare-directory-files:
+ (org-publish-sitemap-requested
+ (plist-get project-plist :auto-sitemap))
+ (sitemap-filename
+ (or (plist-get project-plist :sitemap-filename) "sitemap.org"))
+ (org-publish-sitemap-sort-folders
+ (if (plist-member project-plist :sitemap-sort-folders)
+ (plist-get project-plist :sitemap-sort-folders)
+ org-publish-sitemap-sort-folders))
+ (org-publish-sitemap-sort-files
+ (cond ((plist-member project-plist :sitemap-sort-files)
+ (plist-get project-plist :sitemap-sort-files))
+ ;; For backward compatibility:
+ ((plist-member project-plist :sitemap-alphabetically)
+ (if (plist-get project-plist :sitemap-alphabetically)
+ 'alphabetically nil))
+ (t org-publish-sitemap-sort-files)))
+ (org-publish-sitemap-ignore-case
+ (if (plist-member project-plist :sitemap-ignore-case)
+ (plist-get project-plist :sitemap-ignore-case)
+ org-publish-sitemap-sort-ignore-case))
+ (match (if (eq extension 'any) "^[^\\.]"
+ (concat "^[^\\.].*\\.\\(" extension "\\)$"))))
+ ;; Make sure `org-publish-sitemap-sort-folders' has an accepted
+ ;; value.
+ (unless (memq org-publish-sitemap-sort-folders '(first last))
+ (setq org-publish-sitemap-sort-folders nil))
+
+ (setq org-publish-temp-files nil)
+ (when org-publish-sitemap-requested
+ (cl-pushnew (expand-file-name (concat base-dir sitemap-filename))
+ org-publish-temp-files))
+ (org-publish-get-base-files-1 base-dir recurse match
+ ;; FIXME distinguish exclude regexp
+ ;; for skip-file and skip-dir?
+ exclude-regexp exclude-regexp)
+ (dolist (f include-list org-publish-temp-files)
+ (cl-pushnew (expand-file-name (concat base-dir f))
+ org-publish-temp-files))))
+
+(defun org-publish-get-project-from-filename (filename &optional up)
+ "Return a project that FILENAME belongs to.
+When UP is non-nil, return a meta-project (i.e., with a :components part)
+publishing FILENAME."
+ (let* ((filename (expand-file-name filename))
+ (project
+ (cl-some
+ (lambda (p)
+ ;; Ignore meta-projects.
+ (unless (org-publish-property :components p)
+ (let ((base (file-truename
+ (org-publish-property :base-directory p))))
+ (cond
+ ;; Check if FILENAME is explicitly included in one
+ ;; project.
+ ((cl-some (lambda (f) (file-equal-p f filename))
+ (mapcar (lambda (f) (expand-file-name f base))
+ (org-publish-property :include p)))
+ p)
+ ;; Exclude file names matching :exclude property.
+ ((let ((exclude-re (org-publish-property :exclude p)))
+ (and exclude-re
+ (string-match-p exclude-re
+ (file-relative-name filename base))))
+ nil)
+ ;; Check :extension. Handle special `any'
+ ;; extension.
+ ((let ((extension (org-publish-property :base-extension p)))
+ (not (or (eq extension 'any)
+ (string= (or extension "org")
+ (file-name-extension filename)))))
+ nil)
+ ;; Check if FILENAME belong to project's base
+ ;; directory, or some of its sub-directories
+ ;; if :recursive in non-nil.
+ ((org-publish-property :recursive p)
+ (and (file-in-directory-p filename base) p))
+ ((file-equal-p base (file-name-directory filename)) p)
+ (t nil)))))
+ org-publish-project-alist)))
+ (cond
+ ((not project) nil)
+ ((not up) project)
+ ;; When optional argument UP is non-nil, return the top-most
+ ;; meta-project effectively publishing FILENAME.
+ (t
+ (letrec ((find-parent-project
+ (lambda (project)
+ (or (cl-some
+ (lambda (p)
+ (and (member (car project)
+ (org-publish-property :components p))
+ (funcall find-parent-project p)))
+ org-publish-project-alist)
+ project))))
+ (funcall find-parent-project project))))))
+
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Tools for publishing functions in back-ends
+
+(defun org-publish-org-to (backend filename extension plist &optional pub-dir)
+ "Publish an Org file to a specified back-end.
+
+BACKEND is a symbol representing the back-end used for
+transcoding. FILENAME is the filename of the Org file to be
+published. EXTENSION is the extension used for the output
+string, with the leading dot. PLIST is the property list for the
+given project.
+
+Optional argument PUB-DIR, when non-nil is the publishing
+directory.
+
+Return output file name."
+ (unless (or (not pub-dir) (file-exists-p pub-dir)) (make-directory pub-dir t))
+ ;; Check if a buffer visiting FILENAME is already open.
+ (let* ((org-inhibit-startup t)
+ (visiting (find-buffer-visiting filename))
+ (work-buffer (or visiting (find-file-noselect filename))))
+ (unwind-protect
+ (with-current-buffer work-buffer
+ (let ((output (org-export-output-file-name extension nil pub-dir)))
+ (org-export-to-file backend output
+ nil nil nil (plist-get plist :body-only)
+ ;; Add `org-publish--store-crossrefs' and
+ ;; `org-publish-collect-index' to final output filters.
+ ;; The latter isn't dependent on `:makeindex', since we
+ ;; want to keep it up-to-date in cache anyway.
+ (org-combine-plists
+ plist
+ `(:crossrefs
+ ,(org-publish-cache-get-file-property
+ ;; Normalize file names in cache.
+ (file-truename filename) :crossrefs nil t)
+ :filter-final-output
+ (org-publish--store-crossrefs
+ org-publish-collect-index
+ ,@(plist-get plist :filter-final-output)))))))
+ ;; Remove opened buffer in the process.
+ (unless visiting (kill-buffer work-buffer)))))
+
+(defun org-publish-attachment (_plist filename pub-dir)
+ "Publish a file with no transformation of any kind.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (unless (file-directory-p pub-dir)
+ (make-directory pub-dir t))
+ (let ((output (expand-file-name (file-name-nondirectory filename) pub-dir)))
+ (unless (file-equal-p (expand-file-name (file-name-directory filename))
+ (file-name-as-directory (expand-file-name pub-dir)))
+ (copy-file filename output t))
+ ;; Return file name.
+ output))
+
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Publishing files, sets of files, and indices
+
+(defun org-publish-file (filename &optional project no-cache)
+ "Publish file FILENAME from PROJECT.
+If NO-CACHE is not nil, do not initialize `org-publish-cache'.
+This is needed, since this function is used to publish single
+files, when entire projects are published (see
+`org-publish-projects')."
+ (let* ((project
+ (or project
+ (org-publish-get-project-from-filename filename)
+ (user-error "File %S is not part of any known project"
+ (abbreviate-file-name filename))))
+ (project-plist (cdr project))
+ (publishing-function
+ (pcase (plist-get project-plist :publishing-function)
+ (`nil (user-error "No publishing function chosen"))
+ ((and f (pred listp)) f)
+ (f (list f))))
+ (base-dir
+ (file-name-as-directory
+ (or (org-publish-property :base-directory project)
+ (user-error "Project %S does not have :base-directory defined"
+ (car project)))))
+ (pub-base-dir
+ (file-name-as-directory
+ (or (org-publish-property :publishing-directory project)
+ (user-error
+ "Project %S does not have :publishing-directory defined"
+ (car project)))))
+ (pub-dir
+ (file-name-directory
+ (expand-file-name (file-relative-name filename base-dir)
+ pub-base-dir))))
+
+ (unless no-cache (org-publish-initialize-cache (car project)))
+
+ ;; Allow chain of publishing functions.
+ (dolist (f publishing-function)
+ (when (org-publish-needed-p filename pub-base-dir f pub-dir base-dir)
+ (let ((output (funcall f project-plist filename pub-dir)))
+ (org-publish-update-timestamp filename pub-base-dir f base-dir)
+ (run-hook-with-args 'org-publish-after-publishing-hook
+ filename
+ output))))
+ ;; Make sure to write cache to file after successfully publishing
+ ;; a file, so as to minimize impact of a publishing failure.
+ (org-publish-write-cache-file)))
+
+(defun org-publish-projects (projects)
+ "Publish all files belonging to the PROJECTS alist.
+If `:auto-sitemap' is set, publish the sitemap too. If
+`:makeindex' is set, also produce a file \"theindex.org\"."
+ (dolist (project (org-publish-expand-projects projects))
+ (let ((project-plist (cdr project)))
+ (let ((fun (plist-get project-plist :preparation-function)))
+ (cond ((consp fun) (dolist (f fun) (funcall f project-plist)))
+ ((functionp fun) (funcall fun project-plist))))
+ ;; Each project uses its own cache file.
+ (org-publish-initialize-cache (car project))
+ (when (plist-get project-plist :auto-sitemap)
+ (let ((sitemap-filename
+ (or (plist-get project-plist :sitemap-filename)
+ "sitemap.org"))
+ (sitemap-function
+ (or (plist-get project-plist :sitemap-function)
+ #'org-publish-org-sitemap))
+ (org-publish-sitemap-date-format
+ (or (plist-get project-plist :sitemap-date-format)
+ org-publish-sitemap-date-format))
+ (org-publish-sitemap-file-entry-format
+ (or (plist-get project-plist :sitemap-file-entry-format)
+ org-publish-sitemap-file-entry-format)))
+ (funcall sitemap-function project sitemap-filename)))
+ ;; Publish all files from PROJECT except "theindex.org". Its
+ ;; publishing will be deferred until "theindex.inc" is
+ ;; populated.
+ (let ((theindex
+ (expand-file-name "theindex.org"
+ (plist-get project-plist :base-directory)))
+ (exclude-regexp (plist-get project-plist :exclude)))
+ (dolist (file (org-publish-get-base-files project exclude-regexp))
+ (unless (file-equal-p file theindex)
+ (org-publish-file file project t)))
+ ;; Populate "theindex.inc", if needed, and publish
+ ;; "theindex.org".
+ (when (plist-get project-plist :makeindex)
+ (org-publish-index-generate-theindex
+ project (plist-get project-plist :base-directory))
+ (org-publish-file theindex project t)))
+ (let ((fun (plist-get project-plist :completion-function)))
+ (cond ((consp fun) (dolist (f fun) (funcall f project-plist)))
+ ((functionp fun) (funcall fun project-plist))))
+ (org-publish-write-cache-file))))
+
+(defun org-publish-org-sitemap (project &optional sitemap-filename)
+ "Create a sitemap of pages in set defined by PROJECT.
+Optionally set the filename of the sitemap with SITEMAP-FILENAME.
+Default for SITEMAP-FILENAME is `sitemap.org'."
+ (let* ((project-plist (cdr project))
+ (dir (file-name-as-directory
+ (plist-get project-plist :base-directory)))
+ (localdir (file-name-directory dir))
+ (indent-str (make-string 2 ?\s))
+ (exclude-regexp (plist-get project-plist :exclude))
+ (files (nreverse
+ (org-publish-get-base-files project exclude-regexp)))
+ (sitemap-filename (concat dir (or sitemap-filename "sitemap.org")))
+ (sitemap-title (or (plist-get project-plist :sitemap-title)
+ (concat "Sitemap for project " (car project))))
+ (sitemap-style (or (plist-get project-plist :sitemap-style)
+ 'tree))
+ (sitemap-sans-extension
+ (plist-get project-plist :sitemap-sans-extension))
+ (visiting (find-buffer-visiting sitemap-filename))
+ file sitemap-buffer)
+ (with-current-buffer
+ (let ((org-inhibit-startup t))
+ (setq sitemap-buffer
+ (or visiting (find-file sitemap-filename))))
+ (erase-buffer)
+ (insert (concat "#+TITLE: " sitemap-title "\n\n"))
+ (while (setq file (pop files))
+ (let ((link (file-relative-name file dir))
+ (oldlocal localdir))
+ (when sitemap-sans-extension
+ (setq link (file-name-sans-extension link)))
+ ;; sitemap shouldn't list itself
+ (unless (file-equal-p sitemap-filename file)
+ (if (eq sitemap-style 'list)
+ (message "Generating list-style sitemap for %s" sitemap-title)
+ (message "Generating tree-style sitemap for %s" sitemap-title)
+ (setq localdir (concat (file-name-as-directory dir)
+ (file-name-directory link)))
+ (unless (string= localdir oldlocal)
+ (if (string= localdir dir)
+ (setq indent-str (make-string 2 ?\ ))
+ (let ((subdirs
+ (split-string
+ (directory-file-name
+ (file-name-directory
+ (file-relative-name localdir dir))) "/"))
+ (subdir "")
+ (old-subdirs (split-string
+ (file-relative-name oldlocal dir) "/")))
+ (setq indent-str (make-string 2 ?\ ))
+ (while (string= (car old-subdirs) (car subdirs))
+ (setq indent-str (concat indent-str (make-string 2 ?\ )))
+ (pop old-subdirs)
+ (pop subdirs))
+ (dolist (d subdirs)
+ (setq subdir (concat subdir d "/"))
+ (insert (concat indent-str " + " d "\n"))
+ (setq indent-str (make-string
+ (+ (length indent-str) 2) ?\ )))))))
+ ;; This is common to 'flat and 'tree
+ (let ((entry
+ (org-publish-format-file-entry
+ org-publish-sitemap-file-entry-format file project-plist))
+ (regexp "\\(.*\\)\\[\\([^][]+\\)\\]\\(.*\\)"))
+ (cond ((string-match-p regexp entry)
+ (string-match regexp entry)
+ (insert (concat indent-str " + " (match-string 1 entry)
+ "[[file:" link "]["
+ (match-string 2 entry)
+ "]]" (match-string 3 entry) "\n")))
+ (t
+ (insert (concat indent-str " + [[file:" link "]["
+ entry
+ "]]\n"))))))))
+ (save-buffer))
+ (or visiting (kill-buffer sitemap-buffer))))
+
+(defun org-publish-format-file-entry (fmt file project-plist)
+ (format-spec
+ fmt
+ `((?t . ,(org-publish-find-title file t))
+ (?d . ,(format-time-string org-publish-sitemap-date-format
+ (org-publish-find-date file)))
+ (?a . ,(or (plist-get project-plist :author) user-full-name)))))
+
+(defun org-publish-find-title (file &optional reset)
+ "Find the title of FILE in project."
+ (or
+ (and (not reset) (org-publish-cache-get-file-property file :title nil t))
+ (let* ((org-inhibit-startup t)
+ (visiting (find-buffer-visiting file))
+ (buffer (or visiting (find-file-noselect file))))
+ (with-current-buffer buffer
+ (let ((title
+ (let ((property
+ (plist-get
+ ;; protect local variables in open buffers
+ (if visiting
+ (org-export-with-buffer-copy (org-export-get-environment))
+ (org-export-get-environment))
+ :title)))
+ (if property
+ (org-no-properties (org-element-interpret-data property))
+ (file-name-nondirectory (file-name-sans-extension file))))))
+ (unless visiting (kill-buffer buffer))
+ (org-publish-cache-set-file-property file :title title)
+ title)))))
+
+(defun org-publish-find-date (file)
+ "Find the date of FILE in project.
+This function assumes FILE is either a directory or an Org file.
+If FILE is an Org file and provides a DATE keyword use it. In
+any other case use the file system's modification time. Return
+time in `current-time' format."
+ (if (file-directory-p file) (nth 5 (file-attributes file))
+ (let* ((org-inhibit-startup t)
+ (visiting (find-buffer-visiting file))
+ (file-buf (or visiting (find-file-noselect file nil)))
+ (date (plist-get
+ (with-current-buffer file-buf
+ (if visiting
+ (org-export-with-buffer-copy
+ (org-export-get-environment))
+ (org-export-get-environment)))
+ :date)))
+ (unless visiting (kill-buffer file-buf))
+ ;; DATE is a secondary string. If it contains a timestamp,
+ ;; convert it to internal format. Otherwise, use FILE
+ ;; modification time.
+ (cond ((let ((ts (and (consp date) (assq 'timestamp date))))
+ (and ts
+ (let ((value (org-element-interpret-data ts)))
+ (and (org-string-nw-p value)
+ (org-time-string-to-time value))))))
+ ((file-exists-p file) (nth 5 (file-attributes file)))
+ (t (error "No such file: \"%s\"" file))))))
+
+
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Interactive publishing functions
+
+;;;###autoload
+(defalias 'org-publish-project 'org-publish)
+
+;;;###autoload
+(defun org-publish (project &optional force async)
+ "Publish PROJECT.
+
+PROJECT is either a project name, as a string, or a project
+alist (see `org-publish-project-alist' variable).
+
+When optional argument FORCE is non-nil, force publishing all
+files in PROJECT. With a non-nil optional argument ASYNC,
+publishing will be done asynchronously, in another process."
+ (interactive
+ (list (assoc (completing-read "Publish project: "
+ org-publish-project-alist nil t)
+ org-publish-project-alist)
+ current-prefix-arg))
+ (let ((project (if (not (stringp project)) project
+ ;; If this function is called in batch mode,
+ ;; PROJECT is still a string here.
+ (assoc project org-publish-project-alist))))
+ (cond
+ ((not project))
+ (async
+ (org-export-async-start (lambda (_) nil)
+ `(let ((org-publish-use-timestamps-flag
+ ,(and (not force) org-publish-use-timestamps-flag)))
+ ;; Expand components right now as external process may not
+ ;; be aware of complete `org-publish-project-alist'.
+ (org-publish-projects
+ ',(org-publish-expand-projects (list project))))))
+ (t (save-window-excursion
+ (let ((org-publish-use-timestamps-flag
+ (and (not force) org-publish-use-timestamps-flag)))
+ (org-publish-projects (list project))))))))
+
+;;;###autoload
+(defun org-publish-all (&optional force async)
+ "Publish all projects.
+With prefix argument FORCE, remove all files in the timestamp
+directory and force publishing all projects. With a non-nil
+optional argument ASYNC, publishing will be done asynchronously,
+in another process."
+ (interactive "P")
+ (if async
+ (org-export-async-start (lambda (_) nil)
+ `(progn
+ (when ',force (org-publish-remove-all-timestamps))
+ (let ((org-publish-use-timestamps-flag
+ (if ',force nil ,org-publish-use-timestamps-flag)))
+ (org-publish-projects ',org-publish-project-alist))))
+ (when force (org-publish-remove-all-timestamps))
+ (save-window-excursion
+ (let ((org-publish-use-timestamps-flag
+ (if force nil org-publish-use-timestamps-flag)))
+ (org-publish-projects org-publish-project-alist)))))
+
+
+;;;###autoload
+(defun org-publish-current-file (&optional force async)
+ "Publish the current file.
+With prefix argument FORCE, force publish the file. When
+optional argument ASYNC is non-nil, publishing will be done
+asynchronously, in another process."
+ (interactive "P")
+ (let ((file (buffer-file-name (buffer-base-buffer))))
+ (if async
+ (org-export-async-start (lambda (_) nil)
+ `(let ((org-publish-use-timestamps-flag
+ (if ',force nil ,org-publish-use-timestamps-flag)))
+ (org-publish-file ,file)))
+ (save-window-excursion
+ (let ((org-publish-use-timestamps-flag
+ (if force nil org-publish-use-timestamps-flag)))
+ (org-publish-file file))))))
+
+;;;###autoload
+(defun org-publish-current-project (&optional force async)
+ "Publish the project associated with the current file.
+With a prefix argument, force publishing of all files in
+the project."
+ (interactive "P")
+ (save-window-excursion
+ (let ((project (org-publish-get-project-from-filename
+ (buffer-file-name (buffer-base-buffer)) 'up)))
+ (if project (org-publish project force async)
+ (error "File %s is not part of any known project"
+ (buffer-file-name (buffer-base-buffer)))))))
+
+
+
+;;; Index generation
+
+(defun org-publish-collect-index (output _backend info)
+ "Update index for a file in cache.
+
+OUTPUT is the output from transcoding current file. BACKEND is
+the back-end that was used for transcoding. INFO is a plist
+containing publishing and export options.
+
+The index relative to current file is stored as an alist. An
+association has the following shape: (TERM FILE-NAME PARENT),
+where TERM is the indexed term, as a string, FILE-NAME is the
+original full path of the file where the term in encountered, and
+PARENT is a reference to the headline, if any, containing the
+original index keyword. When non-nil, this reference is a cons
+cell. Its CAR is a symbol among `id', `custom-id' and `name' and
+its CDR is a string."
+ (let ((file (file-truename (plist-get info :input-file))))
+ (org-publish-cache-set-file-property
+ file :index
+ (delete-dups
+ (org-element-map (plist-get info :parse-tree) 'keyword
+ (lambda (k)
+ (when (equal (org-element-property :key k) "INDEX")
+ (let ((parent (org-export-get-parent-headline k)))
+ (list (org-element-property :value k)
+ file
+ (cond
+ ((not parent) nil)
+ ((let ((id (org-element-property :ID parent)))
+ (and id (cons 'id id))))
+ ((let ((id (org-element-property :CUSTOM_ID parent)))
+ (and id (cons 'custom-id id))))
+ (t (cons 'name
+ ;; Remove statistics cookie.
+ (replace-regexp-in-string
+ "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
+ (org-element-property :raw-value parent)))))))))
+ info))))
+ ;; Return output unchanged.
+ output)
+
+(defun org-publish-index-generate-theindex (project directory)
+ "Retrieve full index from cache and build \"theindex.org\".
+PROJECT is the project the index relates to. DIRECTORY is the
+publishing directory."
+ (let ((all-files (org-publish-get-base-files
+ project (plist-get (cdr project) :exclude)))
+ full-index)
+ ;; Compile full index and sort it alphabetically.
+ (dolist (file all-files
+ (setq full-index
+ (sort (nreverse full-index)
+ (lambda (a b) (string< (downcase (car a))
+ (downcase (car b)))))))
+ (let ((index (org-publish-cache-get-file-property file :index)))
+ (dolist (term index)
+ (unless (member term full-index) (push term full-index)))))
+ ;; Write "theindex.inc" in DIRECTORY.
+ (with-temp-file (expand-file-name "theindex.inc" directory)
+ (let ((current-letter nil) (last-entry nil))
+ (dolist (idx full-index)
+ (let* ((entry (org-split-string (car idx) "!"))
+ (letter (upcase (substring (car entry) 0 1)))
+ ;; Transform file into a path relative to publishing
+ ;; directory.
+ (file (file-relative-name
+ (nth 1 idx)
+ (plist-get (cdr project) :base-directory))))
+ ;; Check if another letter has to be inserted.
+ (unless (string= letter current-letter)
+ (insert (format "* %s\n" letter)))
+ ;; Compute the first difference between last entry and
+ ;; current one: it tells the level at which new items
+ ;; should be added.
+ (let* ((rank
+ (if (equal entry last-entry) (1- (length entry))
+ (cl-loop for n from 0 to (length entry)
+ unless (equal (nth n entry) (nth n last-entry))
+ return n)))
+ (len (length (nthcdr rank entry))))
+ ;; For each term after the first difference, create
+ ;; a new sub-list with the term as body. Moreover,
+ ;; linkify the last term.
+ (dotimes (n len)
+ (insert
+ (concat
+ (make-string (* (+ rank n) 2) ?\s) " - "
+ (if (not (= (1- len) n)) (nth (+ rank n) entry)
+ ;; Last term: Link it to TARGET, if possible.
+ (let ((target (nth 2 idx)))
+ (format
+ "[[%s][%s]]"
+ ;; Destination.
+ (pcase (car target)
+ (`nil (format "file:%s" file))
+ (`id (format "id:%s" (cdr target)))
+ (`custom-id (format "file:%s::#%s" file (cdr target)))
+ (_ (format "file:%s::*%s" file (cdr target))))
+ ;; Description.
+ (car (last entry)))))
+ "\n"))))
+ (setq current-letter letter last-entry entry))))
+ ;; Create "theindex.org", if it doesn't exist yet, and provide
+ ;; a default index file.
+ (let ((index.org (expand-file-name "theindex.org" directory)))
+ (unless (file-exists-p index.org)
+ (with-temp-file index.org
+ (insert "#+TITLE: Index\n\n#+INCLUDE: \"theindex.inc\"\n\n")))))))
+
+
+
+;;; External Fuzzy Links Resolution
+;;
+;; This part implements tools to resolve [[file.org::*Some headline]]
+;; links, where "file.org" belongs to the current project.
+
+(defun org-publish--store-crossrefs (output _backend info)
+ "Store cross-references for current published file.
+
+OUPUT is the produced output, as a string. BACKEND is the export
+back-end used, as a symbol. INFO is the final export state, as
+a plist.
+
+This function is meant to be used as a final output filter. See
+`org-publish-org-to'."
+ (org-publish-cache-set-file-property
+ (file-truename (plist-get info :input-file))
+ :crossrefs
+ ;; Update `:crossrefs' so as to remove unused references and search
+ ;; cells. Actually used references are extracted from
+ ;; `:internal-references', with references as strings removed. See
+ ;; `org-export-get-reference' for details.
+ (cl-remove-if (lambda (pair) (stringp (car pair)))
+ (plist-get info :internal-references)))
+ ;; Return output unchanged.
+ output)
+
+(defun org-publish-resolve-external-link (search file)
+ "Return reference for element matching string SEARCH in FILE.
+
+Return value is an internal reference, as a string.
+
+This function allows resolving external links with a search
+option, e.g.,
+
+ [[file.org::*heading][description]]
+ [[file.org::#custom-id][description]]
+ [[file.org::fuzzy][description]]
+
+It only makes sense to use this if export back-end builds
+references with `org-export-get-reference'."
+ (if (not org-publish-cache)
+ (progn
+ (message "Reference %S in file %S cannot be resolved without publishing"
+ search
+ file)
+ "MissingReference")
+ (let* ((filename (file-truename file))
+ (crossrefs
+ (org-publish-cache-get-file-property filename :crossrefs nil t))
+ (cells (org-export-string-to-search-cell search)))
+ (or
+ ;; Look for reference associated to search cells triggered by
+ ;; LINK. It can match when targeted file has been published
+ ;; already.
+ (let ((known (cdr (cl-some (lambda (c) (assoc c crossrefs)) cells))))
+ (and known (org-export-format-reference known)))
+ ;; Search cell is unknown so far. Generate a new internal
+ ;; reference that will be used when the targeted file will be
+ ;; published.
+ (let ((new (org-export-new-reference crossrefs)))
+ (dolist (cell cells) (push (cons cell new) crossrefs))
+ (org-publish-cache-set-file-property filename :crossrefs crossrefs)
+ (org-export-format-reference new))))))
+
+
+
+;;; Caching functions
+
+(defun org-publish-write-cache-file (&optional free-cache)
+ "Write `org-publish-cache' to file.
+If FREE-CACHE, empty the cache."
+ (unless org-publish-cache
+ (error "`org-publish-write-cache-file' called, but no cache present"))
+
+ (let ((cache-file (org-publish-cache-get ":cache-file:")))
+ (unless cache-file
+ (error "Cannot find cache-file name in `org-publish-write-cache-file'"))
+ (with-temp-file cache-file
+ (let (print-level print-length)
+ (insert "(setq org-publish-cache \
+\(make-hash-table :test 'equal :weakness nil :size 100))\n")
+ (maphash (lambda (k v)
+ (insert
+ (format "(puthash %S %s%S org-publish-cache)\n"
+ k (if (or (listp v) (symbolp v)) "'" "") v)))
+ org-publish-cache)))
+ (when free-cache (org-publish-reset-cache))))
+
+(defun org-publish-initialize-cache (project-name)
+ "Initialize the projects cache if not initialized yet and return it."
+
+ (unless project-name
+ (error "Cannot initialize `org-publish-cache' without projects name in \
+`org-publish-initialize-cache'"))
+
+ (unless (file-exists-p org-publish-timestamp-directory)
+ (make-directory org-publish-timestamp-directory t))
+ (unless (file-directory-p org-publish-timestamp-directory)
+ (error "Org publish timestamp: %s is not a directory"
+ org-publish-timestamp-directory))
+
+ (unless (and org-publish-cache
+ (string= (org-publish-cache-get ":project:") project-name))
+ (let* ((cache-file
+ (concat
+ (expand-file-name org-publish-timestamp-directory)
+ project-name ".cache"))
+ (cexists (file-exists-p cache-file)))
+
+ (when org-publish-cache (org-publish-reset-cache))
+
+ (if cexists (load-file cache-file)
+ (setq org-publish-cache
+ (make-hash-table :test 'equal :weakness nil :size 100))
+ (org-publish-cache-set ":project:" project-name)
+ (org-publish-cache-set ":cache-file:" cache-file))
+ (unless cexists (org-publish-write-cache-file nil))))
+ org-publish-cache)
+
+(defun org-publish-reset-cache ()
+ "Empty org-publish-cache and reset it nil."
+ (message "%s" "Resetting org-publish-cache")
+ (when (hash-table-p org-publish-cache)
+ (clrhash org-publish-cache))
+ (setq org-publish-cache nil))
+
+(defun org-publish-cache-file-needs-publishing
+ (filename &optional pub-dir pub-func _base-dir)
+ "Check the timestamp of the last publishing of FILENAME.
+Return non-nil if the file needs publishing. Also check if
+any included files have been more recently published, so that
+the file including them will be republished as well."
+ (unless org-publish-cache
+ (error
+ "`org-publish-cache-file-needs-publishing' called, but no cache present"))
+ (let* ((key (org-publish-timestamp-filename filename pub-dir pub-func))
+ (pstamp (org-publish-cache-get key))
+ (org-inhibit-startup t)
+ included-files-ctime)
+ (when (equal (file-name-extension filename) "org")
+ (let ((visiting (find-buffer-visiting filename))
+ (buf (find-file-noselect filename))
+ (case-fold-search t))
+ (unwind-protect
+ (with-current-buffer buf
+ (goto-char (point-min))
+ (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
+ (let* ((element (org-element-at-point))
+ (included-file
+ (and (eq (org-element-type element) 'keyword)
+ (let ((value (org-element-property :value element)))
+ (and value
+ (string-match
+ "\\`\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)"
+ value)
+ (let ((m (match-string 1 value)))
+ (org-unbracket-string
+ "\"" "\""
+ ;; Ignore search suffix.
+ (if (string-match "::.*?\"?\\'" m)
+ (substring m 0 (match-beginning 0))
+ m))))))))
+ (when included-file
+ (push (org-publish-cache-ctime-of-src
+ (expand-file-name included-file))
+ included-files-ctime)))))
+ (unless visiting (kill-buffer buf)))))
+ (or (null pstamp)
+ (let ((ctime (org-publish-cache-ctime-of-src filename)))
+ (or (< pstamp ctime)
+ (cl-some (lambda (ct) (< ctime ct)) included-files-ctime))))))
+
+(defun org-publish-cache-set-file-property
+ (filename property value &optional project-name)
+ "Set the VALUE for a PROPERTY of file FILENAME in publishing cache to VALUE.
+Use cache file of PROJECT-NAME. If the entry does not exist, it
+will be created. Return VALUE."
+ ;; Evtl. load the requested cache file:
+ (if project-name (org-publish-initialize-cache project-name))
+ (let ((pl (org-publish-cache-get filename)))
+ (if pl (progn (plist-put pl property value) value)
+ (org-publish-cache-get-file-property
+ filename property value nil project-name))))
+
+(defun org-publish-cache-get-file-property
+ (filename property &optional default no-create project-name)
+ "Return the value for a PROPERTY of file FILENAME in publishing cache.
+Use cache file of PROJECT-NAME. Return the value of that PROPERTY,
+or DEFAULT, if the value does not yet exist. Create the entry,
+if necessary, unless NO-CREATE is non-nil."
+ (when project-name (org-publish-initialize-cache project-name))
+ (let ((properties (org-publish-cache-get filename)))
+ (cond ((null properties)
+ (unless no-create
+ (org-publish-cache-set filename (list property default)))
+ default)
+ ((plist-member properties property) (plist-get properties property))
+ (t default))))
+
+(defun org-publish-cache-get (key)
+ "Return the value stored in `org-publish-cache' for key KEY.
+Return nil, if no value or nil is found. Raise an error if the
+cache does not exist."
+ (unless org-publish-cache
+ (error "`org-publish-cache-get' called, but no cache present"))
+ (gethash key org-publish-cache))
+
+(defun org-publish-cache-set (key value)
+ "Store KEY VALUE pair in `org-publish-cache'.
+Returns value on success, else nil. Raise an error if the cache
+does not exist."
+ (unless org-publish-cache
+ (error "`org-publish-cache-set' called, but no cache present"))
+ (puthash key value org-publish-cache))
+
+(defun org-publish-cache-ctime-of-src (file)
+ "Get the ctime of FILE as an integer."
+ (let ((attr (file-attributes
+ (expand-file-name (or (file-symlink-p file) file)
+ (file-name-directory file)))))
+ (if (not attr) (error "No such file: \"%s\"" file)
+ (+ (lsh (car (nth 5 attr)) 16)
+ (cadr (nth 5 attr))))))
+
+
+(provide 'ox-publish)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-publish.el ends here
diff --git a/lisp/ox-texinfo.el b/lisp/ox-texinfo.el
new file mode 100644
index 0000000..35927d9
--- /dev/null
+++ b/lisp/ox-texinfo.el
@@ -0,0 +1,1696 @@
+;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; See Org manual for details.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ox)
+
+(defvar orgtbl-exp-regexp)
+
+
+
+;;; Define Back-End
+
+(org-export-define-backend 'texinfo
+ '((bold . org-texinfo-bold)
+ (center-block . org-texinfo-center-block)
+ (clock . org-texinfo-clock)
+ (code . org-texinfo-code)
+ (drawer . org-texinfo-drawer)
+ (dynamic-block . org-texinfo-dynamic-block)
+ (entity . org-texinfo-entity)
+ (example-block . org-texinfo-example-block)
+ (export-block . org-texinfo-export-block)
+ (export-snippet . org-texinfo-export-snippet)
+ (fixed-width . org-texinfo-fixed-width)
+ (footnote-definition . org-texinfo-footnote-definition)
+ (footnote-reference . org-texinfo-footnote-reference)
+ (headline . org-texinfo-headline)
+ (inline-src-block . org-texinfo-inline-src-block)
+ (inlinetask . org-texinfo-inlinetask)
+ (italic . org-texinfo-italic)
+ (item . org-texinfo-item)
+ (keyword . org-texinfo-keyword)
+ (line-break . org-texinfo-line-break)
+ (link . org-texinfo-link)
+ (node-property . org-texinfo-node-property)
+ (paragraph . org-texinfo-paragraph)
+ (plain-list . org-texinfo-plain-list)
+ (plain-text . org-texinfo-plain-text)
+ (planning . org-texinfo-planning)
+ (property-drawer . org-texinfo-property-drawer)
+ (quote-block . org-texinfo-quote-block)
+ (radio-target . org-texinfo-radio-target)
+ (section . org-texinfo-section)
+ (special-block . org-texinfo-special-block)
+ (src-block . org-texinfo-src-block)
+ (statistics-cookie . org-texinfo-statistics-cookie)
+ (strike-through . org-texinfo-strike-through)
+ (subscript . org-texinfo-subscript)
+ (superscript . org-texinfo-superscript)
+ (table . org-texinfo-table)
+ (table-cell . org-texinfo-table-cell)
+ (table-row . org-texinfo-table-row)
+ (target . org-texinfo-target)
+ (template . org-texinfo-template)
+ (timestamp . org-texinfo-timestamp)
+ (underline . org-texinfo-underline)
+ (verbatim . org-texinfo-verbatim)
+ (verse-block . org-texinfo-verse-block))
+ :filters-alist
+ '((:filter-headline . org-texinfo--filter-section-blank-lines)
+ (:filter-parse-tree . org-texinfo--normalize-headlines)
+ (:filter-section . org-texinfo--filter-section-blank-lines))
+ :menu-entry
+ '(?i "Export to Texinfo"
+ ((?t "As TEXI file" org-texinfo-export-to-texinfo)
+ (?i "As INFO file" org-texinfo-export-to-info)
+ (?o "As INFO file and open"
+ (lambda (a s v b)
+ (if a (org-texinfo-export-to-info t s v b)
+ (org-open-file (org-texinfo-export-to-info nil s v b)))))))
+ :options-alist
+ '((:texinfo-filename "TEXINFO_FILENAME" nil nil t)
+ (:texinfo-class "TEXINFO_CLASS" nil org-texinfo-default-class t)
+ (:texinfo-header "TEXINFO_HEADER" nil nil newline)
+ (:texinfo-post-header "TEXINFO_POST_HEADER" nil nil newline)
+ (:subtitle "SUBTITLE" nil nil parse)
+ (:subauthor "SUBAUTHOR" nil nil newline)
+ (:texinfo-dircat "TEXINFO_DIR_CATEGORY" nil nil t)
+ (:texinfo-dirtitle "TEXINFO_DIR_TITLE" nil nil t)
+ (:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)
+ (:texinfo-printed-title "TEXINFO_PRINTED_TITLE" nil nil t)
+ ;; Other variables.
+ (:texinfo-classes nil nil org-texinfo-classes)
+ (:texinfo-format-headline-function nil nil org-texinfo-format-headline-function)
+ (:texinfo-node-description-column nil nil org-texinfo-node-description-column)
+ (:texinfo-active-timestamp-format nil nil org-texinfo-active-timestamp-format)
+ (:texinfo-inactive-timestamp-format nil nil org-texinfo-inactive-timestamp-format)
+ (:texinfo-diary-timestamp-format nil nil org-texinfo-diary-timestamp-format)
+ (:texinfo-link-with-unknown-path-format nil nil org-texinfo-link-with-unknown-path-format)
+ (:texinfo-tables-verbatim nil nil org-texinfo-tables-verbatim)
+ (:texinfo-table-scientific-notation nil nil org-texinfo-table-scientific-notation)
+ (:texinfo-def-table-markup nil nil org-texinfo-def-table-markup)
+ (:texinfo-text-markup-alist nil nil org-texinfo-text-markup-alist)
+ (:texinfo-format-drawer-function nil nil org-texinfo-format-drawer-function)
+ (:texinfo-format-inlinetask-function nil nil org-texinfo-format-inlinetask-function)))
+
+
+
+;;; User Configurable Variables
+
+(defgroup org-export-texinfo nil
+ "Options for exporting Org mode files to Texinfo."
+ :tag "Org Export Texinfo"
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :group 'org-export)
+
+;;;; Preamble
+
+(defcustom org-texinfo-coding-system nil
+ "Default document encoding for Texinfo output.
+
+If nil it will default to `buffer-file-coding-system'."
+ :group 'org-export-texinfo
+ :type 'coding-system)
+
+(defcustom org-texinfo-default-class "info"
+ "The default Texinfo class."
+ :group 'org-export-texinfo
+ :type '(string :tag "Texinfo class"))
+
+(defcustom org-texinfo-classes
+ '(("info"
+ "@documentencoding AUTO\n@documentlanguage AUTO"
+ ("@chapter %s" . "@unnumbered %s")
+ ("@section %s" . "@unnumberedsec %s")
+ ("@subsection %s" . "@unnumberedsubsec %s")
+ ("@subsubsection %s" . "@unnumberedsubsubsec %s")))
+ "Alist of Texinfo classes and associated header and structure.
+If #+TEXINFO_CLASS is set in the buffer, use its value and the
+associated information. Here is the structure of each cell:
+
+ (class-name
+ header-string
+ (numbered-section . unnumbered-section)
+ ...)
+
+
+The header string
+-----------------
+
+The header string is inserted in the header of the generated
+document, right after \"@setfilename\" and \"@settitle\"
+commands.
+
+If it contains the special string
+
+ \"@documentencoding AUTO\"
+
+\"AUTO\" will be replaced with an appropriate coding system. See
+`org-texinfo-coding-system' for more information. Likewise, if
+the string contains the special string
+
+ \"@documentlanguage AUTO\"
+
+\"AUTO\" will be replaced with the language defined in the
+buffer, through #+LANGUAGE keyword, or globally, with
+`org-export-default-language', which see.
+
+
+The sectioning structure
+------------------------
+
+The sectioning structure of the class is given by the elements
+following the header string. For each sectioning level, a number
+of strings is specified. A %s formatter is mandatory in each
+section string and will be replaced by the title of the section.
+
+Instead of a list of sectioning commands, you can also specify
+a function name. That function will be called with two
+parameters, the reduced) level of the headline, and a predicate
+non-nil when the headline should be numbered. It must return
+a format string in which the section title will be added."
+ :group 'org-export-texinfo
+ :version "24.4"
+ :package-version '(Org . "8.2")
+ :type '(repeat
+ (list (string :tag "Texinfo class")
+ (string :tag "Texinfo header")
+ (repeat :tag "Levels" :inline t
+ (choice
+ (cons :tag "Heading"
+ (string :tag " numbered")
+ (string :tag "unnumbered"))
+ (function :tag "Hook computing sectioning"))))))
+
+;;;; Headline
+
+(defcustom org-texinfo-format-headline-function
+ 'org-texinfo-format-headline-default-function
+ "Function to format headline text.
+
+This function will be called with 5 arguments:
+TODO the todo keyword (string or nil).
+TODO-TYPE the type of todo (symbol: `todo', `done', nil)
+PRIORITY the priority of the headline (integer or nil)
+TEXT the main headline text (string).
+TAGS the tags as a list of strings (list of strings or nil).
+
+The function result will be used in the section format string."
+ :group 'org-export-texinfo
+ :type 'function
+ :version "26.1"
+ :package-version '(Org . "8.3"))
+
+;;;; Node listing (menu)
+
+(defcustom org-texinfo-node-description-column 32
+ "Column at which to start the description in the node listings.
+If a node title is greater than this length, the description will
+be placed after the end of the title."
+ :group 'org-export-texinfo
+ :type 'integer)
+
+;;;; Timestamps
+
+(defcustom org-texinfo-active-timestamp-format "@emph{%s}"
+ "A printf format string to be applied to active timestamps."
+ :group 'org-export-texinfo
+ :type 'string)
+
+(defcustom org-texinfo-inactive-timestamp-format "@emph{%s}"
+ "A printf format string to be applied to inactive timestamps."
+ :group 'org-export-texinfo
+ :type 'string)
+
+(defcustom org-texinfo-diary-timestamp-format "@emph{%s}"
+ "A printf format string to be applied to diary timestamps."
+ :group 'org-export-texinfo
+ :type 'string)
+
+;;;; Links
+
+(defcustom org-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
+ "Format string for links with unknown path type."
+ :group 'org-export-texinfo
+ :type 'string)
+
+;;;; Tables
+
+(defcustom org-texinfo-tables-verbatim nil
+ "When non-nil, tables are exported verbatim."
+ :group 'org-export-texinfo
+ :type 'boolean)
+
+(defcustom org-texinfo-table-scientific-notation "%s\\,(%s)"
+ "Format string to display numbers in scientific notation.
+
+The format should have \"%s\" twice, for mantissa and exponent
+\(i.e. \"%s\\\\times10^{%s}\").
+
+When nil, no transformation is made."
+ :group 'org-export-texinfo
+ :type '(choice
+ (string :tag "Format string")
+ (const :tag "No formatting" nil)))
+
+(defcustom org-texinfo-def-table-markup "@samp"
+ "Default markup for first column in two-column tables.
+
+This should an indicating command, e.g., \"@code\", \"@kbd\" or
+\"@asis\".
+
+It can be overridden locally using the \":indic\" attribute."
+ :group 'org-export-texinfo
+ :type 'string)
+
+;;;; Text markup
+
+(defcustom org-texinfo-text-markup-alist '((bold . "@strong{%s}")
+ (code . code)
+ (italic . "@emph{%s}")
+ (verbatim . verb))
+ "Alist of Texinfo expressions to convert text markup.
+
+The key must be a symbol among `bold', `code', `italic',
+`strike-through', `underscore' and `verbatim'. The value is
+a formatting string to wrap fontified text with.
+
+Value can also be set to the following symbols: `verb' and
+`code'. For the former, Org will use \"@verb\" to create
+a format string and select a delimiter character that isn't in
+the string. For the latter, Org will use \"@code\" to typeset
+and try to protect special characters.
+
+If no association can be found for a given markup, text will be
+returned as-is."
+ :group 'org-export-texinfo
+ :type 'alist
+ :options '(bold code italic strike-through underscore verbatim))
+
+;;;; Drawers
+
+(defcustom org-texinfo-format-drawer-function (lambda (_name contents) contents)
+ "Function called to format a drawer in Texinfo code.
+
+The function must accept two parameters:
+ NAME the drawer name, like \"LOGBOOK\"
+ CONTENTS the contents of the drawer.
+
+The function should return the string to be exported.
+
+The default function simply returns the value of CONTENTS."
+ :group 'org-export-texinfo
+ :version "24.4"
+ :package-version '(Org . "8.2")
+ :type 'function)
+
+;;;; Inlinetasks
+
+(defcustom org-texinfo-format-inlinetask-function
+ 'org-texinfo-format-inlinetask-default-function
+ "Function called to format an inlinetask in Texinfo code.
+
+The function must accept six parameters:
+ TODO the todo keyword, as a string
+ TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
+ PRIORITY the inlinetask priority, as a string
+ NAME the inlinetask name, as a string.
+ TAGS the inlinetask tags, as a list of strings.
+ CONTENTS the contents of the inlinetask, as a string.
+
+The function should return the string to be exported."
+ :group 'org-export-texinfo
+ :type 'function)
+
+;;;; Compilation
+
+(defcustom org-texinfo-info-process '("makeinfo %f")
+ "Commands to process a Texinfo file to an INFO file.
+
+This is a list of strings, each of them will be given to the
+shell as a command. %f in the command will be replaced by the
+relative file name, %F by the absolute file name, %b by the file
+base name (i.e. without directory and extension parts), %o by the
+base directory of the file and %O by the absolute file name of
+the output file."
+ :group 'org-export-texinfo
+ :type '(repeat :tag "Shell command sequence"
+ (string :tag "Shell command")))
+
+(defcustom org-texinfo-logfiles-extensions
+ '("aux" "toc" "cp" "fn" "ky" "pg" "tp" "vr")
+ "The list of file extensions to consider as Texinfo logfiles.
+The logfiles will be remove if `org-texinfo-remove-logfiles' is
+non-nil."
+ :group 'org-export-texinfo
+ :type '(repeat (string :tag "Extension")))
+
+(defcustom org-texinfo-remove-logfiles t
+ "Non-nil means remove the logfiles produced by compiling a Texinfo file.
+By default, logfiles are files with these extensions: .aux, .toc,
+.cp, .fn, .ky, .pg and .tp. To define the set of logfiles to remove,
+set `org-texinfo-logfiles-extensions'."
+ :group 'org-export-latex
+ :type 'boolean)
+
+;;; Constants
+
+(defconst org-texinfo-max-toc-depth 4
+ "Maximum depth for creation of detailed menu listings.
+Beyond this depth, Texinfo will not recognize the nodes and will
+cause errors. Left as a constant in case this value ever
+changes.")
+
+(defconst org-texinfo-supported-coding-systems
+ '("US-ASCII" "UTF-8" "ISO-8859-15" "ISO-8859-1" "ISO-8859-2" "koi8-r" "koi8-u")
+ "List of coding systems supported by Texinfo, as strings.
+Specified coding system will be matched against these strings.
+If two strings share the same prefix (e.g. \"ISO-8859-1\" and
+\"ISO-8859-15\"), the most specific one has to be listed first.")
+
+(defconst org-texinfo-inline-image-rules
+ (list (cons "file"
+ (regexp-opt '("eps" "pdf" "png" "jpg" "jpeg" "gif" "svg"))))
+ "Rules characterizing image files that can be inlined.")
+
+
+;;; Internal Functions
+
+(defun org-texinfo--filter-section-blank-lines (headline _backend _info)
+ "Filter controlling number of blank lines after a section."
+ (replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" "\n\n" headline))
+
+(defun org-texinfo--normalize-headlines (tree _backend info)
+ "Normalize headlines in TREE.
+
+BACK-END is the symbol specifying back-end used for export. INFO
+is a plist used as a communication channel.
+
+Make sure every headline in TREE contains a section, since those
+are required to install a menu. Also put exactly one blank line
+at the end of each section.
+
+Return new tree."
+ (org-element-map tree 'headline
+ (lambda (hl)
+ (org-element-put-property hl :post-blank 1)
+ (let ((contents (org-element-contents hl)))
+ (when contents
+ (let ((first (org-element-map contents '(headline section)
+ #'identity info t)))
+ (unless (eq (org-element-type first) 'section)
+ (apply #'org-element-set-contents
+ hl
+ (cons `(section (:parent ,hl)) contents)))))))
+ info)
+ tree)
+
+(defun org-texinfo--find-verb-separator (s)
+ "Return a character not used in string S.
+This is used to choose a separator for constructs like \\verb."
+ (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
+ (cl-loop for c across ll
+ when (not (string-match (regexp-quote (char-to-string c)) s))
+ return (char-to-string c))))
+
+(defun org-texinfo--text-markup (text markup _info)
+ "Format TEXT depending on MARKUP text markup.
+INFO is a plist used as a communication channel. See
+`org-texinfo-text-markup-alist' for details."
+ (pcase (cdr (assq markup org-texinfo-text-markup-alist))
+ ;; No format string: Return raw text.
+ (`nil text)
+ (`verb
+ (let ((separator (org-texinfo--find-verb-separator text)))
+ (concat "@verb{" separator text separator "}")))
+ (`code
+ (format "@code{%s}" (replace-regexp-in-string "[@{}]" "@\\&" text)))
+ ;; Else use format string.
+ (fmt (format fmt text))))
+
+(defun org-texinfo--get-node (datum info)
+ "Return node or anchor associated to DATUM.
+DATUM is an element or object. INFO is a plist used as
+a communication channel. The function guarantees the node or
+anchor name is unique."
+ (let ((cache (plist-get info :texinfo-node-cache)))
+ (or (cdr (assq datum cache))
+ (let* ((salt 0)
+ (basename
+ (org-texinfo--sanitize-node
+ (if (eq (org-element-type datum) 'headline)
+ (org-texinfo--sanitize-title
+ (org-export-get-alt-title datum info) info)
+ (org-export-get-reference datum info))))
+ (name basename))
+ ;; Ensure NAME is unique and not reserved node name "Top".
+ (while (or (equal name "Top") (rassoc name cache))
+ (setq name (concat basename (format " %d" (cl-incf salt)))))
+ (plist-put info :texinfo-node-cache (cons (cons datum name) cache))
+ name))))
+
+(defun org-texinfo--sanitize-node (title)
+ "Bend string TITLE to node line requirements.
+Trim string and collapse multiple whitespace characters as they
+are not significant. Replace leading left parenthesis, when
+followed by a right parenthesis, with a square bracket. Remove
+periods, commas and colons."
+ (org-trim
+ (replace-regexp-in-string
+ "[ \t]+" " "
+ (replace-regexp-in-string
+ "[:,.]" ""
+ (replace-regexp-in-string "\\`(\\(.*?)\\)" "[\\1" title)))))
+
+(defun org-texinfo--sanitize-title (title info)
+ "Make TITLE suitable as a section name.
+TITLE is a string or a secondary string. INFO is the current
+export state, as a plist."
+ (org-export-data-with-backend
+ title
+ (org-export-create-backend
+ :parent 'texinfo
+ :transcoders '((footnote-reference . ignore)
+ (link . (lambda (object c i) c))
+ (radio-target . (lambda (object c i) c))
+ (target . ignore)))
+ info))
+
+(defun org-texinfo--sanitize-content (text)
+ "Escape special characters in string TEXT.
+Special characters are: @ { }"
+ (replace-regexp-in-string "[@{}]" "@\\&" text))
+
+(defun org-texinfo--wrap-float (value info &optional type label caption short)
+ "Wrap string VALUE within a @float command.
+INFO is the current export state, as a plist. TYPE is float
+type, as a string. LABEL is the cross reference label for the
+float, as a string. CAPTION and SHORT are, respectively, the
+caption and shortcaption used for the float, as secondary
+strings (e.g., returned by `org-export-get-caption')."
+ (let* ((backend
+ (org-export-create-backend
+ :parent 'texinfo
+ :transcoders '((link . (lambda (object c i) c))
+ (radio-target . (lambda (object c i) c))
+ (target . ignore))))
+ (short-backend
+ (org-export-create-backend
+ :parent 'texinfo
+ :transcoders '((footnote-reference . ignore)
+ (inline-src-block . ignore)
+ (link . (lambda (object c i) c))
+ (radio-target . (lambda (object c i) c))
+ (target . ignore)
+ (verbatim . ignore))))
+ (short-str
+ (if (and short caption)
+ (format "@shortcaption{%s}\n"
+ (org-export-data-with-backend short short-backend info))
+ ""))
+ (caption-str
+ (if (or short caption)
+ (format "@caption{%s}\n"
+ (org-export-data-with-backend
+ (or caption short)
+ (if (equal short-str "") short-backend backend)
+ info))
+ "")))
+ (format "@float %s%s\n%s\n%s%s@end float"
+ type (if label (concat "," label) "") value caption-str short-str)))
+
+;;; Template
+
+(defun org-texinfo-template (contents info)
+ "Return complete document string after Texinfo conversion.
+CONTENTS is the transcoded contents string. INFO is a plist
+holding export options."
+ (let ((title (org-export-data (plist-get info :title) info))
+ ;; Copying data is the contents of the first headline in
+ ;; parse tree with a non-nil copying property.
+ (copying (org-element-map (plist-get info :parse-tree) 'headline
+ (lambda (hl)
+ (and (org-not-nil (org-element-property :COPYING hl))
+ (org-element-contents hl)))
+ info t)))
+ (concat
+ "\\input texinfo @c -*- texinfo -*-\n"
+ "@c %**start of header\n"
+ (let ((file (or (plist-get info :texinfo-filename)
+ (let ((f (plist-get info :output-file)))
+ (and f (concat (file-name-sans-extension f) ".info"))))))
+ (and file (format "@setfilename %s\n" file)))
+ (format "@settitle %s\n" title)
+ ;; Insert class-defined header.
+ (org-element-normalize-string
+ (let ((header (nth 1 (assoc (plist-get info :texinfo-class)
+ org-texinfo-classes)))
+ (coding
+ (catch 'coding-system
+ (let ((case-fold-search t)
+ (name (symbol-name (or org-texinfo-coding-system
+ buffer-file-coding-system))))
+ (dolist (system org-texinfo-supported-coding-systems "UTF-8")
+ (when (string-match-p (regexp-quote system) name)
+ (throw 'coding-system system))))))
+ (language (plist-get info :language))
+ (case-fold-search nil))
+ ;; Auto coding system.
+ (replace-regexp-in-string
+ "^@documentencoding \\(AUTO\\)$"
+ coding
+ (replace-regexp-in-string
+ "^@documentlanguage \\(AUTO\\)$" language header t nil 1) t nil 1)))
+ ;; Additional header options set by #+TEXINFO_HEADER.
+ (let ((texinfo-header (plist-get info :texinfo-header)))
+ (and texinfo-header (org-element-normalize-string texinfo-header)))
+ "@c %**end of header\n\n"
+ ;; Additional options set by #+TEXINFO_POST_HEADER.
+ (let ((texinfo-post-header (plist-get info :texinfo-post-header)))
+ (and texinfo-post-header
+ (org-element-normalize-string texinfo-post-header)))
+ ;; Copying.
+ (and copying
+ (format "@copying\n%s@end copying\n\n"
+ (org-element-normalize-string
+ (org-export-data copying info))))
+ ;; Info directory information. Only supply if both title and
+ ;; category are provided.
+ (let ((dircat (plist-get info :texinfo-dircat))
+ (dirtitle
+ (let ((title (plist-get info :texinfo-dirtitle)))
+ (and title
+ (string-match "^\\(?:\\* \\)?\\(.*?\\)\\(\\.\\)?$" title)
+ (format "* %s." (match-string 1 title))))))
+ (when (and dircat dirtitle)
+ (concat "@dircategory " dircat "\n"
+ "@direntry\n"
+ (let ((dirdesc
+ (let ((desc (plist-get info :texinfo-dirdesc)))
+ (cond ((not desc) nil)
+ ((string-suffix-p "." desc) desc)
+ (t (concat desc "."))))))
+ (if dirdesc (format "%-23s %s" dirtitle dirdesc) dirtitle))
+ "\n"
+ "@end direntry\n\n")))
+ ;; Title
+ "@finalout\n"
+ "@titlepage\n"
+ (when (plist-get info :with-title)
+ (concat
+ (format "@title %s\n"
+ (or (plist-get info :texinfo-printed-title) title ""))
+ (let ((subtitle (plist-get info :subtitle)))
+ (when subtitle
+ (format "@subtitle %s\n"
+ (org-export-data subtitle info))))))
+ (when (plist-get info :with-author)
+ (concat
+ ;; Primary author.
+ (let ((author (org-string-nw-p
+ (org-export-data (plist-get info :author) info)))
+ (email (and (plist-get info :with-email)
+ (org-string-nw-p
+ (org-export-data (plist-get info :email) info)))))
+ (cond ((and author email)
+ (format "@author %s (@email{%s})\n" author email))
+ (author (format "@author %s\n" author))
+ (email (format "@author @email{%s}\n" email))))
+ ;; Other authors.
+ (let ((subauthor (plist-get info :subauthor)))
+ (and subauthor
+ (org-element-normalize-string
+ (replace-regexp-in-string "^" "@author " subauthor))))))
+ (and copying "@page\n@vskip 0pt plus 1filll\n@insertcopying\n")
+ "@end titlepage\n\n"
+ ;; Table of contents.
+ (and (plist-get info :with-toc) "@contents\n\n")
+ ;; Configure Top Node when not for TeX. Also include contents
+ ;; from the first section of the document.
+ "@ifnottex\n"
+ "@node Top\n"
+ (format "@top %s\n" title)
+ (let* ((first-section
+ (org-element-map (plist-get info :parse-tree) 'section
+ #'identity info t '(headline)))
+ (top-contents
+ (org-export-data (org-element-contents first-section) info)))
+ (and (org-string-nw-p top-contents) (concat "\n" top-contents)))
+ "@end ifnottex\n\n"
+ ;; Menu.
+ (org-texinfo-make-menu (plist-get info :parse-tree) info 'master)
+ "\n"
+ ;; Document's body.
+ contents "\n"
+ ;; Creator.
+ (and (plist-get info :with-creator)
+ (concat (plist-get info :creator) "\n"))
+ ;; Document end.
+ "@bye")))
+
+
+
+;;; Transcode Functions
+
+;;;; Bold
+
+(defun org-texinfo-bold (_bold contents info)
+ "Transcode BOLD from Org to Texinfo.
+CONTENTS is the text with bold markup. INFO is a plist holding
+contextual information."
+ (org-texinfo--text-markup contents 'bold info))
+
+;;;; Center Block
+
+(defun org-texinfo-center-block (_center-block contents _info)
+ "Transcode a CENTER-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist used
+as a communication channel."
+ contents)
+
+;;;; Clock
+
+(defun org-texinfo-clock (clock _contents info)
+ "Transcode a CLOCK element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ "@noindent"
+ (format "@strong{%s} " org-clock-string)
+ (format (plist-get info :texinfo-inactive-timestamp-format)
+ (concat (org-timestamp-translate (org-element-property :value clock))
+ (let ((time (org-element-property :duration clock)))
+ (and time (format " (%s)" time)))))
+ "@*"))
+
+;;;; Code
+
+(defun org-texinfo-code (code _contents info)
+ "Transcode a CODE object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-texinfo--text-markup (org-element-property :value code) 'code info))
+
+;;;; Drawer
+
+(defun org-texinfo-drawer (drawer contents info)
+ "Transcode a DRAWER element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((name (org-element-property :drawer-name drawer))
+ (output (funcall (plist-get info :texinfo-format-drawer-function)
+ name contents)))
+ output))
+
+;;;; Dynamic Block
+
+(defun org-texinfo-dynamic-block (_dynamic-block contents _info)
+ "Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ contents)
+
+;;;; Entity
+
+(defun org-texinfo-entity (entity _contents _info)
+ "Transcode an ENTITY object from Org to Texinfo."
+ ;; Since there is not specific Texinfo entry in entities, use
+ ;; Texinfo-specific commands whenever possible, and fallback to
+ ;; UTF-8 otherwise.
+ (pcase (org-element-property :name entity)
+ ("AElig" "@AE{}")
+ ("aelig" "@ae{}")
+ ((or "bull" "bullet") "@bullet{}")
+ ("copy" "@copyright{}")
+ ("deg" "@textdegree{}")
+ ((or "dots" "hellip") "@dots{}")
+ ("equiv" "@equiv{}")
+ ((or "euro" "EUR") "@euro{}")
+ ((or "ge" "geq") "@geq{}")
+ ("laquo" "@guillemetleft{}")
+ ("iexcl" "@exclamdown{}")
+ ("imath" "@dotless{i}")
+ ("iquest" "@questiondown{}")
+ ("jmath" "@dotless{j}")
+ ((or "le" "leq") "@leq{}")
+ ("lsaquo" "@guilsinglleft{}")
+ ("mdash" "---")
+ ("minus" "@minus{}")
+ ("nbsp" "@tie{}")
+ ("ndash" "--")
+ ("OElig" "@OE{}")
+ ("oelig" "@oe{}")
+ ("ordf" "@ordf{}")
+ ("ordm" "@ordm{}")
+ ("pound" "@pound{}")
+ ("raquo" "@guillemetright{}")
+ ((or "rArr" "Rightarrow") "@result{}")
+ ("reg" "@registeredsymbol{}")
+ ((or "rightarrow" "to" "rarr") "@arrow{}")
+ ("rsaquo" "@guilsinglright{}")
+ ("thorn" "@th{}")
+ ("THORN" "@TH{}")
+ ((and (pred (string-prefix-p "_")) name) ;spacing entities
+ (format "@w{%s}" (substring name 1)))
+ (_ (org-element-property :utf-8 entity))))
+
+;;;; Example Block
+
+(defun org-texinfo-example-block (example-block _contents info)
+ "Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "@verbatim\n%s@end verbatim"
+ (org-export-format-code-default example-block info)))
+
+;;; Export Block
+
+(defun org-texinfo-export-block (export-block _contents _info)
+ "Transcode a EXPORT-BLOCK element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (string= (org-element-property :type export-block) "TEXINFO")
+ (org-remove-indentation (org-element-property :value export-block))))
+
+;;; Export Snippet
+
+(defun org-texinfo-export-snippet (export-snippet _contents _info)
+ "Transcode a EXPORT-SNIPPET object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (when (eq (org-export-snippet-backend export-snippet) 'texinfo)
+ (org-element-property :value export-snippet)))
+
+;;;; Fixed Width
+
+(defun org-texinfo-fixed-width (fixed-width _contents _info)
+ "Transcode a FIXED-WIDTH element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (format "@example\n%s@end example"
+ (org-remove-indentation
+ (org-texinfo--sanitize-content
+ (org-element-property :value fixed-width)))))
+
+;;;; Footnote Reference
+
+(defun org-texinfo-footnote-reference (footnote _contents info)
+ "Create a footnote reference for FOOTNOTE.
+
+FOOTNOTE is the footnote to define. CONTENTS is nil. INFO is a
+plist holding contextual information."
+ (let ((def (org-export-get-footnote-definition footnote info)))
+ (format "@footnote{%s}"
+ (org-trim (org-export-data def info)))))
+
+;;;; Headline
+
+(defun org-texinfo-headline (headline contents info)
+ "Transcode a HEADLINE element from Org to Texinfo.
+CONTENTS holds the contents of the headline. INFO is a plist
+holding contextual information."
+ (let* ((class (plist-get info :texinfo-class))
+ (level (org-export-get-relative-level headline info))
+ (numberedp (org-export-numbered-headline-p headline info))
+ (class-sectioning (assoc class (plist-get info :texinfo-classes)))
+ ;; Find the index type, if any.
+ (index (org-element-property :INDEX headline))
+ ;; Create node info, to insert it before section formatting.
+ ;; Use custom menu title if present.
+ (node (format "@node %s\n" (org-texinfo--get-node headline info)))
+ ;; Section formatting will set two placeholders: one for the
+ ;; title and the other for the contents.
+ (section-fmt
+ (if (org-not-nil (org-element-property :APPENDIX headline))
+ "@appendix %s\n%s"
+ (let ((sec (if (and (symbolp (nth 2 class-sectioning))
+ (fboundp (nth 2 class-sectioning)))
+ (funcall (nth 2 class-sectioning) level numberedp)
+ (nth (1+ level) class-sectioning))))
+ (cond
+ ;; No section available for that LEVEL.
+ ((not sec) nil)
+ ;; Section format directly returned by a function.
+ ((stringp sec) sec)
+ ;; (numbered-section . unnumbered-section)
+ ((not (consp (cdr sec)))
+ (concat (if (or index (not numberedp)) (cdr sec) (car sec))
+ "\n%s"))))))
+ (todo
+ (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword headline)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (and todo (org-element-property :todo-type headline)))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags headline info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority headline)))
+ (text (org-texinfo--sanitize-title
+ (org-element-property :title headline) info))
+ (full-text (funcall (plist-get info :texinfo-format-headline-function)
+ todo todo-type priority text tags))
+ (contents (if (org-string-nw-p contents) (concat "\n" contents) "")))
+ (cond
+ ;; Case 1: This is a footnote section: ignore it.
+ ((org-element-property :footnote-section-p headline) nil)
+ ;; Case 2: This is the `copying' section: ignore it
+ ;; This is used elsewhere.
+ ((org-not-nil (org-element-property :COPYING headline)) nil)
+ ;; Case 3: An index. If it matches one of the known indexes,
+ ;; print it as such following the contents, otherwise
+ ;; print the contents and leave the index up to the user.
+ (index
+ (concat node
+ (format
+ section-fmt
+ full-text
+ (concat contents
+ (and (member index '("cp" "fn" "ky" "pg" "tp" "vr"))
+ (concat "\n@printindex " index))))))
+ ;; Case 4: This is a deep sub-tree: export it as a list item.
+ ;; Also export as items headlines for which no section
+ ;; format has been found.
+ ((or (not section-fmt) (org-export-low-level-p headline info))
+ ;; Build the real contents of the sub-tree.
+ (concat (and (org-export-first-sibling-p headline info)
+ (format "@%s\n" (if numberedp 'enumerate 'itemize)))
+ "@item\n" full-text "\n"
+ contents
+ (if (org-export-last-sibling-p headline info)
+ (format "@end %s" (if numberedp 'enumerate 'itemize))
+ "\n")))
+ ;; Case 5: Standard headline. Export it as a section.
+ (t (concat node (format section-fmt full-text contents))))))
+
+(defun org-texinfo-format-headline-default-function
+ (todo _todo-type priority text tags)
+ "Default format function for a headline.
+See `org-texinfo-format-headline-function' for details."
+ (concat (when todo (format "@strong{%s} " todo))
+ (when priority (format "@emph{#%s} " priority))
+ text
+ (when tags (format " :%s:" (mapconcat 'identity tags ":")))))
+
+;;;; Inline Src Block
+
+(defun org-texinfo-inline-src-block (inline-src-block _contents _info)
+ "Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((code (org-element-property :value inline-src-block))
+ (separator (org-texinfo--find-verb-separator code)))
+ (concat "@verb{" separator code separator "}")))
+
+;;;; Inlinetask
+
+(defun org-texinfo-inlinetask (inlinetask contents info)
+ "Transcode an INLINETASK element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let ((title (org-export-data (org-element-property :title inlinetask) info))
+ (todo (and (plist-get info :with-todo-keywords)
+ (let ((todo (org-element-property :todo-keyword inlinetask)))
+ (and todo (org-export-data todo info)))))
+ (todo-type (org-element-property :todo-type inlinetask))
+ (tags (and (plist-get info :with-tags)
+ (org-export-get-tags inlinetask info)))
+ (priority (and (plist-get info :with-priority)
+ (org-element-property :priority inlinetask))))
+ (funcall (plist-get info :texinfo-format-inlinetask-function)
+ todo todo-type priority title tags contents)))
+
+(defun org-texinfo-format-inlinetask-default-function
+ (todo _todo-type priority title tags contents)
+ "Default format function for a inlinetasks.
+See `org-texinfo-format-inlinetask-function' for details."
+ (let ((full-title
+ (concat (when todo (format "@strong{%s} " todo))
+ (when priority (format "#%c " priority))
+ title
+ (when tags (format ":%s:" (mapconcat #'identity tags ":"))))))
+ (format "@center %s\n\n%s\n" full-title contents)))
+
+;;;; Italic
+
+(defun org-texinfo-italic (_italic contents info)
+ "Transcode ITALIC from Org to Texinfo.
+CONTENTS is the text with italic markup. INFO is a plist holding
+contextual information."
+ (org-texinfo--text-markup contents 'italic info))
+
+;;;; Item
+
+(defun org-texinfo-item (item contents info)
+ "Transcode an ITEM element from Org to Texinfo.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (format "@item%s\n%s"
+ (let ((tag (org-element-property :tag item)))
+ (if tag (concat " " (org-export-data tag info)) ""))
+ (or contents "")))
+
+;;;; Keyword
+
+(defun org-texinfo-keyword (keyword _contents info)
+ "Transcode a KEYWORD element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (let ((value (org-element-property :value keyword)))
+ (pcase (org-element-property :key keyword)
+ ("TEXINFO" value)
+ ("CINDEX" (format "@cindex %s" value))
+ ("FINDEX" (format "@findex %s" value))
+ ("KINDEX" (format "@kindex %s" value))
+ ("PINDEX" (format "@pindex %s" value))
+ ("TINDEX" (format "@tindex %s" value))
+ ("VINDEX" (format "@vindex %s" value))
+ ("TOC"
+ (cond ((string-match-p "\\<tables\\>" value)
+ (concat "@listoffloats "
+ (org-export-translate "Table" :utf-8 info)))
+ ((string-match-p "\\<listings\\>" value)
+ (concat "@listoffloats "
+ (org-export-translate "Listing" :utf-8 info))))))))
+
+;;;; Line Break
+
+(defun org-texinfo-line-break (_line-break _contents _info)
+ "Transcode a LINE-BREAK object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ "@*\n")
+
+;;;; Link
+
+(defun org-texinfo--@ref (datum description info)
+ "Return @ref command for element or object DATUM.
+DESCRIPTION is the name of the section to print, as a string."
+ (let ((node-name (org-texinfo--get-node datum info))
+ ;; Sanitize DESCRIPTION for cross-reference use. In
+ ;; particular, remove colons as they seem to cause (even
+ ;; within @asis{...} to the Texinfo reader.
+ (title (replace-regexp-in-string
+ "[ \t]*:+" ""
+ (replace-regexp-in-string "," "@comma{}" description))))
+ (if (equal title node-name)
+ (format "@ref{%s}" node-name)
+ (format "@ref{%s, , %s}" node-name title))))
+
+(defun org-texinfo-link (link desc info)
+ "Transcode a LINK object from Org to Texinfo.
+DESC is the description part of the link, or the empty string.
+INFO is a plist holding contextual information. See
+`org-export-data'."
+ (let* ((type (org-element-property :type link))
+ (raw-path (org-element-property :path link))
+ ;; Ensure DESC really exists, or set it to nil.
+ (desc (and (not (string= desc "")) desc))
+ (path (cond
+ ((member type '("http" "https" "ftp"))
+ (concat type ":" raw-path))
+ ((string= type "file") (org-export-file-uri raw-path))
+ (t raw-path))))
+ (cond
+ ((org-export-custom-protocol-maybe link desc 'texinfo))
+ ((org-export-inline-image-p link org-texinfo-inline-image-rules)
+ (org-texinfo--inline-image link info))
+ ((equal type "radio")
+ (let ((destination (org-export-resolve-radio-link link info)))
+ (if (not destination) desc
+ (org-texinfo--@ref destination desc info))))
+ ((member type '("custom-id" "id" "fuzzy"))
+ (let ((destination
+ (if (equal type "fuzzy")
+ (org-export-resolve-fuzzy-link link info)
+ (org-export-resolve-id-link link info))))
+ (pcase (org-element-type destination)
+ (`nil
+ (format org-texinfo-link-with-unknown-path-format
+ (org-texinfo--sanitize-content path)))
+ ;; Id link points to an external file.
+ (`plain-text
+ (if desc (format "@uref{file://%s,%s}" destination desc)
+ (format "@uref{file://%s}" destination)))
+ ((or `headline
+ ;; Targets within headlines cannot be turned into
+ ;; @anchor{}, so we refer to the headline parent
+ ;; directly.
+ (and `target
+ (guard (eq 'headline
+ (org-element-type
+ (org-element-property :parent destination))))))
+ (let ((headline (org-element-lineage destination '(headline) t)))
+ (org-texinfo--@ref
+ headline
+ (or desc (org-texinfo--sanitize-title
+ (org-element-property :title headline) info))
+ info)))
+ (_
+ (org-texinfo--@ref
+ destination
+ (or desc
+ (pcase (org-export-get-ordinal destination info)
+ ((and (pred integerp) n) (number-to-string n))
+ ((and (pred consp) n) (mapconcat #'number-to-string n "."))
+ (_ "???")))
+ info))))) ;cannot guess the description
+ ((equal type "info")
+ (let* ((info-path (split-string path "[:#]"))
+ (info-manual (car info-path))
+ (info-node (or (cadr info-path) "Top"))
+ (title (or desc "")))
+ (format "@ref{%s,%s,,%s,}" info-node title info-manual)))
+ ((string= type "mailto")
+ (format "@email{%s}"
+ (concat (org-texinfo--sanitize-content path)
+ (and desc (concat ", " desc)))))
+ ;; External link with a description part.
+ ((and path desc) (format "@uref{%s, %s}" path desc))
+ ;; External link without a description part.
+ (path (format "@uref{%s}" path))
+ ;; No path, only description. Try to do something useful.
+ (t
+ (format (plist-get info :texinfo-link-with-unknown-path-format) desc)))))
+
+(defun org-texinfo--inline-image (link info)
+ "Return Texinfo code for an inline image.
+LINK is the link pointing to the inline image. INFO is the
+current state of the export, as a plist."
+ (let* ((parent (org-export-get-parent-element link))
+ (label (and (org-element-property :name parent)
+ (org-texinfo--get-node parent info)))
+ (caption (org-export-get-caption parent))
+ (shortcaption (org-export-get-caption parent t))
+ (path (org-element-property :path link))
+ (filename
+ (file-name-sans-extension
+ (if (file-name-absolute-p path) (expand-file-name path) path)))
+ (extension (file-name-extension path))
+ (attributes (org-export-read-attribute :attr_texinfo parent))
+ (height (or (plist-get attributes :height) ""))
+ (width (or (plist-get attributes :width) ""))
+ (alt (or (plist-get attributes :alt) ""))
+ (image (format "@image{%s,%s,%s,%s,%s}"
+ filename width height alt extension)))
+ (cond ((or caption shortcaption)
+ (org-texinfo--wrap-float image
+ info
+ (org-export-translate "Figure" :utf-8 info)
+ label
+ caption
+ shortcaption))
+ (label (concat "@anchor{" label "}\n" image))
+ (t image))))
+
+
+;;;; Menu
+
+(defun org-texinfo-make-menu (scope info &optional master)
+ "Create the menu for inclusion in the Texinfo document.
+
+SCOPE is a headline or a full parse tree. INFO is the
+communication channel, as a plist.
+
+When optional argument MASTER is non-nil, generate a master menu,
+including detailed node listing."
+ (let ((menu (org-texinfo--build-menu scope info)))
+ (when (org-string-nw-p menu)
+ (org-element-normalize-string
+ (format
+ "@menu\n%s@end menu"
+ (concat menu
+ (when master
+ (let ((detailmenu
+ (org-texinfo--build-menu
+ scope info
+ (let ((toc-depth (plist-get info :with-toc)))
+ (if (wholenump toc-depth) toc-depth
+ org-texinfo-max-toc-depth)))))
+ (when (org-string-nw-p detailmenu)
+ (concat "\n@detailmenu\n"
+ "--- The Detailed Node Listing ---\n\n"
+ detailmenu
+ "@end detailmenu\n"))))))))))
+
+(defun org-texinfo--build-menu (scope info &optional level)
+ "Build menu for entries within SCOPE.
+SCOPE is a headline or a full parse tree. INFO is a plist
+containing contextual information. When optional argument LEVEL
+is an integer, build the menu recursively, down to this depth."
+ (cond
+ ((not level)
+ (org-texinfo--format-entries (org-texinfo--menu-entries scope info) info))
+ ((zerop level) nil)
+ (t
+ (org-element-normalize-string
+ (mapconcat
+ (lambda (h)
+ (let ((entries (org-texinfo--menu-entries h info)))
+ (when entries
+ (concat
+ (format "%s\n\n%s\n"
+ (org-export-data (org-export-get-alt-title h info) info)
+ (org-texinfo--format-entries entries info))
+ (org-texinfo--build-menu h info (1- level))))))
+ (org-texinfo--menu-entries scope info) "\n")))))
+
+(defun org-texinfo--format-entries (entries info)
+ "Format all direct menu entries in SCOPE, as a string.
+SCOPE is either a headline or a full Org document. INFO is
+a plist containing contextual information."
+ (org-element-normalize-string
+ (mapconcat
+ (lambda (h)
+ (let* ((title
+ ;; Colons are used as a separator between title and node
+ ;; name. Remove them.
+ (replace-regexp-in-string
+ "[ \t]+:+" ""
+ (org-texinfo--sanitize-title
+ (org-export-get-alt-title h info) info)))
+ (node (org-texinfo--get-node h info))
+ (entry (concat "* " title ":"
+ (if (string= title node) ":"
+ (concat " " node ". "))))
+ (desc (org-element-property :DESCRIPTION h)))
+ (if (not desc) entry
+ (format (format "%%-%ds %%s" org-texinfo-node-description-column)
+ entry desc))))
+ entries "\n")))
+
+(defun org-texinfo--menu-entries (scope info)
+ "List direct children in SCOPE needing a menu entry.
+SCOPE is a headline or a full parse tree. INFO is a plist
+holding contextual information."
+ (let* ((cache (or (plist-get info :texinfo-entries-cache)
+ (plist-get (plist-put info :texinfo-entries-cache
+ (make-hash-table :test #'eq))
+ :texinfo-entries-cache)))
+ (cached-entries (gethash scope cache 'no-cache)))
+ (if (not (eq cached-entries 'no-cache)) cached-entries
+ (puthash scope
+ (org-element-map (org-element-contents scope) 'headline
+ (lambda (h)
+ (and (not (org-not-nil (org-element-property :COPYING h)))
+ (not (org-element-property :footnote-section-p h))
+ (not (org-export-low-level-p h info))
+ h))
+ info nil 'headline)
+ cache))))
+
+;;;; Node Property
+
+(defun org-texinfo-node-property (node-property _contents _info)
+ "Transcode a NODE-PROPERTY element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "%s:%s"
+ (org-element-property :key node-property)
+ (let ((value (org-element-property :value node-property)))
+ (if value (concat " " value) ""))))
+
+;;;; Paragraph
+
+(defun org-texinfo-paragraph (_paragraph contents _info)
+ "Transcode a PARAGRAPH element from Org to Texinfo.
+CONTENTS is the contents of the paragraph, as a string. INFO is
+the plist used as a communication channel."
+ contents)
+
+;;;; Plain List
+
+(defun org-texinfo-plain-list (plain-list contents info)
+ "Transcode a PLAIN-LIST element from Org to Texinfo.
+CONTENTS is the contents of the list. INFO is a plist holding
+contextual information."
+ (let* ((attr (org-export-read-attribute :attr_texinfo plain-list))
+ (indic (let ((i (or (plist-get attr :indic)
+ (plist-get info :texinfo-def-table-markup))))
+ ;; Allow indicating commands with missing @ sign.
+ (if (string-prefix-p "@" i) i (concat "@" i))))
+ (table-type (plist-get attr :table-type))
+ (type (org-element-property :type plain-list))
+ (list-type (cond
+ ((eq type 'ordered) "enumerate")
+ ((eq type 'unordered) "itemize")
+ ((member table-type '("ftable" "vtable")) table-type)
+ (t "table"))))
+ (format "@%s\n%s@end %s"
+ (if (eq type 'descriptive) (concat list-type " " indic) list-type)
+ contents
+ list-type)))
+
+;;;; Plain Text
+
+(defun org-texinfo-plain-text (text info)
+ "Transcode a TEXT string from Org to Texinfo.
+TEXT is the string to transcode. INFO is a plist holding
+contextual information."
+ ;; First protect @, { and }.
+ (let ((output (org-texinfo--sanitize-content text)))
+ ;; Activate smart quotes. Be sure to provide original TEXT string
+ ;; since OUTPUT may have been modified.
+ (when (plist-get info :with-smart-quotes)
+ (setq output
+ (org-export-activate-smart-quotes output :texinfo info text)))
+ ;; LaTeX into @LaTeX{} and TeX into @TeX{}
+ (let ((case-fold-search nil))
+ (setq output (replace-regexp-in-string "\\(?:La\\)?TeX" "@\\&{}" output)))
+ ;; Convert special strings.
+ (when (plist-get info :with-special-strings)
+ (setq output
+ (replace-regexp-in-string
+ "\\.\\.\\." "@dots{}"
+ (replace-regexp-in-string "\\\\-" "@-" output))))
+ ;; Handle break preservation if required.
+ (when (plist-get info :preserve-breaks)
+ (setq output (replace-regexp-in-string
+ "\\(\\\\\\\\\\)?[ \t]*\n" " @*\n" output)))
+ ;; Return value.
+ output))
+
+;;;; Planning
+
+(defun org-texinfo-planning (planning _contents info)
+ "Transcode a PLANNING element from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (concat
+ "@noindent"
+ (mapconcat
+ 'identity
+ (delq nil
+ (list
+ (let ((closed (org-element-property :closed planning)))
+ (when closed
+ (concat
+ (format "@strong{%s} " org-closed-string)
+ (format (plist-get info :texinfo-inactive-timestamp-format)
+ (org-timestamp-translate closed)))))
+ (let ((deadline (org-element-property :deadline planning)))
+ (when deadline
+ (concat
+ (format "@strong{%s} " org-deadline-string)
+ (format (plist-get info :texinfo-active-timestamp-format)
+ (org-timestamp-translate deadline)))))
+ (let ((scheduled (org-element-property :scheduled planning)))
+ (when scheduled
+ (concat
+ (format "@strong{%s} " org-scheduled-string)
+ (format (plist-get info :texinfo-active-timestamp-format)
+ (org-timestamp-translate scheduled)))))))
+ " ")
+ "@*"))
+
+;;;; Property Drawer
+
+(defun org-texinfo-property-drawer (_property-drawer contents _info)
+ "Transcode a PROPERTY-DRAWER element from Org to Texinfo.
+CONTENTS holds the contents of the drawer. INFO is a plist
+holding contextual information."
+ (and (org-string-nw-p contents)
+ (format "@verbatim\n%s@end verbatim" contents)))
+
+;;;; Quote Block
+
+(defun org-texinfo-quote-block (quote-block contents _info)
+ "Transcode a QUOTE-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist
+holding contextual information."
+ (let* ((title (org-element-property :name quote-block))
+ (start-quote (concat "@quotation"
+ (if title
+ (format " %s" title)))))
+ (format "%s\n%s@end quotation" start-quote contents)))
+
+;;;; Radio Target
+
+(defun org-texinfo-radio-target (radio-target text info)
+ "Transcode a RADIO-TARGET object from Org to Texinfo.
+TEXT is the text of the target. INFO is a plist holding
+contextual information."
+ (format "@anchor{%s}%s"
+ (org-texinfo--get-node radio-target info)
+ text))
+
+;;;; Section
+
+(defun org-texinfo-section (section contents info)
+ "Transcode a SECTION element from Org to Texinfo.
+CONTENTS holds the contents of the section. INFO is a plist
+holding contextual information."
+ (let ((parent (org-export-get-parent-headline section)))
+ (when parent ;ignore very first section
+ (org-trim
+ (concat contents "\n" (org-texinfo-make-menu parent info))))))
+
+;;;; Special Block
+
+(defun org-texinfo-special-block (special-block contents _info)
+ "Transcode a SPECIAL-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the block. INFO is a plist used
+as a communication channel."
+ (let ((opt (org-export-read-attribute :attr_texinfo special-block :options))
+ (type (org-element-property :type special-block)))
+ (format "@%s%s\n%s@end %s"
+ type
+ (if opt (concat " " opt) "")
+ (or contents "")
+ type)))
+
+;;;; Src Block
+
+(defun org-texinfo-src-block (src-block _contents info)
+ "Transcode a SRC-BLOCK element from Org to Texinfo.
+CONTENTS holds the contents of the item. INFO is a plist holding
+contextual information."
+ (let* ((lisp (string-match-p "lisp"
+ (org-element-property :language src-block)))
+ (code (org-texinfo--sanitize-content
+ (org-export-format-code-default src-block info)))
+ (value (format
+ (if lisp "@lisp\n%s@end lisp" "@example\n%s@end example")
+ code))
+ (caption (org-export-get-caption src-block))
+ (shortcaption (org-export-get-caption src-block t)))
+ (if (not (or caption shortcaption)) value
+ (org-texinfo--wrap-float value
+ info
+ (org-export-translate "Listing" :utf-8 info)
+ (org-texinfo--get-node src-block info)
+ caption
+ shortcaption))))
+
+;;;; Statistics Cookie
+
+(defun org-texinfo-statistics-cookie (statistics-cookie _contents _info)
+ "Transcode a STATISTICS-COOKIE object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual information."
+ (org-element-property :value statistics-cookie))
+
+
+;;;; Strike-through
+
+(defun org-texinfo-strike-through (_strike-through contents info)
+ "Transcode STRIKE-THROUGH from Org to Texinfo.
+CONTENTS is the text with strike-through markup. INFO is a plist
+holding contextual information."
+ (org-texinfo--text-markup contents 'strike-through info))
+
+;;;; Subscript
+
+(defun org-texinfo-subscript (_subscript contents _info)
+ "Transcode a SUBSCRIPT object from Org to Texinfo.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "@math{_%s}" contents))
+
+;;;; Superscript
+
+(defun org-texinfo-superscript (_superscript contents _info)
+ "Transcode a SUPERSCRIPT object from Org to Texinfo.
+CONTENTS is the contents of the object. INFO is a plist holding
+contextual information."
+ (format "@math{^%s}" contents))
+
+;;;; Table
+
+(defun org-texinfo-table (table contents info)
+ "Transcode a TABLE element from Org to Texinfo.
+CONTENTS is the contents of the table. INFO is a plist holding
+contextual information."
+ (if (eq (org-element-property :type table) 'table.el)
+ (format "@verbatim\n%s@end verbatim"
+ (org-element-normalize-string
+ (org-element-property :value table)))
+ (let* ((col-width (org-export-read-attribute :attr_texinfo table :columns))
+ (columns
+ (if col-width (format "@columnfractions %s" col-width)
+ (org-texinfo-table-column-widths table info)))
+ (caption (org-export-get-caption table))
+ (shortcaption (org-export-get-caption table t))
+ (table-str (format "@multitable %s\n%s@end multitable"
+ columns
+ contents)))
+ (if (not (or caption shortcaption)) table-str
+ (org-texinfo--wrap-float table-str
+ info
+ (org-export-translate "Table" :utf-8 info)
+ (org-texinfo--get-node table info)
+ caption
+ shortcaption)))))
+
+(defun org-texinfo-table-column-widths (table info)
+ "Determine the largest table cell in each column to process alignment.
+TABLE is the table element to transcode. INFO is a plist used as
+a communication channel."
+ (let ((widths (make-vector (cdr (org-export-table-dimensions table info)) 0)))
+ (org-element-map table 'table-row
+ (lambda (row)
+ (let ((idx 0))
+ (org-element-map row 'table-cell
+ (lambda (cell)
+ ;; Length of the cell in the original buffer is only an
+ ;; approximation of the length of the cell in the
+ ;; output. It can sometimes fail (e.g. it considers
+ ;; "/a/" being larger than "ab").
+ (let ((w (- (org-element-property :contents-end cell)
+ (org-element-property :contents-begin cell))))
+ (aset widths idx (max w (aref widths idx))))
+ (cl-incf idx))
+ info)))
+ info)
+ (format "{%s}" (mapconcat (lambda (w) (make-string w ?a)) widths "} {"))))
+
+;;;; Table Cell
+
+(defun org-texinfo-table-cell (table-cell contents info)
+ "Transcode a TABLE-CELL element from Org to Texinfo.
+CONTENTS is the cell contents. INFO is a plist used as
+a communication channel."
+ (concat
+ (let ((scientific-notation
+ (plist-get info :texinfo-table-scientific-notation)))
+ (if (and contents
+ scientific-notation
+ (string-match orgtbl-exp-regexp contents))
+ ;; Use appropriate format string for scientific notation.
+ (format scientific-notation
+ (match-string 1 contents)
+ (match-string 2 contents))
+ contents))
+ (when (org-export-get-next-element table-cell info) "\n@tab ")))
+
+;;;; Table Row
+
+(defun org-texinfo-table-row (table-row contents info)
+ "Transcode a TABLE-ROW element from Org to Texinfo.
+CONTENTS is the contents of the row. INFO is a plist used as
+a communication channel."
+ ;; Rules are ignored since table separators are deduced from
+ ;; borders of the current row.
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let ((rowgroup-tag
+ (if (and (= 1 (org-export-table-row-group table-row info))
+ (org-export-table-has-header-p
+ (org-export-get-parent-table table-row) info))
+ "@headitem "
+ "@item ")))
+ (concat rowgroup-tag contents "\n"))))
+
+;;;; Target
+
+(defun org-texinfo-target (target _contents info)
+ "Transcode a TARGET object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (format "@anchor{%s}" (org-texinfo--get-node target info)))
+
+;;;; Timestamp
+
+(defun org-texinfo-timestamp (timestamp _contents info)
+ "Transcode a TIMESTAMP object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist holding contextual
+information."
+ (let ((value (org-texinfo-plain-text
+ (org-timestamp-translate timestamp) info)))
+ (pcase (org-element-property :type timestamp)
+ ((or `active `active-range)
+ (format (plist-get info :texinfo-active-timestamp-format) value))
+ ((or `inactive `inactive-range)
+ (format (plist-get info :texinfo-inactive-timestamp-format) value))
+ (_ (format (plist-get info :texinfo-diary-timestamp-format) value)))))
+
+;;;; Underline
+
+(defun org-texinfo-underline (_underline contents info)
+ "Transcode UNDERLINE from Org to Texinfo.
+CONTENTS is the text with underline markup. INFO is a plist
+holding contextual information."
+ (org-texinfo--text-markup contents 'underline info))
+
+;;;; Verbatim
+
+(defun org-texinfo-verbatim (verbatim _contents info)
+ "Transcode a VERBATIM object from Org to Texinfo.
+CONTENTS is nil. INFO is a plist used as a communication
+channel."
+ (org-texinfo--text-markup
+ (org-element-property :value verbatim) 'verbatim info))
+
+;;;; Verse Block
+
+(defun org-texinfo-verse-block (_verse-block contents _info)
+ "Transcode a VERSE-BLOCK element from Org to Texinfo.
+CONTENTS is verse block contents. INFO is a plist holding
+contextual information."
+ (format "@display\n%s@end display" contents))
+
+
+;;; Interactive functions
+
+(defun org-texinfo-export-to-texinfo
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to a Texinfo file.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+Return output file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".texi" subtreep))
+ (org-export-coding-system org-texinfo-coding-system))
+ (org-export-to-file 'texinfo outfile
+ async subtreep visible-only body-only ext-plist)))
+
+(defun org-texinfo-export-to-info
+ (&optional async subtreep visible-only body-only ext-plist)
+ "Export current buffer to Texinfo then process through to INFO.
+
+If narrowing is active in the current buffer, only export its
+narrowed part.
+
+If a region is active, export that region.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting file should be accessible through
+the `org-export-stack' interface.
+
+When optional argument SUBTREEP is non-nil, export the sub-tree
+at point, extracting information from the headline properties
+first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only write code
+between \"\\begin{document}\" and \"\\end{document}\".
+
+EXT-PLIST, when provided, is a property list with external
+parameters overriding Org default settings, but still inferior to
+file-local settings.
+
+When optional argument PUB-DIR is set, use it as the publishing
+directory.
+
+Return INFO file's name."
+ (interactive)
+ (let ((outfile (org-export-output-file-name ".texi" subtreep))
+ (org-export-coding-system org-texinfo-coding-system))
+ (org-export-to-file 'texinfo outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-texinfo-compile file)))))
+
+;;;###autoload
+(defun org-texinfo-publish-to-texinfo (plist filename pub-dir)
+ "Publish an org file to Texinfo.
+
+FILENAME is the filename of the Org file to be published. PLIST
+is the property list for the given project. PUB-DIR is the
+publishing directory.
+
+Return output file name."
+ (org-publish-org-to 'texinfo filename ".texi" plist pub-dir))
+
+;;;###autoload
+(defun org-texinfo-convert-region-to-texinfo ()
+ "Assume the current region has Org syntax, and convert it to Texinfo.
+This can be used in any buffer. For example, you can write an
+itemized list in Org syntax in an Texinfo buffer and use this
+command to convert it."
+ (interactive)
+ (org-export-replace-region-by 'texinfo))
+
+(defun org-texinfo-compile (file)
+ "Compile a texinfo file.
+
+FILE is the name of the file being compiled. Processing is done
+through the command specified in `org-texinfo-info-process',
+which see. Output is redirected to \"*Org INFO Texinfo Output*\"
+buffer.
+
+Return INFO file name or an error if it couldn't be produced."
+ (message "Processing Texinfo file %s..." file)
+ (let* ((log-name "*Org INFO Texinfo Output*")
+ (log (get-buffer-create log-name))
+ (output
+ (org-compile-file file org-texinfo-info-process "info"
+ (format "See %S for details" log-name)
+ log)))
+ (when org-texinfo-remove-logfiles
+ (let ((base (file-name-sans-extension output)))
+ (dolist (ext org-texinfo-logfiles-extensions)
+ (let ((file (concat base "." ext)))
+ (when (file-exists-p file) (delete-file file))))))
+ (message "Process completed.")
+ output))
+
+
+(provide 'ox-texinfo)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox-texinfo.el ends here
diff --git a/lisp/ox.el b/lisp/ox.el
new file mode 100644
index 0000000..f39a395
--- /dev/null
+++ b/lisp/ox.el
@@ -0,0 +1,6630 @@
+;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
+
+;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
+
+;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
+;; Keywords: outlines, hypermedia, calendar, wp
+
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;
+;; This library implements a generic export engine for Org, built on
+;; its syntactical parser: Org Elements.
+;;
+;; Besides that parser, the generic exporter is made of three distinct
+;; parts:
+;;
+;; - The communication channel consists of a property list, which is
+;; created and updated during the process. Its use is to offer
+;; every piece of information, would it be about initial environment
+;; or contextual data, all in a single place.
+;;
+;; - The transcoder walks the parse tree, ignores or treat as plain
+;; text elements and objects according to export options, and
+;; eventually calls back-end specific functions to do the real
+;; transcoding, concatenating their return value along the way.
+;;
+;; - The filter system is activated at the very beginning and the very
+;; end of the export process, and each time an element or an object
+;; has been converted. It is the entry point to fine-tune standard
+;; output from back-end transcoders. See "The Filter System"
+;; section for more information.
+;;
+;; The core functions is `org-export-as'. It returns the transcoded
+;; buffer as a string. Its derivatives are `org-export-to-buffer' and
+;; `org-export-to-file'.
+;;
+;; An export back-end is defined with `org-export-define-backend'.
+;; This function can also support specific buffer keywords, OPTION
+;; keyword's items and filters. Refer to function's documentation for
+;; more information.
+;;
+;; If the new back-end shares most properties with another one,
+;; `org-export-define-derived-backend' can be used to simplify the
+;; process.
+;;
+;; Any back-end can define its own variables. Among them, those
+;; customizable should belong to the `org-export-BACKEND' group.
+;;
+;; Tools for common tasks across back-ends are implemented in the
+;; following part of the file.
+;;
+;; Eventually, a dispatcher (`org-export-dispatch') is provided in the
+;; last one.
+;;
+;; See <http://orgmode.org/worg/dev/org-export-reference.html> for
+;; more information.
+
+;;; Code:
+
+(require 'cl-lib)
+(require 'ob-exp)
+(require 'org-element)
+(require 'org-macro)
+(require 'tabulated-list)
+
+(declare-function org-src-coderef-format "org-src" (&optional element))
+(declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
+(declare-function org-publish "ox-publish" (project &optional force async))
+(declare-function org-publish-all "ox-publish" (&optional force async))
+(declare-function org-publish-current-file "ox-publish" (&optional force async))
+(declare-function org-publish-current-project "ox-publish" (&optional force async))
+
+(defvar org-publish-project-alist)
+(defvar org-table-number-fraction)
+(defvar org-table-number-regexp)
+
+
+;;; Internal Variables
+;;
+;; Among internal variables, the most important is
+;; `org-export-options-alist'. This variable define the global export
+;; options, shared between every exporter, and how they are acquired.
+
+(defconst org-export-max-depth 19
+ "Maximum nesting depth for headlines, counting from 0.")
+
+(defconst org-export-options-alist
+ '((:title "TITLE" nil nil parse)
+ (:date "DATE" nil nil parse)
+ (:author "AUTHOR" nil user-full-name parse)
+ (:email "EMAIL" nil user-mail-address t)
+ (:language "LANGUAGE" nil org-export-default-language t)
+ (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
+ (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
+ (:creator "CREATOR" nil org-export-creator-string)
+ (:headline-levels nil "H" org-export-headline-levels)
+ (:preserve-breaks nil "\\n" org-export-preserve-breaks)
+ (:section-numbers nil "num" org-export-with-section-numbers)
+ (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
+ (:with-archived-trees nil "arch" org-export-with-archived-trees)
+ (:with-author nil "author" org-export-with-author)
+ (:with-broken-links nil "broken-links" org-export-with-broken-links)
+ (:with-clocks nil "c" org-export-with-clocks)
+ (:with-creator nil "creator" org-export-with-creator)
+ (:with-date nil "date" org-export-with-date)
+ (:with-drawers nil "d" org-export-with-drawers)
+ (:with-email nil "email" org-export-with-email)
+ (:with-emphasize nil "*" org-export-with-emphasize)
+ (:with-entities nil "e" org-export-with-entities)
+ (:with-fixed-width nil ":" org-export-with-fixed-width)
+ (:with-footnotes nil "f" org-export-with-footnotes)
+ (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
+ (:with-latex nil "tex" org-export-with-latex)
+ (:with-planning nil "p" org-export-with-planning)
+ (:with-priority nil "pri" org-export-with-priority)
+ (:with-properties nil "prop" org-export-with-properties)
+ (:with-smart-quotes nil "'" org-export-with-smart-quotes)
+ (:with-special-strings nil "-" org-export-with-special-strings)
+ (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
+ (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
+ (:with-toc nil "toc" org-export-with-toc)
+ (:with-tables nil "|" org-export-with-tables)
+ (:with-tags nil "tags" org-export-with-tags)
+ (:with-tasks nil "tasks" org-export-with-tasks)
+ (:with-timestamps nil "<" org-export-with-timestamps)
+ (:with-title nil "title" org-export-with-title)
+ (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
+ "Alist between export properties and ways to set them.
+
+The key of the alist is the property name, and the value is a list
+like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
+
+KEYWORD is a string representing a buffer keyword, or nil. Each
+ property defined this way can also be set, during subtree
+ export, through a headline property named after the keyword
+ with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
+ property).
+OPTION is a string that could be found in an #+OPTIONS: line.
+DEFAULT is the default value for the property.
+BEHAVIOR determines how Org should handle multiple keywords for
+ the same property. It is a symbol among:
+ nil Keep old value and discard the new one.
+ t Replace old value with the new one.
+ `space' Concatenate the values, separating them with a space.
+ `newline' Concatenate the values, separating them with
+ a newline.
+ `split' Split values at white spaces, and cons them to the
+ previous list.
+ `parse' Parse value as a list of strings and Org objects,
+ which can then be transcoded with, e.g.,
+ `org-export-data'. It implies `space' behavior.
+
+Values set through KEYWORD and OPTION have precedence over
+DEFAULT.
+
+All these properties should be back-end agnostic. Back-end
+specific properties are set through `org-export-define-backend'.
+Properties redefined there have precedence over these.")
+
+(defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
+ "List of in-buffer keywords that require special treatment.
+These keywords are not directly associated to a property. The
+way they are handled must be hard-coded into
+`org-export--get-inbuffer-options' function.")
+
+(defconst org-export-filters-alist
+ '((:filter-body . org-export-filter-body-functions)
+ (:filter-bold . org-export-filter-bold-functions)
+ (:filter-babel-call . org-export-filter-babel-call-functions)
+ (:filter-center-block . org-export-filter-center-block-functions)
+ (:filter-clock . org-export-filter-clock-functions)
+ (:filter-code . org-export-filter-code-functions)
+ (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
+ (:filter-drawer . org-export-filter-drawer-functions)
+ (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
+ (:filter-entity . org-export-filter-entity-functions)
+ (:filter-example-block . org-export-filter-example-block-functions)
+ (:filter-export-block . org-export-filter-export-block-functions)
+ (:filter-export-snippet . org-export-filter-export-snippet-functions)
+ (:filter-final-output . org-export-filter-final-output-functions)
+ (:filter-fixed-width . org-export-filter-fixed-width-functions)
+ (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
+ (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
+ (:filter-headline . org-export-filter-headline-functions)
+ (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
+ (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
+ (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
+ (:filter-inlinetask . org-export-filter-inlinetask-functions)
+ (:filter-italic . org-export-filter-italic-functions)
+ (:filter-item . org-export-filter-item-functions)
+ (:filter-keyword . org-export-filter-keyword-functions)
+ (:filter-latex-environment . org-export-filter-latex-environment-functions)
+ (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
+ (:filter-line-break . org-export-filter-line-break-functions)
+ (:filter-link . org-export-filter-link-functions)
+ (:filter-node-property . org-export-filter-node-property-functions)
+ (:filter-options . org-export-filter-options-functions)
+ (:filter-paragraph . org-export-filter-paragraph-functions)
+ (:filter-parse-tree . org-export-filter-parse-tree-functions)
+ (:filter-plain-list . org-export-filter-plain-list-functions)
+ (:filter-plain-text . org-export-filter-plain-text-functions)
+ (:filter-planning . org-export-filter-planning-functions)
+ (:filter-property-drawer . org-export-filter-property-drawer-functions)
+ (:filter-quote-block . org-export-filter-quote-block-functions)
+ (:filter-radio-target . org-export-filter-radio-target-functions)
+ (:filter-section . org-export-filter-section-functions)
+ (:filter-special-block . org-export-filter-special-block-functions)
+ (:filter-src-block . org-export-filter-src-block-functions)
+ (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
+ (:filter-strike-through . org-export-filter-strike-through-functions)
+ (:filter-subscript . org-export-filter-subscript-functions)
+ (:filter-superscript . org-export-filter-superscript-functions)
+ (:filter-table . org-export-filter-table-functions)
+ (:filter-table-cell . org-export-filter-table-cell-functions)
+ (:filter-table-row . org-export-filter-table-row-functions)
+ (:filter-target . org-export-filter-target-functions)
+ (:filter-timestamp . org-export-filter-timestamp-functions)
+ (:filter-underline . org-export-filter-underline-functions)
+ (:filter-verbatim . org-export-filter-verbatim-functions)
+ (:filter-verse-block . org-export-filter-verse-block-functions))
+ "Alist between filters properties and initial values.
+
+The key of each association is a property name accessible through
+the communication channel. Its value is a configurable global
+variable defining initial filters.
+
+This list is meant to install user specified filters. Back-end
+developers may install their own filters using
+`org-export-define-backend'. Filters defined there will always
+be prepended to the current list, so they always get applied
+first.")
+
+(defconst org-export-default-inline-image-rule
+ `(("file" .
+ ,(format "\\.%s\\'"
+ (regexp-opt
+ '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
+ "xpm" "pbm" "pgm" "ppm") t))))
+ "Default rule for link matching an inline image.
+This rule applies to links with no description. By default, it
+will be considered as an inline image if it targets a local file
+whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
+\"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
+See `org-export-inline-image-p' for more information about
+rules.")
+
+(defconst org-export-ignored-local-variables
+ '(org-font-lock-keywords
+ org-element--cache org-element--cache-objects org-element--cache-sync-keys
+ org-element--cache-sync-requests org-element--cache-sync-timer)
+ "List of variables not copied through upon buffer duplication.
+Export process takes place on a copy of the original buffer.
+When this copy is created, all Org related local variables not in
+this list are copied to the new buffer. Variables with an
+unreadable value are also ignored.")
+
+(defvar org-export-async-debug nil
+ "Non-nil means asynchronous export process should leave data behind.
+
+This data is found in the appropriate \"*Org Export Process*\"
+buffer, and in files prefixed with \"org-export-process\" and
+located in `temporary-file-directory'.
+
+When non-nil, it will also set `debug-on-error' to a non-nil
+value in the external process.")
+
+(defvar org-export-stack-contents nil
+ "Record asynchronously generated export results and processes.
+This is an alist: its CAR is the source of the
+result (destination file or buffer for a finished process,
+original buffer for a running one) and its CDR is a list
+containing the back-end used, as a symbol, and either a process
+or the time at which it finished. It is used to build the menu
+from `org-export-stack'.")
+
+(defvar org-export-registered-backends nil
+ "List of backends currently available in the exporter.
+This variable is set with `org-export-define-backend' and
+`org-export-define-derived-backend' functions.")
+
+(defvar org-export-dispatch-last-action nil
+ "Last command called from the dispatcher.
+The value should be a list. Its CAR is the action, as a symbol,
+and its CDR is a list of export options.")
+
+(defvar org-export-dispatch-last-position (make-marker)
+ "The position where the last export command was created using the dispatcher.
+This marker will be used with `C-u C-c C-e' to make sure export repetition
+uses the same subtree if the previous command was restricted to a subtree.")
+
+;; For compatibility with Org < 8
+(defvar org-export-current-backend nil
+ "Name, if any, of the back-end used during an export process.
+
+Its value is a symbol such as `html', `latex', `ascii', or nil if
+the back-end is anonymous (see `org-export-create-backend') or if
+there is no export process in progress.
+
+It can be used to teach Babel blocks how to act differently
+according to the back-end used.")
+
+
+
+;;; User-configurable Variables
+;;
+;; Configuration for the masses.
+;;
+;; They should never be accessed directly, as their value is to be
+;; stored in a property list (cf. `org-export-options-alist').
+;; Back-ends will read their value from there instead.
+
+(defgroup org-export nil
+ "Options for exporting Org mode files."
+ :tag "Org Export"
+ :group 'org)
+
+(defgroup org-export-general nil
+ "General options for export engine."
+ :tag "Org Export General"
+ :group 'org-export)
+
+(defcustom org-export-with-archived-trees 'headline
+ "Whether sub-trees with the ARCHIVE tag should be exported.
+
+This can have three different values:
+nil Do not export, pretend this tree is not present.
+t Do export the entire tree.
+`headline' Only export the headline, but skip the tree below it.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"arch:nil\"."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "Not at all" nil)
+ (const :tag "Headline only" headline)
+ (const :tag "Entirely" t))
+ :safe (lambda (x) (memq x '(t nil headline))))
+
+(defcustom org-export-with-author t
+ "Non-nil means insert author name into the exported file.
+This option can also be set with the OPTIONS keyword,
+e.g. \"author:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-clocks nil
+ "Non-nil means export CLOCK keywords.
+This option can also be set with the OPTIONS keyword,
+e.g. \"c:t\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-creator nil
+ "Non-nil means the postamble should contain a creator sentence.
+
+The sentence can be set in `org-export-creator-string', which
+see.
+
+This option can also be set with the OPTIONS keyword, e.g.,
+\"creator:t\"."
+ :group 'org-export-general
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-date t
+ "Non-nil means insert date in the exported document.
+This option can also be set with the OPTIONS keyword,
+e.g. \"date:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-date-timestamp-format nil
+ "Time-stamp format string to use for DATE keyword.
+
+The format string, when specified, only applies if date consists
+in a single time-stamp. Otherwise its value will be ignored.
+
+See `format-time-string' for details on how to build this
+string."
+ :group 'org-export-general
+ :type '(choice
+ (string :tag "Time-stamp format string")
+ (const :tag "No format string" nil))
+ :safe (lambda (x) (or (null x) (stringp x))))
+
+(defcustom org-export-creator-string
+ (format "Emacs %s (Org mode %s)"
+ emacs-version
+ (if (fboundp 'org-version) (org-version) "unknown version"))
+ "Information about the creator of the document.
+This option can also be set on with the CREATOR keyword."
+ :group 'org-export-general
+ :type '(string :tag "Creator string")
+ :safe #'stringp)
+
+(defcustom org-export-with-drawers '(not "LOGBOOK")
+ "Non-nil means export contents of standard drawers.
+
+When t, all drawers are exported. This may also be a list of
+drawer names to export, as strings. If that list starts with
+`not', only drawers with such names will be ignored.
+
+This variable doesn't apply to properties drawers. See
+`org-export-with-properties' instead.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"d:nil\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "All drawers" t)
+ (const :tag "None" nil)
+ (repeat :tag "Selected drawers"
+ (string :tag "Drawer name"))
+ (list :tag "Ignored drawers"
+ (const :format "" not)
+ (repeat :tag "Specify names of drawers to ignore during export"
+ :inline t
+ (string :tag "Drawer name"))))
+ :safe (lambda (x) (or (booleanp x)
+ (and (listp x)
+ (or (cl-every #'stringp x)
+ (and (eq (nth 0 x) 'not)
+ (cl-every #'stringp (cdr x))))))))
+
+(defcustom org-export-with-email nil
+ "Non-nil means insert author email into the exported file.
+This option can also be set with the OPTIONS keyword,
+e.g. \"email:t\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-emphasize t
+ "Non-nil means interpret *word*, /word/, _word_ and +word+.
+
+If the export target supports emphasizing text, the word will be
+typeset in bold, italic, with an underline or strike-through,
+respectively.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"*:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-exclude-tags '("noexport")
+ "Tags that exclude a tree from export.
+
+All trees carrying any of these tags will be excluded from
+export. This is without condition, so even subtrees inside that
+carry one of the `org-export-select-tags' will be removed.
+
+This option can also be set with the EXCLUDE_TAGS keyword."
+ :group 'org-export-general
+ :type '(repeat (string :tag "Tag"))
+ :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
+
+(defcustom org-export-with-fixed-width t
+ "Non-nil means export lines starting with \":\".
+This option can also be set with the OPTIONS keyword,
+e.g. \"::nil\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-footnotes t
+ "Non-nil means Org footnotes should be exported.
+This option can also be set with the OPTIONS keyword,
+e.g. \"f:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-latex t
+ "Non-nil means process LaTeX environments and fragments.
+
+This option can also be set with the OPTIONS line,
+e.g. \"tex:verbatim\". Allowed values are:
+
+nil Ignore math snippets.
+`verbatim' Keep everything in verbatim.
+t Allow export of math snippets."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Do not process math in any way" nil)
+ (const :tag "Interpret math snippets" t)
+ (const :tag "Leave math verbatim" verbatim))
+ :safe (lambda (x) (memq x '(t nil verbatim))))
+
+(defcustom org-export-headline-levels 3
+ "The last level which is still exported as a headline.
+
+Inferior levels will usually produce itemize or enumerate lists
+when exported, but back-end behavior may differ.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"H:2\"."
+ :group 'org-export-general
+ :type 'integer
+ :safe #'integerp)
+
+(defcustom org-export-default-language "en"
+ "The default language for export and clocktable translations, as a string.
+This may have an association in
+`org-clock-clocktable-language-setup',
+`org-export-smart-quotes-alist' and `org-export-dictionary'.
+This option can also be set with the LANGUAGE keyword."
+ :group 'org-export-general
+ :type '(string :tag "Language")
+ :safe #'stringp)
+
+(defcustom org-export-preserve-breaks nil
+ "Non-nil means preserve all line breaks when exporting.
+This option can also be set with the OPTIONS keyword,
+e.g. \"\\n:t\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-entities t
+ "Non-nil means interpret entities when exporting.
+
+For example, HTML export converts \\alpha to &alpha; and \\AA to
+&Aring;.
+
+For a list of supported names, see the constant `org-entities'
+and the user option `org-entities-user'.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"e:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-inlinetasks t
+ "Non-nil means inlinetasks should be exported.
+This option can also be set with the OPTIONS keyword,
+e.g. \"inline:nil\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-planning nil
+ "Non-nil means include planning info in export.
+
+Planning info is the line containing either SCHEDULED:,
+DEADLINE:, CLOSED: time-stamps, or a combination of them.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"p:t\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-priority nil
+ "Non-nil means include priority cookies in export.
+This option can also be set with the OPTIONS keyword,
+e.g. \"pri:t\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-properties nil
+ "Non-nil means export contents of properties drawers.
+
+When t, all properties are exported. This may also be a list of
+properties to export, as strings.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"prop:t\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "All properties" t)
+ (const :tag "None" nil)
+ (repeat :tag "Selected properties"
+ (string :tag "Property name")))
+ :safe (lambda (x) (or (booleanp x)
+ (and (listp x) (cl-every #'stringp x)))))
+
+(defcustom org-export-with-section-numbers t
+ "Non-nil means add section numbers to headlines when exporting.
+
+When set to an integer n, numbering will only happen for
+headlines whose relative level is higher or equal to n.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"num:t\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-select-tags '("export")
+ "Tags that select a tree for export.
+
+If any such tag is found in a buffer, all trees that do not carry
+one of these tags will be ignored during export. Inside trees
+that are selected like this, you can still deselect a subtree by
+tagging it with one of the `org-export-exclude-tags'.
+
+This option can also be set with the SELECT_TAGS keyword."
+ :group 'org-export-general
+ :type '(repeat (string :tag "Tag"))
+ :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
+
+(defcustom org-export-with-smart-quotes nil
+ "Non-nil means activate smart quotes during export.
+This option can also be set with the OPTIONS keyword,
+e.g., \"':t\".
+
+When setting this to non-nil, you need to take care of
+using the correct Babel package when exporting to LaTeX.
+E.g., you can load Babel for french like this:
+
+#+LATEX_HEADER: \\usepackage[french]{babel}"
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-special-strings t
+ "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
+
+When this option is turned on, these strings will be exported as:
+
+ Org HTML LaTeX UTF-8
+ -----+----------+--------+-------
+ \\- &shy; \\-
+ -- &ndash; -- –
+ --- &mdash; --- —
+ ... &hellip; \\ldots …
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"-:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-statistics-cookies t
+ "Non-nil means include statistics cookies in export.
+This option can also be set with the OPTIONS keyword,
+e.g. \"stat:nil\""
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-sub-superscripts t
+ "Non-nil means interpret \"_\" and \"^\" for export.
+
+If you want to control how Org displays those characters, see
+`org-use-sub-superscripts'. `org-export-with-sub-superscripts'
+used to be an alias for `org-use-sub-superscripts' in Org <8.0,
+it is not anymore.
+
+When this option is turned on, you can use TeX-like syntax for
+sub- and superscripts and see them exported correctly.
+
+You can also set the option with #+OPTIONS: ^:t
+
+Several characters after \"_\" or \"^\" will be considered as a
+single item - so grouping with {} is normally not needed. For
+example, the following things will be parsed as single sub- or
+superscripts:
+
+ 10^24 or 10^tau several digits will be considered 1 item.
+ 10^-12 or 10^-tau a leading sign with digits or a word
+ x^2-y^3 will be read as x^2 - y^3, because items are
+ terminated by almost any nonword/nondigit char.
+ x_{i^2} or x^(2-i) braces or parenthesis do grouping.
+
+Still, ambiguity is possible. So when in doubt, use {} to enclose
+the sub/superscript. If you set this variable to the symbol `{}',
+the braces are *required* in order to trigger interpretations as
+sub/superscript. This can be helpful in documents that need \"_\"
+frequently in plain text."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Interpret them" t)
+ (const :tag "Curly brackets only" {})
+ (const :tag "Do not interpret them" nil))
+ :safe (lambda (x) (memq x '(t nil {}))))
+
+(defcustom org-export-with-toc t
+ "Non-nil means create a table of contents in exported files.
+
+The TOC contains headlines with levels up
+to`org-export-headline-levels'. When an integer, include levels
+up to N in the toc, this may then be different from
+`org-export-headline-levels', but it will not be allowed to be
+larger than the number of headline levels. When nil, no table of
+contents is made.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"toc:nil\" or \"toc:3\"."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "No Table of Contents" nil)
+ (const :tag "Full Table of Contents" t)
+ (integer :tag "TOC to level"))
+ :safe (lambda (x) (or (booleanp x)
+ (integerp x))))
+
+(defcustom org-export-with-tables t
+ "Non-nil means export tables.
+This option can also be set with the OPTIONS keyword,
+e.g. \"|:nil\"."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-tags t
+ "If nil, do not export tags, just remove them from headlines.
+
+If this is the symbol `not-in-toc', tags will be removed from
+table of contents entries, but still be shown in the headlines of
+the document.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"tags:nil\"."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "Off" nil)
+ (const :tag "Not in TOC" not-in-toc)
+ (const :tag "On" t))
+ :safe (lambda (x) (memq x '(t nil not-in-toc))))
+
+(defcustom org-export-with-tasks t
+ "Non-nil means include TODO items for export.
+
+This may have the following values:
+t include tasks independent of state.
+`todo' include only tasks that are not yet done.
+`done' include only tasks that are already done.
+nil ignore all tasks.
+list of keywords include tasks with these keywords.
+
+This option can also be set with the OPTIONS keyword,
+e.g. \"tasks:nil\"."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "All tasks" t)
+ (const :tag "No tasks" nil)
+ (const :tag "Not-done tasks" todo)
+ (const :tag "Only done tasks" done)
+ (repeat :tag "Specific TODO keywords"
+ (string :tag "Keyword")))
+ :safe (lambda (x) (or (memq x '(nil t todo done))
+ (and (listp x)
+ (cl-every #'stringp x)))))
+
+(defcustom org-export-with-title t
+ "Non-nil means print title into the exported file.
+This option can also be set with the OPTIONS keyword,
+e.g. \"title:nil\"."
+ :group 'org-export-general
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-time-stamp-file t
+ "Non-nil means insert a time stamp into the exported file.
+The time stamp shows when the file was created. This option can
+also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
+ :group 'org-export-general
+ :type 'boolean
+ :safe #'booleanp)
+
+(defcustom org-export-with-timestamps t
+ "Non nil means allow timestamps in export.
+
+It can be set to any of the following values:
+ t export all timestamps.
+ `active' export active timestamps only.
+ `inactive' export inactive timestamps only.
+ nil do not export timestamps
+
+This only applies to timestamps isolated in a paragraph
+containing only timestamps. Other timestamps are always
+exported.
+
+This option can also be set with the OPTIONS keyword, e.g.
+\"<:nil\"."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "All timestamps" t)
+ (const :tag "Only active timestamps" active)
+ (const :tag "Only inactive timestamps" inactive)
+ (const :tag "No timestamp" nil))
+ :safe (lambda (x) (memq x '(t nil active inactive))))
+
+(defcustom org-export-with-todo-keywords t
+ "Non-nil means include TODO keywords in export.
+When nil, remove all these keywords from the export. This option
+can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
+ :group 'org-export-general
+ :type 'boolean)
+
+(defcustom org-export-allow-bind-keywords nil
+ "Non-nil means BIND keywords can define local variable values.
+This is a potential security risk, which is why the default value
+is nil. You can also allow them through local buffer variables."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-export-with-broken-links nil
+ "Non-nil means do not raise an error on broken links.
+
+When this variable is non-nil, broken links are ignored, without
+stopping the export process. If it is set to `mark', broken
+links are marked as such in the output, with a string like
+
+ [BROKEN LINK: path]
+
+where PATH is the un-resolvable reference.
+
+This option can also be set with the OPTIONS keyword, e.g.,
+\"broken-links:mark\"."
+ :group 'org-export-general
+ :version "26.1"
+ :package-version '(Org . "9.0")
+ :type '(choice
+ (const :tag "Ignore broken links" t)
+ (const :tag "Mark broken links in output" mark)
+ (const :tag "Raise an error" nil)))
+
+(defcustom org-export-snippet-translation-alist nil
+ "Alist between export snippets back-ends and exporter back-ends.
+
+This variable allows providing shortcuts for export snippets.
+
+For example, with a value of \\='((\"h\" . \"html\")), the
+HTML back-end will recognize the contents of \"@@h:<b>@@\" as
+HTML code while every other back-end will ignore it."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(repeat
+ (cons (string :tag "Shortcut")
+ (string :tag "Back-end")))
+ :safe (lambda (x)
+ (and (listp x)
+ (cl-every #'consp x)
+ (cl-every #'stringp (mapcar #'car x))
+ (cl-every #'stringp (mapcar #'cdr x)))))
+
+(defcustom org-export-coding-system nil
+ "Coding system for the exported file."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'coding-system)
+
+(defcustom org-export-copy-to-kill-ring nil
+ "Non-nil means pushing export output to the kill ring.
+This variable is ignored during asynchronous export."
+ :group 'org-export-general
+ :version "26.1"
+ :package-version '(Org . "8.3")
+ :type '(choice
+ (const :tag "Always" t)
+ (const :tag "When export is done interactively" if-interactive)
+ (const :tag "Never" nil)))
+
+(defcustom org-export-initial-scope 'buffer
+ "The initial scope when exporting with `org-export-dispatch'.
+This variable can be either set to `buffer' or `subtree'."
+ :group 'org-export-general
+ :type '(choice
+ (const :tag "Export current buffer" buffer)
+ (const :tag "Export current subtree" subtree)))
+
+(defcustom org-export-show-temporary-export-buffer t
+ "Non-nil means show buffer after exporting to temp buffer.
+When Org exports to a file, the buffer visiting that file is never
+shown, but remains buried. However, when exporting to
+a temporary buffer, that buffer is popped up in a second window.
+When this variable is nil, the buffer remains buried also in
+these cases."
+ :group 'org-export-general
+ :type 'boolean)
+
+(defcustom org-export-in-background nil
+ "Non-nil means export and publishing commands will run in background.
+Results from an asynchronous export are never displayed
+automatically. But you can retrieve them with `\\[org-export-stack]'."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+(defcustom org-export-async-init-file nil
+ "File used to initialize external export process.
+
+Value must be either nil or an absolute file name. When nil, the
+external process is launched like a regular Emacs session,
+loading user's initialization file and any site specific
+configuration. If a file is provided, it, and only it, is loaded
+at start-up.
+
+Therefore, using a specific configuration makes the process to
+load faster and the export more portable."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type '(choice
+ (const :tag "Regular startup" nil)
+ (file :tag "Specific start-up file" :must-match t)))
+
+(defcustom org-export-dispatch-use-expert-ui nil
+ "Non-nil means using a non-intrusive `org-export-dispatch'.
+In that case, no help buffer is displayed. Though, an indicator
+for current export scope is added to the prompt (\"b\" when
+output is restricted to body only, \"s\" when it is restricted to
+the current subtree, \"v\" when only visible elements are
+considered for export, \"f\" when publishing functions should be
+passed the FORCE argument and \"a\" when the export should be
+asynchronous). Also, [?] allows switching back to standard
+mode."
+ :group 'org-export-general
+ :version "24.4"
+ :package-version '(Org . "8.0")
+ :type 'boolean)
+
+
+
+;;; Defining Back-ends
+;;
+;; An export back-end is a structure with `org-export-backend' type
+;; and `name', `parent', `transcoders', `options', `filters', `blocks'
+;; and `menu' slots.
+;;
+;; At the lowest level, a back-end is created with
+;; `org-export-create-backend' function.
+;;
+;; A named back-end can be registered with
+;; `org-export-register-backend' function. A registered back-end can
+;; later be referred to by its name, with `org-export-get-backend'
+;; function. Also, such a back-end can become the parent of a derived
+;; back-end from which slot values will be inherited by default.
+;; `org-export-derived-backend-p' can check if a given back-end is
+;; derived from a list of back-end names.
+;;
+;; `org-export-get-all-transcoders', `org-export-get-all-options' and
+;; `org-export-get-all-filters' return the full alist of transcoders,
+;; options and filters, including those inherited from ancestors.
+;;
+;; At a higher level, `org-export-define-backend' is the standard way
+;; to define an export back-end. If the new back-end is similar to
+;; a registered back-end, `org-export-define-derived-backend' may be
+;; used instead.
+;;
+;; Eventually `org-export-barf-if-invalid-backend' returns an error
+;; when a given back-end hasn't been registered yet.
+
+(cl-defstruct (org-export-backend (:constructor org-export-create-backend)
+ (:copier nil))
+ name parent transcoders options filters blocks menu)
+
+;;;###autoload
+(defun org-export-get-backend (name)
+ "Return export back-end named after NAME.
+NAME is a symbol. Return nil if no such back-end is found."
+ (cl-find-if (lambda (b) (and (eq name (org-export-backend-name b))))
+ org-export-registered-backends))
+
+(defun org-export-register-backend (backend)
+ "Register BACKEND as a known export back-end.
+BACKEND is a structure with `org-export-backend' type."
+ ;; Refuse to register an unnamed back-end.
+ (unless (org-export-backend-name backend)
+ (error "Cannot register a unnamed export back-end"))
+ ;; Refuse to register a back-end with an unknown parent.
+ (let ((parent (org-export-backend-parent backend)))
+ (when (and parent (not (org-export-get-backend parent)))
+ (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
+ ;; If a back-end with the same name as BACKEND is already
+ ;; registered, replace it with BACKEND. Otherwise, simply add
+ ;; BACKEND to the list of registered back-ends.
+ (let ((old (org-export-get-backend (org-export-backend-name backend))))
+ (if old (setcar (memq old org-export-registered-backends) backend)
+ (push backend org-export-registered-backends))))
+
+(defun org-export-barf-if-invalid-backend (backend)
+ "Signal an error if BACKEND isn't defined."
+ (unless (org-export-backend-p backend)
+ (error "Unknown \"%s\" back-end: Aborting export" backend)))
+
+(defun org-export-derived-backend-p (backend &rest backends)
+ "Non-nil if BACKEND is derived from one of BACKENDS.
+BACKEND is an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end. BACKENDS is constituted of symbols."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (when backend
+ (catch 'exit
+ (while (org-export-backend-parent backend)
+ (when (memq (org-export-backend-name backend) backends)
+ (throw 'exit t))
+ (setq backend
+ (org-export-get-backend (org-export-backend-parent backend))))
+ (memq (org-export-backend-name backend) backends))))
+
+(defun org-export-get-all-transcoders (backend)
+ "Return full translation table for BACKEND.
+
+BACKEND is an export back-end, as return by, e.g,,
+`org-export-create-backend'. Return value is an alist where
+keys are element or object types, as symbols, and values are
+transcoders.
+
+Unlike to `org-export-backend-transcoders', this function
+also returns transcoders inherited from parent back-ends,
+if any."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (when backend
+ (let ((transcoders (org-export-backend-transcoders backend))
+ parent)
+ (while (setq parent (org-export-backend-parent backend))
+ (setq backend (org-export-get-backend parent))
+ (setq transcoders
+ (append transcoders (org-export-backend-transcoders backend))))
+ transcoders)))
+
+(defun org-export-get-all-options (backend)
+ "Return export options for BACKEND.
+
+BACKEND is an export back-end, as return by, e.g,,
+`org-export-create-backend'. See `org-export-options-alist'
+for the shape of the return value.
+
+Unlike to `org-export-backend-options', this function also
+returns options inherited from parent back-ends, if any.
+
+Return nil if BACKEND is unknown."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (when backend
+ (let ((options (org-export-backend-options backend))
+ parent)
+ (while (setq parent (org-export-backend-parent backend))
+ (setq backend (org-export-get-backend parent))
+ (setq options (append options (org-export-backend-options backend))))
+ options)))
+
+(defun org-export-get-all-filters (backend)
+ "Return complete list of filters for BACKEND.
+
+BACKEND is an export back-end, as return by, e.g,,
+`org-export-create-backend'. Return value is an alist where
+keys are symbols and values lists of functions.
+
+Unlike to `org-export-backend-filters', this function also
+returns filters inherited from parent back-ends, if any."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (when backend
+ (let ((filters (org-export-backend-filters backend))
+ parent)
+ (while (setq parent (org-export-backend-parent backend))
+ (setq backend (org-export-get-backend parent))
+ (setq filters (append filters (org-export-backend-filters backend))))
+ filters)))
+
+(defun org-export-define-backend (backend transcoders &rest body)
+ "Define a new back-end BACKEND.
+
+TRANSCODERS is an alist between object or element types and
+functions handling them.
+
+These functions should return a string without any trailing
+space, or nil. They must accept three arguments: the object or
+element itself, its contents or nil when it isn't recursive and
+the property list used as a communication channel.
+
+Contents, when not nil, are stripped from any global indentation
+\(although the relative one is preserved). They also always end
+with a single newline character.
+
+If, for a given type, no function is found, that element or
+object type will simply be ignored, along with any blank line or
+white space at its end. The same will happen if the function
+returns the nil value. If that function returns the empty
+string, the type will be ignored, but the blank lines or white
+spaces will be kept.
+
+In addition to element and object types, one function can be
+associated to the `template' (or `inner-template') symbol and
+another one to the `plain-text' symbol.
+
+The former returns the final transcoded string, and can be used
+to add a preamble and a postamble to document's body. It must
+accept two arguments: the transcoded string and the property list
+containing export options. A function associated to `template'
+will not be applied if export has option \"body-only\".
+A function associated to `inner-template' is always applied.
+
+The latter, when defined, is to be called on every text not
+recognized as an element or an object. It must accept two
+arguments: the text string and the information channel. It is an
+appropriate place to protect special chars relative to the
+back-end.
+
+BODY can start with pre-defined keyword arguments. The following
+keywords are understood:
+
+ :filters-alist
+
+ Alist between filters and function, or list of functions,
+ specific to the back-end. See `org-export-filters-alist' for
+ a list of all allowed filters. Filters defined here
+ shouldn't make a back-end test, as it may prevent back-ends
+ derived from this one to behave properly.
+
+ :menu-entry
+
+ Menu entry for the export dispatcher. It should be a list
+ like:
+
+ \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
+
+ where :
+
+ KEY is a free character selecting the back-end.
+
+ DESCRIPTION-OR-ORDINAL is either a string or a number.
+
+ If it is a string, is will be used to name the back-end in
+ its menu entry. If it is a number, the following menu will
+ be displayed as a sub-menu of the back-end with the same
+ KEY. Also, the number will be used to determine in which
+ order such sub-menus will appear (lowest first).
+
+ ACTION-OR-MENU is either a function or an alist.
+
+ If it is an action, it will be called with four
+ arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
+ BODY-ONLY. See `org-export-as' for further explanations on
+ some of them.
+
+ If it is an alist, associations should follow the
+ pattern:
+
+ \\='(KEY DESCRIPTION ACTION)
+
+ where KEY, DESCRIPTION and ACTION are described above.
+
+ Valid values include:
+
+ \\='(?m \"My Special Back-end\" my-special-export-function)
+
+ or
+
+ \\='(?l \"Export to LaTeX\"
+ (?p \"As PDF file\" org-latex-export-to-pdf)
+ (?o \"As PDF file and open\"
+ (lambda (a s v b)
+ (if a (org-latex-export-to-pdf t s v b)
+ (org-open-file
+ (org-latex-export-to-pdf nil s v b)))))))
+
+ or the following, which will be added to the previous
+ sub-menu,
+
+ \\='(?l 1
+ ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
+ (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
+
+ :options-alist
+
+ Alist between back-end specific properties introduced in
+ communication channel and how their value are acquired. See
+ `org-export-options-alist' for more information about
+ structure of the values."
+ (declare (indent 1))
+ (let (filters menu-entry options)
+ (while (keywordp (car body))
+ (let ((keyword (pop body)))
+ (pcase keyword
+ (:filters-alist (setq filters (pop body)))
+ (:menu-entry (setq menu-entry (pop body)))
+ (:options-alist (setq options (pop body)))
+ (_ (error "Unknown keyword: %s" keyword)))))
+ (org-export-register-backend
+ (org-export-create-backend :name backend
+ :transcoders transcoders
+ :options options
+ :filters filters
+ :menu menu-entry))))
+
+(defun org-export-define-derived-backend (child parent &rest body)
+ "Create a new back-end as a variant of an existing one.
+
+CHILD is the name of the derived back-end. PARENT is the name of
+the parent back-end.
+
+BODY can start with pre-defined keyword arguments. The following
+keywords are understood:
+
+ :filters-alist
+
+ Alist of filters that will overwrite or complete filters
+ defined in PARENT back-end. See `org-export-filters-alist'
+ for a list of allowed filters.
+
+ :menu-entry
+
+ Menu entry for the export dispatcher. See
+ `org-export-define-backend' for more information about the
+ expected value.
+
+ :options-alist
+
+ Alist of back-end specific properties that will overwrite or
+ complete those defined in PARENT back-end. Refer to
+ `org-export-options-alist' for more information about
+ structure of the values.
+
+ :translate-alist
+
+ Alist of element and object types and transcoders that will
+ overwrite or complete transcode table from PARENT back-end.
+ Refer to `org-export-define-backend' for detailed information
+ about transcoders.
+
+As an example, here is how one could define \"my-latex\" back-end
+as a variant of `latex' back-end with a custom template function:
+
+ (org-export-define-derived-backend \\='my-latex \\='latex
+ :translate-alist \\='((template . my-latex-template-fun)))
+
+The back-end could then be called with, for example:
+
+ (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
+ (declare (indent 2))
+ (let (filters menu-entry options transcoders)
+ (while (keywordp (car body))
+ (let ((keyword (pop body)))
+ (pcase keyword
+ (:filters-alist (setq filters (pop body)))
+ (:menu-entry (setq menu-entry (pop body)))
+ (:options-alist (setq options (pop body)))
+ (:translate-alist (setq transcoders (pop body)))
+ (_ (error "Unknown keyword: %s" keyword)))))
+ (org-export-register-backend
+ (org-export-create-backend :name child
+ :parent parent
+ :transcoders transcoders
+ :options options
+ :filters filters
+ :menu menu-entry))))
+
+
+
+;;; The Communication Channel
+;;
+;; During export process, every function has access to a number of
+;; properties. They are of two types:
+;;
+;; 1. Environment options are collected once at the very beginning of
+;; the process, out of the original buffer and configuration.
+;; Collecting them is handled by `org-export-get-environment'
+;; function.
+;;
+;; Most environment options are defined through the
+;; `org-export-options-alist' variable.
+;;
+;; 2. Tree properties are extracted directly from the parsed tree,
+;; just before export, by `org-export--collect-tree-properties'.
+
+;;;; Environment Options
+;;
+;; Environment options encompass all parameters defined outside the
+;; scope of the parsed data. They come from five sources, in
+;; increasing precedence order:
+;;
+;; - Global variables,
+;; - Buffer's attributes,
+;; - Options keyword symbols,
+;; - Buffer keywords,
+;; - Subtree properties.
+;;
+;; The central internal function with regards to environment options
+;; is `org-export-get-environment'. It updates global variables with
+;; "#+BIND:" keywords, then retrieve and prioritize properties from
+;; the different sources.
+;;
+;; The internal functions doing the retrieval are:
+;; `org-export--get-global-options',
+;; `org-export--get-buffer-attributes',
+;; `org-export--parse-option-keyword',
+;; `org-export--get-subtree-options' and
+;; `org-export--get-inbuffer-options'
+;;
+;; Also, `org-export--list-bound-variables' collects bound variables
+;; along with their value in order to set them as buffer local
+;; variables later in the process.
+
+;;;###autoload
+(defun org-export-get-environment (&optional backend subtreep ext-plist)
+ "Collect export options from the current buffer.
+
+Optional argument BACKEND is an export back-end, as returned by
+`org-export-create-backend'.
+
+When optional argument SUBTREEP is non-nil, assume the export is
+done against the current sub-tree.
+
+Third optional argument EXT-PLIST is a property list with
+external parameters overriding Org default settings, but still
+inferior to file-local settings."
+ ;; First install #+BIND variables since these must be set before
+ ;; global options are read.
+ (dolist (pair (org-export--list-bound-variables))
+ (set (make-local-variable (car pair)) (nth 1 pair)))
+ ;; Get and prioritize export options...
+ (org-combine-plists
+ ;; ... from global variables...
+ (org-export--get-global-options backend)
+ ;; ... from an external property list...
+ ext-plist
+ ;; ... from in-buffer settings...
+ (org-export--get-inbuffer-options backend)
+ ;; ... and from subtree, when appropriate.
+ (and subtreep (org-export--get-subtree-options backend))))
+
+(defun org-export--parse-option-keyword (options &optional backend)
+ "Parse an OPTIONS line and return values as a plist.
+Optional argument BACKEND is an export back-end, as returned by,
+e.g., `org-export-create-backend'. It specifies which back-end
+specific items to read, if any."
+ (let ((line
+ (let ((s 0) alist)
+ (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*" options s)
+ (setq s (match-end 0))
+ (push (cons (match-string 1 options)
+ (read (match-string 2 options)))
+ alist))
+ alist))
+ ;; Priority is given to back-end specific options.
+ (all (append (org-export-get-all-options backend)
+ org-export-options-alist))
+ (plist))
+ (when line
+ (dolist (entry all plist)
+ (let ((item (nth 2 entry)))
+ (when item
+ (let ((v (assoc-string item line t)))
+ (when v (setq plist (plist-put plist (car entry) (cdr v)))))))))))
+
+(defun org-export--get-subtree-options (&optional backend)
+ "Get export options in subtree at point.
+Optional argument BACKEND is an export back-end, as returned by,
+e.g., `org-export-create-backend'. It specifies back-end used
+for export. Return options as a plist."
+ ;; For each buffer keyword, create a headline property setting the
+ ;; same property in communication channel. The name for the
+ ;; property is the keyword with "EXPORT_" appended to it.
+ (org-with-wide-buffer
+ ;; Make sure point is at a heading.
+ (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
+ (let ((plist
+ ;; EXPORT_OPTIONS are parsed in a non-standard way. Take
+ ;; care of them right from the start.
+ (let ((o (org-entry-get (point) "EXPORT_OPTIONS" 'selective)))
+ (and o (org-export--parse-option-keyword o backend))))
+ ;; Take care of EXPORT_TITLE. If it isn't defined, use
+ ;; headline's title (with no todo keyword, priority cookie or
+ ;; tag) as its fallback value.
+ (cache (list
+ (cons "TITLE"
+ (or (org-entry-get (point) "EXPORT_TITLE" 'selective)
+ (let ((case-fold-search nil))
+ (looking-at org-complex-heading-regexp)
+ (match-string-no-properties 4))))))
+ ;; Look for both general keywords and back-end specific
+ ;; options, with priority given to the latter.
+ (options (append (org-export-get-all-options backend)
+ org-export-options-alist)))
+ ;; Handle other keywords. Then return PLIST.
+ (dolist (option options plist)
+ (let ((property (car option))
+ (keyword (nth 1 option)))
+ (when keyword
+ (let ((value
+ (or (cdr (assoc keyword cache))
+ (let ((v (org-entry-get (point)
+ (concat "EXPORT_" keyword)
+ 'selective)))
+ (push (cons keyword v) cache) v))))
+ (when value
+ (setq plist
+ (plist-put plist
+ property
+ (cl-case (nth 4 option)
+ (parse
+ (org-element-parse-secondary-string
+ value (org-element-restriction 'keyword)))
+ (split (org-split-string value))
+ (t value))))))))))))
+
+(defun org-export--get-inbuffer-options (&optional backend)
+ "Return current buffer export options, as a plist.
+
+Optional argument BACKEND, when non-nil, is an export back-end,
+as returned by, e.g., `org-export-create-backend'. It specifies
+which back-end specific options should also be read in the
+process.
+
+Assume buffer is in Org mode. Narrowing, if any, is ignored."
+ (let* ((case-fold-search t)
+ (options (append
+ ;; Priority is given to back-end specific options.
+ (org-export-get-all-options backend)
+ org-export-options-alist))
+ (regexp (format "^[ \t]*#\\+%s:"
+ (regexp-opt (nconc (delq nil (mapcar #'cadr options))
+ org-export-special-keywords))))
+ plist to-parse)
+ (letrec ((find-properties
+ (lambda (keyword)
+ ;; Return all properties associated to KEYWORD.
+ (let (properties)
+ (dolist (option options properties)
+ (when (equal (nth 1 option) keyword)
+ (cl-pushnew (car option) properties))))))
+ (get-options
+ (lambda (&optional files)
+ ;; Recursively read keywords in buffer. FILES is
+ ;; a list of files read so far. PLIST is the current
+ ;; property list obtained.
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward regexp nil t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (let ((key (org-element-property :key element))
+ (val (org-element-property :value element)))
+ (cond
+ ;; Options in `org-export-special-keywords'.
+ ((equal key "SETUPFILE")
+ (let ((file
+ (expand-file-name
+ (org-unbracket-string "\"" "\"" (org-trim val)))))
+ ;; Avoid circular dependencies.
+ (unless (member file files)
+ (with-temp-buffer
+ (setq default-directory
+ (file-name-directory file))
+ (insert (org-file-contents file 'noerror))
+ (let ((org-inhibit-startup t)) (org-mode))
+ (funcall get-options (cons file files))))))
+ ((equal key "OPTIONS")
+ (setq plist
+ (org-combine-plists
+ plist
+ (org-export--parse-option-keyword
+ val backend))))
+ ((equal key "FILETAGS")
+ (setq plist
+ (org-combine-plists
+ plist
+ (list :filetags
+ (org-uniquify
+ (append
+ (org-split-string val ":")
+ (plist-get plist :filetags)))))))
+ (t
+ ;; Options in `org-export-options-alist'.
+ (dolist (property (funcall find-properties key))
+ (setq
+ plist
+ (plist-put
+ plist property
+ ;; Handle value depending on specified
+ ;; BEHAVIOR.
+ (cl-case (nth 4 (assq property options))
+ (parse
+ (unless (memq property to-parse)
+ (push property to-parse))
+ ;; Even if `parse' implies `space'
+ ;; behavior, we separate line with
+ ;; "\n" so as to preserve
+ ;; line-breaks. However, empty
+ ;; lines are forbidden since `parse'
+ ;; doesn't allow more than one
+ ;; paragraph.
+ (let ((old (plist-get plist property)))
+ (cond ((not (org-string-nw-p val)) old)
+ (old (concat old "\n" val))
+ (t val))))
+ (space
+ (if (not (plist-get plist property))
+ (org-trim val)
+ (concat (plist-get plist property)
+ " "
+ (org-trim val))))
+ (newline
+ (org-trim
+ (concat (plist-get plist property)
+ "\n"
+ (org-trim val))))
+ (split `(,@(plist-get plist property)
+ ,@(org-split-string val)))
+ ((t) val)
+ (otherwise
+ (if (not (plist-member plist property)) val
+ (plist-get plist property)))))))))))))))))
+ ;; Read options in the current buffer and return value.
+ (funcall get-options (and buffer-file-name (list buffer-file-name)))
+ ;; Parse properties in TO-PARSE. Remove newline characters not
+ ;; involved in line breaks to simulate `space' behavior.
+ ;; Finally return options.
+ (dolist (p to-parse plist)
+ (let ((value (org-element-parse-secondary-string
+ (plist-get plist p)
+ (org-element-restriction 'keyword))))
+ (org-element-map value 'plain-text
+ (lambda (s)
+ (org-element-set-element
+ s (replace-regexp-in-string "\n" " " s))))
+ (setq plist (plist-put plist p value)))))))
+
+(defun org-export--get-export-attributes
+ (&optional backend subtreep visible-only body-only)
+ "Return properties related to export process, as a plist.
+Optional arguments BACKEND, SUBTREEP, VISIBLE-ONLY and BODY-ONLY
+are like the arguments with the same names of function
+`org-export-as'."
+ (list :export-options (delq nil
+ (list (and subtreep 'subtree)
+ (and visible-only 'visible-only)
+ (and body-only 'body-only)))
+ :back-end backend
+ :translate-alist (org-export-get-all-transcoders backend)
+ :exported-data (make-hash-table :test #'eq :size 4001)))
+
+(defun org-export--get-buffer-attributes ()
+ "Return properties related to buffer attributes, as a plist."
+ (list :input-buffer (buffer-name (buffer-base-buffer))
+ :input-file (buffer-file-name (buffer-base-buffer))))
+
+(defun org-export--get-global-options (&optional backend)
+ "Return global export options as a plist.
+Optional argument BACKEND, if non-nil, is an export back-end, as
+returned by, e.g., `org-export-create-backend'. It specifies
+which back-end specific export options should also be read in the
+process."
+ (let (plist
+ ;; Priority is given to back-end specific options.
+ (all (append (org-export-get-all-options backend)
+ org-export-options-alist)))
+ (dolist (cell all plist)
+ (let ((prop (car cell)))
+ (unless (plist-member plist prop)
+ (setq plist
+ (plist-put
+ plist
+ prop
+ ;; Evaluate default value provided.
+ (let ((value (eval (nth 3 cell))))
+ (if (eq (nth 4 cell) 'parse)
+ (org-element-parse-secondary-string
+ value (org-element-restriction 'keyword))
+ value)))))))))
+
+(defun org-export--list-bound-variables ()
+ "Return variables bound from BIND keywords in current buffer.
+Also look for BIND keywords in setup files. The return value is
+an alist where associations are (VARIABLE-NAME VALUE)."
+ (when org-export-allow-bind-keywords
+ (letrec ((collect-bind
+ (lambda (files alist)
+ ;; Return an alist between variable names and their
+ ;; value. FILES is a list of setup files names read
+ ;; so far, used to avoid circular dependencies. ALIST
+ ;; is the alist collected so far.
+ (let ((case-fold-search t))
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (while (re-search-forward
+ "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
+ (let ((element (org-element-at-point)))
+ (when (eq (org-element-type element) 'keyword)
+ (let ((val (org-element-property :value element)))
+ (if (equal (org-element-property :key element)
+ "BIND")
+ (push (read (format "(%s)" val)) alist)
+ ;; Enter setup file.
+ (let ((file (expand-file-name
+ (org-unbracket-string "\"" "\"" val))))
+ (unless (member file files)
+ (with-temp-buffer
+ (setq default-directory
+ (file-name-directory file))
+ (let ((org-inhibit-startup t)) (org-mode))
+ (insert (org-file-contents file 'noerror))
+ (setq alist
+ (funcall collect-bind
+ (cons file files)
+ alist))))))))))
+ alist)))))
+ ;; Return value in appropriate order of appearance.
+ (nreverse (funcall collect-bind nil nil)))))
+
+;; defsubst org-export-get-parent must be defined before first use,
+;; was originally defined in the topology section
+
+(defsubst org-export-get-parent (blob)
+ "Return BLOB parent or nil.
+BLOB is the element or object considered."
+ (org-element-property :parent blob))
+
+;;;; Tree Properties
+;;
+;; Tree properties are information extracted from parse tree. They
+;; are initialized at the beginning of the transcoding process by
+;; `org-export--collect-tree-properties'.
+;;
+;; Dedicated functions focus on computing the value of specific tree
+;; properties during initialization. Thus,
+;; `org-export--populate-ignore-list' lists elements and objects that
+;; should be skipped during export, `org-export--get-min-level' gets
+;; the minimal exportable level, used as a basis to compute relative
+;; level for headlines. Eventually
+;; `org-export--collect-headline-numbering' builds an alist between
+;; headlines and their numbering.
+
+(defun org-export--collect-tree-properties (data info)
+ "Extract tree properties from parse tree.
+
+DATA is the parse tree from which information is retrieved. INFO
+is a list holding export options.
+
+Following tree properties are set or updated:
+
+`:headline-offset' Offset between true level of headlines and
+ local level. An offset of -1 means a headline
+ of level 2 should be considered as a level
+ 1 headline in the context.
+
+`:headline-numbering' Alist of all headlines as key and the
+ associated numbering as value.
+
+`:id-alist' Alist of all ID references as key and associated file
+ as value.
+
+Return updated plist."
+ ;; Install the parse tree in the communication channel.
+ (setq info (plist-put info :parse-tree data))
+ ;; Compute `:headline-offset' in order to be able to use
+ ;; `org-export-get-relative-level'.
+ (setq info
+ (plist-put info
+ :headline-offset
+ (- 1 (org-export--get-min-level data info))))
+ ;; From now on, properties order doesn't matter: get the rest of the
+ ;; tree properties.
+ (org-combine-plists
+ info
+ (list :headline-numbering (org-export--collect-headline-numbering data info)
+ :id-alist
+ (org-element-map data 'link
+ (lambda (l)
+ (and (string= (org-element-property :type l) "id")
+ (let* ((id (org-element-property :path l))
+ (file (car (org-id-find id))))
+ (and file (cons id (file-relative-name file))))))))))
+
+(defun org-export--get-min-level (data options)
+ "Return minimum exportable headline's level in DATA.
+DATA is parsed tree as returned by `org-element-parse-buffer'.
+OPTIONS is a plist holding export options."
+ (catch 'exit
+ (let ((min-level 10000))
+ (dolist (datum (org-element-contents data))
+ (when (and (eq (org-element-type datum) 'headline)
+ (not (org-element-property :footnote-section-p datum))
+ (not (memq datum (plist-get options :ignore-list))))
+ (setq min-level (min (org-element-property :level datum) min-level))
+ (when (= min-level 1) (throw 'exit 1))))
+ ;; If no headline was found, for the sake of consistency, set
+ ;; minimum level to 1 nonetheless.
+ (if (= min-level 10000) 1 min-level))))
+
+(defun org-export--collect-headline-numbering (data options)
+ "Return numbering of all exportable, numbered headlines in a parse tree.
+
+DATA is the parse tree. OPTIONS is the plist holding export
+options.
+
+Return an alist whose key is a headline and value is its
+associated numbering \(in the shape of a list of numbers) or nil
+for a footnotes section."
+ (let ((numbering (make-vector org-export-max-depth 0)))
+ (org-element-map data 'headline
+ (lambda (headline)
+ (when (and (org-export-numbered-headline-p headline options)
+ (not (org-element-property :footnote-section-p headline)))
+ (let ((relative-level
+ (1- (org-export-get-relative-level headline options))))
+ (cons
+ headline
+ (cl-loop
+ for n across numbering
+ for idx from 0 to org-export-max-depth
+ when (< idx relative-level) collect n
+ when (= idx relative-level) collect (aset numbering idx (1+ n))
+ when (> idx relative-level) do (aset numbering idx 0))))))
+ options)))
+
+(defun org-export--selected-trees (data info)
+ "List headlines and inlinetasks with a select tag in their tree.
+DATA is parsed data as returned by `org-element-parse-buffer'.
+INFO is a plist holding export options."
+ (let ((select (plist-get info :select-tags)))
+ (if (cl-some (lambda (tag) (member tag select)) (plist-get info :filetags))
+ ;; If FILETAGS contains a select tag, every headline or
+ ;; inlinetask is returned.
+ (org-element-map data '(headline inlinetask) #'identity)
+ (letrec ((selected-trees nil)
+ (walk-data
+ (lambda (data genealogy)
+ (let ((type (org-element-type data)))
+ (cond
+ ((memq type '(headline inlinetask))
+ (let ((tags (org-element-property :tags data)))
+ (if (cl-some (lambda (tag) (member tag select)) tags)
+ ;; When a select tag is found, mark full
+ ;; genealogy and every headline within the
+ ;; tree as acceptable.
+ (setq selected-trees
+ (append
+ genealogy
+ (org-element-map data '(headline inlinetask)
+ #'identity)
+ selected-trees))
+ ;; If at a headline, continue searching in
+ ;; tree, recursively.
+ (when (eq type 'headline)
+ (dolist (el (org-element-contents data))
+ (funcall walk-data el (cons data genealogy)))))))
+ ((or (eq type 'org-data)
+ (memq type org-element-greater-elements))
+ (dolist (el (org-element-contents data))
+ (funcall walk-data el genealogy))))))))
+ (funcall walk-data data nil)
+ selected-trees))))
+
+(defun org-export--skip-p (datum options selected)
+ "Non-nil when element or object DATUM should be skipped during export.
+OPTIONS is the plist holding export options. SELECTED, when
+non-nil, is a list of headlines or inlinetasks belonging to
+a tree with a select tag."
+ (cl-case (org-element-type datum)
+ ((comment comment-block)
+ ;; Skip all comments and comment blocks. Make to keep maximum
+ ;; number of blank lines around the comment so as to preserve
+ ;; local structure of the document upon interpreting it back into
+ ;; Org syntax.
+ (let* ((previous (org-export-get-previous-element datum options))
+ (before (or (org-element-property :post-blank previous) 0))
+ (after (or (org-element-property :post-blank datum) 0)))
+ (when previous
+ (org-element-put-property previous :post-blank (max before after 1))))
+ t)
+ (clock (not (plist-get options :with-clocks)))
+ (drawer
+ (let ((with-drawers-p (plist-get options :with-drawers)))
+ (or (not with-drawers-p)
+ (and (consp with-drawers-p)
+ ;; If `:with-drawers' value starts with `not', ignore
+ ;; every drawer whose name belong to that list.
+ ;; Otherwise, ignore drawers whose name isn't in that
+ ;; list.
+ (let ((name (org-element-property :drawer-name datum)))
+ (if (eq (car with-drawers-p) 'not)
+ (member-ignore-case name (cdr with-drawers-p))
+ (not (member-ignore-case name with-drawers-p))))))))
+ (fixed-width (not (plist-get options :with-fixed-width)))
+ ((footnote-definition footnote-reference)
+ (not (plist-get options :with-footnotes)))
+ ((headline inlinetask)
+ (let ((with-tasks (plist-get options :with-tasks))
+ (todo (org-element-property :todo-keyword datum))
+ (todo-type (org-element-property :todo-type datum))
+ (archived (plist-get options :with-archived-trees))
+ (tags (org-export-get-tags datum options nil t)))
+ (or
+ (and (eq (org-element-type datum) 'inlinetask)
+ (not (plist-get options :with-inlinetasks)))
+ ;; Ignore subtrees with an exclude tag.
+ (cl-loop for k in (plist-get options :exclude-tags)
+ thereis (member k tags))
+ ;; When a select tag is present in the buffer, ignore any tree
+ ;; without it.
+ (and selected (not (memq datum selected)))
+ ;; Ignore commented sub-trees.
+ (org-element-property :commentedp datum)
+ ;; Ignore archived subtrees if `:with-archived-trees' is nil.
+ (and (not archived) (org-element-property :archivedp datum))
+ ;; Ignore tasks, if specified by `:with-tasks' property.
+ (and todo
+ (or (not with-tasks)
+ (and (memq with-tasks '(todo done))
+ (not (eq todo-type with-tasks)))
+ (and (consp with-tasks) (not (member todo with-tasks))))))))
+ ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
+ (node-property
+ (let ((properties-set (plist-get options :with-properties)))
+ (cond ((null properties-set) t)
+ ((consp properties-set)
+ (not (member-ignore-case (org-element-property :key datum)
+ properties-set))))))
+ (planning (not (plist-get options :with-planning)))
+ (property-drawer (not (plist-get options :with-properties)))
+ (statistics-cookie (not (plist-get options :with-statistics-cookies)))
+ (table (not (plist-get options :with-tables)))
+ (table-cell
+ (and (org-export-table-has-special-column-p
+ (org-export-get-parent-table datum))
+ (org-export-first-sibling-p datum options)))
+ (table-row (org-export-table-row-is-special-p datum options))
+ (timestamp
+ ;; `:with-timestamps' only applies to isolated timestamps
+ ;; objects, i.e. timestamp objects in a paragraph containing only
+ ;; timestamps and whitespaces.
+ (when (let ((parent (org-export-get-parent-element datum)))
+ (and (memq (org-element-type parent) '(paragraph verse-block))
+ (not (org-element-map parent
+ (cons 'plain-text
+ (remq 'timestamp org-element-all-objects))
+ (lambda (obj)
+ (or (not (stringp obj)) (org-string-nw-p obj)))
+ options t))))
+ (cl-case (plist-get options :with-timestamps)
+ ((nil) t)
+ (active
+ (not (memq (org-element-property :type datum) '(active active-range))))
+ (inactive
+ (not (memq (org-element-property :type datum)
+ '(inactive inactive-range)))))))))
+
+
+;;; The Transcoder
+;;
+;; `org-export-data' reads a parse tree (obtained with, i.e.
+;; `org-element-parse-buffer') and transcodes it into a specified
+;; back-end output. It takes care of filtering out elements or
+;; objects according to export options and organizing the output blank
+;; lines and white space are preserved. The function memoizes its
+;; results, so it is cheap to call it within transcoders.
+;;
+;; It is possible to modify locally the back-end used by
+;; `org-export-data' or even use a temporary back-end by using
+;; `org-export-data-with-backend'.
+;;
+;; `org-export-transcoder' is an accessor returning appropriate
+;; translator function for a given element or object.
+
+(defun org-export-transcoder (blob info)
+ "Return appropriate transcoder for BLOB.
+INFO is a plist containing export directives."
+ (let ((type (org-element-type blob)))
+ ;; Return contents only for complete parse trees.
+ (if (eq type 'org-data) (lambda (_datum contents _info) contents)
+ (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
+ (and (functionp transcoder) transcoder)))))
+
+(defun org-export-data (data info)
+ "Convert DATA into current back-end format.
+
+DATA is a parse tree, an element or an object or a secondary
+string. INFO is a plist holding export options.
+
+Return a string."
+ (or (gethash data (plist-get info :exported-data))
+ ;; Handle broken links according to
+ ;; `org-export-with-broken-links'.
+ (cl-macrolet
+ ((broken-link-handler
+ (&rest body)
+ `(condition-case err
+ (progn ,@body)
+ (org-link-broken
+ (pcase (plist-get info :with-broken-links)
+ (`nil (user-error "Unable to resolve link: %S" (nth 1 err)))
+ (`mark (org-export-data
+ (format "[BROKEN LINK: %s]" (nth 1 err)) info))
+ (_ nil))))))
+ (let* ((type (org-element-type data))
+ (parent (org-export-get-parent data))
+ (results
+ (cond
+ ;; Ignored element/object.
+ ((memq data (plist-get info :ignore-list)) nil)
+ ;; Plain text.
+ ((eq type 'plain-text)
+ (org-export-filter-apply-functions
+ (plist-get info :filter-plain-text)
+ (let ((transcoder (org-export-transcoder data info)))
+ (if transcoder (funcall transcoder data info) data))
+ info))
+ ;; Secondary string.
+ ((not type)
+ (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
+ ;; Element/Object without contents or, as a special
+ ;; case, headline with archive tag and archived trees
+ ;; restricted to title only.
+ ((or (not (org-element-contents data))
+ (and (eq type 'headline)
+ (eq (plist-get info :with-archived-trees) 'headline)
+ (org-element-property :archivedp data)))
+ (let ((transcoder (org-export-transcoder data info)))
+ (or (and (functionp transcoder)
+ (broken-link-handler
+ (funcall transcoder data nil info)))
+ ;; Export snippets never return a nil value so
+ ;; that white spaces following them are never
+ ;; ignored.
+ (and (eq type 'export-snippet) ""))))
+ ;; Element/Object with contents.
+ (t
+ (let ((transcoder (org-export-transcoder data info)))
+ (when transcoder
+ (let* ((greaterp (memq type org-element-greater-elements))
+ (objectp
+ (and (not greaterp)
+ (memq type org-element-recursive-objects)))
+ (contents
+ (mapconcat
+ (lambda (element) (org-export-data element info))
+ (org-element-contents
+ (if (or greaterp objectp) data
+ ;; Elements directly containing
+ ;; objects must have their indentation
+ ;; normalized first.
+ (org-element-normalize-contents
+ data
+ ;; When normalizing contents of the
+ ;; first paragraph in an item or
+ ;; a footnote definition, ignore
+ ;; first line's indentation: there is
+ ;; none and it might be misleading.
+ (when (eq type 'paragraph)
+ (and
+ (eq (car (org-element-contents parent))
+ data)
+ (memq (org-element-type parent)
+ '(footnote-definition item)))))))
+ "")))
+ (broken-link-handler
+ (funcall transcoder data
+ (if (not greaterp) contents
+ (org-element-normalize-string contents))
+ info)))))))))
+ ;; Final result will be memoized before being returned.
+ (puthash
+ data
+ (cond
+ ((not results) "")
+ ((memq type '(org-data plain-text nil)) results)
+ ;; Append the same white space between elements or objects
+ ;; as in the original buffer, and call appropriate filters.
+ (t
+ (org-export-filter-apply-functions
+ (plist-get info (intern (format ":filter-%s" type)))
+ (let ((blank (or (org-element-property :post-blank data) 0)))
+ (if (eq (org-element-class data parent) 'object)
+ (concat results (make-string blank ?\s))
+ (concat (org-element-normalize-string results)
+ (make-string blank ?\n))))
+ info)))
+ (plist-get info :exported-data))))))
+
+(defun org-export-data-with-backend (data backend info)
+ "Convert DATA into BACKEND format.
+
+DATA is an element, an object, a secondary string or a string.
+BACKEND is a symbol. INFO is a plist used as a communication
+channel.
+
+Unlike to `org-export-with-backend', this function will
+recursively convert DATA using BACKEND translation table."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ ;; Set-up a new communication channel with translations defined in
+ ;; BACKEND as the translate table and a new hash table for
+ ;; memoization.
+ (let ((new-info
+ (org-combine-plists
+ info
+ (list :back-end backend
+ :translate-alist (org-export-get-all-transcoders backend)
+ ;; Size of the hash table is reduced since this
+ ;; function will probably be used on small trees.
+ :exported-data (make-hash-table :test 'eq :size 401)))))
+ (prog1 (org-export-data data new-info)
+ ;; Preserve `:internal-references', as those do not depend on
+ ;; the back-end used; we need to make sure that any new
+ ;; reference when the temporary back-end was active gets through
+ ;; the default one.
+ (plist-put info :internal-references
+ (plist-get new-info :internal-references)))))
+
+(defun org-export-expand (blob contents &optional with-affiliated)
+ "Expand a parsed element or object to its original state.
+
+BLOB is either an element or an object. CONTENTS is its
+contents, as a string or nil.
+
+When optional argument WITH-AFFILIATED is non-nil, add affiliated
+keywords before output."
+ (let ((type (org-element-type blob)))
+ (concat (and with-affiliated
+ (eq (org-element-class blob) 'element)
+ (org-element--interpret-affiliated-keywords blob))
+ (funcall (intern (format "org-element-%s-interpreter" type))
+ blob contents))))
+
+
+
+;;; The Filter System
+;;
+;; Filters allow end-users to tweak easily the transcoded output.
+;; They are the functional counterpart of hooks, as every filter in
+;; a set is applied to the return value of the previous one.
+;;
+;; Every set is back-end agnostic. Although, a filter is always
+;; called, in addition to the string it applies to, with the back-end
+;; used as argument, so it's easy for the end-user to add back-end
+;; specific filters in the set. The communication channel, as
+;; a plist, is required as the third argument.
+;;
+;; From the developer side, filters sets can be installed in the
+;; process with the help of `org-export-define-backend', which
+;; internally stores filters as an alist. Each association has a key
+;; among the following symbols and a function or a list of functions
+;; as value.
+;;
+;; - `:filter-options' applies to the property list containing export
+;; options. Unlike to other filters, functions in this list accept
+;; two arguments instead of three: the property list containing
+;; export options and the back-end. Users can set its value through
+;; `org-export-filter-options-functions' variable.
+;;
+;; - `:filter-parse-tree' applies directly to the complete parsed
+;; tree. Users can set it through
+;; `org-export-filter-parse-tree-functions' variable.
+;;
+;; - `:filter-body' applies to the body of the output, before template
+;; translator chimes in. Users can set it through
+;; `org-export-filter-body-functions' variable.
+;;
+;; - `:filter-final-output' applies to the final transcoded string.
+;; Users can set it with `org-export-filter-final-output-functions'
+;; variable.
+;;
+;; - `:filter-plain-text' applies to any string not recognized as Org
+;; syntax. `org-export-filter-plain-text-functions' allows users to
+;; configure it.
+;;
+;; - `:filter-TYPE' applies on the string returned after an element or
+;; object of type TYPE has been transcoded. A user can modify
+;; `org-export-filter-TYPE-functions' to install these filters.
+;;
+;; All filters sets are applied with
+;; `org-export-filter-apply-functions' function. Filters in a set are
+;; applied in a LIFO fashion. It allows developers to be sure that
+;; their filters will be applied first.
+;;
+;; Filters properties are installed in communication channel with
+;; `org-export-install-filters' function.
+;;
+;; Eventually, two hooks (`org-export-before-processing-hook' and
+;; `org-export-before-parsing-hook') are run at the beginning of the
+;; export process and just before parsing to allow for heavy structure
+;; modifications.
+
+
+;;;; Hooks
+
+(defvar org-export-before-processing-hook nil
+ "Hook run at the beginning of the export process.
+
+This is run before include keywords and macros are expanded and
+Babel code blocks executed, on a copy of the original buffer
+being exported. Visibility and narrowing are preserved. Point
+is at the beginning of the buffer.
+
+Every function in this hook will be called with one argument: the
+back-end currently used, as a symbol.")
+
+(defvar org-export-before-parsing-hook nil
+ "Hook run before parsing an export buffer.
+
+This is run after include keywords and macros have been expanded
+and Babel code blocks executed, on a copy of the original buffer
+being exported. Visibility and narrowing are preserved. Point
+is at the beginning of the buffer.
+
+Every function in this hook will be called with one argument: the
+back-end currently used, as a symbol.")
+
+
+;;;; Special Filters
+
+(defvar org-export-filter-options-functions nil
+ "List of functions applied to the export options.
+Each filter is called with two arguments: the export options, as
+a plist, and the back-end, as a symbol. It must return
+a property list containing export options.")
+
+(defvar org-export-filter-parse-tree-functions nil
+ "List of functions applied to the parsed tree.
+Each filter is called with three arguments: the parse tree, as
+returned by `org-element-parse-buffer', the back-end, as
+a symbol, and the communication channel, as a plist. It must
+return the modified parse tree to transcode.")
+
+(defvar org-export-filter-plain-text-functions nil
+ "List of functions applied to plain text.
+Each filter is called with three arguments: a string which
+contains no Org syntax, the back-end, as a symbol, and the
+communication channel, as a plist. It must return a string or
+nil.")
+
+(defvar org-export-filter-body-functions nil
+ "List of functions applied to transcoded body.
+Each filter is called with three arguments: a string which
+contains no Org syntax, the back-end, as a symbol, and the
+communication channel, as a plist. It must return a string or
+nil.")
+
+(defvar org-export-filter-final-output-functions nil
+ "List of functions applied to the transcoded string.
+Each filter is called with three arguments: the full transcoded
+string, the back-end, as a symbol, and the communication channel,
+as a plist. It must return a string that will be used as the
+final export output.")
+
+
+;;;; Elements Filters
+
+(defvar org-export-filter-babel-call-functions nil
+ "List of functions applied to a transcoded babel-call.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-center-block-functions nil
+ "List of functions applied to a transcoded center block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-clock-functions nil
+ "List of functions applied to a transcoded clock.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-diary-sexp-functions nil
+ "List of functions applied to a transcoded diary-sexp.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-drawer-functions nil
+ "List of functions applied to a transcoded drawer.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-dynamic-block-functions nil
+ "List of functions applied to a transcoded dynamic-block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-example-block-functions nil
+ "List of functions applied to a transcoded example-block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-export-block-functions nil
+ "List of functions applied to a transcoded export-block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-fixed-width-functions nil
+ "List of functions applied to a transcoded fixed-width.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-footnote-definition-functions nil
+ "List of functions applied to a transcoded footnote-definition.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-headline-functions nil
+ "List of functions applied to a transcoded headline.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-horizontal-rule-functions nil
+ "List of functions applied to a transcoded horizontal-rule.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-inlinetask-functions nil
+ "List of functions applied to a transcoded inlinetask.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-item-functions nil
+ "List of functions applied to a transcoded item.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-keyword-functions nil
+ "List of functions applied to a transcoded keyword.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-latex-environment-functions nil
+ "List of functions applied to a transcoded latex-environment.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-node-property-functions nil
+ "List of functions applied to a transcoded node-property.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-paragraph-functions nil
+ "List of functions applied to a transcoded paragraph.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-plain-list-functions nil
+ "List of functions applied to a transcoded plain-list.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-planning-functions nil
+ "List of functions applied to a transcoded planning.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-property-drawer-functions nil
+ "List of functions applied to a transcoded property-drawer.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-quote-block-functions nil
+ "List of functions applied to a transcoded quote block.
+Each filter is called with three arguments: the transcoded quote
+data, as a string, the back-end, as a symbol, and the
+communication channel, as a plist. It must return a string or
+nil.")
+
+(defvar org-export-filter-section-functions nil
+ "List of functions applied to a transcoded section.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-special-block-functions nil
+ "List of functions applied to a transcoded special block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-src-block-functions nil
+ "List of functions applied to a transcoded src-block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-table-functions nil
+ "List of functions applied to a transcoded table.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-table-cell-functions nil
+ "List of functions applied to a transcoded table-cell.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-table-row-functions nil
+ "List of functions applied to a transcoded table-row.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-verse-block-functions nil
+ "List of functions applied to a transcoded verse block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+
+;;;; Objects Filters
+
+(defvar org-export-filter-bold-functions nil
+ "List of functions applied to transcoded bold text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-code-functions nil
+ "List of functions applied to transcoded code text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-entity-functions nil
+ "List of functions applied to a transcoded entity.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-export-snippet-functions nil
+ "List of functions applied to a transcoded export-snippet.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-footnote-reference-functions nil
+ "List of functions applied to a transcoded footnote-reference.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-inline-babel-call-functions nil
+ "List of functions applied to a transcoded inline-babel-call.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-inline-src-block-functions nil
+ "List of functions applied to a transcoded inline-src-block.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-italic-functions nil
+ "List of functions applied to transcoded italic text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-latex-fragment-functions nil
+ "List of functions applied to a transcoded latex-fragment.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-line-break-functions nil
+ "List of functions applied to a transcoded line-break.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-link-functions nil
+ "List of functions applied to a transcoded link.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-radio-target-functions nil
+ "List of functions applied to a transcoded radio-target.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-statistics-cookie-functions nil
+ "List of functions applied to a transcoded statistics-cookie.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-strike-through-functions nil
+ "List of functions applied to transcoded strike-through text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-subscript-functions nil
+ "List of functions applied to a transcoded subscript.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-superscript-functions nil
+ "List of functions applied to a transcoded superscript.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-target-functions nil
+ "List of functions applied to a transcoded target.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-timestamp-functions nil
+ "List of functions applied to a transcoded timestamp.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-underline-functions nil
+ "List of functions applied to transcoded underline text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+(defvar org-export-filter-verbatim-functions nil
+ "List of functions applied to transcoded verbatim text.
+Each filter is called with three arguments: the transcoded data,
+as a string, the back-end, as a symbol, and the communication
+channel, as a plist. It must return a string or nil.")
+
+
+;;;; Filters Tools
+;;
+;; Internal function `org-export-install-filters' installs filters
+;; hard-coded in back-ends (developer filters) and filters from global
+;; variables (user filters) in the communication channel.
+;;
+;; Internal function `org-export-filter-apply-functions' takes care
+;; about applying each filter in order to a given data. It ignores
+;; filters returning a nil value but stops whenever a filter returns
+;; an empty string.
+
+(defun org-export-filter-apply-functions (filters value info)
+ "Call every function in FILTERS.
+
+Functions are called with three arguments: a value, the export
+back-end name and the communication channel. First function in
+FILTERS is called with VALUE as its first argument. Second
+function in FILTERS is called with the previous result as its
+value, etc.
+
+Functions returning nil are skipped. Any function returning the
+empty string ends the process, which returns the empty string.
+
+Call is done in a LIFO fashion, to be sure that developer
+specified filters, if any, are called first."
+ (catch :exit
+ (let* ((backend (plist-get info :back-end))
+ (backend-name (and backend (org-export-backend-name backend))))
+ (dolist (filter filters value)
+ (let ((result (funcall filter value backend-name info)))
+ (cond ((not result))
+ ((equal result "") (throw :exit ""))
+ (t (setq value result))))))))
+
+(defun org-export-install-filters (info)
+ "Install filters properties in communication channel.
+INFO is a plist containing the current communication channel.
+Return the updated communication channel."
+ (let (plist)
+ ;; Install user-defined filters with `org-export-filters-alist'
+ ;; and filters already in INFO (through ext-plist mechanism).
+ (dolist (p org-export-filters-alist)
+ (let* ((prop (car p))
+ (info-value (plist-get info prop))
+ (default-value (symbol-value (cdr p))))
+ (setq plist
+ (plist-put plist prop
+ ;; Filters in INFO will be called
+ ;; before those user provided.
+ (append (if (listp info-value) info-value
+ (list info-value))
+ default-value)))))
+ ;; Prepend back-end specific filters to that list.
+ (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
+ ;; Single values get consed, lists are appended.
+ (let ((key (car p)) (value (cdr p)))
+ (when value
+ (setq plist
+ (plist-put
+ plist key
+ (if (atom value) (cons value (plist-get plist key))
+ (append value (plist-get plist key))))))))
+ ;; Return new communication channel.
+ (org-combine-plists info plist)))
+
+
+
+;;; Core functions
+;;
+;; This is the room for the main function, `org-export-as', along with
+;; its derivative, `org-export-string-as'.
+;; `org-export--copy-to-kill-ring-p' determines if output of these
+;; function should be added to kill ring.
+;;
+;; Note that `org-export-as' doesn't really parse the current buffer,
+;; but a copy of it (with the same buffer-local variables and
+;; visibility), where macros and include keywords are expanded and
+;; Babel blocks are executed, if appropriate.
+;; `org-export-with-buffer-copy' macro prepares that copy.
+;;
+;; File inclusion is taken care of by
+;; `org-export-expand-include-keyword' and
+;; `org-export--prepare-file-contents'. Structure wise, including
+;; a whole Org file in a buffer often makes little sense. For
+;; example, if the file contains a headline and the include keyword
+;; was within an item, the item should contain the headline. That's
+;; why file inclusion should be done before any structure can be
+;; associated to the file, that is before parsing.
+;;
+;; `org-export-insert-default-template' is a command to insert
+;; a default template (or a back-end specific template) at point or in
+;; current subtree.
+
+(defun org-export-copy-buffer ()
+ "Return a copy of the current buffer.
+The copy preserves Org buffer-local variables, visibility and
+narrowing."
+ (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
+ (new-buf (generate-new-buffer (buffer-name))))
+ (with-current-buffer new-buf
+ (funcall copy-buffer-fun)
+ (set-buffer-modified-p nil))
+ new-buf))
+
+(defmacro org-export-with-buffer-copy (&rest body)
+ "Apply BODY in a copy of the current buffer.
+The copy preserves local variables, visibility and contents of
+the original buffer. Point is at the beginning of the buffer
+when BODY is applied."
+ (declare (debug t))
+ (org-with-gensyms (buf-copy)
+ `(let ((,buf-copy (org-export-copy-buffer)))
+ (unwind-protect
+ (with-current-buffer ,buf-copy
+ (goto-char (point-min))
+ (progn ,@body))
+ (and (buffer-live-p ,buf-copy)
+ ;; Kill copy without confirmation.
+ (progn (with-current-buffer ,buf-copy
+ (restore-buffer-modified-p nil))
+ (kill-buffer ,buf-copy)))))))
+
+(defun org-export--generate-copy-script (buffer)
+ "Generate a function duplicating BUFFER.
+
+The copy will preserve local variables, visibility, contents and
+narrowing of the original buffer. If a region was active in
+BUFFER, contents will be narrowed to that region instead.
+
+The resulting function can be evaluated at a later time, from
+another buffer, effectively cloning the original buffer there.
+
+The function assumes BUFFER's major mode is `org-mode'."
+ (with-current-buffer buffer
+ `(lambda ()
+ (let ((inhibit-modification-hooks t))
+ ;; Set major mode. Ignore `org-mode-hook' as it has been run
+ ;; already in BUFFER.
+ (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
+ ;; Copy specific buffer local variables and variables set
+ ;; through BIND keywords.
+ ,@(let ((bound-variables (org-export--list-bound-variables))
+ vars)
+ (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
+ (when (consp entry)
+ (let ((var (car entry))
+ (val (cdr entry)))
+ (and (not (memq var org-export-ignored-local-variables))
+ (or (memq var
+ '(default-directory
+ buffer-file-name
+ buffer-file-coding-system))
+ (assq var bound-variables)
+ (string-match "^\\(org-\\|orgtbl-\\)"
+ (symbol-name var)))
+ ;; Skip unreadable values, as they cannot be
+ ;; sent to external process.
+ (or (not val) (ignore-errors (read (format "%S" val))))
+ (push `(set (make-local-variable (quote ,var))
+ (quote ,val))
+ vars))))))
+ ;; Whole buffer contents.
+ (insert
+ ,(org-with-wide-buffer
+ (buffer-substring-no-properties
+ (point-min) (point-max))))
+ ;; Narrowing.
+ ,(if (org-region-active-p)
+ `(narrow-to-region ,(region-beginning) ,(region-end))
+ `(narrow-to-region ,(point-min) ,(point-max)))
+ ;; Current position of point.
+ (goto-char ,(point))
+ ;; Overlays with invisible property.
+ ,@(let (ov-set)
+ (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
+ (let ((invis-prop (overlay-get ov 'invisible)))
+ (when invis-prop
+ (push `(overlay-put
+ (make-overlay ,(overlay-start ov)
+ ,(overlay-end ov))
+ 'invisible (quote ,invis-prop))
+ ov-set)))))))))
+
+(defun org-export--delete-comment-trees ()
+ "Delete commented trees and commented inlinetasks in the buffer.
+Narrowing, if any, is ignored."
+ (org-with-wide-buffer
+ (goto-char (point-min))
+ (let* ((case-fold-search t)
+ (regexp (concat org-outline-regexp-bol ".*" org-comment-string)))
+ (while (re-search-forward regexp nil t)
+ (let ((element (org-element-at-point)))
+ (when (org-element-property :commentedp element)
+ (delete-region (org-element-property :begin element)
+ (org-element-property :end element))))))))
+
+(defun org-export--prune-tree (data info)
+ "Prune non exportable elements from DATA.
+DATA is the parse tree to traverse. INFO is the plist holding
+export info. Also set `:ignore-list' in INFO to a list of
+objects which should be ignored during export, but not removed
+from tree."
+ (letrec ((ignore nil)
+ ;; First find trees containing a select tag, if any.
+ (selected (org-export--selected-trees data info))
+ (walk-data
+ (lambda (data)
+ ;; Prune non-exportable elements and objects from tree.
+ ;; As a special case, special rows and cells from tables
+ ;; are stored in IGNORE, as they still need to be
+ ;; accessed during export.
+ (when data
+ (let ((type (org-element-type data)))
+ (if (org-export--skip-p data info selected)
+ (if (memq type '(table-cell table-row)) (push data ignore)
+ (org-element-extract-element data))
+ (if (and (eq type 'headline)
+ (eq (plist-get info :with-archived-trees)
+ 'headline)
+ (org-element-property :archivedp data))
+ ;; If headline is archived but tree below has
+ ;; to be skipped, remove contents.
+ (org-element-set-contents data)
+ ;; Move into recursive objects/elements.
+ (mapc walk-data (org-element-contents data)))
+ ;; Move into secondary string, if any.
+ (dolist (p (cdr (assq type
+ org-element-secondary-value-alist)))
+ (mapc walk-data (org-element-property p data))))))))
+ (definitions
+ ;; Collect definitions before possibly pruning them so as
+ ;; to avoid parsing them again if they are required.
+ (org-element-map data '(footnote-definition footnote-reference)
+ (lambda (f)
+ (cond
+ ((eq (org-element-type f) 'footnote-definition) f)
+ ((eq (org-element-property :type f) 'standard) nil)
+ (t (let ((label (org-element-property :label f)))
+ (when label ;Skip anonymous references.
+ (apply
+ #'org-element-create
+ 'footnote-definition `(:label ,label :post-blank 1)
+ (org-element-contents f))))))))))
+ ;; If a select tag is active, also ignore the section before the
+ ;; first headline, if any.
+ (when selected
+ (let ((first-element (car (org-element-contents data))))
+ (when (eq (org-element-type first-element) 'section)
+ (org-element-extract-element first-element))))
+ ;; Prune tree and communication channel.
+ (funcall walk-data data)
+ (dolist (entry (append
+ ;; Priority is given to back-end specific options.
+ (org-export-get-all-options (plist-get info :back-end))
+ org-export-options-alist))
+ (when (eq (nth 4 entry) 'parse)
+ (funcall walk-data (plist-get info (car entry)))))
+ (let ((missing (org-export--missing-definitions data definitions)))
+ (funcall walk-data missing)
+ (org-export--install-footnote-definitions missing data))
+ ;; Eventually set `:ignore-list'.
+ (plist-put info :ignore-list ignore)))
+
+(defun org-export--missing-definitions (tree definitions)
+ "List footnote definitions missing from TREE.
+Missing definitions are searched within DEFINITIONS, which is
+a list of footnote definitions or in the widened buffer."
+ (let* ((list-labels
+ (lambda (data)
+ ;; List all footnote labels encountered in DATA. Inline
+ ;; footnote references are ignored.
+ (org-element-map data 'footnote-reference
+ (lambda (reference)
+ (and (eq (org-element-property :type reference) 'standard)
+ (org-element-property :label reference))))))
+ defined undefined missing-definitions)
+ ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
+ ;; references.
+ (let ((known-definitions
+ (org-element-map tree '(footnote-reference footnote-definition)
+ (lambda (f)
+ (and (or (eq (org-element-type f) 'footnote-definition)
+ (eq (org-element-property :type f) 'inline))
+ (org-element-property :label f)))))
+ seen)
+ (dolist (l (funcall list-labels tree))
+ (cond ((member l seen))
+ ((member l known-definitions) (push l defined))
+ (t (push l undefined)))))
+ ;; Complete MISSING-DEFINITIONS by finding the definition of every
+ ;; undefined label, first by looking into DEFINITIONS, then by
+ ;; searching the widened buffer. This is a recursive process
+ ;; since definitions found can themselves contain an undefined
+ ;; reference.
+ (while undefined
+ (let* ((label (pop undefined))
+ (definition
+ (cond
+ ((cl-some
+ (lambda (d) (and (equal (org-element-property :label d) label)
+ d))
+ definitions))
+ ((pcase (org-footnote-get-definition label)
+ (`(,_ ,beg . ,_)
+ (org-with-wide-buffer
+ (goto-char beg)
+ (let ((datum (org-element-context)))
+ (if (eq (org-element-type datum) 'footnote-reference)
+ datum
+ ;; Parse definition with contents.
+ (save-restriction
+ (narrow-to-region
+ (org-element-property :begin datum)
+ (org-element-property :end datum))
+ (org-element-map (org-element-parse-buffer)
+ 'footnote-definition #'identity nil t))))))
+ (_ nil)))
+ (t (user-error "Definition not found for footnote %s" label)))))
+ (push label defined)
+ (push definition missing-definitions)
+ ;; Look for footnote references within DEFINITION, since
+ ;; we may need to also find their definition.
+ (dolist (l (funcall list-labels definition))
+ (unless (or (member l defined) ;Known label
+ (member l undefined)) ;Processed later
+ (push l undefined)))))
+ ;; MISSING-DEFINITIONS may contain footnote references with inline
+ ;; definitions. Make sure those are changed into real footnote
+ ;; definitions.
+ (mapcar (lambda (d)
+ (if (eq (org-element-type d) 'footnote-definition) d
+ (let ((label (org-element-property :label d)))
+ (apply #'org-element-create
+ 'footnote-definition `(:label ,label :post-blank 1)
+ (org-element-contents d)))))
+ missing-definitions)))
+
+(defun org-export--install-footnote-definitions (definitions tree)
+ "Install footnote definitions in tree.
+
+DEFINITIONS is the list of footnote definitions to install. TREE
+is the parse tree.
+
+If there is a footnote section in TREE, definitions found are
+appended to it. If `org-footnote-section' is non-nil, a new
+footnote section containing all definitions is inserted in TREE.
+Otherwise, definitions are appended at the end of the section
+containing their first reference."
+ (cond
+ ((null definitions))
+ ;; If there is a footnote section, insert definitions there.
+ ((let ((footnote-section
+ (org-element-map tree 'headline
+ (lambda (h) (and (org-element-property :footnote-section-p h) h))
+ nil t)))
+ (and footnote-section
+ (apply #'org-element-adopt-elements
+ footnote-section
+ (nreverse definitions)))))
+ ;; If there should be a footnote section, create one containing all
+ ;; the definitions at the end of the tree.
+ (org-footnote-section
+ (org-element-adopt-elements
+ tree
+ (org-element-create 'headline
+ (list :footnote-section-p t
+ :level 1
+ :title org-footnote-section
+ :raw-value org-footnote-section)
+ (apply #'org-element-create
+ 'section
+ nil
+ (nreverse definitions)))))
+ ;; Otherwise add each definition at the end of the section where it
+ ;; is first referenced.
+ (t
+ (letrec ((seen nil)
+ (insert-definitions
+ (lambda (data)
+ ;; Insert footnote definitions in the same section as
+ ;; their first reference in DATA.
+ (org-element-map data 'footnote-reference
+ (lambda (reference)
+ (when (eq (org-element-property :type reference) 'standard)
+ (let ((label (org-element-property :label reference)))
+ (unless (member label seen)
+ (push label seen)
+ (let ((definition
+ (cl-some
+ (lambda (d)
+ (and (equal (org-element-property :label d)
+ label)
+ d))
+ definitions)))
+ (org-element-adopt-elements
+ (org-element-lineage reference '(section))
+ definition)
+ ;; Also insert definitions for nested
+ ;; references, if any.
+ (funcall insert-definitions definition))))))))))
+ (funcall insert-definitions tree)))))
+
+(defun org-export--remove-uninterpreted-data (data info)
+ "Change uninterpreted elements back into Org syntax.
+DATA is a parse tree or a secondary string. INFO is a plist
+containing export options. It is modified by side effect and
+returned by the function."
+ (org-element-map data
+ '(entity bold italic latex-environment latex-fragment strike-through
+ subscript superscript underline)
+ (lambda (datum)
+ (let ((new
+ (cl-case (org-element-type datum)
+ ;; ... entities...
+ (entity
+ (and (not (plist-get info :with-entities))
+ (list (concat
+ (org-export-expand datum nil)
+ (make-string
+ (or (org-element-property :post-blank datum) 0)
+ ?\s)))))
+ ;; ... emphasis...
+ ((bold italic strike-through underline)
+ (and (not (plist-get info :with-emphasize))
+ (let ((marker (cl-case (org-element-type datum)
+ (bold "*")
+ (italic "/")
+ (strike-through "+")
+ (underline "_"))))
+ (append
+ (list marker)
+ (org-element-contents datum)
+ (list (concat
+ marker
+ (make-string
+ (or (org-element-property :post-blank datum)
+ 0)
+ ?\s)))))))
+ ;; ... LaTeX environments and fragments...
+ ((latex-environment latex-fragment)
+ (and (eq (plist-get info :with-latex) 'verbatim)
+ (list (org-export-expand datum nil))))
+ ;; ... sub/superscripts...
+ ((subscript superscript)
+ (let ((sub/super-p (plist-get info :with-sub-superscript))
+ (bracketp (org-element-property :use-brackets-p datum)))
+ (and (or (not sub/super-p)
+ (and (eq sub/super-p '{}) (not bracketp)))
+ (append
+ (list (concat
+ (if (eq (org-element-type datum) 'subscript)
+ "_"
+ "^")
+ (and bracketp "{")))
+ (org-element-contents datum)
+ (list (concat
+ (and bracketp "}")
+ (and (org-element-property :post-blank datum)
+ (make-string
+ (org-element-property :post-blank datum)
+ ?\s)))))))))))
+ (when new
+ ;; Splice NEW at DATUM location in parse tree.
+ (dolist (e new (org-element-extract-element datum))
+ (unless (equal e "") (org-element-insert-before e datum))))))
+ info nil nil t)
+ ;; Return modified parse tree.
+ data)
+
+;;;###autoload
+(defun org-export-as
+ (backend &optional subtreep visible-only body-only ext-plist)
+ "Transcode current Org buffer into BACKEND code.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+If narrowing is active in the current buffer, only transcode its
+narrowed part.
+
+If a region is active, transcode that region.
+
+When optional argument SUBTREEP is non-nil, transcode the
+sub-tree at point, extracting information from the headline
+properties first.
+
+When optional argument VISIBLE-ONLY is non-nil, don't export
+contents of hidden elements.
+
+When optional argument BODY-ONLY is non-nil, only return body
+code, without surrounding template.
+
+Optional argument EXT-PLIST, when provided, is a property list
+with external parameters overriding Org default settings, but
+still inferior to file-local settings.
+
+Return code as a string."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (org-export-barf-if-invalid-backend backend)
+ (save-excursion
+ (save-restriction
+ ;; Narrow buffer to an appropriate region or subtree for
+ ;; parsing. If parsing subtree, be sure to remove main
+ ;; headline, planning data and property drawer.
+ (cond ((org-region-active-p)
+ (narrow-to-region (region-beginning) (region-end)))
+ (subtreep
+ (org-narrow-to-subtree)
+ (goto-char (point-min))
+ (org-end-of-meta-data)
+ (narrow-to-region (point) (point-max))))
+ ;; Initialize communication channel with original buffer
+ ;; attributes, unavailable in its copy.
+ (let* ((org-export-current-backend (org-export-backend-name backend))
+ (info (org-combine-plists
+ (org-export--get-export-attributes
+ backend subtreep visible-only body-only)
+ (org-export--get-buffer-attributes)))
+ (parsed-keywords
+ (delq nil
+ (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
+ (append (org-export-get-all-options backend)
+ org-export-options-alist))))
+ tree)
+ ;; Update communication channel and get parse tree. Buffer
+ ;; isn't parsed directly. Instead, all buffer modifications
+ ;; and consequent parsing are undertaken in a temporary copy.
+ (org-export-with-buffer-copy
+ ;; Run first hook with current back-end's name as argument.
+ (run-hook-with-args 'org-export-before-processing-hook
+ (org-export-backend-name backend))
+ ;; Include files, delete comments and expand macros.
+ (org-export-expand-include-keyword)
+ (org-export--delete-comment-trees)
+ (org-macro-initialize-templates)
+ (org-macro-replace-all org-macro-templates nil parsed-keywords)
+ ;; Refresh buffer properties and radio targets after
+ ;; potentially invasive previous changes. Likewise, do it
+ ;; again after executing Babel code.
+ (org-set-regexps-and-options)
+ (org-update-radio-target-regexp)
+ (when org-export-babel-evaluate
+ (org-babel-exp-process-buffer)
+ (org-set-regexps-and-options)
+ (org-update-radio-target-regexp))
+ ;; Run last hook with current back-end's name as argument.
+ ;; Update buffer properties and radio targets one last time
+ ;; before parsing.
+ (goto-char (point-min))
+ (save-excursion
+ (run-hook-with-args 'org-export-before-parsing-hook
+ (org-export-backend-name backend)))
+ (org-set-regexps-and-options)
+ (org-update-radio-target-regexp)
+ ;; Update communication channel with environment.
+ (setq info
+ (org-combine-plists
+ info (org-export-get-environment backend subtreep ext-plist)))
+ ;; De-activate uninterpreted data from parsed keywords.
+ (dolist (entry (append (org-export-get-all-options backend)
+ org-export-options-alist))
+ (pcase entry
+ (`(,p ,_ ,_ ,_ parse)
+ (let ((value (plist-get info p)))
+ (plist-put info
+ p
+ (org-export--remove-uninterpreted-data value info))))
+ (_ nil)))
+ ;; Install user's and developer's filters.
+ (setq info (org-export-install-filters info))
+ ;; Call options filters and update export options. We do not
+ ;; use `org-export-filter-apply-functions' here since the
+ ;; arity of such filters is different.
+ (let ((backend-name (org-export-backend-name backend)))
+ (dolist (filter (plist-get info :filter-options))
+ (let ((result (funcall filter info backend-name)))
+ (when result (setq info result)))))
+ ;; Expand export-specific set of macros: {{{author}}},
+ ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
+ ;; be done once regular macros have been expanded, since
+ ;; parsed keywords may contain one of them.
+ (org-macro-replace-all
+ (list
+ (cons "author" (org-element-interpret-data (plist-get info :author)))
+ (cons "date"
+ (let* ((date (plist-get info :date))
+ (value (or (org-element-interpret-data date) "")))
+ (if (and (consp date)
+ (not (cdr date))
+ (eq (org-element-type (car date)) 'timestamp))
+ (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
+ (format "(org-timestamp-format '%S \"$1\")"
+ (org-element-copy (car date)))
+ value)
+ value)))
+ (cons "email" (org-element-interpret-data (plist-get info :email)))
+ (cons "title" (org-element-interpret-data (plist-get info :title)))
+ (cons "results" "$1"))
+ 'finalize
+ parsed-keywords)
+ ;; Parse buffer.
+ (setq tree (org-element-parse-buffer nil visible-only))
+ ;; Prune tree from non-exported elements and transform
+ ;; uninterpreted elements or objects in both parse tree and
+ ;; communication channel.
+ (org-export--prune-tree tree info)
+ (org-export--remove-uninterpreted-data tree info)
+ ;; Call parse tree filters.
+ (setq tree
+ (org-export-filter-apply-functions
+ (plist-get info :filter-parse-tree) tree info))
+ ;; Now tree is complete, compute its properties and add them
+ ;; to communication channel.
+ (setq info (org-export--collect-tree-properties tree info))
+ ;; Eventually transcode TREE. Wrap the resulting string into
+ ;; a template.
+ (let* ((body (org-element-normalize-string
+ (or (org-export-data tree info) "")))
+ (inner-template (cdr (assq 'inner-template
+ (plist-get info :translate-alist))))
+ (full-body (org-export-filter-apply-functions
+ (plist-get info :filter-body)
+ (if (not (functionp inner-template)) body
+ (funcall inner-template body info))
+ info))
+ (template (cdr (assq 'template
+ (plist-get info :translate-alist)))))
+ ;; Remove all text properties since they cannot be
+ ;; retrieved from an external process. Finally call
+ ;; final-output filter and return result.
+ (org-no-properties
+ (org-export-filter-apply-functions
+ (plist-get info :filter-final-output)
+ (if (or (not (functionp template)) body-only) full-body
+ (funcall template full-body info))
+ info))))))))
+
+;;;###autoload
+(defun org-export-string-as (string backend &optional body-only ext-plist)
+ "Transcode STRING into BACKEND code.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+When optional argument BODY-ONLY is non-nil, only return body
+code, without preamble nor postamble.
+
+Optional argument EXT-PLIST, when provided, is a property list
+with external parameters overriding Org default settings, but
+still inferior to file-local settings.
+
+Return code as a string."
+ (with-temp-buffer
+ (insert string)
+ (let ((org-inhibit-startup t)) (org-mode))
+ (org-export-as backend nil nil body-only ext-plist)))
+
+;;;###autoload
+(defun org-export-replace-region-by (backend)
+ "Replace the active region by its export to BACKEND.
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end."
+ (unless (org-region-active-p) (user-error "No active region to replace"))
+ (insert
+ (org-export-string-as
+ (delete-and-extract-region (region-beginning) (region-end)) backend t)))
+
+;;;###autoload
+(defun org-export-insert-default-template (&optional backend subtreep)
+ "Insert all export keywords with default values at beginning of line.
+
+BACKEND is a symbol referring to the name of a registered export
+back-end, for which specific export options should be added to
+the template, or `default' for default template. When it is nil,
+the user will be prompted for a category.
+
+If SUBTREEP is non-nil, export configuration will be set up
+locally for the subtree through node properties."
+ (interactive)
+ (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
+ (when (and subtreep (org-before-first-heading-p))
+ (user-error "No subtree to set export options for"))
+ (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
+ (backend
+ (or backend
+ (intern
+ (org-completing-read
+ "Options category: "
+ (cons "default"
+ (mapcar (lambda (b)
+ (symbol-name (org-export-backend-name b)))
+ org-export-registered-backends))
+ nil t))))
+ options keywords)
+ ;; Populate OPTIONS and KEYWORDS.
+ (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
+ ((org-export-backend-p backend)
+ (org-export-backend-options backend))
+ (t (org-export-backend-options
+ (org-export-get-backend backend)))))
+ (let ((keyword (nth 1 entry))
+ (option (nth 2 entry)))
+ (cond
+ (keyword (unless (assoc keyword keywords)
+ (let ((value
+ (if (eq (nth 4 entry) 'split)
+ (mapconcat #'identity (eval (nth 3 entry)) " ")
+ (eval (nth 3 entry)))))
+ (push (cons keyword value) keywords))))
+ (option (unless (assoc option options)
+ (push (cons option (eval (nth 3 entry))) options))))))
+ ;; Move to an appropriate location in order to insert options.
+ (unless subtreep (beginning-of-line))
+ ;; First (multiple) OPTIONS lines. Never go past fill-column.
+ (when options
+ (let ((items
+ (mapcar
+ #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
+ (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
+ (if subtreep
+ (org-entry-put
+ node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
+ (while items
+ (insert "#+OPTIONS:")
+ (let ((width 10))
+ (while (and items
+ (< (+ width (length (car items)) 1) fill-column))
+ (let ((item (pop items)))
+ (insert " " item)
+ (cl-incf width (1+ (length item))))))
+ (insert "\n")))))
+ ;; Then the rest of keywords, in the order specified in either
+ ;; `org-export-options-alist' or respective export back-ends.
+ (dolist (key (nreverse keywords))
+ (let ((val (cond ((equal (car key) "DATE")
+ (or (cdr key)
+ (with-temp-buffer
+ (org-insert-time-stamp (current-time)))))
+ ((equal (car key) "TITLE")
+ (or (let ((visited-file
+ (buffer-file-name (buffer-base-buffer))))
+ (and visited-file
+ (file-name-sans-extension
+ (file-name-nondirectory visited-file))))
+ (buffer-name (buffer-base-buffer))))
+ (t (cdr key)))))
+ (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
+ (insert
+ (format "#+%s:%s\n"
+ (car key)
+ (if (org-string-nw-p val) (format " %s" val) ""))))))))
+
+(defun org-export-expand-include-keyword (&optional included dir footnotes)
+ "Expand every include keyword in buffer.
+Optional argument INCLUDED is a list of included file names along
+with their line restriction, when appropriate. It is used to
+avoid infinite recursion. Optional argument DIR is the current
+working directory. It is used to properly resolve relative
+paths. Optional argument FOOTNOTES is a hash-table used for
+storing and resolving footnotes. It is created automatically."
+ (let ((case-fold-search t)
+ (file-prefix (make-hash-table :test #'equal))
+ (current-prefix 0)
+ (footnotes (or footnotes (make-hash-table :test #'equal)))
+ (include-re "^[ \t]*#\\+INCLUDE:"))
+ ;; If :minlevel is not set the text-property
+ ;; `:org-include-induced-level' will be used to determine the
+ ;; relative level when expanding INCLUDE.
+ ;; Only affects included Org documents.
+ (goto-char (point-min))
+ (while (re-search-forward include-re nil t)
+ (put-text-property (line-beginning-position) (line-end-position)
+ :org-include-induced-level
+ (1+ (org-reduced-level (or (org-current-level) 0)))))
+ ;; Expand INCLUDE keywords.
+ (goto-char (point-min))
+ (while (re-search-forward include-re nil t)
+ (let ((element (save-match-data (org-element-at-point))))
+ (when (eq (org-element-type element) 'keyword)
+ (beginning-of-line)
+ ;; Extract arguments from keyword's value.
+ (let* ((value (org-element-property :value element))
+ (ind (org-get-indentation))
+ location
+ (file
+ (and (string-match
+ "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
+ (prog1
+ (save-match-data
+ (let ((matched (match-string 1 value)))
+ (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
+ matched)
+ (setq location (match-string 2 matched))
+ (setq matched
+ (replace-match "" nil nil matched 1)))
+ (expand-file-name
+ (org-unbracket-string "\"" "\"" matched)
+ dir)))
+ (setq value (replace-match "" nil nil value)))))
+ (only-contents
+ (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
+ value)
+ (prog1 (org-not-nil (match-string 1 value))
+ (setq value (replace-match "" nil nil value)))))
+ (lines
+ (and (string-match
+ ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
+ value)
+ (prog1 (match-string 1 value)
+ (setq value (replace-match "" nil nil value)))))
+ (env (cond
+ ((string-match "\\<example\\>" value) 'literal)
+ ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
+ 'literal)
+ ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
+ 'literal)))
+ ;; Minimal level of included file defaults to the child
+ ;; level of the current headline, if any, or one. It
+ ;; only applies is the file is meant to be included as
+ ;; an Org one.
+ (minlevel
+ (and (not env)
+ (if (string-match ":minlevel +\\([0-9]+\\)" value)
+ (prog1 (string-to-number (match-string 1 value))
+ (setq value (replace-match "" nil nil value)))
+ (get-text-property (point)
+ :org-include-induced-level))))
+ (args (and (eq env 'literal) (match-string 1 value)))
+ (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
+ (match-string 1 value))))
+ ;; Remove keyword.
+ (delete-region (point) (line-beginning-position 2))
+ (cond
+ ((not file) nil)
+ ((not (file-readable-p file))
+ (error "Cannot include file %s" file))
+ ;; Check if files has already been parsed. Look after
+ ;; inclusion lines too, as different parts of the same file
+ ;; can be included too.
+ ((member (list file lines) included)
+ (error "Recursive file inclusion: %s" file))
+ (t
+ (cond
+ ((eq env 'literal)
+ (insert
+ (let ((ind-str (make-string ind ?\s))
+ (arg-str (if (stringp args) (format " %s" args) ""))
+ (contents
+ (org-escape-code-in-string
+ (org-export--prepare-file-contents file lines))))
+ (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
+ ind-str block arg-str contents ind-str block))))
+ ((stringp block)
+ (insert
+ (let ((ind-str (make-string ind ?\s))
+ (contents
+ (org-export--prepare-file-contents file lines)))
+ (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
+ ind-str block contents ind-str block))))
+ (t
+ (insert
+ (with-temp-buffer
+ (let ((org-inhibit-startup t)
+ (lines
+ (if location
+ (org-export--inclusion-absolute-lines
+ file location only-contents lines)
+ lines)))
+ (org-mode)
+ (insert
+ (org-export--prepare-file-contents
+ file lines ind minlevel
+ (or (gethash file file-prefix)
+ (puthash file (cl-incf current-prefix) file-prefix))
+ footnotes)))
+ (org-export-expand-include-keyword
+ (cons (list file lines) included)
+ (file-name-directory file)
+ footnotes)
+ (buffer-string)))))
+ ;; Expand footnotes after all files have been included.
+ ;; Footnotes are stored at end of buffer.
+ (unless included
+ (org-with-wide-buffer
+ (goto-char (point-max))
+ (maphash (lambda (k v) (insert (format "\n[fn:%s] %s\n" k v)))
+ footnotes)))))))))))
+
+(defun org-export--inclusion-absolute-lines (file location only-contents lines)
+ "Resolve absolute lines for an included file with file-link.
+
+FILE is string file-name of the file to include. LOCATION is a
+string name within FILE to be included (located via
+`org-link-search'). If ONLY-CONTENTS is non-nil only the
+contents of the named element will be included, as determined
+Org-Element. If LINES is non-nil only those lines are included.
+
+Return a string of lines to be included in the format expected by
+`org-export--prepare-file-contents'."
+ (with-temp-buffer
+ (insert-file-contents file)
+ (unless (eq major-mode 'org-mode)
+ (let ((org-inhibit-startup t)) (org-mode)))
+ (condition-case err
+ ;; Enforce consistent search.
+ (let ((org-link-search-must-match-exact-headline nil))
+ (org-link-search location))
+ (error
+ (error "%s for %s::%s" (error-message-string err) file location)))
+ (let* ((element (org-element-at-point))
+ (contents-begin
+ (and only-contents (org-element-property :contents-begin element))))
+ (narrow-to-region
+ (or contents-begin (org-element-property :begin element))
+ (org-element-property (if contents-begin :contents-end :end) element))
+ (when (and only-contents
+ (memq (org-element-type element) '(headline inlinetask)))
+ ;; Skip planning line and property-drawer.
+ (goto-char (point-min))
+ (when (looking-at-p org-planning-line-re) (forward-line))
+ (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
+ (unless (bolp) (forward-line))
+ (narrow-to-region (point) (point-max))))
+ (when lines
+ (org-skip-whitespace)
+ (beginning-of-line)
+ (let* ((lines (split-string lines "-"))
+ (lbeg (string-to-number (car lines)))
+ (lend (string-to-number (cadr lines)))
+ (beg (if (zerop lbeg) (point-min)
+ (goto-char (point-min))
+ (forward-line (1- lbeg))
+ (point)))
+ (end (if (zerop lend) (point-max)
+ (goto-char beg)
+ (forward-line (1- lend))
+ (point))))
+ (narrow-to-region beg end)))
+ (let ((end (point-max)))
+ (goto-char (point-min))
+ (widen)
+ (let ((start-line (line-number-at-pos)))
+ (format "%d-%d"
+ start-line
+ (save-excursion
+ (+ start-line
+ (let ((counter 0))
+ (while (< (point) end) (cl-incf counter) (forward-line))
+ counter))))))))
+
+(defun org-export--prepare-file-contents
+ (file &optional lines ind minlevel id footnotes)
+ "Prepare contents of FILE for inclusion and return it as a string.
+
+When optional argument LINES is a string specifying a range of
+lines, include only those lines.
+
+Optional argument IND, when non-nil, is an integer specifying the
+global indentation of returned contents. Since its purpose is to
+allow an included file to stay in the same environment it was
+created (e.g., a list item), it doesn't apply past the first
+headline encountered.
+
+Optional argument MINLEVEL, when non-nil, is an integer
+specifying the level that any top-level headline in the included
+file should have.
+
+Optional argument ID is an integer that will be inserted before
+each footnote definition and reference if FILE is an Org file.
+This is useful to avoid conflicts when more than one Org file
+with footnotes is included in a document.
+
+Optional argument FOOTNOTES is a hash-table to store footnotes in
+the included document."
+ (with-temp-buffer
+ (insert-file-contents file)
+ (when lines
+ (let* ((lines (split-string lines "-"))
+ (lbeg (string-to-number (car lines)))
+ (lend (string-to-number (cadr lines)))
+ (beg (if (zerop lbeg) (point-min)
+ (goto-char (point-min))
+ (forward-line (1- lbeg))
+ (point)))
+ (end (if (zerop lend) (point-max)
+ (goto-char (point-min))
+ (forward-line (1- lend))
+ (point))))
+ (narrow-to-region beg end)))
+ ;; Remove blank lines at beginning and end of contents. The logic
+ ;; behind that removal is that blank lines around include keyword
+ ;; override blank lines in included file.
+ (goto-char (point-min))
+ (org-skip-whitespace)
+ (beginning-of-line)
+ (delete-region (point-min) (point))
+ (goto-char (point-max))
+ (skip-chars-backward " \r\t\n")
+ (forward-line)
+ (delete-region (point) (point-max))
+ ;; If IND is set, preserve indentation of include keyword until
+ ;; the first headline encountered.
+ (when (and ind (> ind 0))
+ (unless (eq major-mode 'org-mode)
+ (let ((org-inhibit-startup t)) (org-mode)))
+ (goto-char (point-min))
+ (let ((ind-str (make-string ind ?\s)))
+ (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
+ ;; Do not move footnote definitions out of column 0.
+ (unless (and (looking-at org-footnote-definition-re)
+ (eq (org-element-type (org-element-at-point))
+ 'footnote-definition))
+ (insert ind-str))
+ (forward-line))))
+ ;; When MINLEVEL is specified, compute minimal level for headlines
+ ;; in the file (CUR-MIN), and remove stars to each headline so
+ ;; that headlines with minimal level have a level of MINLEVEL.
+ (when minlevel
+ (unless (eq major-mode 'org-mode)
+ (let ((org-inhibit-startup t)) (org-mode)))
+ (org-with-limited-levels
+ (let ((levels (org-map-entries
+ (lambda () (org-reduced-level (org-current-level))))))
+ (when levels
+ (let ((offset (- minlevel (apply #'min levels))))
+ (unless (zerop offset)
+ (when org-odd-levels-only (setq offset (* offset 2)))
+ ;; Only change stars, don't bother moving whole
+ ;; sections.
+ (org-map-entries
+ (lambda ()
+ (if (< offset 0) (delete-char (abs offset))
+ (insert (make-string offset ?*)))))))))))
+ ;; Append ID to all footnote references and definitions, so they
+ ;; become file specific and cannot collide with footnotes in other
+ ;; included files. Further, collect relevant footnote definitions
+ ;; outside of LINES, in order to reintroduce them later.
+ (when id
+ (let ((marker-min (point-min-marker))
+ (marker-max (point-max-marker))
+ (get-new-label
+ (lambda (label)
+ ;; Generate new label from LABEL by prefixing it with
+ ;; "-ID-".
+ (format "-%d-%s" id label)))
+ (set-new-label
+ (lambda (f old new)
+ ;; Replace OLD label with NEW in footnote F.
+ (save-excursion
+ (goto-char (+ (org-element-property :begin f) 4))
+ (looking-at (regexp-quote old))
+ (replace-match new))))
+ (seen-alist))
+ (goto-char (point-min))
+ (while (re-search-forward org-footnote-re nil t)
+ (let ((footnote (save-excursion
+ (backward-char)
+ (org-element-context))))
+ (when (memq (org-element-type footnote)
+ '(footnote-definition footnote-reference))
+ (let* ((label (org-element-property :label footnote)))
+ ;; Update the footnote-reference at point and collect
+ ;; the new label, which is only used for footnotes
+ ;; outsides LINES.
+ (when label
+ (let ((seen (cdr (assoc label seen-alist))))
+ (if seen (funcall set-new-label footnote label seen)
+ (let ((new (funcall get-new-label label)))
+ (push (cons label new) seen-alist)
+ (org-with-wide-buffer
+ (let* ((def (org-footnote-get-definition label))
+ (beg (nth 1 def)))
+ (when (and def
+ (or (< beg marker-min)
+ (>= beg marker-max)))
+ ;; Store since footnote-definition is
+ ;; outside of LINES.
+ (puthash new
+ (org-element-normalize-string (nth 3 def))
+ footnotes))))
+ (funcall set-new-label footnote label new)))))))))
+ (set-marker marker-min nil)
+ (set-marker marker-max nil)))
+ (org-element-normalize-string (buffer-string))))
+
+(defun org-export--copy-to-kill-ring-p ()
+ "Return a non-nil value when output should be added to the kill ring.
+See also `org-export-copy-to-kill-ring'."
+ (if (eq org-export-copy-to-kill-ring 'if-interactive)
+ (not (or executing-kbd-macro noninteractive))
+ (eq org-export-copy-to-kill-ring t)))
+
+
+
+;;; Tools For Back-Ends
+;;
+;; A whole set of tools is available to help build new exporters. Any
+;; function general enough to have its use across many back-ends
+;; should be added here.
+
+;;;; For Affiliated Keywords
+;;
+;; `org-export-read-attribute' reads a property from a given element
+;; as a plist. It can be used to normalize affiliated keywords'
+;; syntax.
+;;
+;; Since captions can span over multiple lines and accept dual values,
+;; their internal representation is a bit tricky. Therefore,
+;; `org-export-get-caption' transparently returns a given element's
+;; caption as a secondary string.
+
+(defun org-export-read-attribute (attribute element &optional property)
+ "Turn ATTRIBUTE property from ELEMENT into a plist.
+
+When optional argument PROPERTY is non-nil, return the value of
+that property within attributes.
+
+This function assumes attributes are defined as \":keyword
+value\" pairs. It is appropriate for `:attr_html' like
+properties.
+
+All values will become strings except the empty string and
+\"nil\", which will become nil. Also, values containing only
+double quotes will be read as-is, which means that \"\" value
+will become the empty string."
+ (let* ((prepare-value
+ (lambda (str)
+ (save-match-data
+ (cond ((member str '(nil "" "nil")) nil)
+ ((string-match "^\"\\(\"+\\)?\"$" str)
+ (or (match-string 1 str) ""))
+ (t str)))))
+ (attributes
+ (let ((value (org-element-property attribute element)))
+ (when value
+ (let ((s (mapconcat 'identity value " ")) result)
+ (while (string-match
+ "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
+ s)
+ (let ((value (substring s 0 (match-beginning 0))))
+ (push (funcall prepare-value value) result))
+ (push (intern (match-string 1 s)) result)
+ (setq s (substring s (match-end 0))))
+ ;; Ignore any string before first property with `cdr'.
+ (cdr (nreverse (cons (funcall prepare-value s) result))))))))
+ (if property (plist-get attributes property) attributes)))
+
+(defun org-export-get-caption (element &optional shortp)
+ "Return caption from ELEMENT as a secondary string.
+
+When optional argument SHORTP is non-nil, return short caption,
+as a secondary string, instead.
+
+Caption lines are separated by a white space."
+ (let ((full-caption (org-element-property :caption element)) caption)
+ (dolist (line full-caption (cdr caption))
+ (let ((cap (funcall (if shortp 'cdr 'car) line)))
+ (when cap
+ (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
+
+
+;;;; For Derived Back-ends
+;;
+;; `org-export-with-backend' is a function allowing to locally use
+;; another back-end to transcode some object or element. In a derived
+;; back-end, it may be used as a fall-back function once all specific
+;; cases have been treated.
+
+(defun org-export-with-backend (backend data &optional contents info)
+ "Call a transcoder from BACKEND on DATA.
+BACKEND is an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end. DATA is an Org element, object, secondary
+string or string. CONTENTS, when non-nil, is the transcoded
+contents of DATA element, as a string. INFO, when non-nil, is
+the communication channel used for export, as a plist."
+ (when (symbolp backend) (setq backend (org-export-get-backend backend)))
+ (org-export-barf-if-invalid-backend backend)
+ (let ((type (org-element-type data)))
+ (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
+ (let* ((all-transcoders (org-export-get-all-transcoders backend))
+ (transcoder (cdr (assq type all-transcoders))))
+ (unless (functionp transcoder) (error "No foreign transcoder available"))
+ (let ((new-info
+ (org-combine-plists
+ info (list
+ :back-end backend
+ :translate-alist all-transcoders
+ :exported-data (make-hash-table :test #'eq :size 401)))))
+ ;; `:internal-references' are shared across back-ends.
+ (prog1 (funcall transcoder data contents new-info)
+ (plist-put info :internal-references
+ (plist-get new-info :internal-references)))))))
+
+
+;;;; For Export Snippets
+;;
+;; Every export snippet is transmitted to the back-end. Though, the
+;; latter will only retain one type of export-snippet, ignoring
+;; others, based on the former's target back-end. The function
+;; `org-export-snippet-backend' returns that back-end for a given
+;; export-snippet.
+
+(defun org-export-snippet-backend (export-snippet)
+ "Return EXPORT-SNIPPET targeted back-end as a symbol.
+Translation, with `org-export-snippet-translation-alist', is
+applied."
+ (let ((back-end (org-element-property :back-end export-snippet)))
+ (intern
+ (or (cdr (assoc back-end org-export-snippet-translation-alist))
+ back-end))))
+
+
+;;;; For Footnotes
+;;
+;; `org-export-collect-footnote-definitions' is a tool to list
+;; actually used footnotes definitions in the whole parse tree, or in
+;; a headline, in order to add footnote listings throughout the
+;; transcoded data.
+;;
+;; `org-export-footnote-first-reference-p' is a predicate used by some
+;; back-ends, when they need to attach the footnote definition only to
+;; the first occurrence of the corresponding label.
+;;
+;; `org-export-get-footnote-definition' and
+;; `org-export-get-footnote-number' provide easier access to
+;; additional information relative to a footnote reference.
+
+(defun org-export-get-footnote-definition (footnote-reference info)
+ "Return definition of FOOTNOTE-REFERENCE as parsed data.
+INFO is the plist used as a communication channel. If no such
+definition can be found, raise an error."
+ (let ((label (org-element-property :label footnote-reference)))
+ (if (not label) (org-element-contents footnote-reference)
+ (let ((cache (or (plist-get info :footnote-definition-cache)
+ (let ((hash (make-hash-table :test #'equal)))
+ (plist-put info :footnote-definition-cache hash)
+ hash))))
+ (or
+ (gethash label cache)
+ (puthash label
+ (org-element-map (plist-get info :parse-tree)
+ '(footnote-definition footnote-reference)
+ (lambda (f)
+ (cond
+ ;; Skip any footnote with a different label.
+ ;; Also skip any standard footnote reference
+ ;; with the same label since those cannot
+ ;; contain a definition.
+ ((not (equal (org-element-property :label f) label)) nil)
+ ((eq (org-element-property :type f) 'standard) nil)
+ ((org-element-contents f))
+ ;; Even if the contents are empty, we can not
+ ;; return nil since that would eventually raise
+ ;; the error. Instead, return the equivalent
+ ;; empty string.
+ (t "")))
+ info t)
+ cache)
+ (error "Definition not found for footnote %s" label))))))
+
+(defun org-export--footnote-reference-map
+ (function data info &optional body-first)
+ "Apply FUNCTION on every footnote reference in DATA.
+INFO is a plist containing export state. By default, as soon as
+a new footnote reference is encountered, FUNCTION is called onto
+its definition. However, if BODY-FIRST is non-nil, this step is
+delayed until the end of the process."
+ (letrec ((definitions nil)
+ (seen-refs nil)
+ (search-ref
+ (lambda (data delayp)
+ ;; Search footnote references through DATA, filling
+ ;; SEEN-REFS along the way. When DELAYP is non-nil,
+ ;; store footnote definitions so they can be entered
+ ;; later.
+ (org-element-map data 'footnote-reference
+ (lambda (f)
+ (funcall function f)
+ (let ((--label (org-element-property :label f)))
+ (unless (and --label (member --label seen-refs))
+ (when --label (push --label seen-refs))
+ ;; Search for subsequent references in footnote
+ ;; definition so numbering follows reading
+ ;; logic, unless DELAYP in non-nil.
+ (cond
+ (delayp
+ (push (org-export-get-footnote-definition f info)
+ definitions))
+ ;; Do not force entering inline definitions,
+ ;; since `org-element-map' already traverses
+ ;; them at the right time.
+ ((eq (org-element-property :type f) 'inline))
+ (t (funcall search-ref
+ (org-export-get-footnote-definition f info)
+ nil))))))
+ info nil
+ ;; Don't enter footnote definitions since it will
+ ;; happen when their first reference is found.
+ ;; Moreover, if DELAYP is non-nil, make sure we
+ ;; postpone entering definitions of inline references.
+ (if delayp '(footnote-definition footnote-reference)
+ 'footnote-definition)))))
+ (funcall search-ref data body-first)
+ (funcall search-ref (nreverse definitions) nil)))
+
+(defun org-export-collect-footnote-definitions (info &optional data body-first)
+ "Return an alist between footnote numbers, labels and definitions.
+
+INFO is the current export state, as a plist.
+
+Definitions are collected throughout the whole parse tree, or
+DATA when non-nil.
+
+Sorting is done by order of references. As soon as a new
+reference is encountered, other references are searched within
+its definition. However, if BODY-FIRST is non-nil, this step is
+delayed after the whole tree is checked. This alters results
+when references are found in footnote definitions.
+
+Definitions either appear as Org data or as a secondary string
+for inlined footnotes. Unreferenced definitions are ignored."
+ (let ((n 0) labels alist)
+ (org-export--footnote-reference-map
+ (lambda (f)
+ ;; Collect footnote number, label and definition.
+ (let ((l (org-element-property :label f)))
+ (unless (and l (member l labels))
+ (cl-incf n)
+ (push (list n l (org-export-get-footnote-definition f info)) alist))
+ (when l (push l labels))))
+ (or data (plist-get info :parse-tree)) info body-first)
+ (nreverse alist)))
+
+(defun org-export-footnote-first-reference-p
+ (footnote-reference info &optional data body-first)
+ "Non-nil when a footnote reference is the first one for its label.
+
+FOOTNOTE-REFERENCE is the footnote reference being considered.
+INFO is a plist containing current export state.
+
+Search is done throughout the whole parse tree, or DATA when
+non-nil.
+
+By default, as soon as a new footnote reference is encountered,
+other references are searched within its definition. However, if
+BODY-FIRST is non-nil, this step is delayed after the whole tree
+is checked. This alters results when references are found in
+footnote definitions."
+ (let ((label (org-element-property :label footnote-reference)))
+ ;; Anonymous footnotes are always a first reference.
+ (or (not label)
+ (catch 'exit
+ (org-export--footnote-reference-map
+ (lambda (f)
+ (let ((l (org-element-property :label f)))
+ (when (and l label (string= label l))
+ (throw 'exit (eq footnote-reference f)))))
+ (or data (plist-get info :parse-tree)) info body-first)))))
+
+(defun org-export-get-footnote-number (footnote info &optional data body-first)
+ "Return number associated to a footnote.
+
+FOOTNOTE is either a footnote reference or a footnote definition.
+INFO is the plist containing export state.
+
+Number is unique throughout the whole parse tree, or DATA, when
+non-nil.
+
+By default, as soon as a new footnote reference is encountered,
+counting process moves into its definition. However, if
+BODY-FIRST is non-nil, this step is delayed until the end of the
+process, leading to a different order when footnotes are nested."
+ (let ((count 0)
+ (seen)
+ (label (org-element-property :label footnote)))
+ (catch 'exit
+ (org-export--footnote-reference-map
+ (lambda (f)
+ (let ((l (org-element-property :label f)))
+ (cond
+ ;; Anonymous footnote match: return number.
+ ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
+ ;; Labels match: return number.
+ ((and label l (string= label l)) (throw 'exit (1+ count)))
+ ;; Otherwise store label and increase counter if label
+ ;; wasn't encountered yet.
+ ((not l) (cl-incf count))
+ ((not (member l seen)) (push l seen) (cl-incf count)))))
+ (or data (plist-get info :parse-tree)) info body-first))))
+
+
+;;;; For Headlines
+;;
+;; `org-export-get-relative-level' is a shortcut to get headline
+;; level, relatively to the lower headline level in the parsed tree.
+;;
+;; `org-export-get-headline-number' returns the section number of an
+;; headline, while `org-export-number-to-roman' allows it to be
+;; converted to roman numbers. With an optional argument,
+;; `org-export-get-headline-number' returns a number to unnumbered
+;; headlines (used for internal id).
+;;
+;; `org-export-low-level-p', `org-export-first-sibling-p' and
+;; `org-export-last-sibling-p' are three useful predicates when it
+;; comes to fulfill the `:headline-levels' property.
+;;
+;; `org-export-get-tags', `org-export-get-category' and
+;; `org-export-get-node-property' extract useful information from an
+;; headline or a parent headline. They all handle inheritance.
+;;
+;; `org-export-get-alt-title' tries to retrieve an alternative title,
+;; as a secondary string, suitable for table of contents. It falls
+;; back onto default title.
+
+(defun org-export-get-relative-level (headline info)
+ "Return HEADLINE relative level within current parsed tree.
+INFO is a plist holding contextual information."
+ (+ (org-element-property :level headline)
+ (or (plist-get info :headline-offset) 0)))
+
+(defun org-export-low-level-p (headline info)
+ "Non-nil when HEADLINE is considered as low level.
+
+INFO is a plist used as a communication channel.
+
+A low level headlines has a relative level greater than
+`:headline-levels' property value.
+
+Return value is the difference between HEADLINE relative level
+and the last level being considered as high enough, or nil."
+ (let ((limit (plist-get info :headline-levels)))
+ (when (wholenump limit)
+ (let ((level (org-export-get-relative-level headline info)))
+ (and (> level limit) (- level limit))))))
+
+(defun org-export-get-headline-number (headline info)
+ "Return numbered HEADLINE numbering as a list of numbers.
+INFO is a plist holding contextual information."
+ (and (org-export-numbered-headline-p headline info)
+ (cdr (assq headline (plist-get info :headline-numbering)))))
+
+(defun org-export-numbered-headline-p (headline info)
+ "Return a non-nil value if HEADLINE element should be numbered.
+INFO is a plist used as a communication channel."
+ (unless (cl-some
+ (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
+ (org-element-lineage headline nil t))
+ (let ((sec-num (plist-get info :section-numbers))
+ (level (org-export-get-relative-level headline info)))
+ (if (wholenump sec-num) (<= level sec-num) sec-num))))
+
+(defun org-export-number-to-roman (n)
+ "Convert integer N into a roman numeral."
+ (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
+ ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
+ ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
+ ( 1 . "I")))
+ (res ""))
+ (if (<= n 0)
+ (number-to-string n)
+ (while roman
+ (if (>= n (caar roman))
+ (setq n (- n (caar roman))
+ res (concat res (cdar roman)))
+ (pop roman)))
+ res)))
+
+(defun org-export-get-tags (element info &optional tags inherited)
+ "Return list of tags associated to ELEMENT.
+
+ELEMENT has either an `headline' or an `inlinetask' type. INFO
+is a plist used as a communication channel.
+
+When non-nil, optional argument TAGS should be a list of strings.
+Any tag belonging to this list will also be removed.
+
+When optional argument INHERITED is non-nil, tags can also be
+inherited from parent headlines and FILETAGS keywords."
+ (cl-remove-if
+ (lambda (tag) (member tag tags))
+ (if (not inherited) (org-element-property :tags element)
+ ;; Build complete list of inherited tags.
+ (let ((current-tag-list (org-element-property :tags element)))
+ (dolist (parent (org-element-lineage element))
+ (dolist (tag (org-element-property :tags parent))
+ (when (and (memq (org-element-type parent) '(headline inlinetask))
+ (not (member tag current-tag-list)))
+ (push tag current-tag-list))))
+ ;; Add FILETAGS keywords and return results.
+ (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
+
+(defun org-export-get-node-property (property blob &optional inherited)
+ "Return node PROPERTY value for BLOB.
+
+PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
+element or object.
+
+If optional argument INHERITED is non-nil, the value can be
+inherited from a parent headline.
+
+Return value is a string or nil."
+ (let ((headline (if (eq (org-element-type blob) 'headline) blob
+ (org-export-get-parent-headline blob))))
+ (if (not inherited) (org-element-property property blob)
+ (let ((parent headline))
+ (catch 'found
+ (while parent
+ (when (plist-member (nth 1 parent) property)
+ (throw 'found (org-element-property property parent)))
+ (setq parent (org-element-property :parent parent))))))))
+
+(defun org-export-get-category (blob info)
+ "Return category for element or object BLOB.
+
+INFO is a plist used as a communication channel.
+
+CATEGORY is automatically inherited from a parent headline, from
+#+CATEGORY: keyword or created out of original file name. If all
+fail, the fall-back value is \"???\"."
+ (or (org-export-get-node-property :CATEGORY blob t)
+ (org-element-map (plist-get info :parse-tree) 'keyword
+ (lambda (kwd)
+ (when (equal (org-element-property :key kwd) "CATEGORY")
+ (org-element-property :value kwd)))
+ info 'first-match)
+ (let ((file (plist-get info :input-file)))
+ (and file (file-name-sans-extension (file-name-nondirectory file))))
+ "???"))
+
+(defun org-export-get-alt-title (headline _)
+ "Return alternative title for HEADLINE, as a secondary string.
+If no optional title is defined, fall-back to the regular title."
+ (let ((alt (org-element-property :ALT_TITLE headline)))
+ (if alt (org-element-parse-secondary-string
+ alt (org-element-restriction 'headline) headline)
+ (org-element-property :title headline))))
+
+(defun org-export-first-sibling-p (blob info)
+ "Non-nil when BLOB is the first sibling in its parent.
+BLOB is an element or an object. If BLOB is a headline, non-nil
+means it is the first sibling in the sub-tree. INFO is a plist
+used as a communication channel."
+ (memq (org-element-type (org-export-get-previous-element blob info))
+ '(nil section)))
+
+(defun org-export-last-sibling-p (blob info)
+ "Non-nil when BLOB is the last sibling in its parent.
+BLOB is an element or an object. INFO is a plist used as
+a communication channel."
+ (not (org-export-get-next-element blob info)))
+
+
+;;;; For Keywords
+;;
+;; `org-export-get-date' returns a date appropriate for the document
+;; to about to be exported. In particular, it takes care of
+;; `org-export-date-timestamp-format'.
+
+(defun org-export-get-date (info &optional fmt)
+ "Return date value for the current document.
+
+INFO is a plist used as a communication channel. FMT, when
+non-nil, is a time format string that will be applied on the date
+if it consists in a single timestamp object. It defaults to
+`org-export-date-timestamp-format' when nil.
+
+A proper date can be a secondary string, a string or nil. It is
+meant to be translated with `org-export-data' or alike."
+ (let ((date (plist-get info :date))
+ (fmt (or fmt org-export-date-timestamp-format)))
+ (cond ((not date) nil)
+ ((and fmt
+ (not (cdr date))
+ (eq (org-element-type (car date)) 'timestamp))
+ (org-timestamp-format (car date) fmt))
+ (t date))))
+
+
+;;;; For Links
+;;
+;; `org-export-custom-protocol-maybe' handles custom protocol defined
+;; in `org-link-parameters'.
+;;
+;; `org-export-get-coderef-format' returns an appropriate format
+;; string for coderefs.
+;;
+;; `org-export-inline-image-p' returns a non-nil value when the link
+;; provided should be considered as an inline image.
+;;
+;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
+;; (i.e. links with "fuzzy" as type) within the parsed tree, and
+;; returns an appropriate unique identifier.
+;;
+;; `org-export-resolve-id-link' returns the first headline with
+;; specified id or custom-id in parse tree, the path to the external
+;; file with the id.
+;;
+;; `org-export-resolve-coderef' associates a reference to a line
+;; number in the element it belongs, or returns the reference itself
+;; when the element isn't numbered.
+;;
+;; `org-export-file-uri' expands a filename as stored in :path value
+;; of a "file" link into a file URI.
+;;
+;; Broken links raise a `org-link-broken' error, which is caught by
+;; `org-export-data' for further processing, depending on
+;; `org-export-with-broken-links' value.
+
+(org-define-error 'org-link-broken "Unable to resolve link; aborting")
+
+(defun org-export-custom-protocol-maybe (link desc backend)
+ "Try exporting LINK with a dedicated function.
+
+DESC is its description, as a string, or nil. BACKEND is the
+back-end used for export, as a symbol.
+
+Return output as a string, or nil if no protocol handles LINK.
+
+A custom protocol has precedence over regular back-end export.
+The function ignores links with an implicit type (e.g.,
+\"custom-id\")."
+ (let ((type (org-element-property :type link)))
+ (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
+ (not backend))
+ (let ((protocol (org-link-get-parameter type :export)))
+ (and (functionp protocol)
+ (funcall protocol
+ (org-link-unescape (org-element-property :path link))
+ desc
+ backend))))))
+
+(defun org-export-get-coderef-format (path desc)
+ "Return format string for code reference link.
+PATH is the link path. DESC is its description."
+ (save-match-data
+ (cond ((not desc) "%s")
+ ((string-match (regexp-quote (concat "(" path ")")) desc)
+ (replace-match "%s" t t desc))
+ (t desc))))
+
+(defun org-export-inline-image-p (link &optional rules)
+ "Non-nil if LINK object points to an inline image.
+
+Optional argument is a set of RULES defining inline images. It
+is an alist where associations have the following shape:
+
+ (TYPE . REGEXP)
+
+Applying a rule means apply REGEXP against LINK's path when its
+type is TYPE. The function will return a non-nil value if any of
+the provided rules is non-nil. The default rule is
+`org-export-default-inline-image-rule'.
+
+This only applies to links without a description."
+ (and (not (org-element-contents link))
+ (let ((case-fold-search t))
+ (catch 'exit
+ (dolist (rule (or rules org-export-default-inline-image-rule))
+ (and (string= (org-element-property :type link) (car rule))
+ (string-match-p (cdr rule)
+ (org-element-property :path link))
+ (throw 'exit t)))))))
+
+(defun org-export-resolve-coderef (ref info)
+ "Resolve a code reference REF.
+
+INFO is a plist used as a communication channel.
+
+Return associated line number in source code, or REF itself,
+depending on src-block or example element's switches. Throw an
+error if no block contains REF."
+ (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
+ (lambda (el)
+ (with-temp-buffer
+ (insert (org-trim (org-element-property :value el)))
+ (let* ((label-fmt (or (org-element-property :label-fmt el)
+ org-coderef-label-format))
+ (ref-re (org-src-coderef-regexp label-fmt ref)))
+ ;; Element containing REF is found. Resolve it to
+ ;; either a label or a line number, as needed.
+ (when (re-search-backward ref-re nil t)
+ (if (org-element-property :use-labels el) ref
+ (+ (or (org-export-get-loc el info) 0)
+ (line-number-at-pos)))))))
+ info 'first-match)
+ (signal 'org-link-broken (list ref))))
+
+(defun org-export-search-cells (datum)
+ "List search cells for element or object DATUM.
+
+A search cell follows the pattern (TYPE . SEARCH) where
+
+ TYPE is a symbol among `headline', `custom-id', `target' and
+ `other'.
+
+ SEARCH is the string a link is expected to match. More
+ accurately, it is
+
+ - headline's title, as a list of strings, if TYPE is
+ `headline'.
+
+ - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
+
+ - target's or radio-target's name as a list of strings if
+ TYPE is `target'.
+
+ - NAME affiliated keyword is TYPE is `other'.
+
+A search cell is the internal representation of a fuzzy link. It
+ignores white spaces and statistics cookies, if applicable."
+ (pcase (org-element-type datum)
+ (`headline
+ (let ((title (split-string
+ (replace-regexp-in-string
+ "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
+ (org-element-property :raw-value datum)))))
+ (delq nil
+ (list
+ (cons 'headline title)
+ (cons 'other title)
+ (let ((custom-id (org-element-property :custom-id datum)))
+ (and custom-id (cons 'custom-id custom-id)))))))
+ (`target
+ (list (cons 'target (split-string (org-element-property :value datum)))))
+ ((and (let name (org-element-property :name datum))
+ (guard name))
+ (list (cons 'other (split-string name))))
+ (_ nil)))
+
+(defun org-export-string-to-search-cell (s)
+ "Return search cells associated to string S.
+S is either the path of a fuzzy link or a search option, i.e., it
+tries to match either a headline (through custom ID or title),
+a target or a named element."
+ (pcase (string-to-char s)
+ (?* (list (cons 'headline (split-string (substring s 1)))))
+ (?# (list (cons 'custom-id (substring s 1))))
+ ((let search (split-string s))
+ (list (cons 'target search) (cons 'other search)))))
+
+(defun org-export-match-search-cell-p (datum cells)
+ "Non-nil when DATUM matches search cells CELLS.
+DATUM is an element or object. CELLS is a list of search cells,
+as returned by `org-export-search-cells'."
+ (let ((targets (org-export-search-cells datum)))
+ (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
+
+(defun org-export-resolve-fuzzy-link (link info)
+ "Return LINK destination.
+
+INFO is a plist holding contextual information.
+
+Return value can be an object or an element:
+
+- If LINK path matches a target object (i.e. <<path>>) return it.
+
+- If LINK path exactly matches the name affiliated keyword
+ (i.e. #+NAME: path) of an element, return that element.
+
+- If LINK path exactly matches any headline name, return that
+ element.
+
+- Otherwise, throw an error.
+
+Assume LINK type is \"fuzzy\". White spaces are not
+significant."
+ (let* ((search-cells (org-export-string-to-search-cell
+ (org-link-unescape (org-element-property :path link))))
+ (link-cache
+ (or (plist-get info :resolve-fuzzy-link-cache)
+ (plist-get (plist-put info
+ :resolve-fuzzy-link-cache
+ (make-hash-table :test #'equal))
+ :resolve-fuzzy-link-cache)))
+ (cached (gethash search-cells link-cache 'not-found)))
+ (if (not (eq cached 'not-found)) cached
+ (let ((matches
+ (org-element-map (plist-get info :parse-tree)
+ (cons 'target org-element-all-elements)
+ (lambda (datum)
+ (and (org-export-match-search-cell-p datum search-cells)
+ datum)))))
+ (unless matches
+ (signal 'org-link-broken (list (org-element-property :path link))))
+ (puthash
+ search-cells
+ ;; There can be multiple matches for un-typed searches, i.e.,
+ ;; for searches not starting with # or *. In this case,
+ ;; prioritize targets and names over headline titles.
+ ;; Matching both a name and a target is not valid, and
+ ;; therefore undefined.
+ (or (cl-some (lambda (datum)
+ (and (not (eq (org-element-type datum) 'headline))
+ datum))
+ matches)
+ (car matches))
+ link-cache)))))
+
+(defun org-export-resolve-id-link (link info)
+ "Return headline referenced as LINK destination.
+
+INFO is a plist used as a communication channel.
+
+Return value can be the headline element matched in current parse
+tree or a file name. Assume LINK type is either \"id\" or
+\"custom-id\". Throw an error if no match is found."
+ (let ((id (org-element-property :path link)))
+ ;; First check if id is within the current parse tree.
+ (or (org-element-map (plist-get info :parse-tree) 'headline
+ (lambda (headline)
+ (when (or (equal (org-element-property :ID headline) id)
+ (equal (org-element-property :CUSTOM_ID headline) id))
+ headline))
+ info 'first-match)
+ ;; Otherwise, look for external files.
+ (cdr (assoc id (plist-get info :id-alist)))
+ (signal 'org-link-broken (list id)))))
+
+(defun org-export-resolve-radio-link (link info)
+ "Return radio-target object referenced as LINK destination.
+
+INFO is a plist used as a communication channel.
+
+Return value can be a radio-target object or nil. Assume LINK
+has type \"radio\"."
+ (let ((path (replace-regexp-in-string
+ "[ \r\t\n]+" " " (org-element-property :path link))))
+ (org-element-map (plist-get info :parse-tree) 'radio-target
+ (lambda (radio)
+ (and (eq (compare-strings
+ (replace-regexp-in-string
+ "[ \r\t\n]+" " " (org-element-property :value radio))
+ nil nil path nil nil t)
+ t)
+ radio))
+ info 'first-match)))
+
+(defun org-export-file-uri (filename)
+ "Return file URI associated to FILENAME."
+ (cond ((string-prefix-p "//" filename) (concat "file:" filename))
+ ((not (file-name-absolute-p filename)) filename)
+ ((org-file-remote-p filename) (concat "file:/" filename))
+ (t
+ (let ((fullname (expand-file-name filename)))
+ (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
+ fullname)))))
+
+;;;; For References
+;;
+;; `org-export-get-reference' associate a unique reference for any
+;; object or element. It uses `org-export-new-reference' and
+;; `org-export-format-reference' to, respectively, generate new
+;; internal references and turn them into a string suitable for
+;; output.
+;;
+;; `org-export-get-ordinal' associates a sequence number to any object
+;; or element.
+
+(defun org-export-new-reference (references)
+ "Return a unique reference, among REFERENCES.
+REFERENCES is an alist whose values are in-use references, as
+numbers. Returns a number, which is the internal representation
+of a reference. See also `org-export-format-reference'."
+ ;; Generate random 7 digits hexadecimal numbers. Collisions
+ ;; increase exponentially with the numbers of references. However,
+ ;; the odds for encountering at least one collision with 1000 active
+ ;; references in the same document are roughly 0.2%, so this
+ ;; shouldn't be the bottleneck.
+ (let ((new (random #x10000000)))
+ (while (rassq new references) (setq new (random #x10000000)))
+ new))
+
+(defun org-export-format-reference (reference)
+ "Format REFERENCE into a string.
+REFERENCE is a number representing a reference, as returned by
+`org-export-new-reference', which see."
+ (format "org%07x" reference))
+
+(defun org-export-get-reference (datum info)
+ "Return a unique reference for DATUM, as a string.
+
+DATUM is either an element or an object. INFO is the current
+export state, as a plist.
+
+This function checks `:crossrefs' property in INFO for search
+cells matching DATUM before creating a new reference. Returned
+reference consists of alphanumeric characters only."
+ (let ((cache (plist-get info :internal-references)))
+ (or (car (rassq datum cache))
+ (let* ((crossrefs (plist-get info :crossrefs))
+ (cells (org-export-search-cells datum))
+ ;; Preserve any pre-existing association between
+ ;; a search cell and a reference, i.e., when some
+ ;; previously published document referenced a location
+ ;; within current file (see
+ ;; `org-publish-resolve-external-link').
+ ;;
+ ;; However, there is no guarantee that search cells are
+ ;; unique, e.g., there might be duplicate custom ID or
+ ;; two headings with the same title in the file.
+ ;;
+ ;; As a consequence, before re-using any reference to
+ ;; an element or object, we check that it doesn't refer
+ ;; to a previous element or object.
+ (new (or (cl-some
+ (lambda (cell)
+ (let ((stored (cdr (assoc cell crossrefs))))
+ (when stored
+ (let ((old (org-export-format-reference stored)))
+ (and (not (assoc old cache)) stored)))))
+ cells)
+ (org-export-new-reference cache)))
+ (reference-string (org-export-format-reference new)))
+ ;; Cache contains both data already associated to
+ ;; a reference and in-use internal references, so as to make
+ ;; unique references.
+ (dolist (cell cells) (push (cons cell new) cache))
+ ;; Retain a direct association between reference string and
+ ;; DATUM since (1) not every object or element can be given
+ ;; a search cell (2) it permits quick lookup.
+ (push (cons reference-string datum) cache)
+ (plist-put info :internal-references cache)
+ reference-string))))
+
+(defun org-export-get-ordinal (element info &optional types predicate)
+ "Return ordinal number of an element or object.
+
+ELEMENT is the element or object considered. INFO is the plist
+used as a communication channel.
+
+Optional argument TYPES, when non-nil, is a list of element or
+object types, as symbols, that should also be counted in.
+Otherwise, only provided element's type is considered.
+
+Optional argument PREDICATE is a function returning a non-nil
+value if the current element or object should be counted in. It
+accepts two arguments: the element or object being considered and
+the plist used as a communication channel. This allows counting
+only a certain type of object (i.e. inline images).
+
+Return value is a list of numbers if ELEMENT is a headline or an
+item. It is nil for keywords. It represents the footnote number
+for footnote definitions and footnote references. If ELEMENT is
+a target, return the same value as if ELEMENT was the closest
+table, item or headline containing the target. In any other
+case, return the sequence number of ELEMENT among elements or
+objects of the same type."
+ ;; Ordinal of a target object refer to the ordinal of the closest
+ ;; table, item, or headline containing the object.
+ (when (eq (org-element-type element) 'target)
+ (setq element
+ (org-element-lineage
+ element
+ '(footnote-definition footnote-reference headline item table))))
+ (cl-case (org-element-type element)
+ ;; Special case 1: A headline returns its number as a list.
+ (headline (org-export-get-headline-number element info))
+ ;; Special case 2: An item returns its number as a list.
+ (item (let ((struct (org-element-property :structure element)))
+ (org-list-get-item-number
+ (org-element-property :begin element)
+ struct
+ (org-list-prevs-alist struct)
+ (org-list-parents-alist struct))))
+ ((footnote-definition footnote-reference)
+ (org-export-get-footnote-number element info))
+ (otherwise
+ (let ((counter 0))
+ ;; Increment counter until ELEMENT is found again.
+ (org-element-map (plist-get info :parse-tree)
+ (or types (org-element-type element))
+ (lambda (el)
+ (cond
+ ((eq element el) (1+ counter))
+ ((not predicate) (cl-incf counter) nil)
+ ((funcall predicate el info) (cl-incf counter) nil)))
+ info 'first-match)))))
+
+
+;;;; For Src-Blocks
+;;
+;; `org-export-get-loc' counts number of code lines accumulated in
+;; src-block or example-block elements with a "+n" switch until
+;; a given element, excluded. Note: "-n" switches reset that count.
+;;
+;; `org-export-unravel-code' extracts source code (along with a code
+;; references alist) from an `element-block' or `src-block' type
+;; element.
+;;
+;; `org-export-format-code' applies a formatting function to each line
+;; of code, providing relative line number and code reference when
+;; appropriate. Since it doesn't access the original element from
+;; which the source code is coming, it expects from the code calling
+;; it to know if lines should be numbered and if code references
+;; should appear.
+;;
+;; Eventually, `org-export-format-code-default' is a higher-level
+;; function (it makes use of the two previous functions) which handles
+;; line numbering and code references inclusion, and returns source
+;; code in a format suitable for plain text or verbatim output.
+
+(defun org-export-get-loc (element info)
+ "Return count of lines of code before ELEMENT.
+
+ELEMENT is an example-block or src-block element. INFO is the
+plist used as a communication channel.
+
+Count includes every line of code in example-block or src-block
+with a \"+n\" or \"-n\" switch before block. Return nil if
+ELEMENT doesn't allow line numbering."
+ (pcase (org-element-property :number-lines element)
+ (`(new . ,n) n)
+ (`(continued . ,n)
+ (let ((loc 0))
+ (org-element-map (plist-get info :parse-tree) '(src-block example-block)
+ (lambda (el)
+ ;; ELEMENT is reached: Quit loop and return locs.
+ (if (eq el element) (+ loc n)
+ ;; Only count lines from src-block and example-block
+ ;; elements with a "+n" or "-n" switch.
+ (let ((linum (org-element-property :number-lines el)))
+ (when linum
+ (let ((lines (org-count-lines
+ (org-element-property :value el))))
+ ;; Accumulate locs or reset them.
+ (pcase linum
+ (`(new . ,n) (setq loc (+ n lines)))
+ (`(continued . ,n) (cl-incf loc (+ n lines)))))))
+ nil)) ;Return nil to stay in the loop.
+ info 'first-match)))))
+
+(defun org-export-unravel-code (element)
+ "Clean source code and extract references out of it.
+
+ELEMENT has either a `src-block' an `example-block' type.
+
+Return a cons cell whose CAR is the source code, cleaned from any
+reference, protective commas and spurious indentation, and CDR is
+an alist between relative line number (integer) and name of code
+reference on that line (string)."
+ (let* ((line 0) refs
+ (value (org-element-property :value element))
+ ;; Remove global indentation from code, if necessary. Also
+ ;; remove final newline character, since it doesn't belongs
+ ;; to the code proper.
+ (code (replace-regexp-in-string
+ "\n\\'" ""
+ (if (or org-src-preserve-indentation
+ (org-element-property :preserve-indent element))
+ value
+ (org-remove-indentation value))))
+ ;; Build a regexp matching a loc with a reference.
+ (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
+ ;; Return value.
+ (cons
+ ;; Code with references removed.
+ (mapconcat
+ (lambda (loc)
+ (cl-incf line)
+ (if (not (string-match ref-re loc)) loc
+ ;; Ref line: remove ref, and add its position in REFS.
+ (push (cons line (match-string 3 loc)) refs)
+ (replace-match "" nil nil loc 1)))
+ (split-string code "\n") "\n")
+ ;; Reference alist.
+ refs)))
+
+(defun org-export-format-code (code fun &optional num-lines ref-alist)
+ "Format CODE by applying FUN line-wise and return it.
+
+CODE is a string representing the code to format. FUN is
+a function. It must accept three arguments: a line of
+code (string), the current line number (integer) or nil and the
+reference associated to the current line (string) or nil.
+
+Optional argument NUM-LINES can be an integer representing the
+number of code lines accumulated until the current code. Line
+numbers passed to FUN will take it into account. If it is nil,
+FUN's second argument will always be nil. This number can be
+obtained with `org-export-get-loc' function.
+
+Optional argument REF-ALIST can be an alist between relative line
+number (i.e. ignoring NUM-LINES) and the name of the code
+reference on it. If it is nil, FUN's third argument will always
+be nil. It can be obtained through the use of
+`org-export-unravel-code' function."
+ (let ((--locs (split-string code "\n"))
+ (--line 0))
+ (concat
+ (mapconcat
+ (lambda (--loc)
+ (cl-incf --line)
+ (let ((--ref (cdr (assq --line ref-alist))))
+ (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
+ --locs "\n")
+ "\n")))
+
+(defun org-export-format-code-default (element info)
+ "Return source code from ELEMENT, formatted in a standard way.
+
+ELEMENT is either a `src-block' or `example-block' element. INFO
+is a plist used as a communication channel.
+
+This function takes care of line numbering and code references
+inclusion. Line numbers, when applicable, appear at the
+beginning of the line, separated from the code by two white
+spaces. Code references, on the other hand, appear flushed to
+the right, separated by six white spaces from the widest line of
+code."
+ ;; Extract code and references.
+ (let* ((code-info (org-export-unravel-code element))
+ (code (car code-info))
+ (code-lines (split-string code "\n")))
+ (if (null code-lines) ""
+ (let* ((refs (and (org-element-property :retain-labels element)
+ (cdr code-info)))
+ ;; Handle line numbering.
+ (num-start (org-export-get-loc element info))
+ (num-fmt
+ (and num-start
+ (format "%%%ds "
+ (length (number-to-string
+ (+ (length code-lines) num-start))))))
+ ;; Prepare references display, if required. Any reference
+ ;; should start six columns after the widest line of code,
+ ;; wrapped with parenthesis.
+ (max-width
+ (+ (apply 'max (mapcar 'length code-lines))
+ (if (not num-start) 0 (length (format num-fmt num-start))))))
+ (org-export-format-code
+ code
+ (lambda (loc line-num ref)
+ (let ((number-str (and num-fmt (format num-fmt line-num))))
+ (concat
+ number-str
+ loc
+ (and ref
+ (concat (make-string (- (+ 6 max-width)
+ (+ (length loc) (length number-str)))
+ ?\s)
+ (format "(%s)" ref))))))
+ num-start refs)))))
+
+
+;;;; For Tables
+;;
+;; `org-export-table-has-special-column-p' and and
+;; `org-export-table-row-is-special-p' are predicates used to look for
+;; meta-information about the table structure.
+;;
+;; `org-table-has-header-p' tells when the rows before the first rule
+;; should be considered as table's header.
+;;
+;; `org-export-table-cell-width', `org-export-table-cell-alignment'
+;; and `org-export-table-cell-borders' extract information from
+;; a table-cell element.
+;;
+;; `org-export-table-dimensions' gives the number on rows and columns
+;; in the table, ignoring horizontal rules and special columns.
+;; `org-export-table-cell-address', given a table-cell object, returns
+;; the absolute address of a cell. On the other hand,
+;; `org-export-get-table-cell-at' does the contrary.
+;;
+;; `org-export-table-cell-starts-colgroup-p',
+;; `org-export-table-cell-ends-colgroup-p',
+;; `org-export-table-row-starts-rowgroup-p',
+;; `org-export-table-row-ends-rowgroup-p',
+;; `org-export-table-row-starts-header-p',
+;; `org-export-table-row-ends-header-p' and
+;; `org-export-table-row-in-header-p' indicate position of current row
+;; or cell within the table.
+
+(defun org-export-table-has-special-column-p (table)
+ "Non-nil when TABLE has a special column.
+All special columns will be ignored during export."
+ ;; The table has a special column when every first cell of every row
+ ;; has an empty value or contains a symbol among "/", "#", "!", "$",
+ ;; "*" "_" and "^". Though, do not consider a first row containing
+ ;; only empty cells as special.
+ (let ((special-column-p 'empty))
+ (catch 'exit
+ (dolist (row (org-element-contents table))
+ (when (eq (org-element-property :type row) 'standard)
+ (let ((value (org-element-contents
+ (car (org-element-contents row)))))
+ (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
+ (setq special-column-p 'special))
+ ((not value))
+ (t (throw 'exit nil))))))
+ (eq special-column-p 'special))))
+
+(defun org-export-table-has-header-p (table info)
+ "Non-nil when TABLE has a header.
+
+INFO is a plist used as a communication channel.
+
+A table has a header when it contains at least two row groups."
+ (let ((cache (or (plist-get info :table-header-cache)
+ (plist-get (setq info
+ (plist-put info :table-header-cache
+ (make-hash-table :test 'eq)))
+ :table-header-cache))))
+ (or (gethash table cache)
+ (let ((rowgroup 1) row-flag)
+ (puthash
+ table
+ (org-element-map table 'table-row
+ (lambda (row)
+ (cond
+ ((> rowgroup 1) t)
+ ((and row-flag (eq (org-element-property :type row) 'rule))
+ (cl-incf rowgroup) (setq row-flag nil))
+ ((and (not row-flag) (eq (org-element-property :type row)
+ 'standard))
+ (setq row-flag t) nil)))
+ info 'first-match)
+ cache)))))
+
+(defun org-export-table-row-is-special-p (table-row _)
+ "Non-nil if TABLE-ROW is considered special.
+All special rows will be ignored during export."
+ (when (eq (org-element-property :type table-row) 'standard)
+ (let ((first-cell (org-element-contents
+ (car (org-element-contents table-row)))))
+ ;; A row is special either when...
+ (or
+ ;; ... it starts with a field only containing "/",
+ (equal first-cell '("/"))
+ ;; ... the table contains a special column and the row start
+ ;; with a marking character among, "^", "_", "$" or "!",
+ (and (org-export-table-has-special-column-p
+ (org-export-get-parent table-row))
+ (member first-cell '(("^") ("_") ("$") ("!"))))
+ ;; ... it contains only alignment cookies and empty cells.
+ (let ((special-row-p 'empty))
+ (catch 'exit
+ (dolist (cell (org-element-contents table-row))
+ (let ((value (org-element-contents cell)))
+ ;; Since VALUE is a secondary string, the following
+ ;; checks avoid expanding it with `org-export-data'.
+ (cond ((not value))
+ ((and (not (cdr value))
+ (stringp (car value))
+ (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
+ (car value)))
+ (setq special-row-p 'cookie))
+ (t (throw 'exit nil)))))
+ (eq special-row-p 'cookie)))))))
+
+(defun org-export-table-row-group (table-row info)
+ "Return TABLE-ROW's group number, as an integer.
+
+INFO is a plist used as the communication channel.
+
+Return value is the group number, as an integer, or nil for
+special rows and rows separators. First group is also table's
+header."
+ (let ((cache (or (plist-get info :table-row-group-cache)
+ (plist-get (setq info
+ (plist-put info :table-row-group-cache
+ (make-hash-table :test 'eq)))
+ :table-row-group-cache))))
+ (cond ((gethash table-row cache))
+ ((eq (org-element-property :type table-row) 'rule) nil)
+ (t (let ((group 0) row-flag)
+ (org-element-map (org-export-get-parent table-row) 'table-row
+ (lambda (row)
+ (if (eq (org-element-property :type row) 'rule)
+ (setq row-flag nil)
+ (unless row-flag (cl-incf group) (setq row-flag t)))
+ (when (eq table-row row) (puthash table-row group cache)))
+ info 'first-match))))))
+
+(defun org-export-table-cell-width (table-cell info)
+ "Return TABLE-CELL contents width.
+
+INFO is a plist used as the communication channel.
+
+Return value is the width given by the last width cookie in the
+same column as TABLE-CELL, or nil."
+ (let* ((row (org-export-get-parent table-cell))
+ (table (org-export-get-parent row))
+ (cells (org-element-contents row))
+ (columns (length cells))
+ (column (- columns (length (memq table-cell cells))))
+ (cache (or (plist-get info :table-cell-width-cache)
+ (plist-get (setq info
+ (plist-put info :table-cell-width-cache
+ (make-hash-table :test 'eq)))
+ :table-cell-width-cache)))
+ (width-vector (or (gethash table cache)
+ (puthash table (make-vector columns 'empty) cache)))
+ (value (aref width-vector column)))
+ (if (not (eq value 'empty)) value
+ (let (cookie-width)
+ (dolist (row (org-element-contents table)
+ (aset width-vector column cookie-width))
+ (when (org-export-table-row-is-special-p row info)
+ ;; In a special row, try to find a width cookie at COLUMN.
+ (let* ((value (org-element-contents
+ (elt (org-element-contents row) column)))
+ (cookie (car value)))
+ ;; The following checks avoid expanding unnecessarily
+ ;; the cell with `org-export-data'.
+ (when (and value
+ (not (cdr value))
+ (stringp cookie)
+ (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
+ (match-string 1 cookie))
+ (setq cookie-width
+ (string-to-number (match-string 1 cookie)))))))))))
+
+(defun org-export-table-cell-alignment (table-cell info)
+ "Return TABLE-CELL contents alignment.
+
+INFO is a plist used as the communication channel.
+
+Return alignment as specified by the last alignment cookie in the
+same column as TABLE-CELL. If no such cookie is found, a default
+alignment value will be deduced from fraction of numbers in the
+column (see `org-table-number-fraction' for more information).
+Possible values are `left', `right' and `center'."
+ ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
+ (require 'org-table)
+ (let* ((row (org-export-get-parent table-cell))
+ (table (org-export-get-parent row))
+ (cells (org-element-contents row))
+ (columns (length cells))
+ (column (- columns (length (memq table-cell cells))))
+ (cache (or (plist-get info :table-cell-alignment-cache)
+ (plist-get (setq info
+ (plist-put info :table-cell-alignment-cache
+ (make-hash-table :test 'eq)))
+ :table-cell-alignment-cache)))
+ (align-vector (or (gethash table cache)
+ (puthash table (make-vector columns nil) cache))))
+ (or (aref align-vector column)
+ (let ((number-cells 0)
+ (total-cells 0)
+ cookie-align
+ previous-cell-number-p)
+ (dolist (row (org-element-contents (org-export-get-parent row)))
+ (cond
+ ;; In a special row, try to find an alignment cookie at
+ ;; COLUMN.
+ ((org-export-table-row-is-special-p row info)
+ (let ((value (org-element-contents
+ (elt (org-element-contents row) column))))
+ ;; Since VALUE is a secondary string, the following
+ ;; checks avoid useless expansion through
+ ;; `org-export-data'.
+ (when (and value
+ (not (cdr value))
+ (stringp (car value))
+ (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
+ (car value))
+ (match-string 1 (car value)))
+ (setq cookie-align (match-string 1 (car value))))))
+ ;; Ignore table rules.
+ ((eq (org-element-property :type row) 'rule))
+ ;; In a standard row, check if cell's contents are
+ ;; expressing some kind of number. Increase NUMBER-CELLS
+ ;; accordingly. Though, don't bother if an alignment
+ ;; cookie has already defined cell's alignment.
+ ((not cookie-align)
+ (let ((value (org-export-data
+ (org-element-contents
+ (elt (org-element-contents row) column))
+ info)))
+ (cl-incf total-cells)
+ ;; Treat an empty cell as a number if it follows
+ ;; a number.
+ (if (not (or (string-match org-table-number-regexp value)
+ (and (string= value "") previous-cell-number-p)))
+ (setq previous-cell-number-p nil)
+ (setq previous-cell-number-p t)
+ (cl-incf number-cells))))))
+ ;; Return value. Alignment specified by cookies has
+ ;; precedence over alignment deduced from cell's contents.
+ (aset align-vector
+ column
+ (cond ((equal cookie-align "l") 'left)
+ ((equal cookie-align "r") 'right)
+ ((equal cookie-align "c") 'center)
+ ((>= (/ (float number-cells) total-cells)
+ org-table-number-fraction)
+ 'right)
+ (t 'left)))))))
+
+(defun org-export-table-cell-borders (table-cell info)
+ "Return TABLE-CELL borders.
+
+INFO is a plist used as a communication channel.
+
+Return value is a list of symbols, or nil. Possible values are:
+`top', `bottom', `above', `below', `left' and `right'. Note:
+`top' (resp. `bottom') only happen for a cell in the first
+row (resp. last row) of the table, ignoring table rules, if any.
+
+Returned borders ignore special rows."
+ (let* ((row (org-export-get-parent table-cell))
+ (table (org-export-get-parent-table table-cell))
+ borders)
+ ;; Top/above border? TABLE-CELL has a border above when a rule
+ ;; used to demarcate row groups can be found above. Hence,
+ ;; finding a rule isn't sufficient to push `above' in BORDERS:
+ ;; another regular row has to be found above that rule.
+ (let (rule-flag)
+ (catch 'exit
+ ;; Look at every row before the current one.
+ (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
+ (cond ((eq (org-element-property :type row) 'rule)
+ (setq rule-flag t))
+ ((not (org-export-table-row-is-special-p row info))
+ (if rule-flag (throw 'exit (push 'above borders))
+ (throw 'exit nil)))))
+ ;; No rule above, or rule found starts the table (ignoring any
+ ;; special row): TABLE-CELL is at the top of the table.
+ (when rule-flag (push 'above borders))
+ (push 'top borders)))
+ ;; Bottom/below border? TABLE-CELL has a border below when next
+ ;; non-regular row below is a rule.
+ (let (rule-flag)
+ (catch 'exit
+ ;; Look at every row after the current one.
+ (dolist (row (cdr (memq row (org-element-contents table))))
+ (cond ((eq (org-element-property :type row) 'rule)
+ (setq rule-flag t))
+ ((not (org-export-table-row-is-special-p row info))
+ (if rule-flag (throw 'exit (push 'below borders))
+ (throw 'exit nil)))))
+ ;; No rule below, or rule found ends the table (modulo some
+ ;; special row): TABLE-CELL is at the bottom of the table.
+ (when rule-flag (push 'below borders))
+ (push 'bottom borders)))
+ ;; Right/left borders? They can only be specified by column
+ ;; groups. Column groups are defined in a row starting with "/".
+ ;; Also a column groups row only contains "<", "<>", ">" or blank
+ ;; cells.
+ (catch 'exit
+ (let ((column (let ((cells (org-element-contents row)))
+ (- (length cells) (length (memq table-cell cells))))))
+ ;; Table rows are read in reverse order so last column groups
+ ;; row has precedence over any previous one.
+ (dolist (row (reverse (org-element-contents table)))
+ (unless (eq (org-element-property :type row) 'rule)
+ (when (equal (org-element-contents
+ (car (org-element-contents row)))
+ '("/"))
+ (let ((column-groups
+ (mapcar
+ (lambda (cell)
+ (let ((value (org-element-contents cell)))
+ (when (member value '(("<") ("<>") (">") nil))
+ (car value))))
+ (org-element-contents row))))
+ ;; There's a left border when previous cell, if
+ ;; any, ends a group, or current one starts one.
+ (when (or (and (not (zerop column))
+ (member (elt column-groups (1- column))
+ '(">" "<>")))
+ (member (elt column-groups column) '("<" "<>")))
+ (push 'left borders))
+ ;; There's a right border when next cell, if any,
+ ;; starts a group, or current one ends one.
+ (when (or (and (/= (1+ column) (length column-groups))
+ (member (elt column-groups (1+ column))
+ '("<" "<>")))
+ (member (elt column-groups column) '(">" "<>")))
+ (push 'right borders))
+ (throw 'exit nil)))))))
+ ;; Return value.
+ borders))
+
+(defun org-export-table-cell-starts-colgroup-p (table-cell info)
+ "Non-nil when TABLE-CELL is at the beginning of a column group.
+INFO is a plist used as a communication channel."
+ ;; A cell starts a column group either when it is at the beginning
+ ;; of a row (or after the special column, if any) or when it has
+ ;; a left border.
+ (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
+ 'identity info 'first-match)
+ table-cell)
+ (memq 'left (org-export-table-cell-borders table-cell info))))
+
+(defun org-export-table-cell-ends-colgroup-p (table-cell info)
+ "Non-nil when TABLE-CELL is at the end of a column group.
+INFO is a plist used as a communication channel."
+ ;; A cell ends a column group either when it is at the end of a row
+ ;; or when it has a right border.
+ (or (eq (car (last (org-element-contents
+ (org-export-get-parent table-cell))))
+ table-cell)
+ (memq 'right (org-export-table-cell-borders table-cell info))))
+
+(defun org-export-table-row-starts-rowgroup-p (table-row info)
+ "Non-nil when TABLE-ROW is at the beginning of a row group.
+INFO is a plist used as a communication channel."
+ (unless (or (eq (org-element-property :type table-row) 'rule)
+ (org-export-table-row-is-special-p table-row info))
+ (let ((borders (org-export-table-cell-borders
+ (car (org-element-contents table-row)) info)))
+ (or (memq 'top borders) (memq 'above borders)))))
+
+(defun org-export-table-row-ends-rowgroup-p (table-row info)
+ "Non-nil when TABLE-ROW is at the end of a row group.
+INFO is a plist used as a communication channel."
+ (unless (or (eq (org-element-property :type table-row) 'rule)
+ (org-export-table-row-is-special-p table-row info))
+ (let ((borders (org-export-table-cell-borders
+ (car (org-element-contents table-row)) info)))
+ (or (memq 'bottom borders) (memq 'below borders)))))
+
+(defun org-export-table-row-in-header-p (table-row info)
+ "Non-nil when TABLE-ROW is located within table's header.
+INFO is a plist used as a communication channel. Always return
+nil for special rows and rows separators."
+ (and (org-export-table-has-header-p
+ (org-export-get-parent-table table-row) info)
+ (eql (org-export-table-row-group table-row info) 1)))
+
+(defun org-export-table-row-starts-header-p (table-row info)
+ "Non-nil when TABLE-ROW is the first table header's row.
+INFO is a plist used as a communication channel."
+ (and (org-export-table-row-in-header-p table-row info)
+ (org-export-table-row-starts-rowgroup-p table-row info)))
+
+(defun org-export-table-row-ends-header-p (table-row info)
+ "Non-nil when TABLE-ROW is the last table header's row.
+INFO is a plist used as a communication channel."
+ (and (org-export-table-row-in-header-p table-row info)
+ (org-export-table-row-ends-rowgroup-p table-row info)))
+
+(defun org-export-table-row-number (table-row info)
+ "Return TABLE-ROW number.
+INFO is a plist used as a communication channel. Return value is
+zero-based and ignores separators. The function returns nil for
+special columns and separators."
+ (when (and (eq (org-element-property :type table-row) 'standard)
+ (not (org-export-table-row-is-special-p table-row info)))
+ (let ((number 0))
+ (org-element-map (org-export-get-parent-table table-row) 'table-row
+ (lambda (row)
+ (cond ((eq row table-row) number)
+ ((eq (org-element-property :type row) 'standard)
+ (cl-incf number) nil)))
+ info 'first-match))))
+
+(defun org-export-table-dimensions (table info)
+ "Return TABLE dimensions.
+
+INFO is a plist used as a communication channel.
+
+Return value is a CONS like (ROWS . COLUMNS) where
+ROWS (resp. COLUMNS) is the number of exportable
+rows (resp. columns)."
+ (let (first-row (columns 0) (rows 0))
+ ;; Set number of rows, and extract first one.
+ (org-element-map table 'table-row
+ (lambda (row)
+ (when (eq (org-element-property :type row) 'standard)
+ (cl-incf rows)
+ (unless first-row (setq first-row row)))) info)
+ ;; Set number of columns.
+ (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
+ ;; Return value.
+ (cons rows columns)))
+
+(defun org-export-table-cell-address (table-cell info)
+ "Return address of a regular TABLE-CELL object.
+
+TABLE-CELL is the cell considered. INFO is a plist used as
+a communication channel.
+
+Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
+zero-based index. Only exportable cells are considered. The
+function returns nil for other cells."
+ (let* ((table-row (org-export-get-parent table-cell))
+ (row-number (org-export-table-row-number table-row info)))
+ (when row-number
+ (cons row-number
+ (let ((col-count 0))
+ (org-element-map table-row 'table-cell
+ (lambda (cell)
+ (if (eq cell table-cell) col-count (cl-incf col-count) nil))
+ info 'first-match))))))
+
+(defun org-export-get-table-cell-at (address table info)
+ "Return regular table-cell object at ADDRESS in TABLE.
+
+Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
+zero-based index. TABLE is a table type element. INFO is
+a plist used as a communication channel.
+
+If no table-cell, among exportable cells, is found at ADDRESS,
+return nil."
+ (let ((column-pos (cdr address)) (column-count 0))
+ (org-element-map
+ ;; Row at (car address) or nil.
+ (let ((row-pos (car address)) (row-count 0))
+ (org-element-map table 'table-row
+ (lambda (row)
+ (cond ((eq (org-element-property :type row) 'rule) nil)
+ ((= row-count row-pos) row)
+ (t (cl-incf row-count) nil)))
+ info 'first-match))
+ 'table-cell
+ (lambda (cell)
+ (if (= column-count column-pos) cell
+ (cl-incf column-count) nil))
+ info 'first-match)))
+
+
+;;;; For Tables Of Contents
+;;
+;; `org-export-collect-headlines' builds a list of all exportable
+;; headline elements, maybe limited to a certain depth. One can then
+;; easily parse it and transcode it.
+;;
+;; Building lists of tables, figures or listings is quite similar.
+;; Once the generic function `org-export-collect-elements' is defined,
+;; `org-export-collect-tables', `org-export-collect-figures' and
+;; `org-export-collect-listings' can be derived from it.
+
+(defun org-export-collect-headlines (info &optional n scope)
+ "Collect headlines in order to build a table of contents.
+
+INFO is a plist used as a communication channel.
+
+When optional argument N is an integer, it specifies the depth of
+the table of contents. Otherwise, it is set to the value of the
+last headline level. See `org-export-headline-levels' for more
+information.
+
+Optional argument SCOPE, when non-nil, is an element. If it is
+a headline, only children of SCOPE are collected. Otherwise,
+collect children of the headline containing provided element. If
+there is no such headline, collect all headlines. In any case,
+argument N becomes relative to the level of that headline.
+
+Return a list of all exportable headlines as parsed elements.
+Footnote sections are ignored."
+ (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
+ ((eq (org-element-type scope) 'headline) scope)
+ ((org-export-get-parent-headline scope))
+ (t (plist-get info :parse-tree))))
+ (limit (plist-get info :headline-levels))
+ (n (if (not (wholenump n)) limit
+ (min (if (eq (org-element-type scope) 'org-data) n
+ (+ (org-export-get-relative-level scope info) n))
+ limit))))
+ (org-element-map (org-element-contents scope) 'headline
+ (lambda (headline)
+ (unless (org-element-property :footnote-section-p headline)
+ (let ((level (org-export-get-relative-level headline info)))
+ (and (<= level n) headline))))
+ info)))
+
+(defun org-export-collect-elements (type info &optional predicate)
+ "Collect referenceable elements of a determined type.
+
+TYPE can be a symbol or a list of symbols specifying element
+types to search. Only elements with a caption are collected.
+
+INFO is a plist used as a communication channel.
+
+When non-nil, optional argument PREDICATE is a function accepting
+one argument, an element of type TYPE. It returns a non-nil
+value when that element should be collected.
+
+Return a list of all elements found, in order of appearance."
+ (org-element-map (plist-get info :parse-tree) type
+ (lambda (element)
+ (and (org-element-property :caption element)
+ (or (not predicate) (funcall predicate element))
+ element))
+ info))
+
+(defun org-export-collect-tables (info)
+ "Build a list of tables.
+INFO is a plist used as a communication channel.
+
+Return a list of table elements with a caption."
+ (org-export-collect-elements 'table info))
+
+(defun org-export-collect-figures (info predicate)
+ "Build a list of figures.
+
+INFO is a plist used as a communication channel. PREDICATE is
+a function which accepts one argument: a paragraph element and
+whose return value is non-nil when that element should be
+collected.
+
+A figure is a paragraph type element, with a caption, verifying
+PREDICATE. The latter has to be provided since a \"figure\" is
+a vague concept that may depend on back-end.
+
+Return a list of elements recognized as figures."
+ (org-export-collect-elements 'paragraph info predicate))
+
+(defun org-export-collect-listings (info)
+ "Build a list of src blocks.
+
+INFO is a plist used as a communication channel.
+
+Return a list of src-block elements with a caption."
+ (org-export-collect-elements 'src-block info))
+
+
+;;;; Smart Quotes
+;;
+;; The main function for the smart quotes sub-system is
+;; `org-export-activate-smart-quotes', which replaces every quote in
+;; a given string from the parse tree with its "smart" counterpart.
+;;
+;; Dictionary for smart quotes is stored in
+;; `org-export-smart-quotes-alist'.
+
+(defconst org-export-smart-quotes-alist
+ '(("da"
+ ;; one may use: »...«, "...", ›...‹, or '...'.
+ ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
+ ;; LaTeX quotes require Babel!
+ (primary-opening
+ :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
+ (primary-closing
+ :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
+ (secondary-opening
+ :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
+ (secondary-closing
+ :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("de"
+ (primary-opening
+ :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
+ (primary-closing
+ :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
+ (secondary-opening
+ :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
+ (secondary-closing
+ :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("en"
+ (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
+ (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
+ (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
+ (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("es"
+ (primary-opening
+ :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
+ :texinfo "@guillemetleft{}")
+ (primary-closing
+ :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
+ :texinfo "@guillemetright{}")
+ (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
+ (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("fr"
+ (primary-opening
+ :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
+ :texinfo "@guillemetleft{}@tie{}")
+ (primary-closing
+ :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
+ :texinfo "@tie{}@guillemetright{}")
+ (secondary-opening
+ :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
+ :texinfo "@guillemetleft{}@tie{}")
+ (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
+ :texinfo "@tie{}@guillemetright{}")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("is"
+ (primary-opening
+ :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
+ (primary-closing
+ :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
+ (secondary-opening
+ :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
+ (secondary-closing
+ :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("no"
+ ;; https://nn.wikipedia.org/wiki/Sitatteikn
+ (primary-opening
+ :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
+ :texinfo "@guillemetleft{}")
+ (primary-closing
+ :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
+ :texinfo "@guillemetright{}")
+ (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
+ (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("nb"
+ ;; https://nn.wikipedia.org/wiki/Sitatteikn
+ (primary-opening
+ :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
+ :texinfo "@guillemetleft{}")
+ (primary-closing
+ :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
+ :texinfo "@guillemetright{}")
+ (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
+ (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("nn"
+ ;; https://nn.wikipedia.org/wiki/Sitatteikn
+ (primary-opening
+ :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
+ :texinfo "@guillemetleft{}")
+ (primary-closing
+ :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
+ :texinfo "@guillemetright{}")
+ (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
+ (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
+ (apostrophe :utf-8 "’" :html "&rsquo;"))
+ ("ru"
+ ;; http://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B2%D1%8B%D1%87%D0%BA%D0%B8#.D0.9A.D0.B0.D0.B2.D1.8B.D1.87.D0.BA.D0.B8.2C_.D0.B8.D1.81.D0.BF.D0.BE.D0.BB.D1.8C.D0.B7.D1.83.D0.B5.D0.BC.D1.8B.D0.B5_.D0.B2_.D1.80.D1.83.D1.81.D1.81.D0.BA.D0.BE.D0.BC_.D1.8F.D0.B7.D1.8B.D0.BA.D0.B5
+ ;; http://www.artlebedev.ru/kovodstvo/sections/104/
+ (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
+ :texinfo "@guillemetleft{}")
+ (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
+ :texinfo "@guillemetright{}")
+ (secondary-opening
+ :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
+ (secondary-closing
+ :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
+ (apostrophe :utf-8 "’" :html: "&#39;"))
+ ("sv"
+ ;; based on https://sv.wikipedia.org/wiki/Citattecken
+ (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
+ (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
+ (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
+ (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
+ (apostrophe :utf-8 "’" :html "&rsquo;")))
+ "Smart quotes translations.
+
+Alist whose CAR is a language string and CDR is an alist with
+quote type as key and a plist associating various encodings to
+their translation as value.
+
+A quote type can be any symbol among `primary-opening',
+`primary-closing', `secondary-opening', `secondary-closing' and
+`apostrophe'.
+
+Valid encodings include `:utf-8', `:html', `:latex' and
+`:texinfo'.
+
+If no translation is found, the quote character is left as-is.")
+
+(defun org-export--smart-quote-status (s info)
+ "Return smart quote status at the beginning of string S.
+INFO is the current export state, as a plist."
+ (let* ((parent (org-element-property :parent s))
+ (cache (or (plist-get info :smart-quote-cache)
+ (let ((table (make-hash-table :test #'eq)))
+ (plist-put info :smart-quote-cache table)
+ table)))
+ (value (gethash parent cache 'missing-data)))
+ (if (not (eq value 'missing-data)) (cdr (assq s value))
+ (let (level1-open full-status)
+ (org-element-map
+ (let ((secondary (org-element-secondary-p s)))
+ (if secondary (org-element-property secondary parent)
+ (org-element-contents parent)))
+ 'plain-text
+ (lambda (text)
+ (let ((start 0) current-status)
+ (while (setq start (string-match "['\"]" text start))
+ (push
+ (cond
+ ((equal (match-string 0 text) "\"")
+ (setf level1-open (not level1-open))
+ (if level1-open 'primary-opening 'primary-closing))
+ ;; Not already in a level 1 quote: this is an
+ ;; apostrophe.
+ ((not level1-open) 'apostrophe)
+ ;; Extract previous char and next char. As
+ ;; a special case, they can also be set to `blank',
+ ;; `no-blank' or nil. Then determine if current
+ ;; match is allowed as an opening quote or a closing
+ ;; quote.
+ (t
+ (let* ((previous
+ (if (> start 0) (substring text (1- start) start)
+ (let ((p (org-export-get-previous-element
+ text info)))
+ (cond ((not p) nil)
+ ((stringp p) (substring p -1))
+ ((memq (org-element-property :post-blank p)
+ '(0 nil))
+ 'no-blank)
+ (t 'blank)))))
+ (next
+ (if (< (1+ start) (length text))
+ (substring text (1+ start) (+ start 2))
+ (let ((n (org-export-get-next-element text info)))
+ (cond ((not n) nil)
+ ((stringp n) (substring n 0 1))
+ (t 'no-blank)))))
+ (allow-open
+ (and (if (stringp previous)
+ (string-match "\\s\"\\|\\s-\\|\\s("
+ previous)
+ (memq previous '(blank nil)))
+ (if (stringp next)
+ (string-match "\\w\\|\\s.\\|\\s_" next)
+ (eq next 'no-blank))))
+ (allow-close
+ (and (if (stringp previous)
+ (string-match "\\w\\|\\s.\\|\\s_" previous)
+ (eq previous 'no-blank))
+ (if (stringp next)
+ (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
+ next)
+ (memq next '(blank nil))))))
+ (cond
+ ((and allow-open allow-close) (error "Should not happen"))
+ (allow-open 'secondary-opening)
+ (allow-close 'secondary-closing)
+ (t 'apostrophe)))))
+ current-status)
+ (cl-incf start))
+ (when current-status
+ (push (cons text (nreverse current-status)) full-status))))
+ info nil org-element-recursive-objects)
+ (puthash parent full-status cache)
+ (cdr (assq s full-status))))))
+
+(defun org-export-activate-smart-quotes (s encoding info &optional original)
+ "Replace regular quotes with \"smart\" quotes in string S.
+
+ENCODING is a symbol among `:html', `:latex', `:texinfo' and
+`:utf-8'. INFO is a plist used as a communication channel.
+
+The function has to retrieve information about string
+surroundings in parse tree. It can only happen with an
+unmodified string. Thus, if S has already been through another
+process, a non-nil ORIGINAL optional argument will provide that
+original string.
+
+Return the new string."
+ (let ((quote-status
+ (copy-sequence (org-export--smart-quote-status (or original s) info))))
+ (replace-regexp-in-string
+ "['\"]"
+ (lambda (match)
+ (or (plist-get
+ (cdr (assq (pop quote-status)
+ (cdr (assoc (plist-get info :language)
+ org-export-smart-quotes-alist))))
+ encoding)
+ match))
+ s nil t)))
+
+;;;; Topology
+;;
+;; Here are various functions to retrieve information about the
+;; neighborhood of a given element or object. Neighbors of interest
+;; are direct parent (`org-export-get-parent'), parent headline
+;; (`org-export-get-parent-headline'), first element containing an
+;; object, (`org-export-get-parent-element'), parent table
+;; (`org-export-get-parent-table'), previous element or object
+;; (`org-export-get-previous-element') and next element or object
+;; (`org-export-get-next-element').
+
+;; defsubst org-export-get-parent must be defined before first use
+
+(defun org-export-get-parent-headline (blob)
+ "Return BLOB parent headline or nil.
+BLOB is the element or object being considered."
+ (org-element-lineage blob '(headline)))
+
+(defun org-export-get-parent-element (object)
+ "Return first element containing OBJECT or nil.
+OBJECT is the object to consider."
+ (org-element-lineage object org-element-all-elements))
+
+(defun org-export-get-parent-table (object)
+ "Return OBJECT parent table or nil.
+OBJECT is either a `table-cell' or `table-element' type object."
+ (org-element-lineage object '(table)))
+
+(defun org-export-get-previous-element (blob info &optional n)
+ "Return previous element or object.
+
+BLOB is an element or object. INFO is a plist used as
+a communication channel. Return previous exportable element or
+object, a string, or nil.
+
+When optional argument N is a positive integer, return a list
+containing up to N siblings before BLOB, from farthest to
+closest. With any other non-nil value, return a list containing
+all of them."
+ (let* ((secondary (org-element-secondary-p blob))
+ (parent (org-export-get-parent blob))
+ (siblings
+ (if secondary (org-element-property secondary parent)
+ (org-element-contents parent)))
+ prev)
+ (catch 'exit
+ (dolist (obj (cdr (memq blob (reverse siblings))) prev)
+ (cond ((memq obj (plist-get info :ignore-list)))
+ ((null n) (throw 'exit obj))
+ ((not (wholenump n)) (push obj prev))
+ ((zerop n) (throw 'exit prev))
+ (t (cl-decf n) (push obj prev)))))))
+
+(defun org-export-get-next-element (blob info &optional n)
+ "Return next element or object.
+
+BLOB is an element or object. INFO is a plist used as
+a communication channel. Return next exportable element or
+object, a string, or nil.
+
+When optional argument N is a positive integer, return a list
+containing up to N siblings after BLOB, from closest to farthest.
+With any other non-nil value, return a list containing all of
+them."
+ (let* ((secondary (org-element-secondary-p blob))
+ (parent (org-export-get-parent blob))
+ (siblings
+ (cdr (memq blob
+ (if secondary (org-element-property secondary parent)
+ (org-element-contents parent)))))
+ next)
+ (catch 'exit
+ (dolist (obj siblings (nreverse next))
+ (cond ((memq obj (plist-get info :ignore-list)))
+ ((null n) (throw 'exit obj))
+ ((not (wholenump n)) (push obj next))
+ ((zerop n) (throw 'exit (nreverse next)))
+ (t (cl-decf n) (push obj next)))))))
+
+
+;;;; Translation
+;;
+;; `org-export-translate' translates a string according to the language
+;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
+;; the dictionary used for the translation.
+
+(defconst org-export-dictionary
+ '(("%e %n: %c"
+ ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
+ ("Author"
+ ("ca" :default "Autor")
+ ("cs" :default "Autor")
+ ("da" :default "Forfatter")
+ ("de" :default "Autor")
+ ("eo" :html "A&#365;toro")
+ ("es" :default "Autor")
+ ("et" :default "Autor")
+ ("fi" :html "Tekij&auml;")
+ ("fr" :default "Auteur")
+ ("hu" :default "Szerz&otilde;")
+ ("is" :html "H&ouml;fundur")
+ ("it" :default "Autore")
+ ("ja" :default "著者" :html "&#33879;&#32773;")
+ ("nl" :default "Auteur")
+ ("no" :default "Forfatter")
+ ("nb" :default "Forfatter")
+ ("nn" :default "Forfattar")
+ ("pl" :default "Autor")
+ ("pt_BR" :default "Autor")
+ ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
+ ("sv" :html "F&ouml;rfattare")
+ ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
+ ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
+ ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
+ ("Continued from previous page"
+ ("de" :default "Fortsetzung von vorheriger Seite")
+ ("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")
+ ("fr" :default "Suite de la page précédente")
+ ("it" :default "Continua da pagina precedente")
+ ("ja" :default "前ページからの続き")
+ ("nl" :default "Vervolg van vorige pagina")
+ ("pt" :default "Continuação da página anterior")
+ ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
+ :utf-8 "(Продолжение)"))
+ ("Continued on next page"
+ ("de" :default "Fortsetzung nächste Seite")
+ ("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")
+ ("fr" :default "Suite page suivante")
+ ("it" :default "Continua alla pagina successiva")
+ ("ja" :default "次ページに続く")
+ ("nl" :default "Vervolg op volgende pagina")
+ ("pt" :default "Continua na página seguinte")
+ ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
+ :utf-8 "(Продолжение следует)"))
+ ("Date"
+ ("ca" :default "Data")
+ ("cs" :default "Datum")
+ ("da" :default "Dato")
+ ("de" :default "Datum")
+ ("eo" :default "Dato")
+ ("es" :default "Fecha")
+ ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
+ ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
+ ("hu" :html "D&aacute;tum")
+ ("is" :default "Dagsetning")
+ ("it" :default "Data")
+ ("ja" :default "日付" :html "&#26085;&#20184;")
+ ("nl" :default "Datum")
+ ("no" :default "Dato")
+ ("nb" :default "Dato")
+ ("nn" :default "Dato")
+ ("pl" :default "Data")
+ ("pt_BR" :default "Data")
+ ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
+ ("sv" :default "Datum")
+ ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
+ ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
+ ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
+ ("Equation"
+ ("da" :default "Ligning")
+ ("de" :default "Gleichung")
+ ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
+ ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
+ ("fr" :ascii "Equation" :default "Équation")
+ ("is" :default "Jafna")
+ ("ja" :default "方程式")
+ ("no" :default "Ligning")
+ ("nb" :default "Ligning")
+ ("nn" :default "Likning")
+ ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
+ ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
+ :utf-8 "Уравнение")
+ ("sv" :default "Ekvation")
+ ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
+ ("Figure"
+ ("da" :default "Figur")
+ ("de" :default "Abbildung")
+ ("es" :default "Figura")
+ ("et" :default "Joonis")
+ ("is" :default "Mynd")
+ ("ja" :default "図" :html "&#22259;")
+ ("no" :default "Illustrasjon")
+ ("nb" :default "Illustrasjon")
+ ("nn" :default "Illustrasjon")
+ ("pt_BR" :default "Figura")
+ ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
+ ("sv" :default "Illustration")
+ ("zh-CN" :html "&#22270;" :utf-8 "图"))
+ ("Figure %d:"
+ ("da" :default "Figur %d")
+ ("de" :default "Abbildung %d:")
+ ("es" :default "Figura %d:")
+ ("et" :default "Joonis %d:")
+ ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
+ ("is" :default "Mynd %d")
+ ("ja" :default "図%d: " :html "&#22259;%d: ")
+ ("no" :default "Illustrasjon %d")
+ ("nb" :default "Illustrasjon %d")
+ ("nn" :default "Illustrasjon %d")
+ ("pt_BR" :default "Figura %d:")
+ ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
+ ("sv" :default "Illustration %d")
+ ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
+ ("Footnotes"
+ ("ca" :html "Peus de p&agrave;gina")
+ ("cs" :default "Pozn\xe1mky pod carou")
+ ("da" :default "Fodnoter")
+ ("de" :html "Fu&szlig;noten" :default "Fußnoten")
+ ("eo" :default "Piednotoj")
+ ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
+ ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
+ ("fi" :default "Alaviitteet")
+ ("fr" :default "Notes de bas de page")
+ ("hu" :html "L&aacute;bjegyzet")
+ ("is" :html "Aftanm&aacute;lsgreinar")
+ ("it" :html "Note a pi&egrave; di pagina")
+ ("ja" :default "脚注" :html "&#33050;&#27880;")
+ ("nl" :default "Voetnoten")
+ ("no" :default "Fotnoter")
+ ("nb" :default "Fotnoter")
+ ("nn" :default "Fotnotar")
+ ("pl" :default "Przypis")
+ ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
+ ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
+ ("sv" :default "Fotnoter")
+ ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
+ :utf-8 "Примітки")
+ ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
+ ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
+ ("List of Listings"
+ ("da" :default "Programmer")
+ ("de" :default "Programmauflistungsverzeichnis")
+ ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
+ ("et" :default "Loendite nimekiri")
+ ("fr" :default "Liste des programmes")
+ ("ja" :default "ソースコード目次")
+ ("no" :default "Dataprogrammer")
+ ("nb" :default "Dataprogrammer")
+ ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
+ :utf-8 "Список распечаток")
+ ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
+ ("List of Tables"
+ ("da" :default "Tabeller")
+ ("de" :default "Tabellenverzeichnis")
+ ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
+ ("et" :default "Tabelite nimekiri")
+ ("fr" :default "Liste des tableaux")
+ ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
+ ("ja" :default "表目次")
+ ("no" :default "Tabeller")
+ ("nb" :default "Tabeller")
+ ("nn" :default "Tabeller")
+ ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
+ ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
+ :utf-8 "Список таблиц")
+ ("sv" :default "Tabeller")
+ ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
+ ("Listing"
+ ("da" :default "Program")
+ ("de" :default "Programmlisting")
+ ("es" :default "Listado de programa")
+ ("et" :default "Loend")
+ ("fr" :default "Programme" :html "Programme")
+ ("ja" :default "ソースコード")
+ ("no" :default "Dataprogram")
+ ("nb" :default "Dataprogram")
+ ("pt_BR" :default "Listagem")
+ ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
+ :utf-8 "Распечатка")
+ ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
+ ("Listing %d:"
+ ("da" :default "Program %d")
+ ("de" :default "Programmlisting %d")
+ ("es" :default "Listado de programa %d")
+ ("et" :default "Loend %d")
+ ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
+ ("ja" :default "ソースコード%d:")
+ ("no" :default "Dataprogram %d")
+ ("nb" :default "Dataprogram %d")
+ ("pt_BR" :default "Listagem %d")
+ ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
+ :utf-8 "Распечатка %d.:")
+ ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
+ ("References"
+ ("fr" :ascii "References" :default "Références")
+ ("de" :default "Quellen")
+ ("es" :default "Referencias"))
+ ("See figure %s"
+ ("fr" :default "cf. figure %s"
+ :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s"))
+ ("See listing %s"
+ ("fr" :default "cf. programme %s"
+ :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s"))
+ ("See section %s"
+ ("da" :default "jævnfør afsnit %s")
+ ("de" :default "siehe Abschnitt %s")
+ ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
+ ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
+ ("fr" :default "cf. section %s")
+ ("ja" :default "セクション %s を参照")
+ ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
+ :ascii "Veja a secao %s")
+ ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
+ :utf-8 "См. раздел %s")
+ ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
+ ("See table %s"
+ ("fr" :default "cf. tableau %s"
+ :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s"))
+ ("Table"
+ ("de" :default "Tabelle")
+ ("es" :default "Tabla")
+ ("et" :default "Tabel")
+ ("fr" :default "Tableau")
+ ("is" :default "Tafla")
+ ("ja" :default "表" :html "&#34920;")
+ ("pt_BR" :default "Tabela")
+ ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
+ :utf-8 "Таблица")
+ ("zh-CN" :html "&#34920;" :utf-8 "表"))
+ ("Table %d:"
+ ("da" :default "Tabel %d")
+ ("de" :default "Tabelle %d")
+ ("es" :default "Tabla %d")
+ ("et" :default "Tabel %d")
+ ("fr" :default "Tableau %d :")
+ ("is" :default "Tafla %d")
+ ("ja" :default "表%d:" :html "&#34920;%d:")
+ ("no" :default "Tabell %d")
+ ("nb" :default "Tabell %d")
+ ("nn" :default "Tabell %d")
+ ("pt_BR" :default "Tabela %d")
+ ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
+ :utf-8 "Таблица %d.:")
+ ("sv" :default "Tabell %d")
+ ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
+ ("Table of Contents"
+ ("ca" :html "&Iacute;ndex")
+ ("cs" :default "Obsah")
+ ("da" :default "Indhold")
+ ("de" :default "Inhaltsverzeichnis")
+ ("eo" :default "Enhavo")
+ ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
+ ("et" :default "Sisukord")
+ ("fi" :html "Sis&auml;llysluettelo")
+ ("fr" :ascii "Sommaire" :default "Table des matières")
+ ("hu" :html "Tartalomjegyz&eacute;k")
+ ("is" :default "Efnisyfirlit")
+ ("it" :default "Indice")
+ ("ja" :default "目次" :html "&#30446;&#27425;")
+ ("nl" :default "Inhoudsopgave")
+ ("no" :default "Innhold")
+ ("nb" :default "Innhold")
+ ("nn" :default "Innhald")
+ ("pl" :html "Spis tre&#x015b;ci")
+ ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
+ ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
+ :utf-8 "Содержание")
+ ("sv" :html "Inneh&aring;ll")
+ ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
+ ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
+ ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
+ ("Unknown reference"
+ ("da" :default "ukendt reference")
+ ("de" :default "Unbekannter Verweis")
+ ("es" :default "Referencia desconocida")
+ ("et" :default "Tundmatu viide")
+ ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
+ ("ja" :default "不明な参照先")
+ ("pt_BR" :default "Referência desconhecida"
+ :ascii "Referencia desconhecida")
+ ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
+ :utf-8 "Неизвестная ссылка")
+ ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
+ "Dictionary for export engine.
+
+Alist whose car is the string to translate and cdr is an alist
+whose car is the language string and cdr is a plist whose
+properties are possible charsets and values translated terms.
+
+It is used as a database for `org-export-translate'. Since this
+function returns the string as-is if no translation was found,
+the variable only needs to record values different from the
+entry.")
+
+(defun org-export-translate (s encoding info)
+ "Translate string S according to language specification.
+
+ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
+and `:utf-8'. INFO is a plist used as a communication channel.
+
+Translation depends on `:language' property. Return the
+translated string. If no translation is found, try to fall back
+to `:default' encoding. If it fails, return S."
+ (let* ((lang (plist-get info :language))
+ (translations (cdr (assoc lang
+ (cdr (assoc s org-export-dictionary))))))
+ (or (plist-get translations encoding)
+ (plist-get translations :default)
+ s)))
+
+
+
+;;; Asynchronous Export
+;;
+;; `org-export-async-start' is the entry point for asynchronous
+;; export. It recreates current buffer (including visibility,
+;; narrowing and visited file) in an external Emacs process, and
+;; evaluates a command there. It then applies a function on the
+;; returned results in the current process.
+;;
+;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
+;; allow exporting to a buffer or a file, asynchronously or not.
+;;
+;; `org-export-output-file-name' is an auxiliary function meant to be
+;; used with `org-export-to-file'. With a given extension, it tries
+;; to provide a canonical file name to write export output to.
+;;
+;; Asynchronously generated results are never displayed directly.
+;; Instead, they are stored in `org-export-stack-contents'. They can
+;; then be retrieved by calling `org-export-stack'.
+;;
+;; Export Stack is viewed through a dedicated major mode
+;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
+;;`org-export-stack-delete', `org-export-stack-view' and
+;;`org-export-stack-clear'.
+;;
+;; For back-ends, `org-export-add-to-stack' add a new source to stack.
+;; It should be used whenever `org-export-async-start' is called.
+
+(defmacro org-export-async-start (fun &rest body)
+ "Call function FUN on the results returned by BODY evaluation.
+
+FUN is an anonymous function of one argument. BODY evaluation
+happens in an asynchronous process, from a buffer which is an
+exact copy of the current one.
+
+Use `org-export-add-to-stack' in FUN in order to register results
+in the stack.
+
+This is a low level function. See also `org-export-to-buffer'
+and `org-export-to-file' for more specialized functions."
+ (declare (indent 1) (debug t))
+ (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
+ ;; Write the full sexp evaluating BODY in a copy of the current
+ ;; buffer to a temporary file, as it may be too long for program
+ ;; args in `start-process'.
+ `(with-temp-message "Initializing asynchronous export process"
+ (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
+ (,temp-file (make-temp-file "org-export-process"))
+ (,coding buffer-file-coding-system))
+ (with-temp-file ,temp-file
+ (insert
+ ;; Null characters (from variable values) are inserted
+ ;; within the file. As a consequence, coding system for
+ ;; buffer contents will not be recognized properly. So,
+ ;; we make sure it is the same as the one used to display
+ ;; the original buffer.
+ (format ";; -*- coding: %s; -*-\n%S"
+ ,coding
+ `(with-temp-buffer
+ (when org-export-async-debug '(setq debug-on-error t))
+ ;; Ignore `kill-emacs-hook' and code evaluation
+ ;; queries from Babel as we need a truly
+ ;; non-interactive process.
+ (setq kill-emacs-hook nil
+ org-babel-confirm-evaluate-answer-no t)
+ ;; Initialize export framework.
+ (require 'ox)
+ ;; Re-create current buffer there.
+ (funcall ,,copy-fun)
+ (restore-buffer-modified-p nil)
+ ;; Sexp to evaluate in the buffer.
+ (print (progn ,,@body))))))
+ ;; Start external process.
+ (let* ((process-connection-type nil)
+ (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
+ (,process
+ (apply
+ #'start-process
+ (append
+ (list "org-export-process"
+ ,proc-buffer
+ (expand-file-name invocation-name invocation-directory)
+ "--batch")
+ (if org-export-async-init-file
+ (list "-Q" "-l" org-export-async-init-file)
+ (list "-l" user-init-file))
+ (list "-l" ,temp-file)))))
+ ;; Register running process in stack.
+ (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
+ ;; Set-up sentinel in order to catch results.
+ (let ((handler ,fun))
+ (set-process-sentinel
+ ,process
+ `(lambda (p status)
+ (let ((proc-buffer (process-buffer p)))
+ (when (eq (process-status p) 'exit)
+ (unwind-protect
+ (if (zerop (process-exit-status p))
+ (unwind-protect
+ (let ((results
+ (with-current-buffer proc-buffer
+ (goto-char (point-max))
+ (backward-sexp)
+ (read (current-buffer)))))
+ (funcall ,handler results))
+ (unless org-export-async-debug
+ (and (get-buffer proc-buffer)
+ (kill-buffer proc-buffer))))
+ (org-export-add-to-stack proc-buffer nil p)
+ (ding)
+ (message "Process `%s' exited abnormally" p))
+ (unless org-export-async-debug
+ (delete-file ,,temp-file)))))))))))))
+
+;;;###autoload
+(defun org-export-to-buffer
+ (backend buffer
+ &optional async subtreep visible-only body-only ext-plist
+ post-process)
+ "Call `org-export-as' with output to a specified buffer.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end.
+
+BUFFER is the name of the output buffer. If it already exists,
+it will be erased first, otherwise, it will be created.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer should then be accessible
+through the `org-export-stack' interface. When ASYNC is nil, the
+buffer is displayed if `org-export-show-temporary-export-buffer'
+is non-nil.
+
+Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
+EXT-PLIST are similar to those used in `org-export-as', which
+see.
+
+Optional argument POST-PROCESS is a function which should accept
+no argument. It is always called within the current process,
+from BUFFER, with point at its beginning. Export back-ends can
+use it to set a major mode there, e.g,
+
+ (defun org-latex-export-as-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ (interactive)
+ (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
+ async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
+
+This function returns BUFFER."
+ (declare (indent 2))
+ (if async
+ (org-export-async-start
+ `(lambda (output)
+ (with-current-buffer (get-buffer-create ,buffer)
+ (erase-buffer)
+ (setq buffer-file-coding-system ',buffer-file-coding-system)
+ (insert output)
+ (goto-char (point-min))
+ (org-export-add-to-stack (current-buffer) ',backend)
+ (ignore-errors (funcall ,post-process))))
+ `(org-export-as
+ ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
+ (let ((output
+ (org-export-as backend subtreep visible-only body-only ext-plist))
+ (buffer (get-buffer-create buffer))
+ (encoding buffer-file-coding-system))
+ (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
+ (org-kill-new output))
+ (with-current-buffer buffer
+ (erase-buffer)
+ (setq buffer-file-coding-system encoding)
+ (insert output)
+ (goto-char (point-min))
+ (and (functionp post-process) (funcall post-process)))
+ (when org-export-show-temporary-export-buffer
+ (switch-to-buffer-other-window buffer))
+ buffer)))
+
+;;;###autoload
+(defun org-export-to-file
+ (backend file &optional async subtreep visible-only body-only ext-plist
+ post-process)
+ "Call `org-export-as' with output to a specified file.
+
+BACKEND is either an export back-end, as returned by, e.g.,
+`org-export-create-backend', or a symbol referring to
+a registered back-end. FILE is the name of the output file, as
+a string.
+
+A non-nil optional argument ASYNC means the process should happen
+asynchronously. The resulting buffer will then be accessible
+through the `org-export-stack' interface.
+
+Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
+EXT-PLIST are similar to those used in `org-export-as', which
+see.
+
+Optional argument POST-PROCESS is called with FILE as its
+argument and happens asynchronously when ASYNC is non-nil. It
+has to return a file name, or nil. Export back-ends can use this
+to send the output file through additional processing, e.g,
+
+ (defun org-latex-export-to-latex
+ (&optional async subtreep visible-only body-only ext-plist)
+ (interactive)
+ (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
+ (org-export-to-file \\='latex outfile
+ async subtreep visible-only body-only ext-plist
+ (lambda (file) (org-latex-compile file)))
+
+The function returns either a file name returned by POST-PROCESS,
+or FILE."
+ (declare (indent 2))
+ (if (not (file-writable-p file)) (error "Output file not writable")
+ (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
+ (encoding (or org-export-coding-system buffer-file-coding-system)))
+ (if async
+ (org-export-async-start
+ `(lambda (file)
+ (org-export-add-to-stack (expand-file-name file) ',backend))
+ `(let ((output
+ (org-export-as
+ ',backend ,subtreep ,visible-only ,body-only
+ ',ext-plist)))
+ (with-temp-buffer
+ (insert output)
+ (let ((coding-system-for-write ',encoding))
+ (write-file ,file)))
+ (or (ignore-errors (funcall ',post-process ,file)) ,file)))
+ (let ((output (org-export-as
+ backend subtreep visible-only body-only ext-plist)))
+ (with-temp-buffer
+ (insert output)
+ (let ((coding-system-for-write encoding))
+ (write-file file)))
+ (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
+ (org-kill-new output))
+ ;; Get proper return value.
+ (or (and (functionp post-process) (funcall post-process file))
+ file))))))
+
+(defun org-export-output-file-name (extension &optional subtreep pub-dir)
+ "Return output file's name according to buffer specifications.
+
+EXTENSION is a string representing the output file extension,
+with the leading dot.
+
+With a non-nil optional argument SUBTREEP, try to determine
+output file's name by looking for \"EXPORT_FILE_NAME\" property
+of subtree at point.
+
+When optional argument PUB-DIR is set, use it as the publishing
+directory.
+
+Return file name as a string."
+ (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
+ (base-name
+ ;; File name may come from EXPORT_FILE_NAME subtree
+ ;; property.
+ (file-name-sans-extension
+ (or (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
+ ;; File name may be extracted from buffer's associated
+ ;; file, if any.
+ (and visited-file (file-name-nondirectory visited-file))
+ ;; Can't determine file name on our own: Ask user.
+ (read-file-name
+ "Output file: " pub-dir nil nil nil
+ (lambda (name)
+ (string= (file-name-extension name t) extension))))))
+ (output-file
+ ;; Build file name. Enforce EXTENSION over whatever user
+ ;; may have come up with. PUB-DIR, if defined, always has
+ ;; precedence over any provided path.
+ (cond
+ (pub-dir
+ (concat (file-name-as-directory pub-dir)
+ (file-name-nondirectory base-name)
+ extension))
+ ((file-name-absolute-p base-name) (concat base-name extension))
+ (t (concat (file-name-as-directory ".") base-name extension)))))
+ ;; If writing to OUTPUT-FILE would overwrite original file, append
+ ;; EXTENSION another time to final name.
+ (if (and visited-file (file-equal-p visited-file output-file))
+ (concat output-file extension)
+ output-file)))
+
+(defun org-export-add-to-stack (source backend &optional process)
+ "Add a new result to export stack if not present already.
+
+SOURCE is a buffer or a file name containing export results.
+BACKEND is a symbol representing export back-end used to generate
+it.
+
+Entries already pointing to SOURCE and unavailable entries are
+removed beforehand. Return the new stack."
+ (setq org-export-stack-contents
+ (cons (list source backend (or process (current-time)))
+ (org-export-stack-remove source))))
+
+(defun org-export-stack ()
+ "Menu for asynchronous export results and running processes."
+ (interactive)
+ (let ((buffer (get-buffer-create "*Org Export Stack*")))
+ (with-current-buffer buffer
+ (org-export-stack-mode)
+ (tabulated-list-print t))
+ (pop-to-buffer buffer))
+ (message "Type \"q\" to quit, \"?\" for help"))
+
+(defun org-export-stack-clear ()
+ "Remove all entries from export stack."
+ (interactive)
+ (setq org-export-stack-contents nil))
+
+(defun org-export-stack-refresh ()
+ "Refresh the export stack."
+ (interactive)
+ (tabulated-list-print t))
+
+(defun org-export-stack-remove (&optional source)
+ "Remove export results at point from stack.
+If optional argument SOURCE is non-nil, remove it instead."
+ (interactive)
+ (let ((source (or source (org-export--stack-source-at-point))))
+ (setq org-export-stack-contents
+ (cl-remove-if (lambda (el) (equal (car el) source))
+ org-export-stack-contents))))
+
+(defun org-export-stack-view (&optional in-emacs)
+ "View export results at point in stack.
+With an optional prefix argument IN-EMACS, force viewing files
+within Emacs."
+ (interactive "P")
+ (let ((source (org-export--stack-source-at-point)))
+ (cond ((processp source)
+ (org-switch-to-buffer-other-window (process-buffer source)))
+ ((bufferp source) (org-switch-to-buffer-other-window source))
+ (t (org-open-file source in-emacs)))))
+
+(defvar org-export-stack-mode-map
+ (let ((km (make-sparse-keymap)))
+ (set-keymap-parent km tabulated-list-mode-map)
+ (define-key km " " 'next-line)
+ (define-key km "\C-n" 'next-line)
+ (define-key km [down] 'next-line)
+ (define-key km "\C-p" 'previous-line)
+ (define-key km "\C-?" 'previous-line)
+ (define-key km [up] 'previous-line)
+ (define-key km "C" 'org-export-stack-clear)
+ (define-key km "v" 'org-export-stack-view)
+ (define-key km (kbd "RET") 'org-export-stack-view)
+ (define-key km "d" 'org-export-stack-remove)
+ km)
+ "Keymap for Org Export Stack.")
+
+(define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
+ "Mode for displaying asynchronous export stack.
+
+Type `\\[org-export-stack]' to visualize the asynchronous export
+stack.
+
+In an Org Export Stack buffer, use \
+\\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
+on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
+`\\[org-export-stack-clear]' to clear
+stack completely.
+
+Removing entries in a stack buffer does not affect files
+or buffers, only display.
+
+\\{org-export-stack-mode-map}"
+ (setq tabulated-list-format
+ (vector (list "#" 4 #'org-export--stack-num-predicate)
+ (list "Back-End" 12 t)
+ (list "Age" 6 nil)
+ (list "Source" 0 nil)))
+ (setq tabulated-list-sort-key (cons "#" nil))
+ (setq tabulated-list-entries #'org-export--stack-generate)
+ (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
+ (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
+ (tabulated-list-init-header))
+
+(defun org-export--stack-generate ()
+ "Generate the asynchronous export stack for display.
+Unavailable sources are removed from the list. Return a list
+appropriate for `tabulated-list-print'."
+ ;; Clear stack from exited processes, dead buffers or non-existent
+ ;; files.
+ (setq org-export-stack-contents
+ (cl-remove-if-not
+ (lambda (el)
+ (if (processp (nth 2 el))
+ (buffer-live-p (process-buffer (nth 2 el)))
+ (let ((source (car el)))
+ (if (bufferp source) (buffer-live-p source)
+ (file-exists-p source)))))
+ org-export-stack-contents))
+ ;; Update `tabulated-list-entries'.
+ (let ((counter 0))
+ (mapcar
+ (lambda (entry)
+ (let ((source (car entry)))
+ (list source
+ (vector
+ ;; Counter.
+ (number-to-string (cl-incf counter))
+ ;; Back-End.
+ (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
+ ;; Age.
+ (let ((info (nth 2 entry)))
+ (if (processp info) (symbol-name (process-status info))
+ (format-seconds "%h:%.2m" (float-time (time-since info)))))
+ ;; Source.
+ (if (stringp source) source (buffer-name source))))))
+ org-export-stack-contents)))
+
+(defun org-export--stack-num-predicate (a b)
+ (< (string-to-number (aref (nth 1 a) 0))
+ (string-to-number (aref (nth 1 b) 0))))
+
+(defun org-export--stack-source-at-point ()
+ "Return source from export results at point in stack."
+ (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
+ (if (not source) (error "Source unavailable, please refresh buffer")
+ (let ((source-name (if (stringp source) source (buffer-name source))))
+ (if (save-excursion
+ (beginning-of-line)
+ (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
+ source
+ ;; SOURCE is not consistent with current line. The stack
+ ;; view is outdated.
+ (error (substitute-command-keys
+ "Source unavailable; type `\\[org-export-stack-refresh]' \
+to refresh buffer")))))))
+
+
+
+;;; The Dispatcher
+;;
+;; `org-export-dispatch' is the standard interactive way to start an
+;; export process. It uses `org-export--dispatch-ui' as a subroutine
+;; for its interface, which, in turn, delegates response to key
+;; pressed to `org-export--dispatch-action'.
+
+;;;###autoload
+(defun org-export-dispatch (&optional arg)
+ "Export dispatcher for Org mode.
+
+It provides an access to common export related tasks in a buffer.
+Its interface comes in two flavors: standard and expert.
+
+While both share the same set of bindings, only the former
+displays the valid keys associations in a dedicated buffer.
+Scrolling (resp. line-wise motion) in this buffer is done with
+SPC and DEL (resp. C-n and C-p) keys.
+
+Set variable `org-export-dispatch-use-expert-ui' to switch to one
+flavor or the other.
+
+When ARG is `\\[universal-argument]', repeat the last export action, with the\
+ same
+set of options used back then, on the current buffer.
+
+When ARG is `\\[universal-argument] \\[universal-argument]', display the \
+asynchronous export stack."
+ (interactive "P")
+ (let* ((input
+ (cond ((equal arg '(16)) '(stack))
+ ((and arg org-export-dispatch-last-action))
+ (t (save-window-excursion
+ (unwind-protect
+ (progn
+ ;; Remember where we are
+ (move-marker org-export-dispatch-last-position
+ (point)
+ (org-base-buffer (current-buffer)))
+ ;; Get and store an export command
+ (setq org-export-dispatch-last-action
+ (org-export--dispatch-ui
+ (list org-export-initial-scope
+ (and org-export-in-background 'async))
+ nil
+ org-export-dispatch-use-expert-ui)))
+ (and (get-buffer "*Org Export Dispatcher*")
+ (kill-buffer "*Org Export Dispatcher*")))))))
+ (action (car input))
+ (optns (cdr input)))
+ (unless (memq 'subtree optns)
+ (move-marker org-export-dispatch-last-position nil))
+ (cl-case action
+ ;; First handle special hard-coded actions.
+ (template (org-export-insert-default-template nil optns))
+ (stack (org-export-stack))
+ (publish-current-file
+ (org-publish-current-file (memq 'force optns) (memq 'async optns)))
+ (publish-current-project
+ (org-publish-current-project (memq 'force optns) (memq 'async optns)))
+ (publish-choose-project
+ (org-publish (assoc (completing-read
+ "Publish project: "
+ org-publish-project-alist nil t)
+ org-publish-project-alist)
+ (memq 'force optns)
+ (memq 'async optns)))
+ (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
+ (otherwise
+ (save-excursion
+ (when arg
+ ;; Repeating command, maybe move cursor to restore subtree
+ ;; context.
+ (if (eq (marker-buffer org-export-dispatch-last-position)
+ (org-base-buffer (current-buffer)))
+ (goto-char org-export-dispatch-last-position)
+ ;; We are in a different buffer, forget position.
+ (move-marker org-export-dispatch-last-position nil)))
+ (funcall action
+ ;; Return a symbol instead of a list to ease
+ ;; asynchronous export macro use.
+ (and (memq 'async optns) t)
+ (and (memq 'subtree optns) t)
+ (and (memq 'visible optns) t)
+ (and (memq 'body optns) t)))))))
+
+(defun org-export--dispatch-ui (options first-key expertp)
+ "Handle interface for `org-export-dispatch'.
+
+OPTIONS is a list containing current interactive options set for
+export. It can contain any of the following symbols:
+`body' toggles a body-only export
+`subtree' restricts export to current subtree
+`visible' restricts export to visible part of buffer.
+`force' force publishing files.
+`async' use asynchronous export process
+
+FIRST-KEY is the key pressed to select the first level menu. It
+is nil when this menu hasn't been selected yet.
+
+EXPERTP, when non-nil, triggers expert UI. In that case, no help
+buffer is provided, but indications about currently active
+options are given in the prompt. Moreover, [?] allows switching
+back to standard interface."
+ (let* ((fontify-key
+ (lambda (key &optional access-key)
+ ;; Fontify KEY string. Optional argument ACCESS-KEY, when
+ ;; non-nil is the required first-level key to activate
+ ;; KEY. When its value is t, activate KEY independently
+ ;; on the first key, if any. A nil value means KEY will
+ ;; only be activated at first level.
+ (if (or (eq access-key t) (eq access-key first-key))
+ (propertize key 'face 'org-warning)
+ key)))
+ (fontify-value
+ (lambda (value)
+ ;; Fontify VALUE string.
+ (propertize value 'face 'font-lock-variable-name-face)))
+ ;; Prepare menu entries by extracting them from registered
+ ;; back-ends and sorting them by access key and by ordinal,
+ ;; if any.
+ (entries
+ (sort (sort (delq nil
+ (mapcar #'org-export-backend-menu
+ org-export-registered-backends))
+ (lambda (a b)
+ (let ((key-a (nth 1 a))
+ (key-b (nth 1 b)))
+ (cond ((and (numberp key-a) (numberp key-b))
+ (< key-a key-b))
+ ((numberp key-b) t)))))
+ 'car-less-than-car))
+ ;; Compute a list of allowed keys based on the first key
+ ;; pressed, if any. Some keys
+ ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
+ ;; available.
+ (allowed-keys
+ (nconc (list 2 22 19 6 1)
+ (if (not first-key) (org-uniquify (mapcar 'car entries))
+ (let (sub-menu)
+ (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
+ (when (eq (car entry) first-key)
+ (setq sub-menu (append (nth 2 entry) sub-menu))))))
+ (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
+ ((not first-key) (list ?P)))
+ (list ?& ?#)
+ (when expertp (list ??))
+ (list ?q)))
+ ;; Build the help menu for standard UI.
+ (help
+ (unless expertp
+ (concat
+ ;; Options are hard-coded.
+ (format "[%s] Body only: %s [%s] Visible only: %s
+\[%s] Export scope: %s [%s] Force publishing: %s
+\[%s] Async export: %s\n\n"
+ (funcall fontify-key "C-b" t)
+ (funcall fontify-value
+ (if (memq 'body options) "On " "Off"))
+ (funcall fontify-key "C-v" t)
+ (funcall fontify-value
+ (if (memq 'visible options) "On " "Off"))
+ (funcall fontify-key "C-s" t)
+ (funcall fontify-value
+ (if (memq 'subtree options) "Subtree" "Buffer "))
+ (funcall fontify-key "C-f" t)
+ (funcall fontify-value
+ (if (memq 'force options) "On " "Off"))
+ (funcall fontify-key "C-a" t)
+ (funcall fontify-value
+ (if (memq 'async options) "On " "Off")))
+ ;; Display registered back-end entries. When a key
+ ;; appears for the second time, do not create another
+ ;; entry, but append its sub-menu to existing menu.
+ (let (last-key)
+ (mapconcat
+ (lambda (entry)
+ (let ((top-key (car entry)))
+ (concat
+ (unless (eq top-key last-key)
+ (setq last-key top-key)
+ (format "\n[%s] %s\n"
+ (funcall fontify-key (char-to-string top-key))
+ (nth 1 entry)))
+ (let ((sub-menu (nth 2 entry)))
+ (unless (functionp sub-menu)
+ ;; Split sub-menu into two columns.
+ (let ((index -1))
+ (concat
+ (mapconcat
+ (lambda (sub-entry)
+ (cl-incf index)
+ (format
+ (if (zerop (mod index 2)) " [%s] %-26s"
+ "[%s] %s\n")
+ (funcall fontify-key
+ (char-to-string (car sub-entry))
+ top-key)
+ (nth 1 sub-entry)))
+ sub-menu "")
+ (when (zerop (mod index 2)) "\n"))))))))
+ entries ""))
+ ;; Publishing menu is hard-coded.
+ (format "\n[%s] Publish
+ [%s] Current file [%s] Current project
+ [%s] Choose project [%s] All projects\n\n\n"
+ (funcall fontify-key "P")
+ (funcall fontify-key "f" ?P)
+ (funcall fontify-key "p" ?P)
+ (funcall fontify-key "x" ?P)
+ (funcall fontify-key "a" ?P))
+ (format "[%s] Export stack [%s] Insert template\n"
+ (funcall fontify-key "&" t)
+ (funcall fontify-key "#" t))
+ (format "[%s] %s"
+ (funcall fontify-key "q" t)
+ (if first-key "Main menu" "Exit")))))
+ ;; Build prompts for both standard and expert UI.
+ (standard-prompt (unless expertp "Export command: "))
+ (expert-prompt
+ (when expertp
+ (format
+ "Export command (C-%s%s%s%s%s) [%s]: "
+ (if (memq 'body options) (funcall fontify-key "b" t) "b")
+ (if (memq 'visible options) (funcall fontify-key "v" t) "v")
+ (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
+ (if (memq 'force options) (funcall fontify-key "f" t) "f")
+ (if (memq 'async options) (funcall fontify-key "a" t) "a")
+ (mapconcat (lambda (k)
+ ;; Strip control characters.
+ (unless (< k 27) (char-to-string k)))
+ allowed-keys "")))))
+ ;; With expert UI, just read key with a fancy prompt. In standard
+ ;; UI, display an intrusive help buffer.
+ (if expertp
+ (org-export--dispatch-action
+ expert-prompt allowed-keys entries options first-key expertp)
+ ;; At first call, create frame layout in order to display menu.
+ (unless (get-buffer "*Org Export Dispatcher*")
+ (delete-other-windows)
+ (org-switch-to-buffer-other-window
+ (get-buffer-create "*Org Export Dispatcher*"))
+ (setq cursor-type nil
+ header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
+ ;; Make sure that invisible cursor will not highlight square
+ ;; brackets.
+ (set-syntax-table (copy-syntax-table))
+ (modify-syntax-entry ?\[ "w"))
+ ;; At this point, the buffer containing the menu exists and is
+ ;; visible in the current window. So, refresh it.
+ (with-current-buffer "*Org Export Dispatcher*"
+ ;; Refresh help. Maintain display continuity by re-visiting
+ ;; previous window position.
+ (let ((pos (window-start)))
+ (erase-buffer)
+ (insert help)
+ (set-window-start nil pos)))
+ (org-fit-window-to-buffer)
+ (org-export--dispatch-action
+ standard-prompt allowed-keys entries options first-key expertp))))
+
+(defun org-export--dispatch-action
+ (prompt allowed-keys entries options first-key expertp)
+ "Read a character from command input and act accordingly.
+
+PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
+a list of characters available at a given step in the process.
+ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
+EXPERTP are the same as defined in `org-export--dispatch-ui',
+which see.
+
+Toggle export options when required. Otherwise, return value is
+a list with action as CAR and a list of interactive export
+options as CDR."
+ (let (key)
+ ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
+ ;; C-p, SPC, DEL).
+ (while (and (setq key (read-char-exclusive prompt))
+ (not expertp)
+ (memq key '(14 16 ?\s ?\d)))
+ (cl-case key
+ (14 (if (not (pos-visible-in-window-p (point-max)))
+ (ignore-errors (scroll-up 1))
+ (message "End of buffer")
+ (sit-for 1)))
+ (16 (if (not (pos-visible-in-window-p (point-min)))
+ (ignore-errors (scroll-down 1))
+ (message "Beginning of buffer")
+ (sit-for 1)))
+ (?\s (if (not (pos-visible-in-window-p (point-max)))
+ (scroll-up nil)
+ (message "End of buffer")
+ (sit-for 1)))
+ (?\d (if (not (pos-visible-in-window-p (point-min)))
+ (scroll-down nil)
+ (message "Beginning of buffer")
+ (sit-for 1)))))
+ (cond
+ ;; Ignore undefined associations.
+ ((not (memq key allowed-keys))
+ (ding)
+ (unless expertp (message "Invalid key") (sit-for 1))
+ (org-export--dispatch-ui options first-key expertp))
+ ;; q key at first level aborts export. At second level, cancel
+ ;; first key instead.
+ ((eq key ?q) (if (not first-key) (error "Export aborted")
+ (org-export--dispatch-ui options nil expertp)))
+ ;; Help key: Switch back to standard interface if expert UI was
+ ;; active.
+ ((eq key ??) (org-export--dispatch-ui options first-key nil))
+ ;; Send request for template insertion along with export scope.
+ ((eq key ?#) (cons 'template (memq 'subtree options)))
+ ;; Switch to asynchronous export stack.
+ ((eq key ?&) '(stack))
+ ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
+ ((memq key '(2 22 19 6 1))
+ (org-export--dispatch-ui
+ (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
+ (6 'force) (1 'async))))
+ (if (memq option options) (remq option options)
+ (cons option options)))
+ first-key expertp))
+ ;; Action selected: Send key and options back to
+ ;; `org-export-dispatch'.
+ ((or first-key (functionp (nth 2 (assq key entries))))
+ (cons (cond
+ ((not first-key) (nth 2 (assq key entries)))
+ ;; Publishing actions are hard-coded. Send a special
+ ;; signal to `org-export-dispatch'.
+ ((eq first-key ?P)
+ (cl-case key
+ (?f 'publish-current-file)
+ (?p 'publish-current-project)
+ (?x 'publish-choose-project)
+ (?a 'publish-all)))
+ ;; Return first action associated to FIRST-KEY + KEY
+ ;; path. Indeed, derived backends can share the same
+ ;; FIRST-KEY.
+ (t (catch 'found
+ (dolist (entry (member (assq first-key entries) entries))
+ (let ((match (assq key (nth 2 entry))))
+ (when match (throw 'found (nth 2 match))))))))
+ options))
+ ;; Otherwise, enter sub-menu.
+ (t (org-export--dispatch-ui options key expertp)))))
+
+
+
+(provide 'ox)
+
+;; Local variables:
+;; generated-autoload-file: "org-loaddefs.el"
+;; End:
+
+;;; ox.el ends here
diff --git a/mk/default.mk b/mk/default.mk
new file mode 100644
index 0000000..0e639d1
--- /dev/null
+++ b/mk/default.mk
@@ -0,0 +1,176 @@
+##----------------------------------------------------------------------
+## NEVER EDIT THIS FILE, PUT ANY ADAPTATIONS INTO local.mk
+##-8<-------------------------------------------------------------------
+## CHECK AND ADAPT THE FOLLOWING DEFINITIONS
+##----------------------------------------------------------------------
+
+# Name of your emacs binary
+EMACS = emacs
+
+# Where local software is found
+prefix = /usr/share
+
+# Where local lisp files go.
+lispdir= $(prefix)/emacs/site-lisp/org
+
+# Where local data files go.
+datadir = $(prefix)/emacs/etc/org
+
+# Where info files go.
+infodir = $(prefix)/info
+
+# Define if you only need info documentation, the default includes html and pdf
+#ORG_MAKE_DOC = info # html pdf
+
+# Define which git branch to switch to during update. Does not switch
+# the branch when undefined.
+GIT_BRANCH =
+
+# Define if you want to include some (or all) files from contrib/lisp
+# just the filename please (no path prefix, no .el suffix), maybe with globbing
+#ORG_ADD_CONTRIB = ox-* # e.g. the contributed exporter
+
+# Where to create temporary files for the testsuite
+# respect TMPDIR if it is already defined in the environment
+TMPDIR ?= /tmp
+testdir = $(TMPDIR)/tmp-orgtest
+
+# Configuration for testing
+# add options before standard load-path
+BTEST_PRE =
+# add options after standard load path
+BTEST_POST =
+ # -L <path-to>/ert # needed for Emacs23, Emacs24 has ert built in
+ # -L <path-to>/ess # needed for running R tests
+ # -L <path-to>/htmlize # need at least version 1.34 for source code formatting
+BTEST_OB_LANGUAGES = awk C fortran maxima lilypond octave perl python
+ # R # requires ESS to be installed and configured
+ # ruby # requires inf-ruby to be installed and configured
+# extra packages to require for testing
+BTEST_EXTRA =
+ # ess-site # load ESS for R tests
+##->8-------------------------------------------------------------------
+## YOU MAY NEED TO ADAPT THESE DEFINITIONS
+##----------------------------------------------------------------------
+
+# How to run tests
+req-ob-lang = --eval '(require '"'"'ob-$(ob-lang))'
+lst-ob-lang = ($(ob-lang) . t)
+req-extra = --eval '(require '"'"'$(req))'
+BTEST_RE ?= \\(org\\|ob\\)
+BTEST_LOAD = \
+ --eval '(add-to-list '"'"'load-path (concat default-directory "lisp"))' \
+ --eval '(add-to-list '"'"'load-path (concat default-directory "testing"))'
+BTEST_INIT = $(BTEST_PRE) $(BTEST_LOAD) $(BTEST_POST)
+
+BTEST = $(BATCH) $(BTEST_INIT) \
+ -l org-batch-test-init \
+ --eval '(setq \
+ org-batch-test t \
+ org-babel-load-languages \
+ (quote ($(foreach ob-lang,\
+ $(BTEST_OB_LANGUAGES) emacs-lisp shell org,\
+ $(lst-ob-lang)))) \
+ org-test-select-re "$(BTEST_RE)" \
+ )' \
+ -l org-loaddefs.el \
+ -l cl -l testing/org-test.el \
+ -l ert -l org -l ox \
+ $(foreach req,$(BTEST_EXTRA),$(req-extra)) \
+ --eval '(org-test-run-batch-tests org-test-select-re)'
+
+# Running a plain emacs with no config and this Org-mode loaded. This
+# should be useful for manual testing and verification of problems.
+NOBATCH = $(EMACSQ) $(BTEST_INIT) -l org -f org-version
+
+# start Emacs with no user and site configuration
+# EMACSQ = -vanilla # XEmacs
+EMACSQ = $(EMACS) -Q
+
+# Using emacs in batch mode.
+BATCH = $(EMACSQ) -batch \
+ --eval '(setq vc-handled-backends nil org-startup-folded nil)'
+
+# Emacs must be started in toplevel directory
+BATCHO = $(BATCH) \
+ --eval '(add-to-list '"'"'load-path "./lisp")'
+
+# How to generate local.mk
+MAKE_LOCAL_MK = $(BATCHO) \
+ --eval '(load "org-compat.el")' \
+ --eval '(load "../mk/org-fixup.el")' \
+ --eval '(org-make-local-mk)'
+
+# Emacs must be started in lisp directory
+BATCHL = $(BATCH) \
+ --eval '(add-to-list '"'"'load-path ".")'
+
+# How to generate org-loaddefs.el
+MAKE_ORG_INSTALL = $(BATCHL) \
+ --eval '(load "org-compat.el")' \
+ --eval '(load "../mk/org-fixup.el")' \
+ --eval '(org-make-org-loaddefs)'
+
+# How to generate org-version.el
+MAKE_ORG_VERSION = $(BATCHL) \
+ --eval '(load "org-compat.el")' \
+ --eval '(load "../mk/org-fixup.el")' \
+ --eval '(org-make-org-version "$(ORGVERSION)" "$(GITVERSION)" "'$(datadir)'")'
+
+# How to byte-compile the whole source directory
+ELCDIR = $(BATCHL) \
+ --eval '(batch-byte-recompile-directory 0)'
+
+# How to byte-compile a single file
+ELC = $(BATCHL) \
+ --eval '(batch-byte-compile)'
+
+# How to make a pdf file from a texinfo file
+TEXI2PDF = texi2pdf --batch --clean --expand
+
+# How to make a pdf file from a tex file
+PDFTEX = pdftex
+
+# How to create directories with leading path components
+# MKDIR = mkdir -m 755 -p # try this if you have no install
+MKDIR = install -m 755 -d
+
+# How to create the info files from the texinfo file
+MAKEINFO = makeinfo
+
+# How to create the HTML file
+TEXI2HTML = makeinfo --html --number-sections
+
+# How to find files
+FIND = find
+
+# How to remove files
+RM = rm -f
+
+# How to remove files recursively
+RMR = rm -fr
+
+# How to change file permissions
+# currently only needed for git-annex due to its "lockdown" feature
+CHMOD = chmod
+
+# How to copy the lisp files and elc files to their destination.
+# CP = cp -p # try this if you have no install
+CP = install -m 644 -p
+
+# How to obtain administrative privileges
+# leave blank if you don't need this
+# SUDO =
+SUDO = sudo
+
+# Name of the program to install info files
+# INSTALL_INFO = ginstall-info # Debian: avoid harmless warning message
+INSTALL_INFO = install-info
+
+# target method for 'compile'
+ORGCM = dirall
+# ORGCM = dirall # 1x slowdown compared to default compilation method
+# ORGCM = single # 4x one Emacs process per compilation
+# ORGCM = source # 5x ditto, but remove compiled file immediately
+# ORGCM = slint1 # 3x possibly elicit more warnings
+# ORGCM = slint2 # 7x possibly elicit even more warnings
diff --git a/mk/org-fixup.el b/mk/org-fixup.el
new file mode 100644
index 0000000..ac28963
--- /dev/null
+++ b/mk/org-fixup.el
@@ -0,0 +1,200 @@
+;;; org-fixup.el --- make life easier for folks without GNU make
+;;
+;; Author: Achim Gratz
+;; Keywords: orgmode
+;; Homepage: http://orgmode.org
+;;
+;; This file is not part of GNU Emacs.
+;;
+;; GNU Emacs is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 3, or (at your option)
+;; any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING. If not, write to the
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;;; Commentary:
+
+(require 'autoload)
+(require 'org-compat "org-compat.el")
+
+(defun org-make-org-version (org-release org-git-version odt-dir)
+ "Make the file org-version.el in the current directory.
+This function is internally used by the build system and should
+be used by foreign build systems or installers to produce this
+file in the installation directory of org-mode. Org will not
+work correctly if this file is not present (except directly from
+the Git work tree)."
+ (with-temp-buffer
+ (insert "\
+;;; org-version.el --- autogenerated file, do not edit
+;;
+;;; Code:
+;;;\#\#\#autoload
+\(defun org-release ()
+ \"The release version of Org.
+Inserted by installing Org mode or when a release is made.\"
+ (let ((org-release \"" org-release "\"))
+ org-release))
+;;;\#\#\#autoload
+\(defun org-git-version ()
+ \"The Git version of org-mode.
+Inserted by installing Org or when a release is made.\"
+ (let ((org-git-version \"" org-git-version "\"))
+ org-git-version))
+;;;\#\#\#autoload
+\(defvar org-odt-data-dir \"" odt-dir "\"
+ \"The location of ODT styles.\")
+\f\n\(provide 'org-version\)
+\f\n;; Local Variables:\n;; version-control: never
+;; no-byte-compile: t
+;; coding: utf-8\n;; End:\n;;; org-version.el ends here\n")
+ (let ((inhibit-read-only t))
+ (write-file "org-version.el"))))
+
+(defun org-make-org-loaddefs ()
+ "Make the file org-loaddefs.el in the current directory.
+This function is internally used by the build system and should
+be used by foreign build systems or installers to produce this
+file in the installation directory of org-mode. Org will not
+work correctly if this file is not up-to-date."
+ (with-temp-buffer
+ (set-visited-file-name "org-loaddefs.el")
+ (insert ";;; org-loaddefs.el --- autogenerated file, do not edit\n;;\n;;; Code:\n")
+ (let ((files (directory-files default-directory
+ nil "^\\(org\\|ob\\|ox\\)\\(-.*\\)?\\.el$")))
+ (mapc (lambda (f) (generate-file-autoloads f)) files))
+ (insert "\f\n(provide 'org-loaddefs)\n")
+ (insert "\f\n;; Local Variables:\n;; version-control: never\n")
+ (insert ";; no-byte-compile: t\n;; no-update-autoloads: t\n")
+ (insert ";; coding: utf-8\n;; End:\n;;; org-loaddefs.el ends here\n")
+ (let ((inhibit-read-only t))
+ (save-buffer))))
+
+(defun org-make-autoloads (&optional compile force)
+ "Make the files org-loaddefs.el and org-version.el in the install directory.
+Finds the install directory by looking for library \"org\".
+Optionally byte-compile lisp files in the install directory or
+force re-compilation. This function is provided for easier
+manual install when the build system can't be used."
+ (let* ((origin default-directory)
+ (dirlisp (org-find-library-dir "org"))
+ (dirorg (concat dirlisp "../" ))
+ (dirodt (if (boundp 'org-odt-data-dir)
+ org-odt-data-dir
+ (concat dirorg "etc/"))))
+ (unwind-protect
+ (progn
+ (cd dirlisp)
+ (org-fixup)
+ (org-make-org-version (org-release) (org-git-version) dirodt)
+ (org-make-org-loaddefs)
+ (when compile (byte-recompile-directory dirlisp 0 force)))
+ (cd origin))))
+
+(defun org-make-autoloads-compile ()
+ "Call org-make-autoloads with compile argument.
+Convenience function for easier invocation from command line."
+ (org-make-autoloads 'compile nil))
+
+(defun org-make-autoloads-compile-force ()
+ "Call org-make-autoloads with compile force arguments.
+Convenience function for easier invocation from command line."
+ (org-make-autoloads 'compile 'force))
+
+;; Internal functions
+
+(defun org-make-local-mk ()
+ "Internal function for the build system."
+ (let ((default "mk/default.mk")
+ (local "local.mk"))
+ (unwind-protect
+ (with-temp-buffer
+ (insert-file-contents default)
+ (goto-char (point-min))
+ (when (search-forward "-8<-" nil t)
+ (forward-line 1)
+ (delete-region (point-min) (point)))
+ (when (search-forward "->8-" nil t)
+ (forward-line 0)
+ (delete-region (point) (point-max)))
+ (goto-char (point-min))
+ (insert "
+# Remove \"oldorg:\" to switch to \"all\" as the default target.
+# Change \"oldorg:\" to an existing target to make that target the default,
+# or define your own target here to become the default target.
+oldorg: # do what the old Makefile did by default.
+
+##----------------------------------------------------------------------
+")
+ (goto-char (point-max))
+ (insert "\
+# See default.mk for further configuration options.
+")
+ (let ((inhibit-read-only t))
+ (write-file local)))
+ nil)))
+
+(defun org-make-letterformat (a4name lettername)
+ "Internal function for the build system."
+ (unwind-protect
+ (with-temp-buffer
+ (insert-file-contents a4name)
+ (goto-char (point-min))
+ (while (search-forward "\\pdflayout=(0l)" nil t)
+ (replace-match "\\pdflayout=(1l)" nil t))
+ (let ((inhibit-read-only t))
+ (write-file lettername)))
+ nil))
+
+;; redefine version functions
+
+(defmacro org-fixup ()
+ (let* ((origin default-directory)
+ (dirlisp (org-find-library-dir "org"))
+ (dirorg (concat dirlisp "../" ))
+ (dirgit (concat dirorg ".git/" ))
+ (org-version "N/A-fixup")
+ (org-git-version "N/A-fixup !!check installation!!"))
+ (if (and (boundp 'org-fake-release) (stringp org-fake-release)
+ (boundp 'org-fake-git-version) (stringp org-fake-git-version))
+ (setq org-version org-fake-release
+ org-git-version org-fake-git-version)
+ (if (load (concat dirlisp "org-version.el") 'noerror 'nomessage 'nosuffix)
+ (setq org-version (org-release)
+ org-git-version (org-git-version))
+ (when (and (file-exists-p dirgit)
+ (executable-find "git"))
+ (unwind-protect
+ (progn
+ (cd dirorg)
+ (let ((git6 (substring (shell-command-to-string "git describe --abbrev=6 HEAD") 0 -1))
+ (git0 (substring (shell-command-to-string "git describe --abbrev=0 HEAD") 0 -1))
+ (gitd (string-match "\\S-"
+ (shell-command-to-string "git status -uno --porcelain"))))
+ (setq org-git-version (concat git6 (when gitd ".dirty") "-git"))
+ (if (string-match "^release_" git0)
+ (setq org-version (substring git0 8))
+ (setq org-version git0))))
+ (cd origin)))))
+ (message "org-fixup.el: redefined Org version")
+ `(progn
+ (defun org-release () ,org-version)
+ (defun org-git-version () ,org-git-version))))
+
+(provide 'org-fixup)
+
+;; Local Variables:
+;; no-byte-compile: t
+;; coding: utf-8
+;; End:
+;;; org-fixup.el ends here
diff --git a/mk/targets.mk b/mk/targets.mk
new file mode 100644
index 0000000..0ccb6ea
--- /dev/null
+++ b/mk/targets.mk
@@ -0,0 +1,167 @@
+.EXPORT_ALL_VARIABLES:
+.NOTPARALLEL: .PHONY
+# Additional distribution files
+DISTFILES_extra= Makefile request-assign-future.txt contrib etc
+
+LISPDIRS = lisp
+OTHERDIRS = doc etc
+CLEANDIRS = contrib testing mk
+SUBDIRS = $(OTHERDIRS) $(LISPDIRS)
+INSTSUB = $(SUBDIRS:%=install-%)
+ORG_MAKE_DOC ?= info html pdf
+
+ifneq ($(wildcard .git),)
+ GITVERSION ?= $(shell git describe --match release\* --abbrev=6 HEAD)
+ ORGVERSION ?= $(subst release_,,$(shell git describe --match release\* --abbrev=0 HEAD))
+ GITSTATUS ?= $(shell git status -uno --porcelain)
+else
+ -include mk/version.mk
+ GITVERSION ?= N/A
+ ORGVERSION ?= N/A
+endif
+DATE = $(shell date +%Y-%m-%d)
+ifneq ($(GITSTATUS),)
+ GITVERSION := $(GITVERSION:.dirty=).dirty
+endif
+
+.PHONY: all oldorg update update2 up0 up1 up2 single $(SUBDIRS) \
+ check test install $(INSTSUB) \
+ info html pdf card refcard doc docs \
+ autoloads cleanall clean $(CLEANDIRS:%=clean%) \
+ clean-install cleanelc cleandirs cleanaddcontrib \
+ cleanlisp cleandoc cleandocs cleantest \
+ compile compile-dirty uncompiled \
+ config config-test config-exe config-all config-eol config-version \
+ vanilla
+
+CONF_BASE = EMACS DESTDIR ORGCM ORG_MAKE_DOC
+CONF_DEST = lispdir infodir datadir testdir
+CONF_TEST = BTEST_PRE BTEST_POST BTEST_OB_LANGUAGES BTEST_EXTRA BTEST_RE
+CONF_EXEC = CP MKDIR RM RMR FIND CHMOD SUDO PDFTEX TEXI2PDF TEXI2HTML MAKEINFO INSTALL_INFO
+CONF_CALL = BATCH BATCHL ELC ELCDIR NOBATCH BTEST MAKE_LOCAL_MK MAKE_ORG_INSTALL MAKE_ORG_VERSION
+config-eol:: EOL = \#
+config-eol:: config-all
+config config-all::
+ $(info )
+ $(info ========= Emacs executable and Installation paths)
+ $(foreach var,$(CONF_BASE),$(info $(var) = $($(var))$(EOL)))
+ $(foreach var,$(CONF_DEST),$(info $(var) = $(DESTDIR)$($(var))$(EOL)))
+ $(info ========= Additional files from contrib/lisp)
+ $(info $(notdir \
+ $(wildcard \
+ $(addsuffix .el, \
+ $(addprefix contrib/lisp/, \
+ $(basename \
+ $(notdir $(ORG_ADD_CONTRIB))))))))
+config-test config-all::
+ $(info )
+ $(info ========= Test configuration)
+ $(foreach var,$(CONF_TEST),$(info $(var) = $($(var))$(EOL)))
+config-exe config-all::
+ $(info )
+ $(info ========= Executables used by make)
+ $(foreach var,$(CONF_EXEC),$(info $(var) = $($(var))$(EOL)))
+config-cmd config-all::
+ $(info )
+ $(info ========= Commands used by make)
+ $(foreach var,$(CONF_CALL),$(info $(var) = $($(var))$(EOL)))
+config config-test config-exe config-all config-version::
+ $(info ========= Org version)
+ $(info make: Org-mode version $(ORGVERSION) ($(GITVERSION) => $(lispdir)))
+ @echo ""
+
+oldorg: compile info # what the old makefile did when no target was specified
+uncompiled: cleanlisp autoloads # for developing
+refcard: card
+update update2:: up0 all
+
+single: ORGCM=single
+single: compile
+
+.PRECIOUS: local.mk
+local.mk:
+ $(info ======================================================)
+ $(info = Invoke "make help" for a synopsis of make targets. =)
+ $(info = Created a default local.mk template. =)
+ $(info = Setting "oldorg" as the default target. =)
+ $(info = Please adapt local.mk to your local setup! =)
+ $(info ======================================================)
+ -@$(MAKE_LOCAL_MK)
+
+all compile::
+ $(foreach dir, doc lisp, $(MAKE) -C $(dir) clean;)
+compile compile-dirty::
+ $(MAKE) -C lisp $@
+all clean-install::
+ $(foreach dir, $(SUBDIRS), $(MAKE) -C $(dir) $@;)
+
+vanilla:
+ -@$(NOBATCH) &
+
+check test:: compile
+check test test-dirty::
+ -$(MKDIR) $(testdir)
+ TMPDIR=$(testdir) $(BTEST)
+ifeq ($(TEST_NO_AUTOCLEAN),) # define this variable to leave $(testdir) around for inspection
+ $(MAKE) cleantest
+endif
+
+up0:: cleanaddcontrib
+up0 up1 up2::
+ git checkout $(GIT_BRANCH)
+ git remote update
+ git pull
+up1 up2:: all
+ $(MAKE) test-dirty
+up2 update2::
+ $(SUDO) $(MAKE) install
+
+install: $(INSTSUB)
+
+install-info: install-doc
+
+doc docs: $(ORG_MAKE_DOC)
+
+info html pdf card:
+ $(MAKE) -C doc $@
+
+$(INSTSUB):
+ $(MAKE) -C $(@:install-%=%) install
+
+autoloads: lisp
+ $(MAKE) -C $< $@
+
+cleandirs:
+ $(foreach dir, $(SUBDIRS), $(MAKE) -C $(dir) cleanall;)
+
+clean: cleanlisp cleandoc
+
+cleanall: cleandirs cleantest cleanaddcontrib
+ -$(FIND) . \( -name \*~ -o -name \*# -o -name .#\* \) -exec $(RM) {} +
+ -$(FIND) $(CLEANDIRS) \( -name \*~ -o -name \*.elc \) -exec $(RM) {} +
+
+$(CLEANDIRS:%=clean%):
+ -$(FIND) $(@:clean%=%) \( -name \*~ -o -name \*.elc \) -exec $(RM) {} +
+
+cleanelc:
+ $(MAKE) -C lisp $@
+
+cleanaddcontrib:
+ -$(RM) $(wildcard $(addprefix lisp/,$(notdir $(wildcard contrib/lisp/*.el))))
+
+cleanlisp: cleanaddcontrib
+cleanlisp cleandoc:
+ $(MAKE) -C $(@:clean%=%) clean
+
+cleandocs:
+ $(MAKE) -C doc clean
+ -$(FIND) doc -name \*~ -exec $(RM) {} \;
+
+cleantest:
+# git-annex creates non-writable directories so that the files within
+# them can't be removed; if rm fails, try to recover by making all
+# directories writable
+ -$(RMR) $(testdir) || { \
+ $(FIND) $(testdir) -type d -exec $(CHMOD) u+w {} + && \
+ $(RMR) $(testdir) ; \
+ }
diff --git a/mk/version.mk b/mk/version.mk
new file mode 100644
index 0000000..9993d5b
--- /dev/null
+++ b/mk/version.mk
@@ -0,0 +1,2 @@
+ORGVERSION ?= 9.0.9
+GITVERSION ?= 9.0.9-dist
diff --git a/request-assign-future.txt b/request-assign-future.txt
new file mode 100644
index 0000000..f0133bd
--- /dev/null
+++ b/request-assign-future.txt
@@ -0,0 +1,44 @@
+Please email the following information to assign@gnu.org, and we
+will send you the assignment form for your past and future changes.
+
+Please use your full legal name (in ASCII characters) as the subject
+line of the message.
+----------------------------------------------------------------------
+REQUEST: SEND FORM FOR PAST AND FUTURE CHANGES
+
+[What is the name of the program or package you're contributing to?]
+
+ Emacs
+
+[Did you copy any files or text written by someone else in these changes?
+Even if that material is free software, we need to know about it.]
+
+
+[Do you have an employer who might have a basis to claim to own
+your changes? Do you attend a school which might make such a claim?]
+
+
+[For the copyright registration, what country are you a citizen of?]
+
+
+[What year were you born?]
+
+
+[Please write your email address here.]
+
+
+[Please write your postal address here.]
+
+
+
+
+
+[Which files have you changed so far, and which new files have you written
+so far?]
+
+
+
+
+
+
+